Search code examples
pythondiscorddiscord.pydiscord-buttons

"This interaction failed" error when i click on button


So i have a code and after running,when i click in Discrord i receive this problem "This interaction "failed

import discord
from discord.ext import commands



class MyView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.add_item(discord.ui.Button(style=discord.ButtonStyle.primary, label="Click me!", custom_id="my_button"))
        
    async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
        user = interaction.user
        await user.send("You clicked the button!")
        
        
class InteractiveCog(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.channel_id = 1226612165453021244

    @commands.command()
    async def message(self, ctx):
        channel = self.client.get_channel(self.channel_id)
        if channel:
            embed = discord.Embed(title="Interactive Message", description="Click the button below!")
            await channel.send(embed=embed, view=MyView())
        
async def setup(client):
    await client.add_cog(InteractiveCog(client))



I am trying to get just a simple response from a button, and after that, I'll change for my bot verification.


Solution

  • The button itself needs the callback. In your code snippet:

    class MyView(discord.ui.View):
        def __init__(self):
            super().__init__()
            self.add_item(discord.ui.Button(style=discord.ButtonStyle.primary, label="Click me!", custom_id="my_button"))
    

    The on_button_click doesn't actually do anything because it's not tied to the button itself.

    In the discord.py docs, you'll see that discord.ui.Button requires a callback.

    This function is a coroutine. The callback associated with this UI item.

    So to add the callback we can do this:

    class MyView(discord.ui.View):
        def __init__(self):
            super().__init__()
            button = discord.ui.Button(style=discord.ButtonStyle.primary, label="Click me!", custom_id="my_button")
            button.callback = self.on_button_click  # Add callback to the button
            self.add_item(button)
            
        async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
            user = interaction.user
            await user.send("You clicked the button!")
    

    An alternative method of doing this would be the decorator for discord.ui.button

    class MyView(discord.ui.View):
        def __init__(self):
            super().__init__()
    
        @discord.ui.button(style=discord.ButtonStyle.primary, label="Click me!", custom_id="my_button")
        async def callback(self, button: discord.ui.Button, interaction: discord.Interaction):
            user = interaction.user
            await user.send("You clicked the button!")
    

    See the documentation for that here