【发布时间】:2020-11-23 02:19:30
【问题描述】:
我正在用 python 开发一个不和谐的机器人,它会祝人们生日快乐。我计划让用户通过命令将他们的生日给机器人,以便它可以将其存储在 txt 文件中。这是到目前为止的代码:
@bot.command(pass_context=True)
async def birthday(ctx,arg1,arg2,arg3,arg4):
try:
if (ctx.user == bot.user):
return
print(arg1 + ', ' + str(arg2) + ', ' + str(arg3) + ', ' + str(arg4))
except:
channel = bot.get_channel(channel_id)
await channel.send('Oops! I didn\'t get that. Please try again using this format:\n!birthday Garfield 19 6 1978')
基本上,如果格式正确,它应该打印得到的信息,如果不正确,则警告用户有问题。这是我收到的错误消息:
Ignoring exception in command birthday:
Traceback (most recent call last):
File "/home/valerie/.local/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "/home/valerie/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 790, in invoke
await self.prepare(ctx)
File "/home/valerie/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 751, in prepare
await self._parse_arguments(ctx)
File "/home/valerie/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 670, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/home/valerie/.local/lib/python3.6/site-packages/discord/ext/commands/core.py", line 516, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: arg4 is a required argument that is missing.
为什么当一切正常时它会抛出异常,甚至在实际出现问题时甚至不运行异常代码?有没有办法解决这个问题?
【问题讨论】:
-
尝试删除 try 和 except 块并让它失败...问题可能是由其他原因引起的...您可以通过这种方式查看导致它的原因...
-
您正在使用裸
except,所以发生的情况是 除了您期望的错误之外的其他一些错误,但是由于您正在捕获所有内容,因此您没有知道它是什么。仅捕获您要处理的特定异常,以便您收到其他异常的错误消息。然后你就会知道问题出在哪里了。 -
由于参数数量错误,Discord 本身无法调用您的函数。 in 你的函数没有任何相关性,因为它实际上从未被执行过。
-
+1 @jasonharper。请注意错误说 arg4 是必需的并且缺少。打印出来,您可能会看到它失败的原因。它可能是无。还为kindall +1,当您运行它时,您将捕获所有错误,并且您不会知道它们是什么。 arg4 问题可能是“类型”错误。使用 'Try: something except as e:' 然后 print(e)
-
@Yatin 我试过了,部分问题是我有 ctx.user 而不是 ctx.author。如果没有错误,现在它可以工作了
标签: python discord.py