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 json
import logging import logging
import os
import glob
default_settings = ('{"TRIVIA_ADMIN_ONLY": false, "EDIT_CC_ADMIN_ONLY": false, "PASSWORD": "PASSWORDHERE", "FILTER": true, "CUSTOMCOMMANDS": true, ' + 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, ' + '"TRIVIA_MAX_SCORE": 10, "TRIVIA_DELAY": 15, "LOGGING": true, "EMAIL": "EMAILHERE", "ADMINROLE": "Transistor", "DOWNLOADMODE" : true, ' +
@ -28,26 +30,10 @@ def loadProverbs():
data = f.readlines() data = f.readlines()
return data 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(): def loadAndCheckSettings():
to_delete = [] to_delete = []
try: try:
current_settings = fileIO("settings.json", "load") current_settings = fileIO("json/settings.json", "load")
default = json.loads(default_settings) default = json.loads(default_settings)
if current_settings.keys() != default.keys(): if current_settings.keys() != default.keys():
logger.warning("Something wrong detected with settings.json. Starting check...") logger.warning("Something wrong detected with settings.json. Starting check...")
@ -63,12 +49,56 @@ def loadAndCheckSettings():
del current_settings[field] del current_settings[field]
logger.warning("Your settings.json was deprecated (missing or useless fields detected). I fixed it. " + 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.") "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 return current_settings
except IOError: 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.") logger.error("Your settings.json is missing. I've created a new one. Edit it with your settings and restart me.")
exit(1) exit(1)
except: 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.") 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 import dataIO
bank = dataIO.fileIO("economy.json", "load")
client = None client = None
#words = dataIO.loadWords() #words = dataIO.loadWords()
#anagram_sessions_timestamps = {} #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 #!payday - Get some cash every 10 minutes
def initialize(c): def initialize(c):
global client global client, bank
bank = dataIO.fileIO("json/economy.json", "load")
client = c client = c
async def checkCommands(message): async def checkCommands(message):
@ -67,7 +67,7 @@ async def checkCommands(message):
async def registerAccount(user, message): async def registerAccount(user, message):
if user.id not in bank: if user.id not in bank:
bank[user.id] = {"name" : user.name, "balance" : 100} 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)))) await client.send_message(message.channel, "{} `Account opened. Current balance: {}`".format(user.mention, str(checkBalance(user.id))))
else: else:
await client.send_message(message.channel, "{} `You already have an account at the Twentysix bank.`".format(user.mention)) 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 accountCheck(id):
if bank[id]["balance"] >= int(amount): if bank[id]["balance"] >= int(amount):
bank[id]["balance"] = 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: else:
return False return False
else: else:
@ -97,7 +97,7 @@ def withdrawMoney(id, amount):
def addMoney(id, amount): def addMoney(id, amount):
if accountCheck(id): if accountCheck(id):
bank[id]["balance"] = 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: else:
return False 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(): class botPlays():
def __init__(self): 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.lastChanged = int(time.perf_counter())
self.delay = 300 self.delay = 300
@ -633,7 +633,7 @@ async def addcom(message):
if newcmd not in cmdlist: if newcmd not in cmdlist:
cmdlist[newcmd] = customtext cmdlist[newcmd] = customtext
commands[message.channel.server.id] = cmdlist commands[message.channel.server.id] = cmdlist
dataIO.fileIO("commands.json", "save", commands) dataIO.fileIO("json/commands.json", "save", commands)
logger.info("Saved commands database.") logger.info("Saved commands database.")
await client.send_message(message.channel, "`Custom command successfully added.`") await client.send_message(message.channel, "`Custom command successfully added.`")
else: else:
@ -656,7 +656,7 @@ async def editcom(message):
if cmd in cmdlist: if cmd in cmdlist:
cmdlist[cmd] = customtext cmdlist[cmd] = customtext
commands[message.channel.server.id] = cmdlist commands[message.channel.server.id] = cmdlist
dataIO.fileIO("commands.json", "save", commands) dataIO.fileIO("json/commands.json", "save", commands)
logger.info("Saved commands database.") logger.info("Saved commands database.")
await client.send_message(message.channel, "`Custom command successfully edited.`") await client.send_message(message.channel, "`Custom command successfully edited.`")
else: else:
@ -678,7 +678,7 @@ async def delcom(message):
if msg[1] in cmdlist: if msg[1] in cmdlist:
cmdlist.pop(msg[1], None) cmdlist.pop(msg[1], None)
commands[message.channel.server.id] = cmdlist commands[message.channel.server.id] = cmdlist
dataIO.fileIO("commands.json", "save", commands) dataIO.fileIO("json/commands.json", "save", commands)
logger.info("Saved commands database.") logger.info("Saved commands database.")
await client.send_message(message.channel, "`Custom command successfully deleted.`") await client.send_message(message.channel, "`Custom command successfully deleted.`")
else: else:
@ -1247,7 +1247,7 @@ async def setVolume(message):
if vol >= 0 and vol <= 1: if vol >= 0 and vol <= 1:
settings["VOLUME"] = vol settings["VOLUME"] = vol
await(client.send_message(message.channel, "`Volume set. Next track will have the desired volume.`")) 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: else:
await(client.send_message(message.channel, "`Volume must be between 0 and 1. Example: !volume 0.50`")) await(client.send_message(message.channel, "`Volume must be between 0 and 1. Example: !volume 0.50`"))
except: except:
@ -1263,7 +1263,7 @@ async def downloadMode(message):
else: else:
settings["DOWNLOADMODE"] = True settings["DOWNLOADMODE"] = True
await(client.send_message(message.channel, "`Download mode enabled.`")) await(client.send_message(message.channel, "`Download mode enabled.`"))
dataIO.fileIO("settings.json", "save", settings) dataIO.fileIO("json/settings.json", "save", settings)
else: else:
await(client.send_message(message.channel, "`I don't take orders from you.`")) await(client.send_message(message.channel, "`I don't take orders from you.`"))
@ -1303,7 +1303,7 @@ async def shush(message):
if isMemberAdmin(message): if isMemberAdmin(message):
await client.send_message(message.channel, "`Ok, I'll ignore this channel.`") await client.send_message(message.channel, "`Ok, I'll ignore this channel.`")
shush_list.append(message.channel.id) 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.") logger.info("Saved silenced channels database.")
else: else:
await client.send_message(message.channel, "`I don't take orders from you.`") 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 isMemberAdmin(message):
if message.channel.id in shush_list: if message.channel.id in shush_list:
shush_list.remove(message.channel.id) 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.") logger.info("Saved silenced channels database.")
await client.send_message(message.channel, "`Aaand I'm back.`") await client.send_message(message.channel, "`Aaand I'm back.`")
else: else:
@ -1331,7 +1331,7 @@ async def addBadWords(message):
word = word.replace("/", " ") word = word.replace("/", " ")
badwords[message.server.id].append(word) badwords[message.server.id].append(word)
await client.send_message(message.channel, "`Updated banned words database.`") 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.") logger.info("Saved filter words.")
else: else:
await client.send_message(message.channel, "`!addwords [word1] [word2] [phrase/with/many/words] (...)`") await client.send_message(message.channel, "`!addwords [word1] [word2] [phrase/with/many/words] (...)`")
@ -1353,7 +1353,7 @@ async def removeBadWords(message):
except: except:
pass pass
await client.send_message(message.channel, "`Updated banned words database.`") 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.") logger.info("Saved filter words.")
else: else:
await client.send_message(message.channel, "`!removewords [word1] [word2] [phrase/with/many/words](...)`") 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] = []
badwords_regex[message.server.id].append(msg) badwords_regex[message.server.id].append(msg)
await client.send_message(message.channel, "`Updated regex filter database.`") 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.") logger.info("Saved regex filter database.")
else: else:
await client.send_message(message.channel, "`I don't take orders from you.`") 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]: if msg in badwords_regex[message.server.id]:
badwords_regex[message.server.id].remove(msg) badwords_regex[message.server.id].remove(msg)
await client.send_message(message.channel, "`Updated regex filter database.`") 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.") logger.info("Saved regex filter database.")
else: else:
await client.send_message(message.channel, "`No match.`") 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 if not added: # twitchAlert wasn't monitoring this streamer
twitchStreams.append({"CHANNELS" : [message.channel.id], "NAME" : msg[1], "ALREADY_ONLINE" : False}) 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])) 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: else:
await client.send_message(message.channel, "`!twitchalert [name]`") await client.send_message(message.channel, "`!twitchalert [name]`")
@ -1500,7 +1500,7 @@ async def removeTwitchAlert(message):
twitchStreams.remove(stream) twitchStreams.remove(stream)
else: else:
twitchStreams[i]["CHANNELS"].remove(message.channel.id) 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])) await client.send_message(message.channel, "`I will stop sending alerts about {}'s stream in this channel.`".format(msg[1]))
return True return True
await client.send_message(message.channel, "`There's no alert for {}'s stream in this channel.`".format(msg[1])) 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) logger.warning(e)
if save: #Saves online status, in case the bot needs to be restarted it can prevent message spam 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 save = False
await asyncio.sleep(CHECK_DELAY) await asyncio.sleep(CHECK_DELAY)
@ -1557,7 +1557,7 @@ async def twitchAlert():
if to_delete: if to_delete:
for invalid_stream in to_delete: for invalid_stream in to_delete:
twitchStreams.remove(invalid_stream) twitchStreams.remove(invalid_stream)
dataIO.fileIO("twitch.json", "save", twitchStreams) dataIO.fileIO("json/twitch.json", "save", twitchStreams)
else: else:
await asyncio.sleep(5) await asyncio.sleep(5)
@ -1596,24 +1596,24 @@ def loadDataFromFiles(loadsettings=False):
proverbs = dataIO.loadProverbs() proverbs = dataIO.loadProverbs()
logger.info("Loaded " + str(len(proverbs)) + " proverbs.") 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.") 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.") 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.") 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.") 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.") logger.info("Loaded " + str(len(twitchStreams)) + " streams to monitor.")
if loadsettings: if loadsettings:
global settings global settings
settings = dataIO.fileIO("settings.json", "load") settings = dataIO.fileIO("json/settings.json", "load")
def main(): def main():
global ball, greetings, greetings_caps, stopwatches, trivia_sessions, message, gameSwitcher, uptime_timer, musicPlayer, currentPlaylist global ball, greetings, greetings_caps, stopwatches, trivia_sessions, message, gameSwitcher, uptime_timer, musicPlayer, currentPlaylist
@ -1622,9 +1622,8 @@ def main():
logger = loggerSetup() logger = loggerSetup()
dataIO.logger = logger dataIO.logger = logger
if not os.path.isfile("twitch.json"): dataIO.migration()
logger.info("Missing twitch.json. Creating it...") dataIO.createEmptyFiles()
dataIO.fileIO("twitch.json", "save", [])
settings = dataIO.loadAndCheckSettings() settings = dataIO.loadAndCheckSettings()
@ -1654,12 +1653,6 @@ def main():
musicPlayer = None musicPlayer = None
currentPlaylist = 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()) loop.create_task(twitchAlert())
#client.run(settings["EMAIL"], settings["PASSWORD"]) #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 @@
[]