1
0
Fork 0
mirror of synced 2024-06-02 18:54:33 +12:00

Changed the MySQl connection to disconnect and reconnect on each query, to avoid timeouts

This commit is contained in:
Phxntxm 2016-07-09 11:02:33 -05:00
parent 5de2c9cc5d
commit 65e25b52ff
6 changed files with 20 additions and 16 deletions

6
bot.py
View file

@ -20,7 +20,7 @@ async def on_ready():
# Change the status upon connection to the default status # Change the status upon connection to the default status
game = discord.Game(name=config.defaultStatus, type=0) game = discord.Game(name=config.defaultStatus, type=0)
await bot.change_status(game) await bot.change_status(game)
cursor = config.connection.cursor() cursor = config.getCursor()
cursor.execute('use {0}'.format(config.db_default)) cursor.execute('use {0}'.format(config.db_default))
cursor.execute('select channel_id from restart_server where id=1') 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!") await bot.send_message(destination, "I have just finished restarting!")
cursor.execute('update restart_server set channel_id=0 where id=1') cursor.execute('update restart_server set channel_id=0 where id=1')
config.connection.commit() config.connection.commit()
config.connection.close()
@bot.event @bot.event
@ -44,9 +45,6 @@ async def on_member_remove(member):
@bot.event @bot.event
async def on_command_error(error, ctx): 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```' fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```'
await bot.say(fmt.format(type(error).__name__, error)) await bot.say(fmt.format(type(error).__name__, error))

View file

@ -20,7 +20,7 @@ def battlingOff():
def updateBattleRecords(winner, loser): def updateBattleRecords(winner, loser):
cursor = config.connection.cursor() cursor = config.getCursor()
cursor.execute('use {0}'.format(config.db_default)) cursor.execute('use {0}'.format(config.db_default))
# Update winners records # Update winners records
@ -37,6 +37,7 @@ def updateBattleRecords(winner, loser):
cursor.execute(sql) cursor.execute(sql)
config.connection.commit() config.connection.commit()
config.connection.close()
# Update losers records # Update losers records
sql = "select record from battle_records where id={0}".format(loser.id) sql = "select record from battle_records where id={0}".format(loser.id)
@ -52,6 +53,7 @@ def updateBattleRecords(winner, loser):
cursor.execute(sql) cursor.execute(sql)
config.connection.commit() config.connection.commit()
config.connection.close()
class Interaction: class Interaction:
@ -130,7 +132,7 @@ class Interaction:
await self.bot.say("Why the heck are you booping me? Get away from me >:c") await self.bot.say("Why the heck are you booping me? Get away from me >:c")
return return
cursor = config.connection.cursor() cursor = config.getCursor()
cursor.execute('use {0}'.format(config.db_boops)) cursor.execute('use {0}'.format(config.db_boops))
sql = "show tables like '" + str(booper.id) + "'" sql = "show tables like '" + str(booper.id) + "'"
cursor.execute(sql) cursor.execute(sql)
@ -162,6 +164,7 @@ class Interaction:
fmt = "{0.mention} has just booped you {1.mention}! That's {2} times now!" fmt = "{0.mention} has just booped you {1.mention}! That's {2} times now!"
await self.bot.say(fmt.format(booper, boopee, amount)) await self.bot.say(fmt.format(booper, boopee, amount))
config.connection.commit() config.connection.commit()
config.connection.close()
def setup(bot): def setup(bot):

View file

@ -14,7 +14,7 @@ class Mod:
@checks.isMod() @checks.isMod()
async def nsfwchannel(self, ctx): async def nsfwchannel(self, ctx):
"""Registers this channel in the database as a 'nsfw' channel''""" """Registers this channel in the database as a 'nsfw' channel''"""
cursor = config.connection.cursor() cursor = config.getCursor()
cursor.execute('use {}'.format(config.db_default)) cursor.execute('use {}'.format(config.db_default))
try: try:
cursor.execute('insert into nsfw_channels (channel_id) values ("{}")'.format(ctx.message.channel.id)) 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'!") await self.bot.say("This channel is already registered as 'nsfw'!")
return return
config.connection.commit() config.connection.commit()
config.connection.close()
await self.bot.say("This channel has just been registered as 'nsfw'! Have fun you naughties ;)") await self.bot.say("This channel has just been registered as 'nsfw'! Have fun you naughties ;)")
@commands.command(pass_context=True, no_pm=True) @commands.command(pass_context=True, no_pm=True)

View file

@ -19,11 +19,12 @@ class Owner:
@checks.isOwner() @checks.isOwner()
async def restart(self, ctx): async def restart(self, ctx):
"""Forces the bot to restart""" """Forces the bot to restart"""
cursor = config.connection.cursor() cursor = config.getCursor()
cursor.execute('use {0}'.format(config.db_default)) cursor.execute('use {0}'.format(config.db_default))
sql = "update restart_server set channel_id={0} where id=1".format(ctx.message.channel.id) sql = "update restart_server set channel_id={0} where id=1".format(ctx.message.channel.id)
cursor.execute(sql) cursor.execute(sql)
config.connection.commit() config.connection.commit()
config.connection.close()
await self.bot.say("Restarting; see you in the next life {0}!".format(ctx.message.author.mention)) await self.bot.say("Restarting; see you in the next life {0}!".format(ctx.message.author.mention))
python = sys.executable python = sys.executable
os.execl(python, python, *sys.argv) os.execl(python, python, *sys.argv)

View file

@ -13,7 +13,7 @@ class Stats:
async def mostboops(self, ctx): async def mostboops(self, ctx):
"""Shows the person you have 'booped' the most, as well as how many times""" """Shows the person you have 'booped' the most, as well as how many times"""
try: try:
cursor = config.connection.cursor() cursor = config.getCursor()
cursor.execute('use {0}'.format(config.db_boops)) cursor.execute('use {0}'.format(config.db_boops))
sql = "select id,amount from `{0}` where amount=(select MAX(amount) from `{0}`)"\ sql = "select id,amount from `{0}` where amount=(select MAX(amount) from `{0}`)"\
.format(ctx.message.author.id) .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( 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'))) ctx.message.author.mention, member.mention, result.get('amount')))
config.connection.commit() config.connection.commit()
config.connection.close()
except Exception as e: except Exception as e:
fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```' fmt = 'An error occurred while processing this request: ```py\n{}: {}\n```'
await self.bot.say(fmt.format(type(e).__name__, e)) await self.bot.say(fmt.format(type(e).__name__, e))
@ -31,7 +32,7 @@ class Stats:
async def listboops(self, ctx): async def listboops(self, ctx):
"""Lists all the users you have booped and the amount of times""" """Lists all the users you have booped and the amount of times"""
members = ctx.message.server.members members = ctx.message.server.members
cursor = config.connection.cursor() cursor = config.getCursor()
cursor.execute('use {}'.format(config.db_boops)) cursor.execute('use {}'.format(config.db_boops))
sql = "select * from `{}`".format(ctx.message.author.id) sql = "select * from `{}`".format(ctx.message.author.id)
cursor.execute(sql) cursor.execute(sql)
@ -45,6 +46,8 @@ class Stats:
amount = r['amount'] amount = r['amount']
if member in members: if member in members:
output += "\n{0.name}: {1} times".format(member,amount) output += "\n{0.name}: {1} times".format(member,amount)
config.connection.commit()
config.connection.close()
await self.bot.say("```{}```".format(output)) await self.bot.say("```{}```".format(output))
@commands.command(pass_context=True, no_pm=True) @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""" """Prints a 'leaderboard' of everyone in the server's battling record"""
try: try:
members = ctx.message.server.members members = ctx.message.server.members
cursor = config.connection.cursor() cursor = config.getCursor()
cursor.execute('use {0}'.format(config.db_default)) cursor.execute('use {0}'.format(config.db_default))
sql = "select * from battle_records" sql = "select * from battle_records"
cursor.execute(sql) cursor.execute(sql)
@ -88,6 +91,7 @@ class Stats:
for index in range(0, len(fmt)): for index in range(0, len(fmt)):
fmt[index] = "{0}) {1}".format(index + 1, fmt[index]) fmt[index] = "{0}) {1}".format(index + 1, fmt[index])
config.connection.commit() config.connection.commit()
config.connection.close()
if len(fmt) == 0: if len(fmt) == 0:
await self.bot.say("```No battling records found from any members in this server```") await self.bot.say("```No battling records found from any members in this server```")
return return

View file

@ -10,9 +10,6 @@ with open("/home/phxntx5/public_html/Bonfire/config.yml", "r") as f:
db_default = global_config.get("db_default") db_default = global_config.get("db_default")
db_boops = global_config.get("db_boops") db_boops = global_config.get("db_boops")
nsfwChannels = global_config.get("nsfw_channel") 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") botDescription = global_config.get("description")
commandPrefix = global_config.get("command_prefix") commandPrefix = global_config.get("command_prefix")
@ -28,8 +25,8 @@ openCommands = global_config.get("openCommands", {})
ownerCommands = global_config.get("ownerCommands", {}) ownerCommands = global_config.get("ownerCommands", {})
voiceCommands = global_config.get("voiceCommands", {}) voiceCommands = global_config.get("voiceCommands", {})
def resetConnection(): def getCursor():
global connection
connection = pymysql.connect(host=global_config.get("db_host"), user=global_config.get("db_user"), connection = pymysql.connect(host=global_config.get("db_host"), user=global_config.get("db_user"),
password=global_config.get("db_user_pass"), charset='utf8mb4', password=global_config.get("db_user_pass"), charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor) cursorclass=pymysql.cursors.DictCursor)
return connection.cursor()