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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
import discord
from discord.ext import commands
from cogs.utils.dataIO import dataIO, fileIO
from cogs.utils.dataIO import dataIO
from collections import namedtuple, defaultdict
from datetime import datetime
from random import randint
@ -23,24 +23,31 @@ slot_payouts = """Slot machine payouts:
Three symbols: +500
Two symbols: Bet * 2"""
class BankError(Exception):
pass
class AccountAlreadyExists(BankError):
pass
class NoAccount(BankError):
pass
class InsufficientBalance(BankError):
pass
class NegativeValue(BankError):
pass
class SameSenderAndReceiver(BankError):
pass
class Bank:
def __init__(self, bot, file_path):
self.accounts = dataIO.load_json(file_path)
@ -106,7 +113,6 @@ class Bank:
self._save_bank()
def transfer_credits(self, sender, receiver, amount):
server = sender.server
if amount < 0:
raise NegativeValue()
if sender is receiver:
@ -195,7 +201,8 @@ class Economy:
global default_settings
self.bot = bot
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
default_settings = self.settings
self.settings = {}
@ -460,7 +467,7 @@ class Economy:
server = ctx.message.server
self.settings[server.id]["SLOT_MIN"] = bid
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)
async def slotmax(self, ctx, bid : int):
@ -468,7 +475,7 @@ class Economy:
server = ctx.message.server
self.settings[server.id]["SLOT_MAX"] = bid
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)
async def slottime(self, ctx, seconds : int):
@ -476,7 +483,7 @@ class Economy:
server = ctx.message.server
self.settings[server.id]["SLOT_TIME"] = 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)
async def paydaytime(self, ctx, seconds : int):
@ -484,7 +491,7 @@ class Economy:
server = ctx.message.server
self.settings[server.id]["PAYDAY_TIME"] = seconds
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)
async def paydaycredits(self, ctx, credits : int):
@ -492,7 +499,7 @@ class Economy:
server = ctx.message.server
self.settings[server.id]["PAYDAY_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?
intervals = ( # Source: http://stackoverflow.com/a/24542445
@ -514,22 +521,25 @@ class Economy:
result.append("{} {}".format(value, name))
return ', '.join(result[:granularity])
def check_folders():
if not os.path.exists("data/economy"):
print("Creating data/economy folder...")
os.makedirs("data/economy")
def check_files():
f = "data/economy/settings.json"
if not fileIO(f, "check"):
if not dataIO.is_valid_json(f):
print("Creating default economy's settings.json...")
fileIO(f, "save", {})
dataIO.save_json(f, {})
f = "data/economy/bank.json"
if not fileIO(f, "check"):
if not dataIO.is_valid_json(f):
print("Creating empty bank.json...")
fileIO(f, "save", {})
dataIO.save_json(f, {})
def setup(bot):
global logger

View File

@ -1,6 +1,6 @@
import discord
from discord.ext import commands
from .utils.dataIO import fileIO, dataIO
from .utils.dataIO import dataIO
from .utils import checks
from __main__ import send_cmd_help, settings
from collections import deque
@ -406,14 +406,14 @@ class Mod:
if not channel:
if current_ch.id not in self.ignore_list["CHANNELS"]:
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.")
else:
await self.bot.say("Channel already in ignore list.")
else:
if channel.id not in self.ignore_list["CHANNELS"]:
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.")
else:
await self.bot.say("Channel already in ignore list.")
@ -424,7 +424,7 @@ class Mod:
server = ctx.message.server
if server.id not in self.ignore_list["SERVERS"]:
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.")
else:
await self.bot.say("This server is already being ignored.")
@ -446,14 +446,14 @@ class Mod:
if not channel:
if current_ch.id in self.ignore_list["CHANNELS"]:
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.")
else:
await self.bot.say("This channel is not in the ignore list.")
else:
if channel.id in self.ignore_list["CHANNELS"]:
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.")
else:
await self.bot.say("That channel is not in the ignore list.")
@ -464,7 +464,7 @@ class Mod:
server = ctx.message.server
if server.id in self.ignore_list["SERVERS"]:
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.")
else:
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())
added += 1
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.")
else:
await self.bot.say("Words already in the filter.")
@ -541,7 +541,7 @@ class Mod:
self.filter[server.id].remove(w.lower())
removed += 1
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.")
else:
await self.bot.say("Those words weren't in the filter.")
@ -699,7 +699,7 @@ class Mod:
if before.nick != after.nick and after.nick is not None:
server = before.server
if not server.id in self.past_nicknames:
if server.id not in self.past_nicknames:
self.past_nicknames[server.id] = {}
if before.id in self.past_nicknames[server.id]:
nicks = deque(self.past_nicknames[server.id][before.id],
@ -712,6 +712,7 @@ class Mod:
dataIO.save_json("data/mod/past_nicknames.json",
self.past_nicknames)
def check_folders():
folders = ("data", "data/mod/")
for folder in folders:
@ -725,28 +726,27 @@ def check_files():
if not os.path.isfile("data/mod/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"):
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"):
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"):
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"):
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"):
print("Creating empty past_nicknames.json...")
fileIO("data/mod/past_nicknames.json", "save", {})
dataIO.save_json("data/mod/past_nicknames.json", {})
def setup(bot):

View File

@ -2,7 +2,7 @@ import discord
from discord.ext import commands
from cogs.utils import checks
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
import importlib
@ -46,7 +46,8 @@ class Owner:
def __init__(self, bot):
self.bot = bot
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)
def __unload(self):
@ -425,7 +426,7 @@ class Owner:
comm_obj.enabled = False
comm_obj.hidden = True
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.")
@command_disabler.command()
@ -433,7 +434,7 @@ class Owner:
"""Enables commands/subcommands"""
if command in self.disabled_commands:
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.")
else:
await self.bot.say("That command is not disabled.")
@ -672,10 +673,12 @@ class Owner:
return 'Last updated: ``{}``\nCommit: ``{}``\nHash: ``{}``'.format(
*version)
def check_files():
if not os.path.isfile("data/red/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):
check_files()

View File

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

View File

@ -2,7 +2,7 @@ import discord
from discord.ext import commands
from random import randint
from random import choice as randchoice
from .utils.dataIO import fileIO
from .utils.dataIO import dataIO
from .utils import checks
import datetime
import time
@ -14,7 +14,8 @@ class Trivia:
def __init__(self, bot):
self.bot = bot
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)
@checks.mod_or_permissions(administrator=True)
@ -32,7 +33,7 @@ class Trivia:
"""Points required to win"""
if score > 0:
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)))
else:
await self.bot.say("Score must be superior to 0.")
@ -42,7 +43,7 @@ class Trivia:
"""Maximum seconds to answer"""
if seconds > 4:
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)))
else:
await self.bot.say("Seconds must be at least 5.")
@ -56,7 +57,7 @@ class Trivia:
else:
self.settings["TRIVIA_BOT_PLAYS"] = True
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)
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)
await trvsession.check_answer(message)
def check_folders():
folders = ("data", "data/trivia/")
for folder in folders:
@ -279,12 +281,14 @@ def check_folders():
print("Creating " + folder + " folder...")
os.makedirs(folder)
def check_files():
settings = {"TRIVIA_MAX_SCORE" : 10, "TRIVIA_TIMEOUT" : 120, "TRIVIA_DELAY" : 15, "TRIVIA_BOT_PLAYS" : False}
if not os.path.isfile("data/trivia/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):
global trivia_manager