Search code examples
pythondiscord

Discord.py - When a button is pressed it sends a message


I have been trying to make a python discord bot that sends an embedded message with interactive buttons underneath. So far it looks like this:

enter image description here

I'm not sure how to make the buttons respond though. When you click the button, it just says, "This Interaction Failed"

Here's my code:

@bot.command()
async def question(ctx):
    await ctx.message.delete()
    e = discord.Embed(title="TRIVIA QUESTION", description="When did the dinosours become extinct?")
    await ctx.send(embed=e, content="", components=[Button(style=ButtonStyle.red, label="60 million years ago", custom_id="button1", disabled = True), Button(style=ButtonStyle.red, label="65 million years ago", custom_id="button2")])

------------------------EDIT-------------------------

Looking at the documentation commented by hYg-Cain (https://devkiki7000.gitbook.io/discord-components/guide/getting-started#send-selects) I put this line in my code:

res = await bot.wait_for("button_click", timeout=10)

This waits for the user to click a button and then this:

if res.custom_id == "button1":
            await ctx.send("You got it right. ")

Means if the button pressed had an id of button1 it sent a message.


Solution

  • I think you'd have to write a check function to get the ID of the button clicked and then handle it via if/else stuff

    def check_button(i: discord.Interaction, button):
            return i.author == ctx.author and i.message == msg
    
    @bot.command()
    async def question(ctx):
        await ctx.message.delete()
        e = discord.Embed(title="TRIVIA QUESTION", description="When did the dinosours become extinct?")
        msg = await ctx.send(embed=e, content="", components=[Button(style=ButtonStyle.red, label="60 million years ago", custom_id="button1", disabled = True), Button(style=ButtonStyle.red, label="65 million years ago", custom_id="button2")])
    
       interaction, button = await client.wait_for('button_click', check=check_button)    
       if button.custom_id == "button1":
           # do stuff
       elif button.custom_id == "button2":
           # do other stuff
       else:
           # how did we get here
    

    however, maybe it is easier to implement this as select option https://devkiki7000.gitbook.io/discord-components/guide/getting-started#send-selects