Skip to content
Advertisement

Programming a Discord bot in Python- Can’t figure out how to set up reaction roles

I’m working on setting up reaction roles with my bot, here’s my code:

@client.event
async def on_raw_reaction_add(payload):
  message_id = payload.message_id
  if message_id == 789543211429265418:
    guild_id = payload.guild_id
    guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)

    if payload.emoji.name == 'red_circle':
      role = discord.utils.get(guild_roles, name='Red')
    elif payload.emoji.name == 'orange_circle':
      role = discord.utils.get(guild_roles, name='Orange')
    elif payload.emoji.name == 'yellow_circle':
      role = discord.utils.get(guild_roles, name='Yellow')
      
    if role is not None:
      member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
      if member is not None:
        await member.add_roles(role)
        print("done")
      else:
        print("Member not found")
    
    else:
      print("Role not found")

Whenever a certain reaction is added, instead of giving a role it gives me an error:

File "main.py", line 203, in on_raw_reaction_add
    if role is not None:
UnboundLocalError: local variable 'role' referenced before assignment

Not sure how to fix this, any tips?

Advertisement

Answer

if payload.emoji.name == 'red_circle':
      role = discord.utils.get(guild_roles, name='Red')
elif payload.emoji.name == 'orange_circle':
      role = discord.utils.get(guild_roles, name='Orange')
elif payload.emoji.name == 'yellow_circle':
      role = discord.utils.get(guild_roles, name='Yellow')

this will only define role when these conditions are met. You should probably define it before doing this comparison, or have an else: to catch and define it.

role = None

or

else:
  role = None
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement