【问题标题】:Discord.py bot, assign role when a user adds reactionDiscord.py 机器人,当用户添加反应时分配角色
【发布时间】:2021-05-01 06:26:20
【问题描述】:

我正在制作一个我从 youtube video 看到的机器人 这是我写的代码

@client.event
async def on_raw_reaction_add(payload):
  message_id = payload.message_id
  if message_id == [message id]:
    guild_id = payload.guild_id
    guild = discord.utils.find(lambda g :g.id == guild_id, client.guilds)
    
    role = discord.utils.get(guild.roles, name=payload.emoji.name)

    if role is not None:
      member_user = discord.utils.find(lambda m : m.id == payload.member.id, guild.members)
      if member_user is not None:
        await member_user.add_roles(role)
        print("Done")
      else:
        print("Member not Found")
        print(member_user)
    else:
      print("Role not Found")

但每次我做出反应时,控制台都会给我“未找到成员”和“无”作为用户 ID。 我在获取用户 ID 方面做错了吗?还是完全是其他地方的问题?

第一次在 python 中编码任何东西。在此先感谢:)

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    我们这样做是为了根据用户对欢迎消息的反应为他们分配角色。您可以尝试一下,看看它是否也适用于您的情况

        @bot.event
        async def on_raw_reaction_add(payload):
            guild = bot.get_guild(payload.guild_id)
            rolesDict = {role.name : role for role in guild.roles}
            member = guild.get_member(payload.user_id)
            user = bot.get_user(payload.user_id)
            if(payload.message_id == 769218692948295721):
                for roleName in ["Role1", "Role2", "Role3"]:
                    await member.remove_roles(rolesDict.get(roleName))
                    
                if(str(payload.emoji) == "\U0001F986"):
                    role = rolesDict.get("Role1")
                    await member.add_roles(role)
                elif(str(payload.emoji) == "?"):
                    role = rolesDict.get("Role2")
                    await member.add_roles(role)
                elif(str(payload.emoji) == "?"):
                    role = rolesDict.get("Role3")
                    await member.add_roles(role)
    

    【讨论】:

      【解决方案2】:

      如果您没有正确设置您的Intents,您将无法使用guild.members,并且看到您正在遵循一个过时的 YouTube 教程,我假设您没有。

      在创建commands.Bot 实例时,传入意图,并启用members 意图:

      intents = discord.Intents.default()
      intents.members = True
      client = commands.Bot(command_prefix=..., intents=intents)
      

      然后,在您的机器人仪表板上启用它们。有关如何执行此操作的信息在文档中:https://discordpy.readthedocs.io/en/latest/intents.html#privileged-intents

      【讨论】:

      • 谢谢你的评论真的很有帮助
      • 嗯,你的帖子中没有discord.Clientcommands.Bot,所以我只是假设它是Bot,但解决方案对他们来说都是一样的,所以它有效无论哪种方式。
      猜你喜欢
      • 2019-02-12
      • 2019-05-31
      • 2019-04-20
      • 2021-04-18
      • 2020-10-03
      • 2019-09-22
      • 1970-01-01
      • 2021-08-26
      • 2021-08-04
      相关资源
      最近更新 更多