I’m working on setting up reaction roles with my bot, here’s my code:
JavaScript
x
26
26
1
@client.event
2
async def on_raw_reaction_add(payload):
3
message_id = payload.message_id
4
if message_id == 789543211429265418:
5
guild_id = payload.guild_id
6
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
7
8
if payload.emoji.name == 'red_circle':
9
role = discord.utils.get(guild_roles, name='Red')
10
elif payload.emoji.name == 'orange_circle':
11
role = discord.utils.get(guild_roles, name='Orange')
12
elif payload.emoji.name == 'yellow_circle':
13
role = discord.utils.get(guild_roles, name='Yellow')
14
15
if role is not None:
16
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
17
if member is not None:
18
await member.add_roles(role)
19
print("done")
20
else:
21
print("Member not found")
22
23
else:
24
print("Role not found")
25
26
Whenever a certain reaction is added, instead of giving a role it gives me an error:
JavaScript
1
4
1
File "main.py", line 203, in on_raw_reaction_add
2
if role is not None:
3
UnboundLocalError: local variable 'role' referenced before assignment
4
Not sure how to fix this, any tips?
Advertisement
Answer
JavaScript
1
7
1
if payload.emoji.name == 'red_circle':
2
role = discord.utils.get(guild_roles, name='Red')
3
elif payload.emoji.name == 'orange_circle':
4
role = discord.utils.get(guild_roles, name='Orange')
5
elif payload.emoji.name == 'yellow_circle':
6
role = discord.utils.get(guild_roles, name='Yellow')
7
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.
JavaScript
1
2
1
role = None
2
or
JavaScript
1
3
1
else:
2
role = None
3