From 59594a54d9a577af3bc26645f3d71c03bda75a4a Mon Sep 17 00:00:00 2001 From: Phxntxm Date: Sun, 17 Jul 2016 10:17:47 -0500 Subject: [PATCH] Changed all references to MySQL saving content, to json content --- .gitignore | 1 + cogs/core.py | 58 +++++++------------ cogs/interaction.py | 85 +++++++++------------------ cogs/mod.py | 115 +++++++++++++++---------------------- cogs/overwatch.py | 37 ++++-------- cogs/owner.py | 6 +- cogs/stats.py | 133 ++++++++++++++++++------------------------- cogs/twitch.py | 78 ++++++++----------------- cogs/utils/config.py | 11 ++-- 9 files changed, 197 insertions(+), 327 deletions(-) diff --git a/.gitignore b/.gitignore index 196467d..5d6c1a9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ config.yml +config.json .idea __pycache__ nohup.out diff --git a/cogs/core.py b/cogs/core.py index 33fe577..68a7e6c 100644 --- a/cogs/core.py +++ b/cogs/core.py @@ -82,15 +82,9 @@ class Core: query = '+'.join(search) url += query - # This will check if the channel is a 'nsfw' channel, if so add 'explicit' to the search term - #cursor = config.getCursor() - #cursor.execute('use {}'.format(config.db_default)) - #cursor.execute('select * from nsfw_channels') - #result = cursor.fetchall() nsfw_channels = config.getContent("nsfw_channels") - if {'channel_id': '{}'.format(ctx.message.channel.id)} in result: + if ctx.message.channel.id in nsfw_channels: url += ",+explicit&filter_id=95938" - config.closeConnection() # Get the response from derpibooru and parse the 'searc' result from it response = urllib.request.urlopen(url) @@ -152,19 +146,15 @@ class Core: @commands.group(pass_context=True, invoke_without_command=True, no_pm=True) async def tag(self, ctx, *tag: str): - """This can be used for custom tags + """This can be used to call custom tags The format to call a custom tag is !tag """ tag = ' '.join(tag).strip() - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select * from tags where server_id=%s and tag=%s', (ctx.message.server.id, tag)) - result = cursor.fetchone() - if result is None: + tags = config.getContent('tags') + result = [tag for tag in tags if tag['tag'] == tag and tag['server_id'] == ctx.message.server.id] + if len(result) == 0: await self.bot.say('That tag does not exist!') - config.closeConnection() return - await self.bot.say("{}".format(result['result'])) - config.closeConnection() + await self.bot.say("{}".format(result[0]['result'])) @tag.command(name='add', aliases=['create', 'start'], pass_context=True, no_pm=True) @checks.customPermsOrRole("kick_members") @@ -173,22 +163,19 @@ class Core: Format to add a tag is !tag add - """ result = ' '.join(result).strip() tag = result[0:result.find('-')].strip() - result = result[result.find('-') + 2:].strip() + tag_result = result[result.find('-') + 2:].strip() if len(tag) == 0 or len(result) == 0: await self.bot.say("Please provide the format for the tag in: !tag add - ") return - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select * from tags where server_id=%s and tag=%s', (ctx.message.server.id, tag)) - response = cursor.fetchone() - if response is not None: - await self.bot.say('That tag already exists! Please remove it and re-add it if you want to change it') - config.closeConnection() - return - sql = 'insert into tags (server_id, tag, result) values (%s, %s, %s)' - cursor.execute(sql, (ctx.message.server.id, tag, result)) + tags = config.getContent('tags') + for tag in tags: + if tag['tag'] == tag and tag['server_id'] == ctx.message.server.id: + tag['result'] = tag_result + config.saveContent('tags',tags) + return + tags.append({'server_id':ctx.message.server.id,'tag':tag,'result':tag_result}) + config.saveContent('tags',tags) await self.bot.say("I have just added the tag `{0}`! You can call this tag by entering !tag {0}".format(tag)) - config.closeConnection() @tag.command(name='delete', aliases=['remove', 'stop'], pass_context=True, no_pm=True) @checks.customPermsOrRole("kick_members") @@ -196,17 +183,16 @@ class Core: """Use this to remove a tag that from use for this server Format to delete a tag is !tag delete """ tag = ' '.join(tag).strip() - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select * from tags where server_id=%s and tag=%s', (ctx.message.server.id, tag)) - result = cursor.fetchone() - if result is None: + tags = config.getContent('tags') + result = [tag for tag in tags if tag['tag'] == tag and tag['server_id'] == ctx.message.server.id] + if len(result) == 0: await self.bot.say("The tag {} does not exist! You can't remove something if it doesn't exist...".format(tag)) - config.closeConnection() return - cursor.execute('delete from tags where server_id=%s and tag=%s', (ctx.message.server.id, tag)) + for tag in tags: + if tag['tag'] == tag and tag['server_id'] == ctx.message.server.id: + tags.remove(tag) + config.saveContent('tags',tags) await self.bot.say('I have just removed the tag `{}`'.format(tag)) - config.closeConnection() def setup(bot): diff --git a/cogs/interaction.py b/cogs/interaction.py index 8406654..faee1c8 100644 --- a/cogs/interaction.py +++ b/cogs/interaction.py @@ -20,36 +20,21 @@ def battlingOff(): def updateBattleRecords(winner, loser): - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - - # Update winners records - sql = "select record from battle_records where id='{}'".format(winner.id) - cursor.execute(sql) - result = cursor.fetchone() - if result is not None: - result = result['record'].split('-') - result[0] = str(int(result[0]) + 1) - sql = "update battle_records set record ='{}' where id='{}'".format("-".join(result), winner.id) - cursor.execute(sql) + battles = config.getContent('battle_records') + if battles is not None: + record = battles.get(winner.id) + if record is not None: + result = record.split('-') + result[0] = str(int(result[0]) + 1) + battles[winner.id] = result.join("-") + record = battles.get(loser.id) + if record is not None: + result = record.split('-') + result[1] = str(int(result[1]) + 1) + battles[loser.id] = result.join("-") else: - sql = "insert into battle_records (id,record) values ('{}','1-0')".format(winner.id) - cursor.execute(sql) - - # Update losers records - sql = "select record from battle_records where id={0}".format(loser.id) - cursor.execute(sql) - result = cursor.fetchone() - if result is not None: - result = result['record'].split('-') - result[1] = str(int(result[1]) + 1) - sql = "update battle_records set record ='{0}' where id='{1}'".format('-'.join(result), loser.id) - cursor.execute(sql) - else: - sql = "insert into battle_records (id,record) values ('{0}','0-1')".format(loser.id) - cursor.execute(sql) - - config.closeConnection() + battles = {winner.id:"1-0",loser.id:"0-1"} + config.saveContent('battle_records',battles) class Interaction: @@ -131,38 +116,24 @@ class Interaction: await self.bot.say("Why the heck are you booping me? Get away from me >:c") return - cursor = config.getCursor() - cursor.execute('use {0}'.format(config.db_boops)) - sql = "show tables like '" + str(booper.id) + "'" - cursor.execute(sql) - result = cursor.fetchone() + boops = config.getContent('boops') + if boops is None: + boops = {} amount = 1 - # Booper's table exists, continue - if result is not None: - sql = "select `amount` from `" + booper.id + "` where id='" + str(boopee.id) + "'" - cursor.execute(sql) - result = cursor.fetchone() - # Boopee's entry exists, continue - if result is not None: - amount = result.get('amount') + 1 - sql = "update `" + str(booper.id) + "` set amount = " + str(amount) + " where id=" + str( - boopee.id) - cursor.execute(sql) - # Boopee does not exist, need to create the field for it - else: - sql = "insert into `" + str(booper.id) + "` (id,amount) values ('" + str(boopee.id) + "',1)" - cursor.execute(sql) - # Booper's table does not exist, need to create the table + booper_boops = boops.get(ctx.message.author.id) + if booper_boops is None: + boops[ctx.message.author.id] = {boopee.id:1} + elif booper_boops.get(boopee.id) is None: + booper_boops[boopee.id] = 1 + boops[ctx.message.author.id] = booper_boops else: - sql = "create table `" + str(booper.id) + \ - "` (`id` varchar(255) not null,`amount` int(11) not null" + \ - ",primary key (`id`)) engine=InnoDB default charset=utf8 collate=utf8_bin" - cursor.execute(sql) - sql = "insert into `" + str(booper.id) + "` (id,amount) values ('" + str(boopee.id) + "',1)" - cursor.execute(sql) + amount = booper_boops.get(boopee.id) + 1 + booper_boops[boopee.id] = amount + boops[ctx.message.author.id] = booper_boops + + config.saveContent('boops',boops) fmt = "{0.mention} has just booped you {1.mention}! That's {2} times now!" await self.bot.say(fmt.format(booper, boopee, amount)) - config.closeConnection() def setup(bot): diff --git a/cogs/mod.py b/cogs/mod.py index a922923..2dba542 100644 --- a/cogs/mod.py +++ b/cogs/mod.py @@ -29,32 +29,25 @@ class Mod: @checks.customPermsOrRole("kick_members") async def nsfw_add(self, ctx): """Registers this channel as a 'nsfw' channel""" - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - try: - cursor.execute('insert into nsfw_channels (channel_id) values ("{}")'.format(ctx.message.channel.id)) - except pymysql.IntegrityError: + nsfw_channels = config.getContent('nsfw_channels') + if ctx.message.channel.id in nsfw_channels: await self.bot.say("This channel is already registered as 'nsfw'!") - config.closeConnection() - return - config.closeConnection() - await self.bot.say("This channel has just been registered as 'nsfw'! Have fun you naughties ;)") + else: + nsfw_channels.append(ctx.message.channel.id) + config.saveContent('nsfw_channels',nsfw_channels) + await self.bot.say("This channel has just been registered as 'nsfw'! Have fun you naughties ;)") @nsfw.command(name="remove", aliases=["delete"], pass_context=True) @checks.customPermsOrRole("kick_members") async def nsfw_remove(self, ctx, no_pm=True): """Removes this channel as a 'nsfw' channel""" - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select * from nsfw_channels where channel_id="{}"'.format(ctx.message.channel.id)) - if cursor.fetchone() is None: + nsfw_channels = config.getContent('nsfw_channels') + if not ctx.message.channel.id in nsfw_channels: await self.bot.say("This channel is not registered as a ''nsfw' channel!") - config.closeConnection() - return - - cursor.execute('delete from nsfw_channels where channel_id="{}"'.format(ctx.message.channel.id)) - config.closeConnection() - await self.bot.say("This channel has just been unregistered as a nsfw channel") + else: + nsfw_channels.remove(ctx.message.channel.id) + config.saveContent('nsfw_channels',nsfw_channels) + await self.bot.say("This channel has just been unregistered as a nsfw channel") @commands.command(pass_context=True, no_pm=True) @checks.customPermsOrRole("manage_server") @@ -80,24 +73,21 @@ class Mod: await self.bot.say("Valid permissions are: ```{}```".format("\n".join("{}".format(i) for i in valid_perms))) return command = " ".join(command) - - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_perms)) - cursor.execute("show tables like '{}'".format(ctx.message.server.id)) - result = cursor.fetchone() - if result is None: + + custom_perms = config.getContent('custom_permissions') + if custom_perms is None: await self.bot.say("There are no custom permissions setup on this server yet!") return - sql = "select perms from `" + ctx.message.server.id + "` where command=%s" - cursor.execute(sql, (command,)) - result = cursor.fetchone() - if result is None: - await self.bot.say("That command has no custom permissions setup on it!") + server_perms = custom_perms.get(ctx.message.server.id) + if server_perms is None: + await self.bot.say("There are no custom permissions setup on this server yet!") return - - await self.bot.say( - "You need to have the permission `{}` to use the command `{}` in this server".format(result['perms'], - command)) + command_perms = server_perms.get(command) + if command_perms is None: + await self.bot.say("That command has no custom permissions setup on it!") + else: + await self.bot.say("You need to have the permission `{}` " \ + "to use the command `{}` in this server".format(command_perms,command)) @perms.command(name="add", aliases=["setup,create"], pass_context=True, no_pm=True) @commands.has_permissions(manage_server=True) @@ -126,33 +116,19 @@ class Mod: await self.bot.say("{} does not appear to be a valid permission! Valid permissions are: ```{}```" .format(permissions, "\n".join(valid_perms))) return + + custom_perms = config.getContent('custom_permissions') + if custom_perms is None: + custom_perms = {} + server_perms = custom_perms.get(ctx.message.server.id) + if server_perms is None: + custom_perms[ctx.message.server.id] = {command:permissions} else: - sid = ctx.message.server.id - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_perms)) - cursor.execute("show tables like %s", (sid,)) - result = cursor.fetchone() - if result is None: - # Server's data doesn't exist yet, need to create it - sql = "create table `" + sid + "` (`command` varchar(32) not null,`perms` " \ - "varchar(32) not null,primary key (`command`))" \ - " engine=InnoDB default charset=utf8 collate=utf8_bin" - cursor.execute(sql) - sql = "insert into `" + sid + "` (command, perms) values(%s, %s)" - cursor.execute(sql, (command, permissions)) - else: - sql = "select perms from `" + sid + "`where command=%s" - cursor.execute(sql, (command,)) - if cursor.fetchone() is None: - sql = "insert into `" + sid + "` (command, perms) values(%s, %s)" - cursor.execute(sql, (command, permissions)) - else: - sql = "update `" + sid + "` set perms=%s where command=%s" - cursor.execute(sql, (permissions, command)) - + server_perms[command] = permissions + custom_perms[ctx.message.server.id] = server_perms + config.saveContent('custom_permissions',custom_perms) await self.bot.say("I have just added your custom permissions; " "you now need to have `{}` permissions to use the command `{}`".format(permissions, command)) - config.closeConnection() @perms.command(name="remove", aliases=["delete"], pass_context=True, no_pm=True) @commands.has_permissions(manage_server=True) @@ -160,23 +136,22 @@ class Mod: """Removes the custom permissions setup on the command specified""" cmd = " ".join(command) sid = ctx.message.server.id - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_perms)) - cursor.execute("show tables like %s", (sid,)) - result = cursor.fetchone() - if result is None: + custom_perms = config.getContent('custom_permissions') + if custom_perms is None: await self.bot.say("You do not have custom permissions setup on this server yet!") return - sql = "select * from `"+sid+"` where command=%s" - cursor.execute(sql, (cmd,)) - result = cursor.fetchone() - if result is None: + server_perms = custom_perms.get(ctx.message.server.id) + if server_perms is None: + await self.bot.say("There are no custom permissions setup on this server yet!") + return + command_perms = server_perms.get(command) + if command_perms is None: await self.bot.say("You do not have custom permissions setup on this command yet!") return - sql = "delete from `"+sid+"` where command=%s" - cursor.execute(sql, (cmd,)) + del server_perms[command] + custom_perms[ctx.message.server.id] = server_perms + config.saveContent('custom_permissions',custom_perms) await self.bot.say("I have just removed the custom permissions for {}!".format(cmd)) - config.closeConnection() def setup(bot): bot.add_cog(Mod(bot)) diff --git a/cogs/overwatch.py b/cogs/overwatch.py index 9db5913..478819d 100644 --- a/cogs/overwatch.py +++ b/cogs/overwatch.py @@ -31,15 +31,11 @@ class Overwatch: Capitalization also matters""" if user is None: user = ctx.message.author - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select battletag from overwatch where id=%s', (user.id,)) - result = cursor.fetchone() - config.closeConnection() - if result is None: + bt = config.getContent('overwatch').get(ctx.message.author.id) + + if bt is None: await self.bot.say("I do not have this user's battletag saved!") return - bt = result['battletag'] await self.bot.say("Searching profile information....") try: @@ -78,32 +74,23 @@ class Overwatch: await self.bot.say("Profile does not exist! Battletags are picky, " "format needs to be `user#xxxx`. Capitalization matters") return - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select * from overwatch where id=%s', (ctx.message.author.id,)) - result = cursor.fetchone() - if result: - cursor.execute('update overwatch set battletag=%s where id=%s', (bt, ctx.message.author.id)) - await self.bot.say("I have updated your saved battletag {}".format(ctx.message.author.mention)) - else: - cursor.execute('insert into overwatch (id, battletag) values (%s, %s)', (ctx.message.author.id, bt)) - await self.bot.say("I have just saved your battletag {}".format(ctx.message.author.mention)) - config.closeConnection() + ow = config.getContent('overwatch') + ow[ctx.message.author.id] = bt + config.saveContent('overwatch',ow) + + await self.bot.say("I have just saved your battletag {}".format(ctx.message.author.mention)) @ow.command(pass_context=True, name="delete", aliases=['remove'], no_pm=True) @checks.customPermsOrRole("none") async def delete(self, ctx): """Removes your battletag from the records""" - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select * from overwatch where id=%s', (ctx.message.author.id,)) - result = cursor.fetchone() - if result: - cursor.execute('delete from overwatch where id=%s', (ctx.message.author.id,)) + result = config.getContent('overwatch') + if result.get(ctx.message.author.id): + del result[ctx.message.author.id] + config.saveContent('overwatch',result) await self.bot.say("I no longer have your battletag saved {}".format(ctx.message.author.mention)) else: await self.bot.say("I don't even have your battletag saved {}".format(ctx.message.author.mention)) - config.closeConnection() def setup(bot): diff --git a/cogs/owner.py b/cogs/owner.py index 0d23e6a..2e4a4c8 100644 --- a/cogs/owner.py +++ b/cogs/owner.py @@ -22,11 +22,7 @@ class Owner: @commands.check(checks.isOwner) async def restart(self, ctx): """Forces the bot to restart""" - cursor = config.getCursor() - cursor.execute('use {0}'.format(config.db_default)) - sql = "update restart_server set channel_id={0} where id=1".format(ctx.message.channel.id) - cursor.execute(sql) - config.closeConnection() + config.saveContent('restart_server',ctx.message.channel.id) await self.bot.say("Restarting; see you in the next life {0}!".format(ctx.message.author.mention)) python = sys.executable os.execl(python, python, *sys.argv) diff --git a/cogs/stats.py b/cogs/stats.py index 0041c2c..5749eec 100644 --- a/cogs/stats.py +++ b/cogs/stats.py @@ -16,96 +16,75 @@ class Stats: async def mostboops(self, ctx): """Shows the person you have 'booped' the most, as well as how many times""" try: - cursor = config.getCursor() - cursor.execute('use {0}'.format(config.db_boops)) - sql = "select id,amount from `{0}` where amount=(select MAX(amount) from `{0}`)"\ - .format(ctx.message.author.id) - cursor.execute(sql) - result = cursor.fetchone() - member = find(lambda m: m.id == result.get('id'), self.bot.get_all_members()) + boops = config.getContent('boops') + if not boops.get(ctx.message.author.id): + await self.bot.say("You have not booped anyone {} Why the heck not...?".format(ctx.message.author.mention)) + return + + most_boops = 0 + for b_id,amt in boops.get(ctx.message.author.id): + if amt > most_boops: + most_boops = amt + most_id = b_id + + member = find(lambda m: m.id == b_id, self.bot.get_all_members()) await self.bot.say("{0} you have booped {1} the most amount of times, coming in at {2} times".format( - ctx.message.author.mention, member.mention, result.get('amount'))) - config.closeConnection() - except pymysql.ProgrammingError: - await self.bot.say("You have not booped anyone {} Why the heck not...?".format(ctx.message.author.mention)) - except Exception as e: - fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```' - await self.bot.say(fmt.format(type(e).__name__, e)) + ctx.message.author.mention, member.mention, most_boops)) @commands.command(pass_context=True, no_pm=True) @checks.customPermsOrRole("none") async def listboops(self, ctx): - try: - """Lists all the users you have booped and the amount of times""" - members = ctx.message.server.members - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_boops)) - sql = "select * from `{}`".format(ctx.message.author.id) - cursor.execute(sql) - result = cursor.fetchall() - if result is None: - await self.bot.say("You have not booped anyone!") - return - output = "You have booped:" - for r in result: - member = find(lambda m: m.id == r['id'], self.bot.get_all_members()) - amount = r['amount'] - if member in members: - output += "\n{0.name}: {1} times".format(member, amount) - config.closeConnection() - await self.bot.say("```{}```".format(output)) - except pymysql.ProgrammingError: + """Lists all the users you have booped and the amount of times""" + members = ctx.message.server.members + boops = config.getContent('boops') + if boops is None or boops.get(ctx.message.author.id): await self.bot.say("You have not booped anyone {} Why the heck not...?".format(ctx.message.author.mention)) + return + output = "You have booped:" + for b_id,amt in boops.get(ctx.message.author.id): + member = find(lambda m: m.id == b_id, self.bot.get_all_members()) + if member in members: + output += "\n{0.name}: {1} times".format(member.name, amt) + await self.bot.say("```{}```".format(output)) @commands.command(pass_context=True, no_pm=True) @checks.customPermsOrRole("none") async def mostwins(self, ctx): """Prints a 'leaderboard' of everyone in the server's battling record""" - try: - members = ctx.message.server.members - cursor = config.getCursor() - cursor.execute('use {0}'.format(config.db_default)) - sql = "select * from battle_records" - cursor.execute(sql) - result = cursor.fetchall() - count = 0 - fmt = [] - if result is not None: - for r in result: - member = find(lambda m: m.id == r['id'], self.bot.get_all_members()) - if member in members: - record = r['record'] + members = ctx.message.server.members + battles = config.getContent('battle_records') + count = 0 + fmt = [] + if battles is not None: + for m_id,record in battles: + member = find(lambda m: m.id == m_id, self.bot.get_all_members()) + if member in members: + winAmt = int(record.split('-')[0]) + loseAmt = int(record.split('-')[1]) + percentage = winAmt / (winAmt + loseAmt) - winAmt = int(record.split('-')[0]) - loseAmt = int(record.split('-')[1]) - percentage = winAmt / (winAmt + loseAmt) + position = count - position = count - - indexPercentage = 0 - if count > 0: - indexRecord = re.search('\d+-\d+', fmt[position - 1]).group(0) - indexWin = int(indexRecord.split('-')[0]) - indexLose = int(indexRecord.split('-')[1]) - indexPercentage = indexWin / (indexWin + indexLose) - while position > 0 and indexPercentage < percentage: - position -= 1 - indexRecord = re.search('\d+-\d+', fmt[position - 1]).group(0) - indexWin = int(indexRecord.split('-')[0]) - indexLose = int(indexRecord.split('-')[1]) - indexPercentage = indexWin / (indexWin + indexLose) - fmt.insert(position, "{0} has a battling record of {1}".format(member.name, record)) - count += 1 - for index in range(0, len(fmt)): - fmt[index] = "{0}) {1}".format(index + 1, fmt[index]) - config.closeConnection() - if len(fmt) == 0: - await self.bot.say("```No battling records found from any members in this server```") - return - await self.bot.say("```{}```".format("\n".join(fmt))) - except Exception as e: - fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```' - await self.bot.say(fmt.format(type(e).__name__, e)) + indexPercentage = 0 + if count > 0: + indexRecord = re.search('\d+-\d+', fmt[position - 1]).group(0) + indexWin = int(indexRecord.split('-')[0]) + indexLose = int(indexRecord.split('-')[1]) + indexPercentage = indexWin / (indexWin + indexLose) + while position > 0 and indexPercentage < percentage: + position -= 1 + indexRecord = re.search('\d+-\d+', fmt[position - 1]).group(0) + indexWin = int(indexRecord.split('-')[0]) + indexLose = int(indexRecord.split('-')[1]) + indexPercentage = indexWin / (indexWin + indexLose) + fmt.insert(position, "{0} has a battling record of {1}".format(member.name, record)) + count += 1 + for index in range(0, len(fmt)): + fmt[index] = "{0}) {1}".format(index + 1, fmt[index]) + if len(fmt) == 0: + await self.bot.say("```No battling records found from any members in this server```") + return + await self.bot.say("```{}```".format("\n".join(fmt))) def setup(bot): diff --git a/cogs/twitch.py b/cogs/twitch.py index d0c6e9d..d646db1 100644 --- a/cogs/twitch.py +++ b/cogs/twitch.py @@ -27,11 +27,8 @@ class Twitch: async def checkChannels(self): await self.bot.wait_until_ready() while not self.bot.is_closed: - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select * from twitch') - result = cursor.fetchall() - for r in result: + twitch = config.getContent('twitch') + for id,r in twitch.items(): server = discord.utils.find(lambda s: s.id == r['server_id'], self.bot.servers) member = discord.utils.find(lambda m: m.id == r['user_id'], server.members) url = r['twitch_url'] @@ -39,11 +36,11 @@ class Twitch: notify = r['notifications_on'] user = re.search("(?<=twitch.tv/)(.*)", url).group(1) if not live and notify and channelOnline(user): - cursor.execute('update twitch set live=1 where user_id="{}"'.format(r['user_id'])) + twitch[id]['live'] = 1 await self.bot.send_message(server, "{} has just gone live! " "View their stream at {}".format(member.name, url)) elif live and not channelOnline(user): - cursor.execute('update twitch set live=0 where user_id="{}"'.format(r['user_id'])) + twitch[id]['live'] = 0 await self.bot.send_message(server, "{} has just gone offline! Catch them next time they stream at {}" .format(member.name, url)) @@ -55,10 +52,9 @@ class Twitch: async def twitch(self, *, member: discord.Member=None): """Use this command to check the twitch info of a user""" if member is not None: - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select twitch_url from twitch where user_id="{}"'.format(member.id)) - result = cursor.fetchone() + twitch = config.getContent('twitch') + result = twitch.get(ctx.message.author.id) + if result is not None: url = result['twitch_url'] user = re.search("(?<=twitch.tv/)(.*)", url).group(1) @@ -69,10 +65,8 @@ class Twitch: fmt += "\nFollowers: {}".format(data['followers']) fmt += "\nURL: {}".format(url) await self.bot.say("```{}```".format(fmt)) - config.closeConnection() else: await self.bot.say("{} has not saved their twitch URL yet!".format(member.name)) - config.closeConnection() @twitch.command(name='add', pass_context=True, no_pm=True) @checks.customPermsOrRole("none") @@ -92,36 +86,29 @@ class Twitch: "What would be the point of adding a nonexistant twitch user? Silly") return - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select twitch_url from twitch where user_id="{}"'.format(ctx.message.author.id)) - result = cursor.fetchone() + twitch = config.getContent('twitch') + result = twitch.get(ctx.message.author.id) + if result is not None: - cursor.execute('update twitch set twitch_url="{}" where user_id="{}"'.format(url, ctx.message.author.id)) + twitch[ctx.message.author.id]['twitch_url'] = result else: - cursor.execute('insert into twitch (user_id,server_id,twitch_url' - ',notifications_on,live) values ("{}","{}","{}",1,0)' - .format(ctx.message.author.id, ctx.message.server.id, url)) + twitch[ctx.message.author.id] = {'twitch_url':url,'server_id':ctx.message.server.id,'notifications_on': 1,'live':0} + config.saveContent('twitch',twitch) await self.bot.say("I have just saved your twitch url {}".format(ctx.message.author.mention)) - config.closeConnection() @twitch.command(name='remove', aliases=['delete'], pass_context=True, no_pm=True) @checks.customPermsOrRole("none") async def remove_twitch_url(self, ctx): """Removes your twitch URL""" - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select twitch_url from twitch where user_id="{}"'.format(ctx.message.author.id)) - result = cursor.fetchone() - if result is not None: - cursor.execute('delete from twitch where user_id="{}"'.format(ctx.message.author.id)) + twitch = config.getContent('twitch') + if twitch.get(ctx.message.author.id) is not None: + del twitch[ctx.message.author.id] + config.saveContent('twitch',twitch) await self.bot.say("I am no longer saving your twitch URL {}".format(ctx.message.author.mention)) - config.closeConnection() else: await self.bot.say( "I do not have your twitch URL added {}. You can save your twitch url with !twitch add".format( ctx.message.author.mention)) - config.closeConnection() @twitch.group(pass_context=True, no_pm=True, invoke_without_command=True) @checks.customPermsOrRole("none") @@ -133,55 +120,40 @@ class Twitch: @checks.customPermsOrRole("none") async def notify_on(self, ctx): """Turns twitch notifications on""" - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select notifications_on from twitch where user_id="{}"'.format(ctx.message.author.id)) - result = cursor.fetchone() + twitch = config.getContent('twitch') + result = twitch.get(ctx.message.author.id) if result is None: await self.bot.say( "I do not have your twitch URL added {}. You can save your twitch url with !twitch add".format( ctx.message.author.mention)) - config.closeConnection() - return elif result['notifications_on']: await self.bot.say("What do you want me to do, send two notifications? Not gonna happen {}".format( ctx.message.author.mention)) - config.closeConnection() - return else: - cursor.execute('update twitch set notifications_on=1 where user_id="{}"'.format(ctx.message.author.id)) + twitch[ctx.message.author.id]['notifications_on'] = 1 + config.saveContent('twitch',twitch) await self.bot.say("I will notify if you go live {}, you'll get a bajillion followers I promise c:".format( ctx.message.author.mention)) - config.closeConnection() - return @notify.command(name='off', aliases=['stop,no'], pass_context=True, no_pm=True) @checks.customPermsOrRole("none") async def notify_off(self, ctx): """Turns twitch notifications off""" - cursor = config.getCursor() - cursor.execute('use {}'.format(config.db_default)) - cursor.execute('select notifications_on from twitch where user_id="{}"'.format(ctx.message.author.id)) - result = cursor.fetchone() - if result is None: + twitch = config.getContent('twitch') + if twitch.get(ctx.message.author.id) is None: await self.bot.say( "I do not have your twitch URL added {}. You can save your twitch url with !twitch add".format( ctx.message.author.mention)) - config.closeConnection() - return elif not result['notifications_on']: await self.bot.say("I am already set to not notify if you go live! Pay attention brah {}".format( ctx.message.author.mention)) - config.closeConnection() - return else: - cursor.execute('update twitch set notifications_on=0 where user_id="{}"'.format(ctx.message.author.id)) + twitch[ctx.message.author.id]['notifications_on'] = 0 + config.saveContent('twitch',twitch) await self.bot.say( "I will not notify if you go live anymore {}, " "are you going to stream some lewd stuff you don't want people to see?~".format( ctx.message.author.mention)) - config.closeConnection() - return def setup(bot): diff --git a/cogs/utils/config.py b/cogs/utils/config.py index 957b722..fd1d026 100644 --- a/cogs/utils/config.py +++ b/cogs/utils/config.py @@ -50,7 +50,10 @@ def saveContent(key: str, content): jf.close() def getContent(key: str): - with open("/home/phxntx5/public_html/Bonfire/config.json", "r+") as jf: - data = json.load(jf) - jf.close() - return data[key] + try: + with open("/home/phxntx5/public_html/Bonfire/config.json", "r+") as jf: + data = json.load(jf) + jf.close() + return data[key] + except KeyError: + return None