我正在用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.
为什么当一切都可以正常运行时却抛出异常,而实际上却出现问题时甚至不运行异常代码?有办法解决这个问题吗?
答案 0 :(得分:0)
在代码中的某处,您正在调用Birthday函数,该函数需要5个参数。您没有提供所需数量的参数。这就是代码失败的原因。
如果您仔细阅读异常的最后一行,则会清楚地看到该错误。
discord.ext.commands.errors.MissingRequiredArgument: arg4 is a required argument that is missing.
您需要提供未提供的arg4
。
答案 1 :(得分:0)
这是一般性评论,但太大而无法放入评论中... (所以请忽略您认为合适的内容)
您可以将args分组,并使用", ".join()
使代码更简洁:
@bot.command(pass_context=True)
async def birthday(ctx, *args):
try:
if (ctx.user == bot.user):
return
print(", ".join(args))
except:
...