2
votes

I want a user to be assigned a role when they choose a certain reaction in my welcome-and-roles discord channel. I've looked everywhere and can't find code in python that works with the most up-to-date version of discord.py. Here is what I have so far:

import discord

client = discord.Client()

TOKEN = os.getenv('METABOT_DISCORD_TOKEN')


@client.event
async def on_reaction_add(reaction, user):
    role_channel_id = '700895165665247325'
    if reaction.message.channel.id != role_channel_id:
        return
    if str(reaction.emoji) == "<:WarThunder:745425772944162907>":
        await client.add_roles(user, name='War Thunder')


print("Server Running")

client.run(TOKEN)
1
What's wrong with the program? Do you get errors when adding a reaction or does the code just not do anything? - Allister
I don’t get any error codes, but yes the code simply doesn’t do anything. - MrMetacom

1 Answers

1
votes

Use on_raw_reaction_add instead of on_reaction_add, As on_reaction_add will only work if the message is in bot's cache while on_raw_reaction_add will work regardless of the state of the internal message cache.

All the IDS, Role IDs, Channel IDs, Message IDs..., are INTEGER not STRING, that is a reason why your code not works, as its comparing INT with STR.

Also you need to get the role, you can't just pass in the name of the role

Below is the working code

@client.event
async def on_raw_reaction_add(payload):
    if payload.channel_id == 123131 and payload.message_id == 12121212: #channel and message IDs should be integer:
        if str(payload.emoji) == "<:WarThunder:745425772944162907>":
            role = discord.utils.get(payload.member.guild.roles, name='War Thunder')
            await payload.member.add_roles(role)

Edit: For on_raw_reaction_remove

@client.event
async def on_raw_reaction_remove(payload):
    if payload.channel_id == 123131 and payload.message_id == 12121212: #channel and message IDs should be integer:
        if str(payload.emoji) == "<:WarThunder:745425772944162907>":
            #we can't use payload.member as its not a thing for on_raw_reaction_remove
            guild = bot.get_guild(payload.guild_id)
            member = guild.get_member(payload.user_id)
            role = discord.utils.get(guild.roles, name='War Thunder')
            await member.add_roles(role)