discord.py-rewrite - управление исключениями с помощью cogs - PullRequest
0 голосов
/ 03 мая 2019

Итак, в моем основном файле bot.py, у меня есть:

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)

Теперь у меня также есть файл cog, куда я иногда хочу выдать исключение Bot().MyException:

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")

Когда я запускаю код, если a_condition был проверен, программа вызывает исключение MyException, но BOT не отправляет нужное сообщение в функции on_command_error() в bot.py. Вместо этого исключение печатается в консоли, и я получаю это сообщение об ошибке:

Command raised an exception: MyException: arg

Может кто-нибудь подсказать, пожалуйста, как заставить БОТ сказать желаемое сообщение в on_command_error() в bot.py?

Ответы [ 2 ]

1 голос
/ 03 мая 2019

Команды будут вызывать только исключения, полученные из CommandError. Когда ваша команда вызывает исключение, отличное от CommandError, оно будет заключено в 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)
0 голосов
/ 03 мая 2019

@ Patrick Haugh Большое спасибо за эту информацию, мне удалось решить эту проблему, унаследовав MyException класс от commands.CommandError вместо Exception.

В основном написав:

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

вместо:

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

и затем оставив:

@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)
...