我对编程相对较新,正在尝试为我所在的服务器编写一个机器人。我理想情况下希望根据用户发送包含“gm”或“早上好”的消息来将用户分配给特定角色'。现在,机器人可以读取消息并发送回复。但我有点迷失在尝试弄清楚如何在读取“gm”消息后实际将角色添加到用户。
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
async def addRole(user : discord.Member, role : discord.Role = BagChaser):
if role in user.roles:
return
else: await user.add_roles(role)
@client.event
async def on_message(message):
if message.author == client.user:
return
msg = message.content.lower()
words_list = ['gm', 'good morning']
if any(word in msg for word in words_list):
# await addRole(message.author, BagChaser)
await message.channel.send(f'Lets get this bag, {message.author}')
await message.author.add_roles(BagChaser)`
注释行和最后一行是如何将“BagChaser”角色添加到消息作者的一些想法。我尝试将 addRole 函数中的角色参数设置为 BagChaser,因为它永远不会改变,但这似乎不正确。该角色已在我的服务器中创建,但我不确定如何让机器人了解代码中的该角色。任何帮助将不胜感激!
我尝试明确指出我的角色,但无法得到认可。
你需要一个角色对象,为此,你需要一个公会对象,你可以通过
message.author.guild
获得它。
由此可以获取Role对象:
role = await message.author.guild.get_role(ROLE_ID)
注意,角色ID需要您自己获取。最简单的方法是进入 Discord 并启用开发者设置,然后右键单击某人个人资料中的角色并单击“复制 ID”。一旦你有了这个角色对象,你就可以使用
message.author.add_roles(role)
应用它。
完整代码:
role_id = ...
author = message.author;
role = await author.guild.get_role(role_id)
await author.add_roles(role)
确保您的机器人具有管理角色权限