我在 Replit 论坛上问过这个问题 但开发人员不确定这个问题。
我和我的朋友想给我们的机器人添加一个功能,给用户角色“Baguette_Team”,并发布一条消息说如果他们发布一条消息“我喜欢法式面包!”,他们就会重新获得这个角色。
到目前为止这是我的代码:
import os, re, discord
from discord.ext import commands
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
client =
commands.Bot(command_prefix="!", intents= discord.Intents.all())
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
print("message was: " + message.content)
if message.author == client.user:
return
if message.content == 'I love baguettes!':
role = message.guild.get_role(1085983212855115887)
#discord.utils.get(message.guild.roles, id="1085983212855115887")
await message.author.add_roles(message.author, role, reason="You said the magic words!", atomic=True)
await message.channel.send('So do I! In fact, I have given you the Baguette Team role!')
client.run(DISCORD_TOKEN)
这是错误:
Traceback (most recent call last):
File "/home/runner/Blockcoin-Bot/venv/lib/python 3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "main.py", line 22, in on_message
await member.add_roles(role)
File "/home/runner/Blockcoin-BotIvenv/lib/python 3.10/site-packages/discord/member.py", line 1044, in add rotes
await req(guild_id, user_id, role.id, reason, eason)
AttributeError: 'NoneType' object has no attribute 'id'
如果需要,我可以提供服务器邀请链接。
错误很可能意味着找不到角色,或者您没有正确添加角色。假设你有正确的角色 ID,
你获得角色的方式是正确的。在docs中,您可以通过
Guild.get_role(role_id)
(非异步命令)从公会获得角色。
discord.utils.get
。
这可能是问题所在。您正在使用正确的命令,但参数不正确。在docs中,它显示您使用以下内容:
await add_roles(*roles, reason=None, atomic=True)
。但是,您将 message.author
作为第一个位置参数。相反,将其更改为角色。
例如:
await message.author.add_roles(role, reason="You said the magic words!", atomic=True)
只需从位置参数中删除
message.author
。