discord.py button interactions not working

1.2k Views Asked by At

discord.py version 2.1.1

I'm trying to make a simple embed with buttons that a user can interact with. The button and embedded view are adding just fine when I do the command, but when I click on the button I see the button turn into an animating-ellipsis, and then I see, "This interaction failed" in red below the button. From what I can tell, the button's onclick interaction just isn't firing at all since I don't see the print happening.

Currently, I'm trying to just do it using discord.ui and would prefer that, but I'm willing to use whatever it takes to make this work.

Here's the important bits at top of the file:

import discord

from discord.ext import commands
from discord.ui import Button

from dotenv import load_dotenv
from types import SimpleNamespace

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

intents = discord.Intents.default()
intents.message_content = True
intents.guild_reactions = True
intents.guild_messages = True

bot = commands.Bot(command_prefix='!',intents=intents)

Here is the main code inside a @bot.command:

    embed = discord.Embed(title='My Embedded Object', description='This is an embedded object with a button.')
    view = MyView()
    view.add_item(Button(label='My Button'))
    message = await ctx.send(embed=embed, view=view)

    # Register the view for button interaction
    interaction = await bot.wait_for("button_click", check=lambda i: i.message.id == message.id)
    await view.callback(interaction)

Here is my view object:

class MyView(discord.ui.View):
    def __init__(self):
        super().__init__()

    async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
        print('Test')
        if button.label == 'My Button':
            await interaction.followup.send('Button clicked!')

Bottom of file:

bot.run(TOKEN)

Error

I've tried giving the bot all admin privileges in the developer window hoping it had something to do with that but no cigar.

1

There are 1 best solutions below

0
Hazzu On

You are not handling it correctly. If you want your bot to respond to button clicks, you need to associate a callback to this component. The most practical way to do this is using the discord.ui.button decorator:

class MyView(discord.ui.View):
   def __init__(self):
      super().__init__()

   @discord.ui.button(label="My button")
   async def say_hello(interaction, button):
      await interaction.response.send_message("Hello! I saw your click!")

async def my_command(ctx):
   embed = discord.Embed(
      title='My Embedded Object',
      description='This is an embedded object with a button.'
   )
   message = await ctx.send(embed=embed, view=MyView())