From aabd46bb33879a015c0f7c5330bf1fbfa48ae836 Mon Sep 17 00:00:00 2001 From: bmintz Date: Mon, 30 Jul 2018 00:15:38 -0500 Subject: [PATCH] bot: add error handler --- bot.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 70815de..7a3969d 100755 --- a/bot.py +++ b/bot.py @@ -1,9 +1,15 @@ #!/usr/bin/env python3 # encoding: utf-8 +import logging + import discord from discord.ext import commands +logging.basicConfig(level=logging.WARNING) +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + class Bot(commands.AutoShardedBot): def __init__(self, **kwargs): super().__init__(command_prefix=commands.when_mentioned, **kwargs) @@ -18,8 +24,29 @@ class Bot(commands.AutoShardedBot): super().run(self.config['tokens'].pop('discord')) async def on_ready(self): - print('Logged on as {0} (ID: {0.id})'.format(self.user)) + logger.info('Logged on as {0} (ID: {0.id})'.format(self.user)) + # https://github.com/Rapptz/RoboDanny/blob/ca75fae7de132e55270e53d89bc19dd2958c2ae0/bot.py#L77-L85 + async def on_command_error(self, context, error): + if isinstance(error, commands.NoPrivateMessage): + await context.author.send('This command cannot be used in private messages.') + elif isinstance(error, commands.DisabledCommand): + message = 'Sorry. This command is disabled and cannot be used.' + try: + await context.author.send(message) + except discord.Forbidden: + await context.send(message) + elif isinstance(error, commands.UserInputError): + await context.send(error) + elif isinstance(error, commands.NotOwner): + logger.error('%s tried to run %s but is not the owner', context.author, context.command.name) + elif isinstance(error, commands.CommandInvokeError): + await context.send('An internal error occured while trying to run that command.') + + logger.error('In %s:', context.command.qualified_name) + logger.error(''.join(traceback.format_tb(error.original.__traceback__))) + # pylint: disable=logging-format-interpolation + logger.error('{0.__class__.__name__}: {0}'.format(error.original)) bot = Bot()