Обработчик ошибок CommandOnCooldown не улавливает ошибку! Протестировали все

#python #error-handling #discord #discord.py #discord.py-rewrite

#python #обработка ошибок #Discord #discord.py

Вопрос:

Я просмотрел другие похожие вопросы, исправления не работают, это мой код.

  @bot.event
async def on_command_error(ctx, error):

    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send("Command On Cooldown. Sorry fo rugly text. I will fix it - Kwuartz")
        m, s = divmod(error.retry_after, 60)
        h, m = divmod(m, 60)
        d, h = divmod(h, 60)

        if int(h) == 0 and int(m) == 0:
            embed = discord.Embed(colour=0x1ABC9C)
            embed.title = "**Command Cooldown:**"
            embed.description = f"**Why this happened:**nThis command is on a cooldown of **{int(s)} seconds** on a per user basis."
            await ctx.send(embed = embed)

        elif int(d) == 0 and int(h) == 0 and int(m) != 0:
            embed = discord.Embed(colour=0x1ABC9C)
            embed.title = "**Command Cooldown:**"
            embed.description = f"**Why this happened:**nThis command is on a cooldown of **{int(m)} minutes** and **{int(s)} seconds** on a per user basis."
            await ctx.send(embed = embed)

        elif int(d) == 0 and int(h) != 0:
            embed = discord.Embed(colour=0x1ABC9C)
            embed.title = "**Command Cooldown:**"
            embed.description = f"**Why this happened:**nThis command is on a cooldown of **{int(h)} hours**, **{int(m)} minutes** and **{int(s)} seconds** on a per user basis."
            await ctx.send(embed = embed)

        else:
            embed = discord.Embed(colour=0x1ABC9C)
            embed.title = "**Command Cooldown:**"
            embed.description = f"**Why this happened:**nThis command is on a cooldown of **{int(d)} days**, **{int(h)} hours**, **{int(m)} minutes** and **{int(s)} seconds** on a per user basis."
            await ctx.send(embed = embed)

    elif isinstance(error, commands.CommandNotFound):
        embed = discord.Embed(colour=0x1ABC9C)
        embed.title = "**Command Error:**"
        embed.description = f":x: **Why this happened:**nThe command you specified does not exist."
        await ctx.send(embed = embed)

    else:
        raise error
  

PS: Я новичок, поэтому у меня могут быть глупые ошибки. Извините! При необходимости я приложу больше кода

Вывод на консоль:

Игнорирование исключения в on_message Traceback (последний последний вызов): File «C:UsersOnlyMeAppDataRoamingPythonPython38site-packagesdiscordclient.py «, строка 333, в файле _run_event ожидает coro(*args, **kwargs) «C:UsersOnlyMePythonProjectsAtomImpulseBotmain_setup.py «, строка 158, в файле on_message await bot.process_commands(сообщение) «C:UsersOnlyMeAppDataRoamingPythonPython38site-packagesdiscordextcommandsbot.py «, строка 940, в process_commands ожидаютself.invoke(ctx) Файл «C:UsersOnlyMeAppDataRoamingPythonPython38site-packagesdiscordextcommandsbot.py «, строка 907, в файле invoke await ctx.command.dispatch_error(ctx, exc) «C:UsersOnlyMeAppDataRoamingPythonPython38site-packagesdiscordextcommandscore.py «, строка 422, в dispatch_error ожидание ввода (cog, ctx, ошибка) файла «C:UsersOnlyMeAppDataRoamingPythonPython38site-packagesdiscordextcommandscore.py «, строка 71, в завернутом ret = await coro(*аргументы, **kwargs) Файл «C:UsersOnlyMePythonProjectsAtomImpulseBotcogsmoderation_commands.py «, строка 225, в файле с ошибкой clear_error «C:UsersOnlyMeAppDataRoamingPythonPython38site-packagesdiscordextcommandsbot .py», строка 903, в invoke await ctx.command.invoke(ctx) Файл «C:UsersOnlyMeAppDataRoamingPythonPython38site-packagesdiscordextcommandscore.py «, строка 851, в вызове await self.prepare(ctx) Файл «C:UsersOnlyMeAppDataRoamingPythonPython38site-packagesdiscordextcommandscore.py «, строка 785, в prepare self._prepare_cooldowns(ctx) Файл «C:UsersOnlyMeAppDataRoamingPythonPython38site-packagesdiscordextcommandscore.py «, строка 773, в _prepare_cooldowns вызвать CommandOnCooldown(bucket, retry_after) discord.ext.commands.errors.CommandOnCooldown: вы находитесь на перезарядке. Повторите попытку через 9.53 с

Ответ №1:

Если вы хотите получить время в формате hours, minutes, seconds, , вы можете использовать оператор modulo в своих интересах:

 d = math.floor(error.retry_after / 60 / 60 / 24) 
h = math.floor(error.retry_after / 60 / 60) 
m = math.floor(error.retry_after / 60) 
s = error.retry_after % 60
  

Если on_command_error не улавливает все, это потому, что оно применяется только к ошибкам команд.

PS. Пожалуйста, укажите вашу проблему, чтобы ее было легче исправить.

Вот каким был мой код, когда он работал:

 if isinstance(error, commands.CommandOnCooldown):
    retryAfter = [math.floor(error.retry_after / 360), math.floor(error.retry_after / 60), error.retry_after % 60]
    await ctx.send('You cannot use command `%s%s` for %s hours, %s minutes, and %.2f seconds.' % (
    str(bot.command_prefix), str(ctx.command), retryAfter[0], retryAfter[1], retryAfter[2]))
    print('Command "%s" is on a %.3f second cooldown' % (ctx.command, error.retry_after))
  

Комментарии:

1. Раньше это работало как ошибка, и я видел, как многие люди классифицировали это как ошибку. Я получаю команду CommandOnCooldown в консоли, но мой обработчик ошибок не запускается. Там написано discord.ext.commands.errors. CommandOnCooldown. Поэтому он классифицируется как ошибка.

2. commands.CommandNotFound Работает ли? Проблема относится только к CommandOnCooldown ?

3. Нет, ошибка не улавливается. Я попытался создать время перезарядки, специфичное для каждого comamnd, у которого есть время перезарядки, и это работает, но я хочу сделать глобальное.