Home > Software engineering >  How do I get this command to work in different places at the same time?? discord.py
How do I get this command to work in different places at the same time?? discord.py

Time:10-16

I want this command to work in different places at the same time. When I run it on one channel, and my friend runs it on another channel, the command starts to be duplicated when one of us presses the button. I don't click anything, but if my friend clicks on the button in his channel, the message will be sent in both channels.

import random
import string
import discord
from discord_components import DiscordComponents, Button, ButtonStyle

@bot.command()
async def random_screenshot(ctx):
    while True:
        letters = string.ascii_lowercase   string.digits
        rand_string = ''.join(random.choice(letters) for i in range(6))
        link = "https://prnt.sc/"   str(rand_string)

        await ctx.send(link,
                                 components=[
                                     Button(style=ButtonStyle.blue, label="Next", emoji="➡")])

        await bot.wait_for('button_click')

This usually happens with all commands when i use the while loop

CodePudding user response:

The while loop isn't the problem here (though it's a separate problem).

What's happening is that await bot.wait_for("button_click") doesn't care what button is pressed. This means that when the command is run twice, then a button is clicked, both messages respond.

You'll want to make sure that the wait_for only continues if the button is our message's button (instead of another message's button). To do that, you'll need to do two things.

First, we need to generate a random string and set our button's custom id to it. This is so that we can know which button was pressed depending on its custom id. But wait, the discord_components library already generates an ID for us when we create the Button object, so we can just remember its ID like so:

button = Button(style=ButtonStyle.blue, label="Next", emoji="➡")
button_id = button.custom_id
await ctx.send(link, components=[button])

Second, we'll need to pass a function to wait_for as the check keyword argument that only returns True if the button clicked was our button. Something like so:

def check_interaction(interaction):
    return interaction.custom_id == button_id
await bot.wait_for("button_click", check=check_interaction)

Now your command should only respond to its own button presses :D

  • Related