global variable not defined inside async function

Viewed 684

I have an async function that is supposed to add reactions to a list until a certain reaction is pressed then it will add all appropriate roles. to do this I have a global variable "reactions = []" that gets reset when the "ok" reaction is pressed. VS Code is telling me this on the line "for react in reactions:" : "reactions is used before it is defined. Move the definition before." this is confusing because roleEmojis is another global variable but that works fine. here is my code:

import os
import discord
import time
from discord.utils import get
from discord.ext import commands

token = "TOKEN"
BOT = commands.Bot("£")
reactions_list = []

@BOT.event
async def on_reaction_add(reaction , user):
    if reaction.emoji in roleEmojis.keys() and user != BOT.user:
        if reaction == get(reaction.message.guild.emojis, name = "OK"):
            for react in reactions_list:
                await user.add_roles(roleEmojis[react.emoji])
            reactions_list = []
        else:
            reactions_list.append(reaction)

BOT.run(token)

Side note: I haven't yet figured out how to detect when someone has "un-reacted" to a message, id appreciate any help there

2 Answers

use global reactions in your local method to make use of global variable

And as per the error you mentioned your error lies in for loop which I cant see in code snipped. In python you need to explicitly mentioned if you're using global variable. (except if it is a list and your using that through function parameter or any other data type which uses address).

Ex-

a=0
def b():
    a=1
b()
print(a)

Will result 0

a=0
def b():
    global a
    a=1
b()
print(a)

will result 1

In addition to global variables, you can also create variables accessible from anywhere like so:

BOT = commands.Bot("£")
BOT.reactions_list = []

@BOT.event
async def on_reaction_add(reaction , user):
    print(BOT.reactions_list) # proves it's accessible from anywhere
    # rest of your code
Related