如何使用 on_command_error() 检测 AttributeError

How Use on_command_error() to detect AttributeError

我正在尝试检测何时有人在服务器外部使用命令。我只想拥有一个 on_command_error() 函数,因此我试图检测属性错误:'NoneType' 没有属性 'id'。但是,我现在不知道该放什么,我尝试了 AttributeError,但它检测不到它。

@bot.event
async def on_command_error(ctx, error):
  if isinstance(error, AttributeError):
    await ctx.send('You Cannot Use This Command Outside Of The Server')
  else:
    print(error)

有谁知道 AttributeError 现在使用的参数是什么? 谢谢!

Discord.py 实际上有一个针对公会专用命令的内置检查。 commands.guild_only().

因此,在定义不一致命令 (@bot.command()) 的检查下方(或之前),添加装饰器 @commands.guild_only.

如果此命令 运行 在服务器之外,它将引发 NoPrivateMessage 异常。您可以使用错误处理程序来捕获此错误并相应地发送消息。

你真的不应该在错误处理程序中处理这样的错误,尽管如此你可以用下面的方法来处理:

@bot.event
async def on_command_error(ctx, error):
    # If an error happens inside the command,
    # discord.py wraps it around with `commands.CommandInvokeError` 
    # which has the `original` attribute which is the "original" error
    error = getattr(error, "original", error)
    if isinstance(error, AttributeError):
        ...
    elif isinstance(error, commands.MissingPermissions):