如何处理“ MissingRequiredArgument”错误

时间:2020-08-31 04:56:01

标签: python error-handling discord discord.py discord.py-rewrite

我在discord.py的重写分支中创建了一个机器人,可以说这是我的代码:

@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.

3 个答案:

答案 0 :(得分:0)

执行此操作的最佳方法是使用错误事件。

@ok.error
async def on_command_error(error, ctx):
    await ctx.send(“You did not give me anything to repeat!”)

请注意,@ok.error是有意的,因为它只允许该命令运行,以免干扰您拥有的其他命令。

答案 1 :(得分:0)

我不确定其他答案是否可行

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, MissingRequiredArgument):
        await ctx.send("A parameter is missing") 

答案 2 :(得分:0)

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”默认设置为“无”(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