Discord.py:我的程序似乎无法区分错误(MissingPerms,BotMissingPerms),因此使用了错误的处理程序

问题描述 投票:0回答:1

我正在尝试捕获一些用户错误使用命令可能产生的错误。为了测试这一点,我创建了一个命令,该命令会按需引发错误,并且应该捕获这些错误。问题是,我尝试捕获commands.BotMissingPermisionscommands.MissingPermissionscommands.CommandOnCooldown的尝试似乎被忽略并作为commands.CommandInvokeError处理。捕获其他错误,例如TooManyArgumentsNotOwner也很好。

那是我的代码:

Import discord
from discord.ext Import commands

bot = commands.Bot(command_prefix='~')

@bot.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    await ctx.send('missing perms')
  elif isinstance(error, commands.BotMissingPermissions):
    await ctx.send('bot missing perms')
  elif isinstance(error, commands.CommandOnCooldown):
    await ctx.send('cooldown')
  elif isinstance(error, commands.CommandInvokeError):
    await ctx.send('invoke')
  else:
    await ctx.send('should not happen')

@bot.command
async def doError(ctx, type : int):
  if(type == 0):
    raise commands.MissingPermissions
  elif(type == 1):
    raise commands.BotMissingPermissions
  elif(type == 2):
    raise commands.CommandOnCooldown

bot.run(token)

这是我第一次在这里提问,因此,如果您需要更多信息,请告诉我

python-3.x error-handling command discord.py
1个回答
0
投票

您试图捕获的命令错误是在执行命令回调(从检查,转换器等开始)之前引发的。回调中引发的异常将包装在CommandInvokeError中,因此很清楚它们来自何处。

例如,您可能有一个错误处理程序,如

CommandInvokeError

和类似]的命令>

@bot.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.TooManyArguments):
    await ctx.send('too many arguments')
  elif isinstance(error, commands.CommandInvokeError):
    await ctx.send('invoke')
  else:
    await ctx.send('should not happen')

如果您实际上向命令传递了太多参数,则命令处理机制将产生@bot.command async def doError(ctx, type : int): raise commands.TooManyArguments 异常并将其传递给处理程序。另一方面,如果您的回调

产生TooManyArguments异常,则命令机制将采用该异常,将其包装在TooManyArguments中,然后将其传递给处理程序。
© www.soinside.com 2019 - 2024. All rights reserved.