From 65e25b52ff7a5133a7fc35ef0bef18c86c771582 Mon Sep 17 00:00:00 2001 From: Phxntxm Date: Sat, 9 Jul 2016 11:02:33 -0500 Subject: [PATCH] Changed the MySQl connection to disconnect and reconnect on each query, to avoid timeouts --- bot.py | 6 ++---- cogs/interaction.py | 7 +++++-- cogs/mod.py | 3 ++- cogs/owner.py | 3 ++- cogs/stats.py | 10 +++++++--- cogs/utils/config.py | 7 ++----- 6 files changed, 20 insertions(+), 16 deletions(-) diff --git a/bot.py b/bot.py index 3c1cd88..f374652 100644 --- a/bot.py +++ b/bot.py @@ -20,7 +20,7 @@ async def on_ready(): # Change the status upon connection to the default status game = discord.Game(name=config.defaultStatus, type=0) await bot.change_status(game) - cursor = config.connection.cursor() + cursor = config.getCursor() cursor.execute('use {0}'.format(config.db_default)) cursor.execute('select channel_id from restart_server where id=1') @@ -30,6 +30,7 @@ async def on_ready(): await bot.send_message(destination, "I have just finished restarting!") cursor.execute('update restart_server set channel_id=0 where id=1') config.connection.commit() + config.connection.close() @bot.event @@ -44,9 +45,6 @@ async def on_member_remove(member): @bot.event async def on_command_error(error, ctx): - if isinstance(error,pymysql.OperationalError): - config.resetConnection() - await bot.say("The connection to the MySQL server was lost! Please try your command one more time {}".format(ctx.message.author.mention)) fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```' await bot.say(fmt.format(type(error).__name__, error)) diff --git a/cogs/interaction.py b/cogs/interaction.py index de895e3..953639e 100644 --- a/cogs/interaction.py +++ b/cogs/interaction.py @@ -20,7 +20,7 @@ def battlingOff(): def updateBattleRecords(winner, loser): - cursor = config.connection.cursor() + cursor = config.getCursor() cursor.execute('use {0}'.format(config.db_default)) # Update winners records @@ -37,6 +37,7 @@ def updateBattleRecords(winner, loser): cursor.execute(sql) config.connection.commit() + config.connection.close() # Update losers records sql = "select record from battle_records where id={0}".format(loser.id) @@ -52,6 +53,7 @@ def updateBattleRecords(winner, loser): cursor.execute(sql) config.connection.commit() + config.connection.close() class Interaction: @@ -130,7 +132,7 @@ class Interaction: await self.bot.say("Why the heck are you booping me? Get away from me >:c") return - cursor = config.connection.cursor() + cursor = config.getCursor() cursor.execute('use {0}'.format(config.db_boops)) sql = "show tables like '" + str(booper.id) + "'" cursor.execute(sql) @@ -162,6 +164,7 @@ class Interaction: fmt = "{0.mention} has just booped you {1.mention}! That's {2} times now!" await self.bot.say(fmt.format(booper, boopee, amount)) config.connection.commit() + config.connection.close() def setup(bot): diff --git a/cogs/mod.py b/cogs/mod.py index 2f3cce6..09f01d1 100644 --- a/cogs/mod.py +++ b/cogs/mod.py @@ -14,7 +14,7 @@ class Mod: @checks.isMod() async def nsfwchannel(self, ctx): """Registers this channel in the database as a 'nsfw' channel''""" - cursor = config.connection.cursor() + 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)) @@ -22,6 +22,7 @@ class Mod: await self.bot.say("This channel is already registered as 'nsfw'!") return config.connection.commit() + config.connection.close() await self.bot.say("This channel has just been registered as 'nsfw'! Have fun you naughties ;)") @commands.command(pass_context=True, no_pm=True) diff --git a/cogs/owner.py b/cogs/owner.py index dad5a95..aa0a325 100644 --- a/cogs/owner.py +++ b/cogs/owner.py @@ -19,11 +19,12 @@ class Owner: @checks.isOwner() async def restart(self, ctx): """Forces the bot to restart""" - cursor = config.connection.cursor() + 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.connection.commit() + config.connection.close() 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 28cc515..8034f44 100644 --- a/cogs/stats.py +++ b/cogs/stats.py @@ -13,7 +13,7 @@ class Stats: async def mostboops(self, ctx): """Shows the person you have 'booped' the most, as well as how many times""" try: - cursor = config.connection.cursor() + 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) @@ -23,6 +23,7 @@ class Stats: 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.connection.commit() + config.connection.close() 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)) @@ -31,7 +32,7 @@ class Stats: async def listboops(self, ctx): """Lists all the users you have booped and the amount of times""" members = ctx.message.server.members - cursor = config.connection.cursor() + cursor = config.getCursor() cursor.execute('use {}'.format(config.db_boops)) sql = "select * from `{}`".format(ctx.message.author.id) cursor.execute(sql) @@ -45,6 +46,8 @@ class Stats: amount = r['amount'] if member in members: output += "\n{0.name}: {1} times".format(member,amount) + config.connection.commit() + config.connection.close() await self.bot.say("```{}```".format(output)) @commands.command(pass_context=True, no_pm=True) @@ -52,7 +55,7 @@ class Stats: """Prints a 'leaderboard' of everyone in the server's battling record""" try: members = ctx.message.server.members - cursor = config.connection.cursor() + cursor = config.getCursor() cursor.execute('use {0}'.format(config.db_default)) sql = "select * from battle_records" cursor.execute(sql) @@ -88,6 +91,7 @@ class Stats: for index in range(0, len(fmt)): fmt[index] = "{0}) {1}".format(index + 1, fmt[index]) config.connection.commit() + config.connection.close() if len(fmt) == 0: await self.bot.say("```No battling records found from any members in this server```") return diff --git a/cogs/utils/config.py b/cogs/utils/config.py index 57629d0..40f18ef 100644 --- a/cogs/utils/config.py +++ b/cogs/utils/config.py @@ -10,9 +10,6 @@ with open("/home/phxntx5/public_html/Bonfire/config.yml", "r") as f: db_default = global_config.get("db_default") db_boops = global_config.get("db_boops") nsfwChannels = global_config.get("nsfw_channel") -connection = pymysql.connect(host=global_config.get("db_host"), user=global_config.get("db_user"), - password=global_config.get("db_user_pass"), charset='utf8mb4', - cursorclass=pymysql.cursors.DictCursor) botDescription = global_config.get("description") commandPrefix = global_config.get("command_prefix") @@ -28,8 +25,8 @@ openCommands = global_config.get("openCommands", {}) ownerCommands = global_config.get("ownerCommands", {}) voiceCommands = global_config.get("voiceCommands", {}) -def resetConnection(): - global connection +def getCursor(): connection = pymysql.connect(host=global_config.get("db_host"), user=global_config.get("db_user"), password=global_config.get("db_user_pass"), charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) + return connection.cursor()