Settings and empty files generated at runtime

Settings and empty files are now generated at runtime
Easier first run process, the user can input email, password and admin
role directly into the terminal
This commit is contained in:
Twentysix 2016-01-12 22:05:00 +01:00
parent 797ac6d76a
commit 1162df4157
11 changed files with 79 additions and 64 deletions

View File

@ -1 +0,0 @@
{}

View File

@ -1,5 +1,7 @@
import json
import logging
import os
import glob
default_settings = ('{"TRIVIA_ADMIN_ONLY": false, "EDIT_CC_ADMIN_ONLY": false, "PASSWORD": "PASSWORDHERE", "FILTER": true, "CUSTOMCOMMANDS": true, ' +
'"TRIVIA_MAX_SCORE": 10, "TRIVIA_DELAY": 15, "LOGGING": true, "EMAIL": "EMAILHERE", "ADMINROLE": "Transistor", "DOWNLOADMODE" : true, ' +
@ -28,26 +30,10 @@ def loadProverbs():
data = f.readlines()
return data
def loadTrivia():
w = {}
with open("questions.txt", "r") as f:
for line in f:
line = line.replace("\n", "")
line = line.split("|")
w[line[0]] = line[1]
return w
def loadWords():
w = []
with open("words.dat", "r") as f:
for line in f:
w += line
return w
def loadAndCheckSettings():
to_delete = []
try:
current_settings = fileIO("settings.json", "load")
current_settings = fileIO("json/settings.json", "load")
default = json.loads(default_settings)
if current_settings.keys() != default.keys():
logger.warning("Something wrong detected with settings.json. Starting check...")
@ -63,12 +49,56 @@ def loadAndCheckSettings():
del current_settings[field]
logger.warning("Your settings.json was deprecated (missing or useless fields detected). I fixed it. " +
"If the file was missing any field I've added it and put default values. You might want to check it.")
fileIO("settings.json", "save", current_settings)
fileIO("json/settings.json", "save", current_settings)
return current_settings
except IOError:
fileIO("settings.json", "save", json.loads(default_settings))
fileIO("json/settings.json", "save", json.loads(default_settings))
logger.error("Your settings.json is missing. I've created a new one. Edit it with your settings and restart me.")
exit(1)
except:
logger.error("Your settings.json seems to be invalid. Check it. If you're unable to fix it delete it and I'll create a new one the next start.")
exit(1)
exit(1)
def migration():
if not os.path.exists("json/"):
os.makedirs("json")
logger.info("Creating json folder...")
if not os.path.exists("cache/"): #Stores youtube audio for DOWNLOADMODE
os.makedirs("cache")
if not os.path.exists("trivia/"):
os.makedirs("trivia")
files = glob.glob("*.json")
if files != []:
logger.info("Moving your json files into the json folder...")
for f in files:
logger.info("Moving {}...".format(f))
os.rename(f, "json/" + f)
def createEmptyFiles():
files = {"twitch.json": [], "commands.json": {}, "economy.json" : {}, "filter.json" : {}, "regex_filter.json" : {}, "shushlist.json" : []}
games = ["Multi Theft Auto", "her Turn()", "Tomb Raider II", "some music.", "NEO Scavenger", "Python", "World Domination", "with your heart."]
files["games.json"] = games
for f, data in files.items() :
if not os.path.isfile("json/" + f):
logger.info("Missing {}. Creating it...".format(f))
fileIO("json/" + f, "save", data)
if not os.path.isfile("json/settings.json"):
logger.info("Missing settings.json. Creating it...\n")
fileIO("json/settings.json", "save", json.loads(default_settings))
print("You have to configure your settings. If you'd like to do it manually, close this window.\nOtherwise type your bot's account email. DO NOT use your own account for the bot, make a new one.\n\nEmail:")
email = input(">")
print("Now enter the password.")
password = input(">")
print("Admin role? Leave empty for default (Transistor)")
admin_role = input(">")
if admin_role == "":
admin_role = "Transistor"
new_settings = json.loads(default_settings)
new_settings["EMAIL"] = email
new_settings["PASSWORD"] = password
new_settings["ADMINROLE"] = admin_role
fileIO("json/settings.json", "save", new_settings )
logger.info("Settings have been saved.")

View File

@ -1 +0,0 @@
{}

View File

@ -3,7 +3,6 @@ import time
import dataIO
bank = dataIO.fileIO("economy.json", "load")
client = None
#words = dataIO.loadWords()
#anagram_sessions_timestamps = {}
@ -37,7 +36,8 @@ economy_exp = """ **Economy. Get rich and have fun with imaginary currency!**
#!payday - Get some cash every 10 minutes
def initialize(c):
global client
global client, bank
bank = dataIO.fileIO("json/economy.json", "load")
client = c
async def checkCommands(message):
@ -67,7 +67,7 @@ async def checkCommands(message):
async def registerAccount(user, message):
if user.id not in bank:
bank[user.id] = {"name" : user.name, "balance" : 100}
dataIO.fileIO("economy.json", "save", bank)
dataIO.fileIO("json/economy.json", "save", bank)
await client.send_message(message.channel, "{} `Account opened. Current balance: {}`".format(user.mention, str(checkBalance(user.id))))
else:
await client.send_message(message.channel, "{} `You already have an account at the Twentysix bank.`".format(user.mention))
@ -88,7 +88,7 @@ def withdrawMoney(id, amount):
if accountCheck(id):
if bank[id]["balance"] >= int(amount):
bank[id]["balance"] = bank[id]["balance"] - int(amount)
dataIO.fileIO("economy.json", "save", bank)
dataIO.fileIO("json/economy.json", "save", bank)
else:
return False
else:
@ -97,7 +97,7 @@ def withdrawMoney(id, amount):
def addMoney(id, amount):
if accountCheck(id):
bank[id]["balance"] = bank[id]["balance"] + int(amount)
dataIO.fileIO("economy.json", "save", bank)
dataIO.fileIO("json/economy.json", "save", bank)
else:
return False

View File

@ -1 +0,0 @@
{}

View File

@ -1 +0,0 @@
["Multi Theft Auto", "her Turn()", "Tomb Raider II", "some music.", "NEO Scavenger", "Python", "World Domination", "with your heart."]

55
red.py
View File

@ -487,7 +487,7 @@ class Trivia():
class botPlays():
def __init__(self):
self.games = dataIO.fileIO("games.json", "load")
self.games = dataIO.fileIO("json/games.json", "load")
self.lastChanged = int(time.perf_counter())
self.delay = 300
@ -633,7 +633,7 @@ async def addcom(message):
if newcmd not in cmdlist:
cmdlist[newcmd] = customtext
commands[message.channel.server.id] = cmdlist
dataIO.fileIO("commands.json", "save", commands)
dataIO.fileIO("json/commands.json", "save", commands)
logger.info("Saved commands database.")
await client.send_message(message.channel, "`Custom command successfully added.`")
else:
@ -656,7 +656,7 @@ async def editcom(message):
if cmd in cmdlist:
cmdlist[cmd] = customtext
commands[message.channel.server.id] = cmdlist
dataIO.fileIO("commands.json", "save", commands)
dataIO.fileIO("json/commands.json", "save", commands)
logger.info("Saved commands database.")
await client.send_message(message.channel, "`Custom command successfully edited.`")
else:
@ -678,7 +678,7 @@ async def delcom(message):
if msg[1] in cmdlist:
cmdlist.pop(msg[1], None)
commands[message.channel.server.id] = cmdlist
dataIO.fileIO("commands.json", "save", commands)
dataIO.fileIO("json/commands.json", "save", commands)
logger.info("Saved commands database.")
await client.send_message(message.channel, "`Custom command successfully deleted.`")
else:
@ -1247,7 +1247,7 @@ async def setVolume(message):
if vol >= 0 and vol <= 1:
settings["VOLUME"] = vol
await(client.send_message(message.channel, "`Volume set. Next track will have the desired volume.`"))
dataIO.fileIO("settings.json", "save", settings)
dataIO.fileIO("json/settings.json", "save", settings)
else:
await(client.send_message(message.channel, "`Volume must be between 0 and 1. Example: !volume 0.50`"))
except:
@ -1263,7 +1263,7 @@ async def downloadMode(message):
else:
settings["DOWNLOADMODE"] = True
await(client.send_message(message.channel, "`Download mode enabled.`"))
dataIO.fileIO("settings.json", "save", settings)
dataIO.fileIO("json/settings.json", "save", settings)
else:
await(client.send_message(message.channel, "`I don't take orders from you.`"))
@ -1303,7 +1303,7 @@ async def shush(message):
if isMemberAdmin(message):
await client.send_message(message.channel, "`Ok, I'll ignore this channel.`")
shush_list.append(message.channel.id)
dataIO.fileIO("shushlist.json", "save", shush_list)
dataIO.fileIO("json/shushlist.json", "save", shush_list)
logger.info("Saved silenced channels database.")
else:
await client.send_message(message.channel, "`I don't take orders from you.`")
@ -1312,7 +1312,7 @@ async def talk(message):
if isMemberAdmin(message):
if message.channel.id in shush_list:
shush_list.remove(message.channel.id)
dataIO.fileIO("shushlist.json", "save", shush_list)
dataIO.fileIO("json/shushlist.json", "save", shush_list)
logger.info("Saved silenced channels database.")
await client.send_message(message.channel, "`Aaand I'm back.`")
else:
@ -1331,7 +1331,7 @@ async def addBadWords(message):
word = word.replace("/", " ")
badwords[message.server.id].append(word)
await client.send_message(message.channel, "`Updated banned words database.`")
dataIO.fileIO("filter.json", "save", badwords)
dataIO.fileIO("json/filter.json", "save", badwords)
logger.info("Saved filter words.")
else:
await client.send_message(message.channel, "`!addwords [word1] [word2] [phrase/with/many/words] (...)`")
@ -1353,7 +1353,7 @@ async def removeBadWords(message):
except:
pass
await client.send_message(message.channel, "`Updated banned words database.`")
dataIO.fileIO("filter.json", "save", badwords)
dataIO.fileIO("json/filter.json", "save", badwords)
logger.info("Saved filter words.")
else:
await client.send_message(message.channel, "`!removewords [word1] [word2] [phrase/with/many/words](...)`")
@ -1383,7 +1383,7 @@ async def addRegex(message):
badwords_regex[message.server.id] = []
badwords_regex[message.server.id].append(msg)
await client.send_message(message.channel, "`Updated regex filter database.`")
dataIO.fileIO("regex_filter.json", "save", badwords_regex)
dataIO.fileIO("json/regex_filter.json", "save", badwords_regex)
logger.info("Saved regex filter database.")
else:
await client.send_message(message.channel, "`I don't take orders from you.`")
@ -1397,7 +1397,7 @@ async def removeRegex(message):
if msg in badwords_regex[message.server.id]:
badwords_regex[message.server.id].remove(msg)
await client.send_message(message.channel, "`Updated regex filter database.`")
dataIO.fileIO("regex_filter.json", "save", badwords_regex)
dataIO.fileIO("json/regex_filter.json", "save", badwords_regex)
logger.info("Saved regex filter database.")
else:
await client.send_message(message.channel, "`No match.`")
@ -1482,7 +1482,7 @@ async def addTwitchAlert(message):
if not added: # twitchAlert wasn't monitoring this streamer
twitchStreams.append({"CHANNELS" : [message.channel.id], "NAME" : msg[1], "ALREADY_ONLINE" : False})
dataIO.fileIO("twitch.json", "save", twitchStreams)
dataIO.fileIO("json/twitch.json", "save", twitchStreams)
await client.send_message(message.channel, "`I will always send an alert in this channel whenever {}'s stream is online. Use !stoptwitchalert [name] to stop it.`".format(msg[1]))
else:
await client.send_message(message.channel, "`!twitchalert [name]`")
@ -1500,7 +1500,7 @@ async def removeTwitchAlert(message):
twitchStreams.remove(stream)
else:
twitchStreams[i]["CHANNELS"].remove(message.channel.id)
dataIO.fileIO("twitch.json", "save", twitchStreams)
dataIO.fileIO("json/twitch.json", "save", twitchStreams)
await client.send_message(message.channel, "`I will stop sending alerts about {}'s stream in this channel.`".format(msg[1]))
return True
await client.send_message(message.channel, "`There's no alert for {}'s stream in this channel.`".format(msg[1]))
@ -1547,7 +1547,7 @@ async def twitchAlert():
logger.warning(e)
if save: #Saves online status, in case the bot needs to be restarted it can prevent message spam
dataIO.fileIO("twitch.json", "save", twitchStreams)
dataIO.fileIO("json/twitch.json", "save", twitchStreams)
save = False
await asyncio.sleep(CHECK_DELAY)
@ -1557,7 +1557,7 @@ async def twitchAlert():
if to_delete:
for invalid_stream in to_delete:
twitchStreams.remove(invalid_stream)
dataIO.fileIO("twitch.json", "save", twitchStreams)
dataIO.fileIO("json/twitch.json", "save", twitchStreams)
else:
await asyncio.sleep(5)
@ -1596,24 +1596,24 @@ def loadDataFromFiles(loadsettings=False):
proverbs = dataIO.loadProverbs()
logger.info("Loaded " + str(len(proverbs)) + " proverbs.")
commands = dataIO.fileIO("commands.json", "load")
commands = dataIO.fileIO("json/commands.json", "load")
logger.info("Loaded " + str(len(commands)) + " lists of custom commands.")
badwords = dataIO.fileIO("filter.json", "load")
badwords = dataIO.fileIO("json/filter.json", "load")
logger.info("Loaded " + str(len(badwords)) + " lists of filtered words.")
badwords_regex = dataIO.fileIO("regex_filter.json", "load")
badwords_regex = dataIO.fileIO("json/regex_filter.json", "load")
logger.info("Loaded " + str(len(badwords_regex)) + " regex lists.")
shush_list = dataIO.fileIO("shushlist.json", "load")
shush_list = dataIO.fileIO("json/shushlist.json", "load")
logger.info("Loaded " + str(len(shush_list)) + " silenced channels.")
twitchStreams = dataIO.fileIO("twitch.json", "load")
twitchStreams = dataIO.fileIO("json/twitch.json", "load")
logger.info("Loaded " + str(len(twitchStreams)) + " streams to monitor.")
if loadsettings:
global settings
settings = dataIO.fileIO("settings.json", "load")
settings = dataIO.fileIO("json/settings.json", "load")
def main():
global ball, greetings, greetings_caps, stopwatches, trivia_sessions, message, gameSwitcher, uptime_timer, musicPlayer, currentPlaylist
@ -1622,9 +1622,8 @@ def main():
logger = loggerSetup()
dataIO.logger = logger
if not os.path.isfile("twitch.json"):
logger.info("Missing twitch.json. Creating it...")
dataIO.fileIO("twitch.json", "save", [])
dataIO.migration()
dataIO.createEmptyFiles()
settings = dataIO.loadAndCheckSettings()
@ -1654,12 +1653,6 @@ def main():
musicPlayer = None
currentPlaylist = None
if not os.path.exists("cache/"): #Stores youtube audio for DOWNLOADMODE
os.makedirs("cache")
if not os.path.exists("trivia/"):
os.makedirs("trivia")
loop.create_task(twitchAlert())
#client.run(settings["EMAIL"], settings["PASSWORD"])

View File

@ -1 +0,0 @@
{}

View File

@ -1 +0,0 @@
{"TRIVIA_BOT_PLAYS": false, "LOGGING": true, "ADMINROLE": "Transistor", "CUSTOMCOMMANDS": true, "VOLUME": 0.2, "DEBUG_ID": "IgnoreThis", "TRIVIA_MAX_SCORE": 10, "EDIT_CC_ADMIN_ONLY": false, "TRIVIA_DELAY": 15, "TRIVIA_ADMIN_ONLY": false, "EMAIL": "EMAILHERE", "TRIVIA_TIMEOUT": 120, "FILTER": true, "PASSWORD": "PASSWORDHERE", "DOWNLOADMODE": true}

View File

@ -1 +0,0 @@
[]

View File

@ -1 +0,0 @@
[]