我正在尝试捕获一些用户错误使用命令可能产生的错误。为了测试这一点,我创建了一个命令,该命令会按需引发错误,并且应该捕获这些错误。问题是,我尝试捕获commands.BotMissingPermisions
,commands.MissingPermissions
和commands.CommandOnCooldown
的尝试似乎被忽略并作为commands.CommandInvokeError
处理。捕获其他错误,例如TooManyArguments
或NotOwner
也很好。
那是我的代码:
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)
这是我第一次在这里提问,因此,如果您需要更多信息,请告诉我
您试图捕获的命令错误是在执行命令回调(从检查,转换器等开始)之前引发的。回调中引发的异常将包装在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
中,然后将其传递给处理程序。