'"local variable referenced before assignment" error when trying to get emoji ID and compare it

I would like to get from an emoji in the ctx.guild the corresponding ID, because this is not changeable and so it is easier to query it and not get in the way if suddenly the name is changed. But now the following problem:

I always get the following error when I try to make an entry in the database:

    roles = rxner.find_one({"role1": role1.id}, {"emoji": emoji2}) # Search for existing entry about role + emoji
UnboundLocalError: local variable 'emoji2' referenced before assignment

My code to get the ID looks like this so far:

for em in ctx.guild.emojis: # loop over emojis
    if str(em.id) == emoji:
        emoji2 = em.id # get the ID
        break # break

roles = rxner.find_one({"role1": role1.id}, {"emoji": emoji2})  # Search for existing entry about role + emoji
emojicheck = rxner.find_one({"emoji": emoji})  # Check which role + emoji belong together
roletofind = rxner.find_one({"role1": role1.id})

This must be where the error is somewhere, but I don't know exactly where.

I've looked at many posts here, even defined emoji globally, but that didn't help. I also tried to return the emoji but none of that works. As I set emoji: str as a required argument in the command that totally works but if the name is changed or something, I can't work with that anymore. Is there a solution how to get the ID in an easier way/fix the problem?

And yes, I looked at the following posts:



Solution 1:[1]

The error message is quite clear: emoji2 isn't defined by the time you get to the roles definition. This would mean that str(em.id) == emoji never is true.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ades