FileIO to DataIO conversion (#410)

This commit is contained in:
Twentysix 2016-10-10 03:40:09 +02:00 committed by GitHub
parent 7dc597a272
commit 7a3c963009
8 changed files with 110 additions and 90 deletions

View File

@ -1,6 +1,6 @@
from discord.ext import commands from discord.ext import commands
from .utils.chat_formatting import * from .utils.chat_formatting import *
from .utils.dataIO import fileIO from .utils.dataIO import dataIO
from .utils import checks from .utils import checks
from __main__ import user_allowed, send_cmd_help from __main__ import user_allowed, send_cmd_help
import os import os
@ -10,7 +10,8 @@ from copy import deepcopy
class Alias: class Alias:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.aliases = fileIO("data/alias/aliases.json", "load") self.file_path = "data/alias/aliases.json"
self.aliases = dataIO.load_json(self.file_path)
@commands.group(pass_context=True, no_pm=True) @commands.group(pass_context=True, no_pm=True)
async def alias(self, ctx): async def alias(self, ctx):
@ -42,7 +43,7 @@ class Alias:
self.aliases[server.id] = {} self.aliases[server.id] = {}
if command not in self.bot.commands: if command not in self.bot.commands:
self.aliases[server.id][command] = to_execute self.aliases[server.id][command] = to_execute
fileIO("data/alias/aliases.json", "save", self.aliases) dataIO.save_json(self.file_path, self.aliases)
await self.bot.say("Alias '{}' added.".format(command)) await self.bot.say("Alias '{}' added.".format(command))
else: else:
await self.bot.say("Cannot add '{}' because it's a real bot " await self.bot.say("Cannot add '{}' because it's a real bot "
@ -84,7 +85,7 @@ class Alias:
server = ctx.message.server server = ctx.message.server
if server.id in self.aliases: if server.id in self.aliases:
self.aliases[server.id].pop(command, None) self.aliases[server.id].pop(command, None)
fileIO("data/alias/aliases.json", "save", self.aliases) dataIO.save_json(self.file_path, self.aliases)
await self.bot.say("Alias '{}' deleted.".format(command)) await self.bot.say("Alias '{}' deleted.".format(command))
@alias.command(name="list", pass_context=True, no_pm=True) @alias.command(name="list", pass_context=True, no_pm=True)
@ -153,7 +154,7 @@ class Alias:
del self.aliases[sid][alias] del self.aliases[sid][alias]
for alias, command in to_add: # For fixing caps for alias, command in to_add: # For fixing caps
self.aliases[sid][alias] = command self.aliases[sid][alias] = command
fileIO("data/alias/aliases.json", "save", self.aliases) dataIO.save_json(self.file_path, self.aliases)
def first_word(self, msg): def first_word(self, msg):
return msg.split(" ")[0] return msg.split(" ")[0]
@ -175,9 +176,9 @@ def check_file():
aliases = {} aliases = {}
f = "data/alias/aliases.json" f = "data/alias/aliases.json"
if not fileIO(f, "check"): if not dataIO.is_valid_json(f):
print("Creating default alias's aliases.json...") print("Creating default alias's aliases.json...")
fileIO(f, "save", aliases) dataIO.save_json(f, aliases)
def setup(bot): def setup(bot):

View File

@ -1,17 +1,18 @@
import discord
from discord.ext import commands from discord.ext import commands
from .utils.dataIO import fileIO from .utils.dataIO import dataIO
from .utils import checks from .utils import checks
from __main__ import user_allowed, send_cmd_help from __main__ import user_allowed
import os import os
import re import re
class CustomCommands: class CustomCommands:
"""Custom commands.""" """Custom commands."""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.c_commands = fileIO("data/customcom/commands.json", "load") self.file_path = "data/customcom/commands.json"
self.c_commands = dataIO.load_json(self.file_path)
@commands.command(pass_context=True, no_pm=True) @commands.command(pass_context=True, no_pm=True)
@checks.mod_or_permissions(administrator=True) @checks.mod_or_permissions(administrator=True)
@ -32,7 +33,7 @@ class CustomCommands:
if command not in cmdlist: if command not in cmdlist:
cmdlist[command] = text cmdlist[command] = text
self.c_commands[server.id] = cmdlist self.c_commands[server.id] = cmdlist
fileIO("data/customcom/commands.json", "save", self.c_commands) dataIO.save_json(self.file_path, self.c_commands)
await self.bot.say("Custom command successfully added.") await self.bot.say("Custom command successfully added.")
else: else:
await self.bot.say("This command already exists. Use editcom to edit it.") await self.bot.say("This command already exists. Use editcom to edit it.")
@ -52,7 +53,7 @@ class CustomCommands:
if command in cmdlist: if command in cmdlist:
cmdlist[command] = text cmdlist[command] = text
self.c_commands[server.id] = cmdlist self.c_commands[server.id] = cmdlist
fileIO("data/customcom/commands.json", "save", self.c_commands) dataIO.save_json(self.file_path, self.c_commands)
await self.bot.say("Custom command successfully edited.") await self.bot.say("Custom command successfully edited.")
else: else:
await self.bot.say("That command doesn't exist. Use addcom [command] [text]") await self.bot.say("That command doesn't exist. Use addcom [command] [text]")
@ -73,7 +74,7 @@ class CustomCommands:
if command in cmdlist: if command in cmdlist:
cmdlist.pop(command, None) cmdlist.pop(command, None)
self.c_commands[server.id] = cmdlist self.c_commands[server.id] = cmdlist
fileIO("data/customcom/commands.json", "save", self.c_commands) dataIO.save_json(self.file_path, self.c_commands)
await self.bot.say("Custom command successfully deleted.") await self.bot.say("Custom command successfully deleted.")
else: else:
await self.bot.say("That command doesn't exist.") await self.bot.say("That command doesn't exist.")
@ -172,9 +173,9 @@ def check_folders():
def check_files(): def check_files():
f = "data/customcom/commands.json" f = "data/customcom/commands.json"
if not fileIO(f, "check"): if not dataIO.is_valid_json(f):
print("Creating empty commands.json...") print("Creating empty commands.json...")
fileIO(f, "save", {}) dataIO.save_json(f, {})
def setup(bot): def setup(bot):
check_folders() check_folders()

View File

@ -1,5 +1,5 @@
from discord.ext import commands from discord.ext import commands
from cogs.utils.dataIO import dataIO, fileIO from cogs.utils.dataIO import dataIO
from cogs.utils import checks from cogs.utils import checks
from cogs.utils.chat_formatting import box from cogs.utils.chat_formatting import box
from __main__ import send_cmd_help, set_cog from __main__ import send_cmd_help, set_cog
@ -16,12 +16,13 @@ class Downloader:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.path = "data/downloader/" self.path = "data/downloader/"
self.file_path = "data/downloader/repos.json"
# {name:{url,cog1:{installed},cog1:{installed}}} # {name:{url,cog1:{installed},cog1:{installed}}}
self.repos = fileIO("data/downloader/repos.json", "load") self.repos = dataIO.load_json(self.file_path)
self.update_repos() self.update_repos()
def save_repos(self): def save_repos(self):
fileIO("data/downloader/repos.json", "save", self.repos) dataIO.save_json(self.file_path, self.repos)
@commands.group(pass_context=True) @commands.group(pass_context=True)
@checks.is_owner() @checks.is_owner()
@ -255,7 +256,7 @@ class Downloader:
info_file = os.path.join(cogs[cog].get('folder'), "info.json") info_file = os.path.join(cogs[cog].get('folder'), "info.json")
if os.path.isfile(info_file): if os.path.isfile(info_file):
try: try:
data = fileIO(info_file, "load") data = dataIO.load_json(info_file)
except: except:
return None return None
return data return data
@ -338,9 +339,9 @@ def check_files():
{'community': {'url': "https://github.com/Twentysix26/Red-Cogs.git"}} {'community': {'url': "https://github.com/Twentysix26/Red-Cogs.git"}}
f = "data/downloader/repos.json" f = "data/downloader/repos.json"
if not fileIO(f, "check"): if not dataIO.is_valid_json(f):
print("Creating default data/downloader/repos.json") print("Creating default data/downloader/repos.json")
fileIO(f, "save", repos) dataIO.save_json(f, repos)
def setup(bot): def setup(bot):

View File

@ -1,6 +1,6 @@
import discord import discord
from discord.ext import commands from discord.ext import commands
from cogs.utils.dataIO import dataIO, fileIO from cogs.utils.dataIO import dataIO
from collections import namedtuple, defaultdict from collections import namedtuple, defaultdict
from datetime import datetime from datetime import datetime
from random import randint from random import randint
@ -23,24 +23,31 @@ slot_payouts = """Slot machine payouts:
Three symbols: +500 Three symbols: +500
Two symbols: Bet * 2""" Two symbols: Bet * 2"""
class BankError(Exception): class BankError(Exception):
pass pass
class AccountAlreadyExists(BankError): class AccountAlreadyExists(BankError):
pass pass
class NoAccount(BankError): class NoAccount(BankError):
pass pass
class InsufficientBalance(BankError): class InsufficientBalance(BankError):
pass pass
class NegativeValue(BankError): class NegativeValue(BankError):
pass pass
class SameSenderAndReceiver(BankError): class SameSenderAndReceiver(BankError):
pass pass
class Bank: class Bank:
def __init__(self, bot, file_path): def __init__(self, bot, file_path):
self.accounts = dataIO.load_json(file_path) self.accounts = dataIO.load_json(file_path)
@ -106,7 +113,6 @@ class Bank:
self._save_bank() self._save_bank()
def transfer_credits(self, sender, receiver, amount): def transfer_credits(self, sender, receiver, amount):
server = sender.server
if amount < 0: if amount < 0:
raise NegativeValue() raise NegativeValue()
if sender is receiver: if sender is receiver:
@ -195,7 +201,8 @@ class Economy:
global default_settings global default_settings
self.bot = bot self.bot = bot
self.bank = Bank(bot, "data/economy/bank.json") self.bank = Bank(bot, "data/economy/bank.json")
self.settings = fileIO("data/economy/settings.json", "load") self.file_path = "data/economy/settings.json"
self.settings = dataIO.load_json(self.file_path)
if "PAYDAY_TIME" in self.settings: #old format if "PAYDAY_TIME" in self.settings: #old format
default_settings = self.settings default_settings = self.settings
self.settings = {} self.settings = {}
@ -460,7 +467,7 @@ class Economy:
server = ctx.message.server server = ctx.message.server
self.settings[server.id]["SLOT_MIN"] = bid self.settings[server.id]["SLOT_MIN"] = bid
await self.bot.say("Minimum bid is now " + str(bid) + " credits.") await self.bot.say("Minimum bid is now " + str(bid) + " credits.")
fileIO("data/economy/settings.json", "save", self.settings) dataIO.save_json(self.file_path, self.settings)
@economyset.command(pass_context=True) @economyset.command(pass_context=True)
async def slotmax(self, ctx, bid : int): async def slotmax(self, ctx, bid : int):
@ -468,7 +475,7 @@ class Economy:
server = ctx.message.server server = ctx.message.server
self.settings[server.id]["SLOT_MAX"] = bid self.settings[server.id]["SLOT_MAX"] = bid
await self.bot.say("Maximum bid is now " + str(bid) + " credits.") await self.bot.say("Maximum bid is now " + str(bid) + " credits.")
fileIO("data/economy/settings.json", "save", self.settings) dataIO.save_json(self.file_path, self.settings)
@economyset.command(pass_context=True) @economyset.command(pass_context=True)
async def slottime(self, ctx, seconds : int): async def slottime(self, ctx, seconds : int):
@ -476,7 +483,7 @@ class Economy:
server = ctx.message.server server = ctx.message.server
self.settings[server.id]["SLOT_TIME"] = seconds self.settings[server.id]["SLOT_TIME"] = seconds
await self.bot.say("Cooldown is now " + str(seconds) + " seconds.") await self.bot.say("Cooldown is now " + str(seconds) + " seconds.")
fileIO("data/economy/settings.json", "save", self.settings) dataIO.save_json(self.file_path, self.settings)
@economyset.command(pass_context=True) @economyset.command(pass_context=True)
async def paydaytime(self, ctx, seconds : int): async def paydaytime(self, ctx, seconds : int):
@ -484,7 +491,7 @@ class Economy:
server = ctx.message.server server = ctx.message.server
self.settings[server.id]["PAYDAY_TIME"] = seconds self.settings[server.id]["PAYDAY_TIME"] = seconds
await self.bot.say("Value modified. At least " + str(seconds) + " seconds must pass between each payday.") await self.bot.say("Value modified. At least " + str(seconds) + " seconds must pass between each payday.")
fileIO("data/economy/settings.json", "save", self.settings) dataIO.save_json(self.file_path, self.settings)
@economyset.command(pass_context=True) @economyset.command(pass_context=True)
async def paydaycredits(self, ctx, credits : int): async def paydaycredits(self, ctx, credits : int):
@ -492,10 +499,10 @@ class Economy:
server = ctx.message.server server = ctx.message.server
self.settings[server.id]["PAYDAY_CREDITS"] = credits self.settings[server.id]["PAYDAY_CREDITS"] = credits
await self.bot.say("Every payday will now give " + str(credits) + " credits.") await self.bot.say("Every payday will now give " + str(credits) + " credits.")
fileIO("data/economy/settings.json", "save", self.settings) dataIO.save_json(self.file_path, self.settings)
def display_time(self, seconds, granularity=2): # What would I ever do without stackoverflow? def display_time(self, seconds, granularity=2): # What would I ever do without stackoverflow?
intervals = ( # Source: http://stackoverflow.com/a/24542445 intervals = ( # Source: http://stackoverflow.com/a/24542445
('weeks', 604800), # 60 * 60 * 24 * 7 ('weeks', 604800), # 60 * 60 * 24 * 7
('days', 86400), # 60 * 60 * 24 ('days', 86400), # 60 * 60 * 24
('hours', 3600), # 60 * 60 ('hours', 3600), # 60 * 60
@ -514,29 +521,32 @@ class Economy:
result.append("{} {}".format(value, name)) result.append("{} {}".format(value, name))
return ', '.join(result[:granularity]) return ', '.join(result[:granularity])
def check_folders(): def check_folders():
if not os.path.exists("data/economy"): if not os.path.exists("data/economy"):
print("Creating data/economy folder...") print("Creating data/economy folder...")
os.makedirs("data/economy") os.makedirs("data/economy")
def check_files(): def check_files():
f = "data/economy/settings.json" f = "data/economy/settings.json"
if not fileIO(f, "check"): if not dataIO.is_valid_json(f):
print("Creating default economy's settings.json...") print("Creating default economy's settings.json...")
fileIO(f, "save", {}) dataIO.save_json(f, {})
f = "data/economy/bank.json" f = "data/economy/bank.json"
if not fileIO(f, "check"): if not dataIO.is_valid_json(f):
print("Creating empty bank.json...") print("Creating empty bank.json...")
fileIO(f, "save", {}) dataIO.save_json(f, {})
def setup(bot): def setup(bot):
global logger global logger
check_folders() check_folders()
check_files() check_files()
logger = logging.getLogger("red.economy") logger = logging.getLogger("red.economy")
if logger.level == 0: # Prevents the logger from being loaded again in case of module reload if logger.level == 0: # Prevents the logger from being loaded again in case of module reload
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename='data/economy/economy.log', encoding='utf-8', mode='a') handler = logging.FileHandler(filename='data/economy/economy.log', encoding='utf-8', mode='a')
handler.setFormatter(logging.Formatter('%(asctime)s %(message)s', datefmt="[%d/%m/%Y %H:%M]")) handler.setFormatter(logging.Formatter('%(asctime)s %(message)s', datefmt="[%d/%m/%Y %H:%M]"))

View File

@ -1,6 +1,6 @@
import discord import discord
from discord.ext import commands from discord.ext import commands
from .utils.dataIO import fileIO, dataIO from .utils.dataIO import dataIO
from .utils import checks from .utils import checks
from __main__ import send_cmd_help, settings from __main__ import send_cmd_help, settings
from collections import deque from collections import deque
@ -102,7 +102,7 @@ class Mod:
invite = "" invite = ""
if can_ban: if can_ban:
try: try:
try: # We don't want blocked DMs preventing us from banning try: # We don't want blocked DMs preventing us from banning
msg = await self.bot.send_message(user, "You have been banned and " msg = await self.bot.send_message(user, "You have been banned and "
"then unbanned as a quick way to delete your messages.\n" "then unbanned as a quick way to delete your messages.\n"
"You can now join the server again.{}".format(invite)) "You can now join the server again.{}".format(invite))
@ -406,14 +406,14 @@ class Mod:
if not channel: if not channel:
if current_ch.id not in self.ignore_list["CHANNELS"]: if current_ch.id not in self.ignore_list["CHANNELS"]:
self.ignore_list["CHANNELS"].append(current_ch.id) self.ignore_list["CHANNELS"].append(current_ch.id)
fileIO("data/mod/ignorelist.json", "save", self.ignore_list) dataIO.save_json("data/mod/ignorelist.json", self.ignore_list)
await self.bot.say("Channel added to ignore list.") await self.bot.say("Channel added to ignore list.")
else: else:
await self.bot.say("Channel already in ignore list.") await self.bot.say("Channel already in ignore list.")
else: else:
if channel.id not in self.ignore_list["CHANNELS"]: if channel.id not in self.ignore_list["CHANNELS"]:
self.ignore_list["CHANNELS"].append(channel.id) self.ignore_list["CHANNELS"].append(channel.id)
fileIO("data/mod/ignorelist.json", "save", self.ignore_list) dataIO.save_json("data/mod/ignorelist.json", self.ignore_list)
await self.bot.say("Channel added to ignore list.") await self.bot.say("Channel added to ignore list.")
else: else:
await self.bot.say("Channel already in ignore list.") await self.bot.say("Channel already in ignore list.")
@ -424,7 +424,7 @@ class Mod:
server = ctx.message.server server = ctx.message.server
if server.id not in self.ignore_list["SERVERS"]: if server.id not in self.ignore_list["SERVERS"]:
self.ignore_list["SERVERS"].append(server.id) self.ignore_list["SERVERS"].append(server.id)
fileIO("data/mod/ignorelist.json", "save", self.ignore_list) dataIO.save_json("data/mod/ignorelist.json", self.ignore_list)
await self.bot.say("This server has been added to the ignore list.") await self.bot.say("This server has been added to the ignore list.")
else: else:
await self.bot.say("This server is already being ignored.") await self.bot.say("This server is already being ignored.")
@ -446,14 +446,14 @@ class Mod:
if not channel: if not channel:
if current_ch.id in self.ignore_list["CHANNELS"]: if current_ch.id in self.ignore_list["CHANNELS"]:
self.ignore_list["CHANNELS"].remove(current_ch.id) self.ignore_list["CHANNELS"].remove(current_ch.id)
fileIO("data/mod/ignorelist.json", "save", self.ignore_list) dataIO.save_json("data/mod/ignorelist.json", self.ignore_list)
await self.bot.say("This channel has been removed from the ignore list.") await self.bot.say("This channel has been removed from the ignore list.")
else: else:
await self.bot.say("This channel is not in the ignore list.") await self.bot.say("This channel is not in the ignore list.")
else: else:
if channel.id in self.ignore_list["CHANNELS"]: if channel.id in self.ignore_list["CHANNELS"]:
self.ignore_list["CHANNELS"].remove(channel.id) self.ignore_list["CHANNELS"].remove(channel.id)
fileIO("data/mod/ignorelist.json", "save", self.ignore_list) dataIO.save_json("data/mod/ignorelist.json", self.ignore_list)
await self.bot.say("Channel removed from ignore list.") await self.bot.say("Channel removed from ignore list.")
else: else:
await self.bot.say("That channel is not in the ignore list.") await self.bot.say("That channel is not in the ignore list.")
@ -464,7 +464,7 @@ class Mod:
server = ctx.message.server server = ctx.message.server
if server.id in self.ignore_list["SERVERS"]: if server.id in self.ignore_list["SERVERS"]:
self.ignore_list["SERVERS"].remove(server.id) self.ignore_list["SERVERS"].remove(server.id)
fileIO("data/mod/ignorelist.json", "save", self.ignore_list) dataIO.save_json("data/mod/ignorelist.json", self.ignore_list)
await self.bot.say("This server has been removed from the ignore list.") await self.bot.say("This server has been removed from the ignore list.")
else: else:
await self.bot.say("This server is not in the ignore list.") await self.bot.say("This server is not in the ignore list.")
@ -515,7 +515,7 @@ class Mod:
self.filter[server.id].append(w.lower()) self.filter[server.id].append(w.lower())
added += 1 added += 1
if added: if added:
fileIO("data/mod/filter.json", "save", self.filter) dataIO.save_json("data/mod/filter.json", self.filter)
await self.bot.say("Words added to filter.") await self.bot.say("Words added to filter.")
else: else:
await self.bot.say("Words already in the filter.") await self.bot.say("Words already in the filter.")
@ -541,7 +541,7 @@ class Mod:
self.filter[server.id].remove(w.lower()) self.filter[server.id].remove(w.lower())
removed += 1 removed += 1
if removed: if removed:
fileIO("data/mod/filter.json", "save", self.filter) dataIO.save_json("data/mod/filter.json", self.filter)
await self.bot.say("Words removed from filter.") await self.bot.say("Words removed from filter.")
else: else:
await self.bot.say("Those words weren't in the filter.") await self.bot.say("Those words weren't in the filter.")
@ -672,7 +672,7 @@ class Mod:
can_delete = message.channel.permissions_for(server.me).manage_messages can_delete = message.channel.permissions_for(server.me).manage_messages
if (message.author.id == self.bot.user.id or if (message.author.id == self.bot.user.id or
self.immune_from_filter(message) or not can_delete): # Owner, admins and mods are immune to the filter self.immune_from_filter(message) or not can_delete): # Owner, admins and mods are immune to the filter
return return
if server.id in self.filter.keys(): if server.id in self.filter.keys():
@ -699,7 +699,7 @@ class Mod:
if before.nick != after.nick and after.nick is not None: if before.nick != after.nick and after.nick is not None:
server = before.server server = before.server
if not server.id in self.past_nicknames: if server.id not in self.past_nicknames:
self.past_nicknames[server.id] = {} self.past_nicknames[server.id] = {}
if before.id in self.past_nicknames[server.id]: if before.id in self.past_nicknames[server.id]:
nicks = deque(self.past_nicknames[server.id][before.id], nicks = deque(self.past_nicknames[server.id][before.id],
@ -712,6 +712,7 @@ class Mod:
dataIO.save_json("data/mod/past_nicknames.json", dataIO.save_json("data/mod/past_nicknames.json",
self.past_nicknames) self.past_nicknames)
def check_folders(): def check_folders():
folders = ("data", "data/mod/") folders = ("data", "data/mod/")
for folder in folders: for folder in folders:
@ -725,28 +726,27 @@ def check_files():
if not os.path.isfile("data/mod/blacklist.json"): if not os.path.isfile("data/mod/blacklist.json"):
print("Creating empty blacklist.json...") print("Creating empty blacklist.json...")
fileIO("data/mod/blacklist.json", "save", []) dataIO.save_json("data/mod/blacklist.json", [])
if not os.path.isfile("data/mod/whitelist.json"): if not os.path.isfile("data/mod/whitelist.json"):
print("Creating empty whitelist.json...") print("Creating empty whitelist.json...")
fileIO("data/mod/whitelist.json", "save", []) dataIO.save_json("data/mod/whitelist.json", [])
if not os.path.isfile("data/mod/ignorelist.json"): if not os.path.isfile("data/mod/ignorelist.json"):
print("Creating empty ignorelist.json...") print("Creating empty ignorelist.json...")
fileIO("data/mod/ignorelist.json", "save", ignore_list) dataIO.save_json("data/mod/ignorelist.json", ignore_list)
if not os.path.isfile("data/mod/filter.json"): if not os.path.isfile("data/mod/filter.json"):
print("Creating empty filter.json...") print("Creating empty filter.json...")
fileIO("data/mod/filter.json", "save", {}) dataIO.save_json("data/mod/filter.json", {})
if not os.path.isfile("data/mod/past_names.json"): if not os.path.isfile("data/mod/past_names.json"):
print("Creating empty past_names.json...") print("Creating empty past_names.json...")
fileIO("data/mod/past_names.json", "save", {}) dataIO.save_json("data/mod/past_names.json", {})
if not os.path.isfile("data/mod/past_nicknames.json"): if not os.path.isfile("data/mod/past_nicknames.json"):
print("Creating empty past_nicknames.json...") print("Creating empty past_nicknames.json...")
fileIO("data/mod/past_nicknames.json", "save", {}) dataIO.save_json("data/mod/past_nicknames.json", {})
def setup(bot): def setup(bot):

View File

@ -2,7 +2,7 @@ import discord
from discord.ext import commands from discord.ext import commands
from cogs.utils import checks from cogs.utils import checks
from __main__ import set_cog, send_cmd_help, settings from __main__ import set_cog, send_cmd_help, settings
from .utils.dataIO import fileIO from .utils.dataIO import dataIO
from .utils.chat_formatting import pagify from .utils.chat_formatting import pagify
import importlib import importlib
@ -46,7 +46,8 @@ class Owner:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.setowner_lock = False self.setowner_lock = False
self.disabled_commands = fileIO("data/red/disabled_commands.json", "load") self.file_path = "data/red/disabled_commands.json"
self.disabled_commands = dataIO.load_json(self.file_path)
self.session = aiohttp.ClientSession(loop=self.bot.loop) self.session = aiohttp.ClientSession(loop=self.bot.loop)
def __unload(self): def __unload(self):
@ -425,7 +426,7 @@ class Owner:
comm_obj.enabled = False comm_obj.enabled = False
comm_obj.hidden = True comm_obj.hidden = True
self.disabled_commands.append(command) self.disabled_commands.append(command)
fileIO("data/red/disabled_commands.json", "save", self.disabled_commands) dataIO.save_json(self.file_path, self.disabled_commands)
await self.bot.say("Command has been disabled.") await self.bot.say("Command has been disabled.")
@command_disabler.command() @command_disabler.command()
@ -433,7 +434,7 @@ class Owner:
"""Enables commands/subcommands""" """Enables commands/subcommands"""
if command in self.disabled_commands: if command in self.disabled_commands:
self.disabled_commands.remove(command) self.disabled_commands.remove(command)
fileIO("data/red/disabled_commands.json", "save", self.disabled_commands) dataIO.save_json(self.file_path, self.disabled_commands)
await self.bot.say("Command enabled.") await self.bot.say("Command enabled.")
else: else:
await self.bot.say("That command is not disabled.") await self.bot.say("That command is not disabled.")
@ -672,10 +673,12 @@ class Owner:
return 'Last updated: ``{}``\nCommit: ``{}``\nHash: ``{}``'.format( return 'Last updated: ``{}``\nCommit: ``{}``\nHash: ``{}``'.format(
*version) *version)
def check_files(): def check_files():
if not os.path.isfile("data/red/disabled_commands.json"): if not os.path.isfile("data/red/disabled_commands.json"):
print("Creating empty disabled_commands.json...") print("Creating empty disabled_commands.json...")
fileIO("data/red/disabled_commands.json", "save", []) dataIO.save_json("data/red/disabled_commands.json", [])
def setup(bot): def setup(bot):
check_files() check_files()

View File

@ -1,6 +1,6 @@
import discord import discord
from discord.ext import commands from discord.ext import commands
from .utils.dataIO import fileIO from .utils.dataIO import dataIO
from .utils.chat_formatting import * from .utils.chat_formatting import *
from .utils import checks from .utils import checks
from __main__ import send_cmd_help from __main__ import send_cmd_help
@ -19,10 +19,10 @@ class Streams:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.twitch_streams = fileIO("data/streams/twitch.json", "load") self.twitch_streams = dataIO.load_json("data/streams/twitch.json")
self.hitbox_streams = fileIO("data/streams/hitbox.json", "load") self.hitbox_streams = dataIO.load_json("data/streams/hitbox.json")
self.beam_streams = fileIO("data/streams/beam.json", "load") self.beam_streams = dataIO.load_json("data/streams/beam.json")
self.settings = fileIO("data/streams/settings.json", "load") self.settings = dataIO.load_json("data/streams/settings.json")
@commands.command() @commands.command()
async def hitbox(self, stream: str): async def hitbox(self, stream: str):
@ -126,7 +126,7 @@ class Streams:
await self.bot.say("Alert activated. I will notify this channel " await self.bot.say("Alert activated. I will notify this channel "
"everytime {} is live.".format(stream)) "everytime {} is live.".format(stream))
fileIO("data/streams/twitch.json", "save", self.twitch_streams) dataIO.save_json("data/streams/twitch.json", self.twitch_streams)
@streamalert.command(name="hitbox", pass_context=True) @streamalert.command(name="hitbox", pass_context=True)
async def hitbox_alert(self, ctx, stream: str): async def hitbox_alert(self, ctx, stream: str):
@ -170,7 +170,7 @@ class Streams:
await self.bot.say("Alert activated. I will notify this channel " await self.bot.say("Alert activated. I will notify this channel "
"everytime {} is live.".format(stream)) "everytime {} is live.".format(stream))
fileIO("data/streams/hitbox.json", "save", self.hitbox_streams) dataIO.save_json("data/streams/hitbox.json", self.hitbox_streams)
@streamalert.command(name="beam", pass_context=True) @streamalert.command(name="beam", pass_context=True)
async def beam_alert(self, ctx, stream: str): async def beam_alert(self, ctx, stream: str):
@ -214,7 +214,7 @@ class Streams:
await self.bot.say("Alert activated. I will notify this channel " await self.bot.say("Alert activated. I will notify this channel "
"everytime {} is live.".format(stream)) "everytime {} is live.".format(stream))
fileIO("data/streams/beam.json", "save", self.beam_streams) dataIO.save_json("data/streams/beam.json", self.beam_streams)
@streamalert.command(name="stop", pass_context=True) @streamalert.command(name="stop", pass_context=True)
async def stop_alert(self, ctx): async def stop_alert(self, ctx):
@ -257,9 +257,9 @@ class Streams:
for s in to_delete: for s in to_delete:
self.beam_streams.remove(s) self.beam_streams.remove(s)
fileIO("data/streams/twitch.json", "save", self.twitch_streams) dataIO.save_json("data/streams/twitch.json", self.twitch_streams)
fileIO("data/streams/hitbox.json", "save", self.hitbox_streams) dataIO.save_json("data/streams/hitbox.json", self.hitbox_streams)
fileIO("data/streams/beam.json", "save", self.beam_streams) dataIO.save_json("data/streams/beam.json", self.beam_streams)
await self.bot.say("There will be no more stream alerts in this " await self.bot.say("There will be no more stream alerts in this "
"channel.") "channel.")
@ -277,7 +277,7 @@ class Streams:
https://blog.twitch.tv/client-id-required-for-kraken-api-calls-afbb8e95f843""" https://blog.twitch.tv/client-id-required-for-kraken-api-calls-afbb8e95f843"""
self.settings["TWITCH_TOKEN"] = token self.settings["TWITCH_TOKEN"] = token
fileIO("data/streams/settings.json", "save", self.settings) dataIO.save_json("data/streams/settings.json", self.settings)
await self.bot.say('Twitch Client-ID set.') await self.bot.say('Twitch Client-ID set.')
async def hitbox_online(self, stream): async def hitbox_online(self, stream):
@ -397,9 +397,9 @@ class Streams:
if old != (self.twitch_streams, self.hitbox_streams, if old != (self.twitch_streams, self.hitbox_streams,
self.beam_streams): self.beam_streams):
fileIO("data/streams/twitch.json", "save", self.twitch_streams) dataIO.save_json("data/streams/twitch.json", self.twitch_streams)
fileIO("data/streams/hitbox.json", "save", self.hitbox_streams) dataIO.save_json("data/streams/hitbox.json", self.hitbox_streams)
fileIO("data/streams/beam.json", "save", self.beam_streams) dataIO.save_json("data/streams/beam.json", self.beam_streams)
await asyncio.sleep(CHECK_DELAY) await asyncio.sleep(CHECK_DELAY)
@ -412,24 +412,24 @@ def check_folders():
def check_files(): def check_files():
f = "data/streams/twitch.json" f = "data/streams/twitch.json"
if not fileIO(f, "check"): if not dataIO.is_valid_json(f):
print("Creating empty twitch.json...") print("Creating empty twitch.json...")
fileIO(f, "save", []) dataIO.save_json(f, [])
f = "data/streams/hitbox.json" f = "data/streams/hitbox.json"
if not fileIO(f, "check"): if not dataIO.is_valid_json(f):
print("Creating empty hitbox.json...") print("Creating empty hitbox.json...")
fileIO(f, "save", []) dataIO.save_json(f, [])
f = "data/streams/beam.json" f = "data/streams/beam.json"
if not fileIO(f, "check"): if not dataIO.is_valid_json(f):
print("Creating empty beam.json...") print("Creating empty beam.json...")
fileIO(f, "save", []) dataIO.save_json(f, [])
f = "data/streams/settings.json" f = "data/streams/settings.json"
if not fileIO(f, "check"): if not dataIO.is_valid_json(f):
print("Creating empty settings.json...") print("Creating empty settings.json...")
fileIO(f, "save", {}) dataIO.save_json(f, {})
def setup(bot): def setup(bot):

View File

@ -2,7 +2,7 @@ import discord
from discord.ext import commands from discord.ext import commands
from random import randint from random import randint
from random import choice as randchoice from random import choice as randchoice
from .utils.dataIO import fileIO from .utils.dataIO import dataIO
from .utils import checks from .utils import checks
import datetime import datetime
import time import time
@ -14,7 +14,8 @@ class Trivia:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.trivia_sessions = [] self.trivia_sessions = []
self.settings = fileIO("data/trivia/settings.json", "load") self.file_path = "data/trivia/settings.json"
self.settings = dataIO.load_json(self.file_path)
@commands.group(pass_context=True) @commands.group(pass_context=True)
@checks.mod_or_permissions(administrator=True) @checks.mod_or_permissions(administrator=True)
@ -32,7 +33,7 @@ class Trivia:
"""Points required to win""" """Points required to win"""
if score > 0: if score > 0:
self.settings["TRIVIA_MAX_SCORE"] = score self.settings["TRIVIA_MAX_SCORE"] = score
fileIO("data/trivia/settings.json", "save", self.settings) dataIO.save_json(self.file_path, self.settings)
await self.bot.say("Points required to win set to {}".format(str(score))) await self.bot.say("Points required to win set to {}".format(str(score)))
else: else:
await self.bot.say("Score must be superior to 0.") await self.bot.say("Score must be superior to 0.")
@ -42,7 +43,7 @@ class Trivia:
"""Maximum seconds to answer""" """Maximum seconds to answer"""
if seconds > 4: if seconds > 4:
self.settings["TRIVIA_DELAY"] = seconds self.settings["TRIVIA_DELAY"] = seconds
fileIO("data/trivia/settings.json", "save", self.settings) dataIO.save_json(self.file_path, self.settings)
await self.bot.say("Maximum seconds to answer set to {}".format(str(seconds))) await self.bot.say("Maximum seconds to answer set to {}".format(str(seconds)))
else: else:
await self.bot.say("Seconds must be at least 5.") await self.bot.say("Seconds must be at least 5.")
@ -56,7 +57,7 @@ class Trivia:
else: else:
self.settings["TRIVIA_BOT_PLAYS"] = True self.settings["TRIVIA_BOT_PLAYS"] = True
await self.bot.say("I'll gain a point everytime you don't answer in time.") await self.bot.say("I'll gain a point everytime you don't answer in time.")
fileIO("data/trivia/settings.json", "save", self.settings) dataIO.save_json(self.file_path, self.settings)
@commands.command(pass_context=True) @commands.command(pass_context=True)
async def trivia(self, ctx, list_name : str=None): async def trivia(self, ctx, list_name : str=None):
@ -272,6 +273,7 @@ async def check_messages(message):
trvsession = await get_trivia_by_channel(message.channel) trvsession = await get_trivia_by_channel(message.channel)
await trvsession.check_answer(message) await trvsession.check_answer(message)
def check_folders(): def check_folders():
folders = ("data", "data/trivia/") folders = ("data", "data/trivia/")
for folder in folders: for folder in folders:
@ -279,12 +281,14 @@ def check_folders():
print("Creating " + folder + " folder...") print("Creating " + folder + " folder...")
os.makedirs(folder) os.makedirs(folder)
def check_files(): def check_files():
settings = {"TRIVIA_MAX_SCORE" : 10, "TRIVIA_TIMEOUT" : 120, "TRIVIA_DELAY" : 15, "TRIVIA_BOT_PLAYS" : False} settings = {"TRIVIA_MAX_SCORE" : 10, "TRIVIA_TIMEOUT" : 120, "TRIVIA_DELAY" : 15, "TRIVIA_BOT_PLAYS" : False}
if not os.path.isfile("data/trivia/settings.json"): if not os.path.isfile("data/trivia/settings.json"):
print("Creating empty settings.json...") print("Creating empty settings.json...")
fileIO("data/trivia/settings.json", "save", settings) dataIO.save_json("data/trivia/settings.json", settings)
def setup(bot): def setup(bot):
global trivia_manager global trivia_manager