【问题标题】:How to explicitly add role to a user in discord bot如何在不和谐的机器人中明确地为用户添加角色
【发布时间】:2022-12-03 03:32:35
【问题描述】:

我对编程比较陌生,正在尝试为我所在的服务器编写机器人代码。理想情况下,我希望根据用户发送包含“gm”或“早上好”的消息,将用户分配给特定角色.现在,机器人可以阅读消息并发送回复。但是我有点迷茫,试图弄清楚如何在读取“gm”消息后实际将角色添加到用户。


`@client.event 异步定义 on_ready(): print(f'我们已经登录为{client.user}')

async def addRole(用户:discord.Member,角色:discord.Role = BagChaser):

if role in user.roles:
    return
else: await user.add_roles(role)

@client.event 异步定义 on_message(消息): 如果 message.author == client.user: 返回

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,因为它永远不会改变,但这似乎不正确。该角色已在我的服务器中创建,但我不确定如何让机器人知道代码中的该角色。任何帮助将不胜感激!

我试着明确地指出我的角色,但我无法得到它的认可。

【问题讨论】:

    标签: python discord bots


    【解决方案1】:

    您需要一个角色对象,为此,您需要一个公会对象,您可以通过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)
    

    确保您的机器人具有管理角色权限

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2021-01-15
      • 2020-11-08
      • 2021-01-22
      • 2018-08-11
      • 2019-02-02
      相关资源
      最近更新 更多