向命令传递错误类型参数时的句柄错误

2024-06-16 11:00:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想处理这样一种情况:有人在discord上执行“c”命令,并传递一个不存在的角色作为参数。我得到以下错误日志:

@bot.command()
# Send DM to people that have the role
async def c(ctx, role: discord.Role, *, dm):
    try:
        for members in role.members:
            await members.create_dm.send(f'Massage from {ctx.author.display.name}: {dm}')
            print('Message sent to a member')
    except RoleNotFound:
        print('Role not found')
Ignoring exception in command c:
Traceback (most recent call last):
  File "C:\Users\Rafael\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Rafael\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\Rafael\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\Rafael\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\Rafael\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "C:\Users\Rafael\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "C:\Users\Rafael\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
    ret = await instance.convert(ctx, argument)
  File "C:\Users\Rafael\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\converter.py", line 635, in convert
    raise RoleNotFound(argument)

所以,我想用try/except来处理它,但是在它进入try块之前,错误就发生了

我不想阻止这个错误,但要处理它


Tags: inlibpackageslocalsiteawaitusersappdata
1条回答
网友
1楼 · 发布于 2024-06-16 11:00:36

您必须自己为此添加一个错误处理程序,您可以用另一种方式执行此操作,并且必须通过commands.YourError。要使用它,您不需要导入其他内容,而是构建自己的“函数”并重新构造代码

查看以下代码:

@bot.command()
# Send DM to people that have the role
async def c(ctx, role: discord.Role, *, dm):
    for members in role.members:
        await members.create_dm.send(f'Massage from {ctx.author.display.name}: {dm}')
        print('Message sent to a member')

@c.error
async def dm_error(ctx, error):
    if isinstance(error, commands.RoleNotFound):
        await ctx.send("Role not found")

您还可以生成更多错误,但不能首先使用except,因为您可以将其用于AttributeErrorSyntaxError或类似的内容

相关问题 更多 >