【问题标题】:User assigned roles using discord.py使用 discord.py 为用户分配的角色
【发布时间】:2020-01-26 02:29:41
【问题描述】:

我正在尝试使用 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'

【问题讨论】:

  • 您发布的代码 sn-p 似乎与错误无关。你能发布你的整个代码和完整的回溯吗?
  • 这是一个错字,您在参数列表中的星号后面缺少一个逗号:async def role(ctx, *, role: discord.Role):

标签: discord.py


【解决方案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

【讨论】:

    猜你喜欢
    • 2021-04-08
    • 2022-01-19
    • 2010-10-09
    • 2019-08-11
    • 1970-01-01
    • 2021-03-17
    • 2021-04-17
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多