Search code examples
pythonpycord

How to edit a buttons style when it's clicked. (Pycord) using edit_message()


So I'm making a little discord bot and I want to make the buttons change from red to green when there clicked I've tried a couple ways to actually do it but don't seem to work I get errors like something 2 arguments etc... I'm not using a class for the buttons.

In the pycord documentation it says view= but view= what?

I've also tried putting the color into a variable then reassigning the variable when the button is clicked.

Example:

@client.command()
async def test(ctx):
    test = discord.Embed(
        title="test",
        colour=discord.Colour.random()
    )
    style = red
    buttontest = discord.ui.Button(
        label="test", 
        style=discord.ButtonStyle.style, 
        disabled=False
    )

    async def se_callback(interation):

        style = green

        await interation.response.edit_message(view=style)
        # This is what I've tried but doesn't work. #

    buttontest.callback = se_callback

    view.item_add(buttontest)

    await ctx.reply(embed=sample, view=view)

Here's how I'm formatting my buttons

Code:

@client.command()
async def test(ctx):
    test = discord.Embed(
        title="test",
        colour=discord.Colour.random()
    )

    buttontest = discord.ui.Button(
        label="test", 
        style=discord.ButtonStyle.red, 
        disabled=False
    )

    async def se_callback(interation):

        buttontest.style = discord.ButtonStyle.green

        await interation.response.edit_message(view=buttontest.style)
        # This is what I've tried but doesn't work. #

    buttontest.callback = se_callback

    view.item_add(buttontest)

    await ctx.reply(embed=sample, view=view)

Solution

  • All interactions (besides slash commands) need a view.

    You can get this by doing

    from discord.ui import View
    

    Then you can make a variable that holds the view. Ex view = View()

    You can then add the button to the view like view = View(buttontest) or the way you are doing right now. You can then just do view=view

    Here is a very good video explaining how to use buttons in Pycord. https://www.youtube.com/watch?v=kNUuYEWGOxA&scrlybrkr=6facec35