Home > Mobile >  How to get returned data from buttons
How to get returned data from buttons

Time:10-02

### This is a class for making buttons
import discord

class SelectionButtons(discord.ui.View):
    def __init__(self, *, timeout = 60):
        super().__init__(timeout = timeout)

    @discord.ui.button(label = '1', style = discord.ButtonStyle.blurple)
    async def button1(self, button: discord.ui.Button, interaction: discord.Interaction):
        return 1
    @discord.ui.button(label = '<', style = discord.ButtonStyle.red)
    async def buttonback(self, button: discord.ui.Button, interaction: discord.Interaction):
        return '<'

In another file, I call that class with the following script


view = SelectionButtons()
user_response = await context.send(embed = embed, view = view)


if user_response == 1:
    print('1')
elif user_response == '<':
    print('<')

How do I get the response from user if he reacted on the buttons?

CodePudding user response:

You could assign a variable to the user's input and then access it with with the view in your other file.

class SelectionButtons(discord.ui.View):
    def __init__(self, *, timeout = 60):
        super().__init__(timeout = timeout)
        self.choice = None

    @discord.ui.button(label = '1', style = discord.ButtonStyle.blurple)
    async def button1(self, button: discord.ui.Button, interaction: discord.Interaction):
        self.choice = "1"
        # self.stop() would go here
    @discord.ui.button(label = '<', style = discord.ButtonStyle.red)
    async def buttonback(self, button: discord.ui.Button, interaction: discord.Interaction):
        self.choice = "<"
        # self.stop() would go here
view = SelectionButtons()
await context.send(embed = embed, view = view)

# Wait statement goes here

print(view.choice)

Note that it will print None at first.
You can either wait until your view is finished with await view.wait() (Call self.stop() at the end of the button functions to have the view finish right after clicking a button), or check after a certain time with await asyncio.sleep() or check in a while loop. Choose what works best for you.

  • Related