python - 如何处理“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.
解决方案
这个错误不能通过 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
.
推荐阅读
- python-3.x - 在python中使用带有apply的自定义函数时出现IndexingError
- mongodb - 在没有 _id 分组的情况下获取单个数组的 $concatArray 结果?
- python - 如何提高 CPU 利用率以在 for 循环中处理数据帧?
- javascript - 如果父组件更改,防止子组件卸载和重新安装
- microsoft-graph-api - Microsoft Graph API - 计算所有拥有许可证的用户
- typescript - 如何在角度8中仅选择一个动态形式的复选框
- sql - SQLDeveloper 假脱机到用户配置文件
- python - 如何使用 Wagtail 编辑器和 Wagtail-Streamfield 发送 HTML 电子邮件?
- react-native - 如何在 React Native 中覆盖键盘?
- nginx - Openresty log_by_lua_block 非阻塞 http-request