如何解决如何处理“ MissingRequiredArgument”错误 第一种方法:第二种方法
我在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.
解决方法
执行此操作的最佳方法是使用错误事件。
@ok.error
async def on_command_error(error,ctx):
await ctx.send(“You did not give me anything to repeat!”)
请注意,@ok.error
是有意的,因为它只允许该命令运行,以免干扰您拥有的其他命令。
我不确定其他答案是否可行
@bot.event
async def on_command_error(ctx,error):
if isinstance(error,MissingRequiredArgument):
await ctx.send("A parameter is missing")
,
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,commands.MissingRequiredArgument):
print('You did not give me anything to repeat!')
我在这里使用@bot.event
表示将为所有没有参数的命令处理错误(换句话说,发生MissingRequiredArgument
错误的命令)
如果只想使用“ ok”命令,请使用@ok.error
而不是@bot.event
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。