discord-interactions.py

Recipes

Complete features to copy: poll, pagination, tickets, applications, help menu.

Each recipe is a whole feature, ready to paste into the skeleton from Getting started. Imports are at the top of each block.

Poll with vote counter#

One vote per person, the counters update in the message, and anyone can change their mind.

poll.py
from discord_interactions import container, create_button, respond_to_interaction, update_messagefrom discord_interactions.slash import String, option polls = {}  # {message_id: {"question": str, "votes": {user_id: "yes" | "no"}}}  def poll_card(question, yes=0, no=0):    return (        container(f"## {question}", accent_color=0x5865F2)        .add(f"Yes: **{yes}**   No: **{no}**")        .row(            create_button("vote", "Yes", style="success", data={"c": "yes"}),            create_button("vote", "No", style="danger", data={"c": "no"}),        )    )  @slash.command(description="Start a poll")@option(String("question", "The question", max_length=200))async def poll(ctx, question):    await ctx.respond(components=[poll_card(question)])    message = await ctx.interaction.original_response()    polls[message.id] = {"question": question, "votes": {}}  @router.on("vote")async def vote(interaction, data):    poll = polls.get(interaction.message.id)    if poll is None:        await respond_to_interaction(interaction, "This poll is over.", ephemeral=True)        return    poll["votes"][interaction.user.id] = data["c"]  # voting again replaces the previous choice    yes = sum(1 for c in poll["votes"].values() if c == "yes")    no = len(poll["votes"]) - yes    await update_message(interaction, components=[poll_card(poll["question"], yes, no)])

Both buttons share the vote base_id and differ by data. Polls live in memory: after a restart, a click answers "This poll is over". To keep them, replace the dict with a database.

Pagination#

A long list split into pages, with Previous and Next. The page number travels in the button.

pagination.py
from discord_interactions import container, create_button, update_message ITEMS = [f"Item #{i}" for i in range(1, 48)]PER_PAGE = 10  def page(number):    total = (len(ITEMS) - 1) // PER_PAGE + 1    lines = ITEMS[number * PER_PAGE : (number + 1) * PER_PAGE]    return (        container(f"## Inventory, page {number + 1}/{total}")        .add("\n".join(f"- {line}" for line in lines))        .row(            create_button("page", "Previous", style="secondary", data={"p": number - 1}, disabled=number == 0),            create_button("page", "Next", style="secondary", data={"p": number + 1}, disabled=number == total - 1),        )    )  @slash.command(description="Show the inventory")async def inventory(ctx):    await ctx.respond(components=[page(0)])  @router.on("page")async def change_page(interaction, data):    await update_message(interaction, components=[page(data["p"])])

The buttons are greyed out on the first and last page: no way to go out of bounds. Both buttons have different data, hence different custom_ids.

Support tickets#

A permanent button opens a modal; on submit, the bot creates a private thread with the person.

tickets.py
import discord from discord_interactions import ModalBuilder, container, create_button, respond_to_interaction, send_message, send_modalfrom discord_interactions.slash import default_permissions  @slash.command(description="Install the ticket panel")@default_permissions(manage_guild=True)async def panel(ctx):    card = container("## Need help?").add("Open a ticket, the team answers you here.").row(        create_button("open_ticket", "Open a ticket", emoji="🎫")    )    await send_message(ctx.channel, components=[card])    await ctx.respond("Panel installed.", ephemeral=True)  @router.on("open_ticket")async def open_ticket(interaction):    modal = (        ModalBuilder("ticket", "New ticket")        .text_input("subject", "Subject", max_length=80)        .paragraph("details", "Describe your problem")    )    await send_modal(interaction, modal)  # no defer before a modal  @router.modal("ticket")async def ticket_received(interaction, values):    thread = await interaction.channel.create_thread(        name=f"ticket-{interaction.user.name}",        type=discord.ChannelType.private_thread,    )    await thread.add_user(interaction.user)    await send_message(thread, components=[container(f"## {values['subject']}").add(values["details"])])    await respond_to_interaction(interaction, f"Ticket opened: {thread.mention}", ephemeral=True)

The bot needs "Create Private Threads" and "Send Messages in Threads". The button keeps working after a restart: the router only looks at the custom_id, not at an object in memory.

Applications reviewed by the team#

The applicant fills a modal; the team receives the application with Accept and Decline. The applicant's ID travels in the buttons, signed so nobody can forge them.

applications.py
import os from discord_interactions import (    ModalBuilder,    container,    create_signed_button,    parse_signed_custom_id,    respond_to_interaction,    send_message,    update_message,) SECRET = os.environ["BUTTON_SECRET"]STAFF_CHANNEL = 123456789012345678  @slash.command(description="Apply to the team")async def apply(ctx):    modal = (        ModalBuilder("application", "Application")        .text_input("age", "Your age", max_length=3)        .radio("role", "Position", [("Moderation", "mod"), ("Events", "events")])        .paragraph("motivation", "Why you?", max_length=1000)    )    await ctx.send_modal(modal)  @router.modal("application")async def application(interaction, values):    data = {"u": interaction.user.id}    card = (        container(f"## Application from {interaction.user}", accent_color=0xFEE75C)        .add(f"**Age**: {values['age']}\n**Position**: {values['role']}")        .separator()        .add(values["motivation"])        .row(            create_signed_button("decision", SECRET, data={**data, "ok": 1}, label="Accept", style="success"),            create_signed_button("decision", SECRET, data={**data, "ok": 0}, label="Decline", style="danger"),        )    )    await send_message(interaction.client.get_channel(STAFF_CHANNEL), components=[card])    await respond_to_interaction(interaction, "Application sent, thank you!", ephemeral=True)  @router.on("decision")async def decision(interaction):    _, data, valid, _ = parse_signed_custom_id(interaction.data["custom_id"], SECRET)    if not valid:        await respond_to_interaction(interaction, "Invalid button.", ephemeral=True)        return    verdict = "accepted" if data["ok"] else "declined"    await update_message(interaction, components=[container(f"Application {verdict} by {interaction.user.mention}")])    applicant = await interaction.client.fetch_user(data["u"])    await applicant.send(f"Your application was {verdict}.")

The router recognises decision like a regular button; parse_signed_custom_id then checks the signature. We respond to the interaction before messaging the applicant, to stay under 3 seconds.

BUTTON_SECRET is a long random string, kept out of the code like the token.

Help menu by category#

A menu changes the card's content depending on the chosen category.

help.py
from discord_interactions import container, create_select_menu, select_option, update_message HELP = {    "games": ("🎮", "Games", "`/die` rolls a die\n`/poll` starts a vote"),    "tools": ("🔧", "Tools", "`/remind` schedules a reminder\n`/weather` gives the weather"),    "moderation": ("🛡️", "Moderation", "`/clear` empties the channel\n`/warn` warns a member"),}  def help_card(category="games"):    emoji, title, text = HELP[category]    options = [select_option(t, key, emoji=e, default=key == category) for key, (e, t, _) in HELP.items()]    return container(f"## {emoji} {title}").add(text).separator().row(create_select_menu("help", "Category", options=options))  @slash.command(description="List of commands")async def help(ctx):    await ctx.respond(components=[help_card()], ephemeral=True)  @router.select("help")async def help_category(interaction):    await update_message(interaction, components=[help_card(interaction.data["values"][0])])

Expiring button#

A challenge that can only be accepted within 30 seconds, then the button greys out by itself.

challenge.py
from discord_interactions import create_action_row, create_button, disable_all, respond_to_interaction, update_message  @slash.command(description="Start a challenge")async def challenge(ctx):    button = create_button("accept_challenge", "Accept", style="success", data={"by": ctx.user.id})    await ctx.respond(f"{ctx.user.mention} starts a challenge! 30 seconds to accept.", components=[create_action_row(button)])    disable_all(await ctx.interaction.original_response(), delay_ms=30_000)  @router.on("accept_challenge")async def accept(interaction, data):    if interaction.user.id == data["by"]:        await respond_to_interaction(interaction, "You cannot accept your own challenge.", ephemeral=True)        return    await update_message(interaction, content=f"<@{data['by']}> vs {interaction.user.mention}: let's go!", components=[])

Type a name: create_button, ModalBuilder, cooldown.