首页 > 解决方案 > 如何处理“MissingRequiredArgument”错误

问题描述

我在 discord.py 的 rewrite 分支中制作了一个机器人,可以说这是我的代码:

@bot.command()
async def ok(ctx,con):
    try:
        await ctx.send(con)
    except commands.MissingRequiredArgument:
        await ctx.send('You did not give me anything to repeat!')

我想要做的是处理 MissingRequiredArgument 错误,但我编写的代码仍然给出错误而不是返回You did not give me anything to repeat!,如果有人能告诉我如何处理它,我将不胜感激。确切的错误:

Ignoring exception in command translate:
Traceback (most recent call last):
  File "C:\Users\jatinder\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\jatinder\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 790, in invoke
    await self.prepare(ctx)
  File "C:\Users\jatinder\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 751, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\jatinder\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 679, in _parse_arguments
    kwargs[name] = await self.transform(ctx, param)
  File "C:\Users\jatinder\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 516, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: con is a required argument that is missing.

标签: pythonerror-handlingdiscorddiscord.pydiscord.py-rewrite

解决方案


这个错误不能通过 try/except 处理,我不知道为什么,但我有两种方法可以处理这个问题。

第一种方法:


@bot.command()
async def ok(ctx, con=None):
    if con == None: return await ctx.send('You did not give me anything to repeat!')
    # Do whatever here, if you come here it means the user gave something to repeat

'con' 默认设置为 None (con=None)。如果用户不提供任何东西,它将保持无。但是,如果用户提供了一些东西,那么它将是他所提供的。if 语句将检测 'con' 是否等于 None,如果是,则表示用户没有返回任何内容。

第二种方法


@bot.command()
async def ok(ctx, con):
    # Do whatever here, if you come here it means the user gave something to repeat

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        print('You did not give me anything to repeat!')

@bot.event在这里使用的意思是所有没有参数的命令都会处理错误(换句话说,得到MissingRequiredArgument错误的命令)如果你只想为“ok”命令工作,使用@ok.error而不是@bot.event.


推荐阅读