BluePigeon
BluePigeon

Reputation: 1812

discord.py-rewrite - Manipulating exceptions through cogs

So, on my main file bot.py, I have:

class Bot(commands.Bot):

    # BOT ATTRIBUTES

    class MyException(Exception):
        def __init__(self, argument):
            self.argument = argument

bot = Bot(...)

@bot.event
async def on_command_error(ctx, error):
    if isistance(error, bot.MyException):
        await ctx.send("{} went wrong!".format(error.argument))
    else:
        print(error)

Now I also have a cog file, where I sometimes want to throw the Bot().MyException exception:

class Cog(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def a_command(self, ctx):
        if a_condition:
            raise self.bot.MyException("arg")

When I run the code, if the a_condition has been validated, the program raises the MyException exception, but the BOT do not send the desired message in the on_command_error() function in bot.py. Instead, the exception gets printed in the console and I get this error message:

Command raised an exception: MyException: arg

Can anyone please tell me how to make the BOT say the desired message in on_command_error() in bot.py?

Upvotes: 0

Views: 830

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61063

Commands will only raise exceptions derived from CommandError. When your command raises a non-CommandError exception, it will be wrapped in a CommandInvokeError:

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandInvokeError):
        if isinstance(error.original, bot.MyException):
            await ctx.send("{} went wrong!".format(error.argument))
            return
    print(error)

Upvotes: 2

Related Questions