我正在尝试使用discord.py为不和谐的服务器对机器人进行编程。我想创建一个命令,允许用户为自己分配名称颜色(即红色或蓝色),我试图通过创建角色来实现此目的。但是我在使用最新形式的discord.py分配角色时遇到了一些麻烦。
@client.command()
async def role(ctx, * role: discord.Role):
user = ctx.message.author
await user.add_roles(role)
有人知道如何解决我遇到的错误。错误如下:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'id'
答案 0 :(得分:1)
在我看来,问题在于'*'...
如果您使用代码并添加打印行以查看实际传递给您的方法的内容,您将看到以下结果:
代码
@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