【问题标题】:Handling discord.py specific errors in on_command_error() event在 on_command_error() 事件中处理 discord.py 特定错误
【发布时间】:2021-04-25 15:33:59
【问题描述】:

我的 discord bot 使用与服务器中的另一个 bot 相同的命令前缀,这会导致控制台在每次有人使用另一个 bot 时发送CommandNotFound 错误。我看到另一个问题,有人回答说您可以像这样处理错误:

@client.event
async def on_command_error(ctx, error):
    #print(error) -- returns error description
    if (error == CommandNotFound):
        return
    raise error

但是这个解决方案只是抛出一个 NameError 说 CommandNotFound 没有找到。在看到控制台输出显示 discord.ext.commands.errors.CommandNotFound 而不是 CommandNotFound 像其他 python 特定错误之后,我也尝试了这个。

@client.event
async def on_command_error(ctx, error):
    if (error == (discord.ext.commands.errors.CommandNotFound)):
         return
    raise error

我怎样才能做到这一点?

【问题讨论】:

  • 错误参数是对象还是类?您是否尝试过使用 isinstance 代替?由于 raise 有效,它应该已经是一个对象,因此,您必须首先比较类型,最好使用isinstance
  • 另外,根据文档,异常位于discord.ext.commands.CommandNotFound 下。您是否使用from discord.ext.commands import CommandNotFound 导入了它?

标签: python python-3.x discord discord.py discord.py-rewrite


【解决方案1】:

如果您收到NameError,则表示您引用的内容在您引用的范围内不存在(即未定义)。你需要导入CommandNotFound:

from discord.ext.commands import CommandNotFound

然后检查它:

@client.event
async def on_command_error(ctx, error):
    # Or, if you've already imported `commands`, you could write
    # commands.CommandNotFound here instead of explicitly importing it.
    if isinstance(error, CommandNotFound):  # Using `==` is incorrect
        return
    raise error

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2021-05-28
    • 2021-02-17
    • 2023-02-11
    • 2020-09-03
    • 1970-01-01
    • 2021-08-31
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多