1
votes

i'm working on a bot for my discord channel and i'm learning python while doing it and i want to give role when a user adds reaction the code i came up with is this

@client.event
async def on_reaction_add(reaction, user):
    ChID = '487165969903517696'
    if reaction.message != ChID:
        return;
    if user.reaction.emoji == "????":
        CSGO = discord.utils.get(user.server.roles, name="CSGO_P")
        await client.add_roles(user, CSGO)

but it doesn't work what i basically want is there is a message that i sent in a channel with this Channel ID: 487165969903517696 and then my bot sends a embed message with "role=emoji" content. like CSGO=:runner: and then adds those reaction emojis to its message (embed) now i want to say if a user clicks one of those emojis the bot must give him/her a role like CSGO_P

By The Way i came up with an on_message event at first and it was working fine but i thought it's more User Friendly if they add reaction instead of typing for example !CSGO and i've just started python ( 2days ago )

3

3 Answers

8
votes

The on_reaction_add event is a little limited, because it is only triggered by messages that are stored in the Client.messages dequeue. This is a cache (default size 5000) that stops your bot from responding to activity on old messages. There's no guarantee if you restart your bot that it will still be "watching" that message.

One thing you could do is send a message when your bot logs in, and add the role to users who react to that message

@bot.event
async def on_ready():
    channel = bot.get_channel('487165969903517696')
    role = discord.utils.get(user.server.roles, name="CSGO_P")
    message = await bot.send_message(channel, "React to me!")
    while True:
        reaction = await bot.wait_for_reaction(emoji="🏃", message=message)
        await bot.add_roles(reaction.message.author, role)
11
votes

@tristo @patrick-haugh Thank you both! It works fine... i mixed both of your ideas and made this one and it works just fine !

@client.event
async def on_ready():
    Channel = client.get_channel('YOUR_CHANNEL_ID')
    Text= "YOUR_MESSAGE_HERE"
    Moji = await client.send_message(Channel, Text)
    await client.add_reaction(Moji, emoji='🏃')
@client.event
async def on_reaction_add(reaction, user):
    Channel = client.get_channel('YOUR_CHANNEL_ID')
    if reaction.message.channel.id != Channel
    return
    if reaction.emoji == "🏃":
      Role = discord.utils.get(user.server.roles, name="YOUR_ROLE_NAME_HERE")
      await client.add_roles(user, Role)

thanks alot guys!

5
votes

You have a ; after your return.
Also, you use user.reaction.emoji instead of just reaction.emoji
This

@client.event
async def on_reaction_add(reaction, user):
  ChID = '487165969903517696'
  if reaction.message.channel.id != ChID:
    return
  if reaction.emoji == "🏃":
    CSGO = discord.utils.get(user.server.roles, name="CSGO_P")
    await client.add_roles(user, CSGO)

should work fine