在我看来,问题在于“*”...
如果您使用您的代码并添加一个打印行来查看实际传递给您的方法的内容,您将看到以下结果:
代码
@client.command()
async def role(ctx, * role: discord.Role):
print(role)
user = ctx.message.author
await user.add_roles(role)
输出
(<Role id=671750373761089546 name='Red'>,)
Ignoring exception in command role:
Traceback (most recent call last):
File "/home/dual/PyProjects/Discord/Chandler/env/lib/python3.7/site-packages/discord/ext/commands/core.py", line 79, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 57, in role
await user.add_roles(role)
File "/home/dual/PyProjects/Discord/Chandler/env/lib/python3.7/site-packages/discord/member.py", line 616, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'tuple' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/dual/PyProjects/Discord/Chandler/env/lib/python3.7/site-packages/discord/ext/commands/bot.py", line 863, in invoke
await ctx.command.invoke(ctx)
File "/home/dual/PyProjects/Discord/Chandler/env/lib/python3.7/site-packages/discord/ext/commands/core.py", line 728, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/dual/PyProjects/Discord/Chandler/env/lib/python3.7/site-packages/discord/ext/commands/core.py", line 88, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'id'
如果您删除“*”并保持其他所有内容相同,这就是它的样子:
代码
@client.command()
async def role(ctx, role: discord.Role):
print(role)
user = ctx.message.author
await user.add_roles(role)
输出
Red
如果没有“*”,角色将添加到调用该命令的用户。这仅适用于角色拼写正确且区分大小写的情况,因此我建议实施某种输入验证。
编辑:
This article 解释了 python 中的 *args 和 **kwargs。检查它以更好地了解如何将参数传递给函数可能很有用:D