diff --git a/cogs/exception-handler.py b/cogs/exception-handler.py new file mode 100644 index 0000000..30b779c --- /dev/null +++ b/cogs/exception-handler.py @@ -0,0 +1,40 @@ +from discord.ext import commands +from discord import Interaction +from discord.app_commands import AppCommandError +import logging + + +class ExceptionHandler(commands.Cog): + def __init__(self, bot: commands.Bot) -> None: + self.bot = bot + + @commands.Cog.listener() + async def on_command_error(self, ctx: commands.Context, error) -> None: + await ctx.send(f'Hmm...do you know what this error means:\n\n{error}') + + # attaching the handler when the cog is loaded + # and storing the old handler + # this is required for option 1 + def cog_load(self): + tree = self.bot.tree + self._old_tree_error = tree.on_error + tree.on_error = self.on_app_command_error + + # detaching the handler when the cog is unloaded + # this is optional for option 1 + def cog_unload(self): + tree = self.bot.tree + tree.on_error = self._old_tree_error + + # the global error handler for all app commands (slash & ctx menus) + async def on_app_command_error( + self, + interaction: Interaction, + error: AppCommandError + ): + logging.error(f'interaction: {interaction} / error: {error}') + await interaction.channel.send(f'Hmm...do you know what this error means:\n\n{error}') + + +async def setup(bot: commands.Bot) -> None: + await bot.add_cog(ExceptionHandler(bot)) \ No newline at end of file