角色在反应问题上添加两次

问题描述 投票:0回答:1

我目前正在创建一个on_raw_reaction_add事件,如果用户在消息中添加了反应,它将为他们提供一个角色。我有一个小问题,当用户添加一个表情符号if payload.emoji.id !=it添加两个角色而不是特定反应的角色。

无论具体的表情符号ID如何,都会发生这种情况。

帮助赞赏。

这是我的代码:

@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):  # Will be dispatched every time a user adds a reaction to a message the bot can se
    botroom = self.bot.get_channel(572943295039406101)
    if not payload.guild_id:
        # In this case, the reaction was added in a DM channel with the bot
        return 

    if payload.message_id != 573104280299372556: # ID of the message you want reactions added to.
        return

    guild = self.bot.get_guild(payload.guild_id)  # You need the guild to get the member who reacted
    member = guild.get_member(payload.user_id)  # Now you have the key part, the member who should receive the role

    if payload.emoji.id != 572943613554720789:
        lol = discord.utils.get(guild.roles, name="LoL")
        lol = discord.Object(559792606364565505)  # Pass the role's ID here
        await member.add_roles(lol, reason='Reaction role')  # Finally add the role to the member

    if payload.emoji.id != 572950778386317323:
        wow = discord.utils.get(guild.roles, name="WoW")
        wow = discord.Object(558650247413235712)  # Pass the role's ID here
        await member.add_roles(wow, reason='Reaction role')  # Finally add the role to the member  
python-3.x discord.py discord.py-rewrite
1个回答
0
投票

这是一种更通用的方法。我们维护反应名称到角色名称的映射,然后每当有人做出反应时,我们在字典中查找他们的反应并获得相关角色:

emoji_role_map = {
    "1\N{COMBINING ENCLOSING KEYCAP}": "LoL",  # This is the default :one:
    "my_custom_emoji": "WoW"
}

@commands.Cog.listener()
async def on_raw_reaction_add(self, payload): 
    botroom = self.bot.get_channel(572943295039406101)
    if not payload.guild_id:
        # In this case, the reaction was added in a DM channel with the bot
        return 
    if payload.message_id != 573104280299372556: # ID of the message you want reactions added to.
        return
    guild = self.bot.get_guild(payload.guild_id)  # You need the guild to get the member who reacted
    member = guild.get_member(payload.user_id)  # Now you have the key part, the member who should receive the role
    role_name = emoji_role_map.get(payload.emoji.name)
    if role_name:  # None if not found
        role = discord.utils.get(guild.roles, name=role)
        await member.add_roles(role, reason='Reaction role') 

这有几个优点:您可以从任何地方加载该映射,因此您可以将角色授予逻辑与实际的表情符号和角色分离,您现在可以在多个服务器上设置它,只要名称是同样,您现在可以使用默认的表情符号来获得角色,而您无法使用您的系统。

© www.soinside.com 2019 - 2024. All rights reserved.