discord-interactions.py

Buttons

Send a button, react to the click, carry data, disable after use.

A button always works in two steps: you send it with a custom_id, then you react when someone clicks it. This page starts with the simplest case and adds one idea per example.

Every example assumes the skeleton from Getting started: a slash = SlashManager(client), a router = InteractionRouter() and an on_interaction that calls router.handle.

1. A button that answers#

from discord_interactions import create_action_row, create_button, respond_to_interaction  @slash.command(description="A simple button")async def button(ctx):    row = create_action_row(create_button("hello", "Click me"))    await ctx.respond("Here is a button:", components=[row])  @router.on("hello")async def hello(interaction):    await respond_to_interaction(interaction, f"Thanks {interaction.user.mention}!", ephemeral=True)

What happens:

  1. /button sends a message with a button whose custom_id is hello.
  2. On click, Discord sends an interaction to your bot. router.handle reads hello and calls the function decorated with @router.on("hello").
  3. The function answers with an ephemeral message: only the person who clicked sees it.

2. Edit the message instead of sending a new one#

update_message replaces the message that holds the button. It is the basis of counters, confirmations and pagination.

from discord_interactions import create_action_row, create_button, update_message  @slash.command(description="Counter")async def counter(ctx):    await ctx.respond("Counter: 0", components=[create_action_row(create_button("plus", "+1"))])  @router.on("plus")async def plus(interaction):    value = int(interaction.message.content.split(": ")[1]) + 1    await update_message(interaction, content=f"Counter: {value}")

Without components=, the buttons stay in place. Pass components=[] to remove them.

3. Styles#

row = create_action_row(    create_button("a", "Primary", style="primary"),  # blurple (default)    create_button("b", "Secondary", style="secondary"),  # grey    create_button("c", "Confirm", style="success"),  # green    create_button("d", "Delete", style="danger"),  # red    create_link_button("https://discord.com", "Open a link"),  # grey with an arrow)

A link button opens a URL: it has no custom_id and never triggers your bot. A premium button (create_premium_button(sku_id)) opens the purchase of one of your app's SKUs.

4. Emoji and disabled buttons#

create_button("like", "Like", emoji="👍")create_button("coin", "Pay", emoji="<:coin:123456789012345678>")  # server emojicreate_button("closed", "Closed", disabled=True)  # greyed out, not clickablecreate_button("alone", emoji="🔄")  # emoji only, no text

5. Yes / No: several buttons, one decision#

from discord_interactions import create_action_row, create_button, update_message  @slash.command(description="Delete your data")async def delete(ctx):    choice = create_action_row(        create_button("confirm", "Yes, delete", style="danger"),        create_button("cancel", "No", style="secondary"),    )    await ctx.respond("Are you sure? This cannot be undone.", components=[choice], ephemeral=True)  @router.on("confirm")async def confirm(interaction):    await update_message(interaction, content="Data deleted.", components=[])  @router.on("cancel")async def cancel(interaction):    await update_message(interaction, content="Nothing was deleted.", components=[])

components=[] removes the buttons after the choice: nobody can click twice.

6. Carry data in the button#

A button can carry a small dict. It comes back untouched on click, without a database. Add a second parameter to your function to receive it.

from discord_interactions import create_action_row, create_button, respond_to_interaction  @slash.command(description="Shop")async def shop(ctx):    row = create_action_row(        create_button("buy", "Sword (150)", data={"item": "sword", "price": 150}),        create_button("buy", "Shield (90)", data={"item": "shield", "price": 90}),    )    await ctx.respond("What do you want to buy?", components=[row])  @router.on("buy")async def buy(interaction, data):    await respond_to_interaction(interaction, f"You bought: {data['item']} for {data['price']} coins.", ephemeral=True)

Both buttons share the same buy function: only data differs. The module writes the custom_id as buy:<encoded data> and the router only looks at the part before :.

7. Only for the command author#

By default anyone can click. Store the author's ID in the data and compare it on click.

@slash.command(description="Roll a die")async def die(ctx):    button = create_button("reroll", "Reroll", data={"author": ctx.user.id})    await ctx.respond(f"Result: {random.randint(1, 6)}", components=[create_action_row(button)])  @router.on("reroll")async def reroll(interaction, data):    if interaction.user.id != data["author"]:        await respond_to_interaction(interaction, "This is not your die.", ephemeral=True)        return    await update_message(interaction, content=f"Result: {random.randint(1, 6)}")

For anything involving money or moderation, sign the custom_id: see Routing.

8. Disable the buttons after a delay#

@slash.command(description="60-second poll")async def poll(ctx):    choice = create_action_row(create_button("pizza", "Pizza"), create_button("sushi", "Sushi"))    await ctx.respond("What do we eat?", components=[choice])    message = await ctx.interaction.original_response()    disable_all(message, delay_ms=60_000)

After 60 seconds, every button of the message is greyed out. disable_all returns a handle: .cancel() cancels, .refresh(ms) restarts the timer.

9. More than 5 buttons#

A row holds 5 buttons at most, and a message 5 rows. create_auto_rows splits a list for you:

buttons = [create_button("num", str(n), data={"n": n}) for n in range(1, 13)]await ctx.respond("Pick a number", components=create_auto_rows(buttons))  # 3 rows: 5 + 5 + 2

Common errors#

What you see Why Fix
"This interaction failed" under the button No response within 3 seconds, or no route for this custom_id Check that on_interaction calls router.handle and that the ID in @router.on(...) matches exactly. For slow work, start with defer_interaction(interaction, update=True)
Nothing happens and no error on_interaction is declared twice, or commands.Bot has another on_interaction A single on_interaction that calls router.handle
400 Bad Request (50035), custom_id ... duplicated Two buttons of the same message share a custom_id Add data that tells them apart: data={"n": 1}, data={"n": 2}
400 Bad Request (50035), Must be 5 or fewer in length More than 5 buttons in a row create_auto_rows(buttons)
ValueError: custom_id trop long Too much data in data= Store an ID, keep the rest on the bot side
400 Bad Request (40060), already been acknowledged Your function responds twice The second response must be send_followup, or use respond(...) which picks for you
404 Not Found (10062), Unknown interaction Response sent after the 3 seconds defer_interaction first, then send_followup

The Common errors page explains all of them in detail.

Type a name: create_button, ModalBuilder, cooldown.