【问题标题】:Discord.py: My programm seems to be unable to differentiate between errors(MissingPerms, BotMissingPerms) and therefore uses the wrong handlerDiscord.py:我的程序似乎无法区分错误(MissingPerms、BotMissingPerms),因此使用了错误的处理程序
【发布时间】:2020-04-27 12:14:30
【问题描述】:

我正在尝试捕获一些可能由用户错误地使用命令产生的错误。 为了测试这一点,我创建了一个按需引发错误的命令和一个应该捕获它们的函数。 问题是,我试图捕捉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】:

    您尝试捕获的命令错误应在执行命令的回调之前引发(来自检查、转换器等)。回调中引发的异常将被包裹在 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 异常,那么命令机制将接受该异常,将其包装在CommandInvokeError 中,然后将其传递给处理程序。

    【讨论】:

    • 非常感谢!所以不可能像这样区分BotMissingPermsMissingPerms?感谢您让我的问题更具可读性
    • 如果这些错误是由检查引发的,那么您的代码将起作用。 (您会注意到这两个错误都继承自 CheckFailure)。否则,您可以在处理程序的开头使用 if isinstance(error, CommandInvokeError): error = error.original 之类的内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 2011-01-05
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多