Home > Enterprise >  Discord.py Reaction Roles with custom emojis
Discord.py Reaction Roles with custom emojis

Time:10-15

I have been working on a discord bot for reaction roles. The idea is it registers the message, the role, and the emoji to a .JSON file and executes the role update on on_raw_reaction_remove or on_raw_reaction_add

Now, the problem is it DOES ADD the custom reactions to the specified message. However, it doesn't give the respected role on reaction_add. I couldn't find a way to fix this problem. My opinion is that the problem could be the way the bot registers custom emojis. Here is an example:

[
    {
        "role_id": 897227510574616656,
        "emoji": "\ud83d\ude04",
        "message_id": "898215881136570418"
    },
    {
        "role_id": 897227510574616656,
        "emoji": "<:custom:898198216611344424>",
        "message_id": "898215881136570418"
    }
]
@client.event
async def on_raw_reaction_add(payload):
    if payload.member.bot:
        pass
    else:
        with open('data.json') as react_file:
            data = json.load(react_file)
            for x in data:
                if x['emoji'] == payload.emoji.name:
                    role = discord.utils.get(client.get_guild(
                        payload.guild_id).roles, id=x['role_id'])

                    await payload.member.add_roles(role)

@client.command()
@commands.has_permissions(administrator=True, manage_roles=True)
async def add(ctx, msg_id, emoji, role: discord.Role):
    msg= await ctx.fetch_message(msg_id)
    await msg.add_reaction(emoji)

    with open('data.json') as json_file:
        data = json.load(json_file)

        new_react_role = {'role_id': role.id,
        'emoji': emoji,
        'message_id': msg_id}

        data.append(new_react_role)

    with open('data.json', 'w') as f:
        json.dump(data, f, indent=4)```

CodePudding user response:

You did not save the emoji.name in the json file, so in your check you would need to do something more like if x['emoji'] == str(payload.emoji): for it to work.

else:
    with open('data.json') as react_file:
        data = json.load(react_file)
        for x in data:
            if x['emoji'] == str(payload.emoji):
                role = discord.utils.get(client.get_guild(
                    payload.guild_id).roles, id=x['role_id'])

The emoji.name would only print out something like custom instead of the <:custom:898198216611344424> that is saved in your json file. str(emoji) prints out the whole thing, like in your file.

  • Related