Discord py bot limit player to one reaction for a poll

Viewed 275

I have been developing a discord py bot for a bit and have been trying to implement the ability to create a poll and have each person reaction only once to the poll. I have already got a successful poll creation (including bot reactions to start the vote). However, I am struggling to get the limiting the player reactions to only the listed reactions and to only one reaction on each poll.

Here is the code so far for controlling reactions to the message

async def on_reaction_add(reaction, user):
channel = discord.utils.get(user.guild.channels, name=pollchannel)
print(reaction.message.id)
if user.name != botname and reaction.message.channel == channel:
    cache_msg = discord.utils.get(client.cached_messages, id=reaction.message.id)
    print(cache_msg.reactions)
    print(reaction.emoji)
    if reaction.emoji not in cache_msg.reactions:
        await reaction.remove(user)
    elif len(reaction.message.reactions) > 1:
        await reaction.remove(user)

I have been testing and trying different things but can't get it to work as intended. Currently it always removes reaction messages. It seems that checking if the reaction emoji is in the cache (even though when I print them to console I can see that it is in the cache) it isn't finding it. The elif statement almost works but I want to have each person able to add a single reaction and this seems to just limit the message to only keep the reactions added by the bot.

Any help is appreciated!

1 Answers

When printing cache_msg.reaction, you get a list of reactions along with other information, such as reaction.author, reaction.count, etcetera. Therefore, you need to iterate through the specific reaction information. This is the code below, along with further explanation.

@client.event
async def on_reaction_add(reaction, user):
    channel = discord.utils.get(user.guild.channels, name=pollchannel)
    print(reaction.message.id)
    # I recommend using ids instead, since any user could have your bot's name
    if user.id != botid and reaction.message.channel == channel:
        cache_msg = discord.utils.get(client.cached_messages, id=reaction.message.id)
        print(cache_msg.reactions)
        print(reaction.emoji)

        # Check every reaction in the cache_msg
        for r in cache_msg.reactions:
            # Check if the user is an author of the reaction
            # AND check if the user is not a bot
            # AND check if this reaction emoji isn't the one they just reacted with
            if user in await r.users().flatten() and not user.bot and str(r) != str(reaction.emoji):
                # Remove their previous reaction
                await cache_msg.remove_reaction(r.emoji, user)

Working gif

Helpful Links:

Related