raphiel
raphiel

Reputation: 852

Discord.py Stop while true loop if command is sended twice

I made this code:

                    while True:

                        reaction = await self.client.wait_for('reaction_add')

                        emoji, user = reaction

                        if user.id != alwuid:
                            continue

                        if emoji.emoji == '◀️':
                            site = site - 1
                            if site < 0:
                                site = len(example_list) - 1
                            await msg.edit(embed=Embeds.txt("Side", example_list[site], ctx.author))
                        elif emoji.emoji == '▶️':
                            site = site + 1
                            if (site + 1) > len(example_list):
                                site = 0
                            await msg.edit(embed=Embeds.txt("Side", example_list[site], ctx.author))

And now I'm searching for a way to stop this loop if a second loop is generated: Somebody make this command !list, and he can change the page and so ..., and if he run the command second times I want, that if he use the reactions, not the old message also edited, I want only the newest message ...

Upvotes: 0

Views: 417

Answers (1)

jacksoor
jacksoor

Reputation: 490

You need to use checks if you don't want a command to trigger on any reaction to messages:

def reaction_check(msg):
    def check(reaction, user):
        if reaction.message.id != msg.id:
            return False
        return True
    return check

Then use this check in wait_for:

reaction = await self.client.wait_for('reaction_add', check=reaction_check(msg))

Now wait_for() will be only triggered if a reaction was added to the passed msg. You can also add more logic to this check e.g. if the user reacting to this message is the one who called the command.

As for the second problem of stopping your loop if another is triggered, you will need to look into Synchronization Primitives but I'd suggest just adding timeout=x to wait_for() and catch asyncio.TimeoutError after x seconds of no activity: https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for

Upvotes: 1

Related Questions