1
0
Fork 0
mirror of synced 2024-05-19 20:12:30 +12:00

Added universal exception handling, removed most exception handling from the commands themselves

This commit is contained in:
Phxntxm 2016-07-09 07:57:25 -05:00
parent 15bfd2775d
commit c00b7d446d
7 changed files with 153 additions and 210 deletions

3
bot.py
View file

@ -44,6 +44,9 @@ 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(e).__name__, e))

View file

@ -16,13 +16,9 @@ class Core:
@commands.command()
async def joke(self):
"""Prints a random riddle"""
try:
fortuneCommand = "/usr/bin/fortune riddles"
fortune = subprocess.check_output(fortuneCommand.split()).decode("utf-8")
await self.bot.say(fortune)
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))
@commands.command()
async def urban(self, *msg: str):
@ -38,14 +34,10 @@ class Core:
await self.bot.say(data['list'][0]['definition'])
except discord.HTTPException:
await self.bot.say('```Error: Definition is too long for me to send```')
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))
@commands.command(pass_context=True)
async def derpi(self, ctx, *search: str):
"""Provides a random image from the first page of derpibooru.org for the following term"""
try:
if len(search) > 0:
url = 'https://derpibooru.org/search.json?q='
query = '+'.join(search)
@ -73,20 +65,13 @@ class Core:
data = urllib.parse.urlencode({'link': imageLink}).encode('ascii')
response = urllib.request.urlopen(url, data).read().decode('utf-8')
await self.bot.say(response)
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))
@commands.command(pass_context=True)
async def roll(self, ctx):
"""Rolls a six sided die"""
try:
num = random.randint(1, 6)
fmt = '{0.message.author.name} has rolled a die and got the number {1}!'
await self.bot.say(fmt.format(ctx, num))
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))
def setup(bot):

View file

@ -62,7 +62,6 @@ class Interaction:
@commands.command(pass_context=True, no_pm=True)
async def battle(self, ctx, player2: discord.Member):
"""Challenges the mentioned user to a battle"""
try:
global battleP1
global battleP2
global battling
@ -87,15 +86,11 @@ class Interaction:
t = Timer(180, battlingOff)
t.start()
battling = True
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))
@commands.command(no_pm=True)
@checks.battled(battleP2)
async def accept(self):
"""Accepts the battle challenge"""
try:
if not battling:
return
num = random.randint(1, 100)
@ -107,28 +102,20 @@ class Interaction:
await self.bot.say(fmt.format(battleP2.mention, battleP1.mention))
updateBattleRecords(battleP2, battleP1)
battlingOff()
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))
@commands.command(no_pm=True)
@checks.battled(battleP2)
async def decline(self):
"""Declines the battle challenge"""
try:
if not battling:
return
await self.bot.say("{0} has chickened out! {1} wins by default!".format(battleP2.mention, battleP1.mention))
updateBattleRecords(battleP1, battleP2)
battlingOff()
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))
@commands.command(pass_context=True, no_pm=True)
async def boop(self, ctx, boopee: discord.Member):
"""Boops the mentioned person"""
try:
booper = ctx.message.author
if len(ctx.message.mentions) == 0:
await self.bot.say("You must mention someone in the room " + ctx.message.author.mention + "!")
@ -175,9 +162,6 @@ 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()
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))
def setup(bot):

View file

@ -11,24 +11,16 @@ class Mod:
@checks.isAdmin()
async def leave(self, ctx):
"""Forces the bot to leave the server"""
try:
await self.bot.say('Why must I leave? Hopefully I can come back :c')
await self.bot.leave_server(ctx.message.server)
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))
@commands.command(pass_context=True)
@checks.isMod()
async def say(self, ctx, *msg: str):
"""Tells the bot to repeat what you say"""
try:
msg = ' '.join(msg)
await self.bot.say(msg)
await self.bot.delete_message(ctx.message)
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))
def setup(bot):

View file

@ -19,7 +19,6 @@ class Owner:
@checks.isOwner()
async def restart(self, ctx):
"""Forces the bot to restart"""
try:
cursor = config.connection.cursor()
cursor.execute('use {0}'.format(config.db_default))
sql = "update restart_server set channel_id={0} where id=1".format(ctx.message.channel.id)
@ -28,15 +27,11 @@ class Owner:
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)
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))
@commands.command(pass_context=True)
@checks.isOwner()
async def py(self, ctx):
"""Executes code"""
try:
match_single = getter.findall(ctx.message.content)
match_multi = multi.findall(ctx.message.content)
if not match_single and not match_multi:
@ -50,61 +45,42 @@ class Owner:
config.loop.create_task(self.bot.say("```{0}```".format(v)))
exec(match_multi[0])
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))
@commands.command(pass_context=True)
@checks.isOwner()
async def shutdown(self, ctx):
"""Shuts the bot down"""
try:
fmt = 'Shutting down, I will miss you {0.author.name}'
await self.bot.say(fmt.format(ctx.message))
await self.bot.logout()
await self.bot.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))
@commands.command()
@checks.isOwner()
async def avatar(self, content: str):
"""Changes the avatar for the bot to the filename following the command"""
try:
file = '/home/phxntx5/public_html/bot/images/' + content
with open(file, 'rb') as fp:
await self.bot.edit_profile(avatar=fp.read())
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))
@commands.command()
@checks.isOwner()
async def name(self, newNick: str):
"""Changes the bot's name"""
try:
await self.bot.edit_profile(username=newNick)
await self.bot.say('Changed username to ' + newNick)
# Restart the bot after this, as profile changes are not immediate
python = sys.executable
os.execl(python, python, *sys.argv)
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))
@commands.command()
@checks.isOwner()
async def status(self, *stat: str):
"""Changes the bot's 'playing' status"""
try:
newStatus = ' '.join(stat)
game = discord.Game(name=newStatus, type=0)
await self.bot.change_status(game)
await self.bot.say("Just changed my status to '{0}'!".format(newStatus))
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))
def setup(bot):

View file

@ -198,11 +198,8 @@ class Music:
@commands.command(pass_context=True, no_pm=True)
async def queuelength(self, ctx):
"""Prints the length of the queue"""
try:
await self.bot.say("There are a total of {} songs in the queue"
.format(str(self.get_voice_state(ctx.message.server).songs.qsize())))
except:
await self.bot.say(traceback.format_exc())
@commands.command(pass_context=True, no_pm=True)
async def skip(self, ctx):

View file

@ -27,3 +27,9 @@ adminCommands = global_config.get("adminCommands", {})
openCommands = global_config.get("openCommands", {})
ownerCommands = global_config.get("ownerCommands", {})
voiceCommands = global_config.get("voiceCommands", {})
def resetConnection()
global connection
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)