# discord-interactions-py 0.3.0 > Python module for Discord interactions on top of discord.py: buttons, select menus, Components V2, modals and slash commands, built as raw Discord API payloads. No `discord.ui.View`, no `app_commands.CommandTree`. Docs: https://discordpy.levraiberet.ovh/docs/en/0.3.0/ ## Rules for writing code with this module 1. Install `pip install levraiberet-discord-interactions`, import `discord_interactions` (slash commands: `discord_interactions.slash`). Python 3.9+, discord.py 2.6+. 2. Do NOT use `discord.ui.View`, `discord.ui.Button`, `discord.ui.Modal` or `app_commands`: this module replaces them. Components are plain dicts built by `create_*` functions or builders (`container()`, `section()`, `ModalBuilder`). 3. One entry point for components: `router = InteractionRouter()` and `@client.event async def on_interaction(interaction): await router.handle(interaction)`. Slash commands are handled by `slash = SlashManager(client)` on its own (auto-synced on ready). 4. Routing uses the `base_id`, the part of `custom_id` before `:`. `@router.on("id")` for buttons and selects, `@router.modal("id")` for modals. Handler signature: `(interaction)`, `(interaction, data)` or `(interaction, data, base_id)`; for a modal, `data` holds the submitted values. 5. `create_button("id", "Label", data={...})` stores data in the custom_id (100 characters max in total) and it comes back as `data`. Use `create_signed_button` / `parse_signed_custom_id` when the data must not be forged. 6. Every interaction must be answered within 3 seconds, exactly once: `respond_to_interaction`, `update_message` (edits the clicked message), `send_modal`, or `defer_interaction` then `send_followup` / `edit_original_response`. `respond()` and `ctx.respond()` switch to a followup automatically. 7. A modal must be the first response (never after a defer). 5 components max per modal. Read values with `values["id"]`: `str` for text and radio, `bool` for a checkbox, `list` for selects, checkbox groups and uploads. 8. Select values are always a list. Users, roles, channels: `parse_values(interaction).users("id")`, `.roles("id")`, `.channels("id")`, `.mentionables("id")`. 9. Components V2 (`container`, `section`, `mediaGallery`, `separator`, `textDisplay`) cannot be mixed with embeds. The IS_COMPONENTS_V2 flag is added automatically and `content` is turned into a text display. 10. Discord limits: 5 buttons per row, 5 rows (V1), 25 select options, 80-character button labels, unique custom_id per message. ## Contents - Getting started: Install the module and run a bot with a slash command and a button. - Buttons: Send a button, react to the click, carry data, disable after use. - Select menus: Text, user, role and channel select menus, reading the choices, common errors. - Components V2: Containers, sections, thumbnails, galleries, files and separators. - Modals: Forms with text, select menus, radio buttons, checkboxes and file uploads. - Slash commands: Declare commands, their typed options, groups and autocomplete. - Cooldowns and permissions: Rate-limit commands and control who can use them, and where. - Routing and custom_id: Send every click to its function, carry data and sign it. - Messages and updates: Send, reply, defer, edit, then change the components of an existing message. - Common errors: What "This interaction failed", 10062, 40060, 50035 and 50013 mean, and how to fix them. - Recipes: Complete features to copy: poll, pagination, tickets, applications, help menu. - Using with an AI: Give the whole documentation to Claude, ChatGPT, Cursor or Copilot so they write correct code. - Upgrading to 0.3: What changes between 0.2 and 0.3, and what to adapt. - Reference: Buttons, Select menus, Builders, Components V2, Modal fields, Types and constants, Building modals, Reading values, Sending and replying, Updating components, Payloads, Routing, Signed custom_id, Shortcuts, custom_id, HTTP, Slash commands, Context, Options, Permissions, Cooldowns, Autocomplete, Middlewares, Localization, Sync, Errors, Other ## Getting started Install the module and run a bot with a slash command and a button. Your first bot answers `/hello` with a button, and the click updates the message. Thirty lines, no `View`, no `CommandTree`. ### Installation ```bash pip install levraiberet-discord-interactions ``` The package is imported as `discord_interactions`. Requires Python 3.9 and discord.py 2.6 or later. ### The complete bot ```python import os import discord from discord_interactions import InteractionRouter, create_action_row, create_button, update_message from discord_interactions.slash import SlashManager client = discord.Client(intents=discord.Intents.default()) slash = SlashManager(client) router = InteractionRouter() @slash.command(description="Says hello") async def hello(ctx): button = create_button("wave", "Wave back", style="success") await ctx.respond(f"Hello {ctx.user.mention}!", components=[create_action_row(button)]) @router.on("wave") async def wave(interaction): await update_message(interaction, content="Hello to you too", components=[]) @client.event async def on_interaction(interaction): await router.handle(interaction) client.run(os.environ["DISCORD_BOT_TOKEN"]) ``` Run it: ```bash DISCORD_BOT_TOKEN=your_token python bot.py ``` > **Tip:** > Pass `default_guilds=[GUILD_ID]` to `SlashManager` while developing: commands show up instantly in that guild. ### What happens 1. `SlashManager` registers `/hello` and syncs it with Discord on startup. 2. `ctx.respond` sends the response through the API directly, without discord.py views. 3. The button carries the `custom_id` `wave`. On click, `router.handle` calls the function declared with `@router.on("wave")`. 4. `update_message` edits the original message instead of sending a new one. ### Module layout | Import | Contents | | --- | --- | | `discord_interactions` | Components, builders, modals, sending messages, router | | `discord_interactions.slash` | Slash commands, options, permissions, cooldowns | Everything you need is imported from these two entry points. ### Next The guides follow the order of a real bot: [buttons](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/boutons/), [select menus](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/menus/), Components V2, modals, slash commands, then routing and messages. Every page ends with a table of common errors. To go fast: the [recipes](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/recettes/) are complete features to copy, the [Common errors](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/erreurs/) page explains each Discord error code, and [Using with an AI](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/ia/) hands the whole docs to Claude, ChatGPT or Cursor. The [reference](https://discordpy.levraiberet.ovh/docs/en/0.3.0/api/) details every function, with an example. ## 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](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/introduction/): a `slash = SlashManager(client)`, a `router = InteractionRouter()` and an `on_interaction` that calls `router.handle`. ### 1. A button that answers ```python 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. > **Warning:** > Every click needs a response **within 3 seconds**. Otherwise Discord shows "This interaction failed" under the button, even if your code worked. ### 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. ```python 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 ```python 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 ```python create_button("like", "Like", emoji="👍") create_button("coin", "Pay", emoji="<:coin:123456789012345678>") # server emoji create_button("closed", "Closed", disabled=True) # greyed out, not clickable create_button("alone", emoji="🔄") # emoji only, no text ``` ### 5. Yes / No: several buttons, one decision ```python 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. ```python 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:` and the router only looks at the part before `:`. > **Note:** > The whole `custom_id` fits in **100 characters**. Store IDs and short keys, never whole objects. Beyond that, `create_button` raises `ValueError: custom_id trop long` before anything is sent. ### 7. Only for the command author By default anyone can click. Store the author's ID in the data and compare it on click. ```python @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](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/routage/). ### 8. Disable the buttons after a delay ```python @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: ```python 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](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/erreurs/) page explains all of them in detail. ## Select menus Text, user, role and channel select menus, reading the choices, common errors. A select menu works like a button: you **send** it with a `custom_id`, then you **react** when someone picks something. The only difference: instead of a click, you receive a **list of values**. Every example assumes the skeleton from [Getting started](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/introduction/): `slash`, `router` and an `on_interaction` that calls `router.handle`. ### 1. The simplest menu ```python from discord_interactions import create_action_row, create_select_menu, respond_to_interaction @slash.command(description="Your favourite colour") async def colour(ctx): menu = create_select_menu( "colour", # the custom_id the router will recognise placeholder="Pick a colour", # grey text before a choice options=["Red", "Green", "Blue"], ) await ctx.respond("Which colour?", components=[create_action_row(menu)]) @router.select("colour") async def colour_picked(interaction): choice = interaction.data["values"][0] await respond_to_interaction(interaction, f"You picked: {choice}", ephemeral=True) ``` What happens: 1. `/colour` sends a message with a menu. Like a button, the menu goes in a row (`create_action_row`), alone. 2. When someone picks "Green", Discord sends an interaction with `custom_id = "colour"` and `values = ["Green"]`. 3. `@router.select("colour")` catches it. `interaction.data["values"]` is **always a list**, even when only one choice is allowed: hence the `[0]`. > **Warning:** > As with a button, you have **3 seconds** to respond. Without a response, Discord shows "This interaction failed" and the menu goes back to its initial state. ### 2. A value different from the displayed text What the user sees (`label`) and what your code receives (`value`) can differ. Handy to receive IDs instead of sentences. ```python menu = create_select_menu( "language", options=[ select_option("Python", "py", "Simple and readable", emoji="🐍"), select_option("Rust", "rs", "Fast and safe", emoji="🦀"), select_option("JavaScript", "js", "Everywhere on the web", emoji="🟨"), ], ) ``` `select_option(label, value, description, emoji, default)`: only `label` is required. When "Python" is picked, your code receives `["py"]`. Options accept several equivalent forms: ```python options = [ "Red", # label = value = "Red" ("Green", "green"), # (label, value) ("Blue", "blue", "The colour of the sky"), # (label, value, description) select_option("Black", "black", emoji="⚫", default=True), # preselected ] ``` ### 3. Several choices at once ```python menu = create_select_menu( "toppings", placeholder="Toppings (up to 3)", min_values=1, # at least 1 max_values=3, # at most 3 options=["Cheese", "Ham", "Mushrooms", "Olives", "Pineapple"], ) @router.select("toppings") async def toppings(interaction): choice = interaction.data["values"] # e.g. ["Cheese", "Olives"] await respond_to_interaction(interaction, "Your pizza: " + ", ".join(choice), ephemeral=True) ``` `min_values=0` lets users clear everything, which is useful for "remove all my roles". ### 4. Keep the choice displayed in the menu After a choice, Discord resets the menu on screen. To keep the selection visible, send the menu back with the chosen option marked `default=True`, through `update_message`: ```python def size_menu(chosen=None): options = [select_option(s, s.lower(), default=(s.lower() == chosen)) for s in ("Small", "Medium", "Large")] return create_action_row(create_select_menu("size", "Size", options=options)) @slash.command(description="Order a coffee") async def coffee(ctx): await ctx.respond("Which size?", components=[size_menu()]) @router.select("size") async def size(interaction): chosen = interaction.data["values"][0] await update_message(interaction, content=f"Size: **{chosen}**", components=[size_menu(chosen)]) ``` The message is edited in place: the text changes and the menu keeps "Medium" displayed. ### 5. User select Discord fills the list with the server members itself. You write no options. ```python from discord_interactions import create_action_row, create_user_select_menu, parse_values @slash.command(description="Build a team") async def team(ctx): menu = create_user_select_menu("team", "Pick up to 4 players", max_values=4) await ctx.respond(components=[create_action_row(menu)]) @router.select("team") async def team_picked(interaction): values = parse_values(interaction) players = values.users("team") # list of discord.Member await respond_to_interaction(interaction, "Team: " + " ".join(p.mention for p in players)) ``` `interaction.data["values"]` would only hold IDs as text (`["80351110224678912"]`). `parse_values(...).users(...)` gives you the discord.py objects directly, with their name, roles and so on. ### 6. Role, channel and mentionable selects Same principle, one function per type: ```python create_role_select_menu("roles", "Pick roles", max_values=3) create_channel_select_menu("channel", "Pick a channel") create_channel_select_menu("voice", "Voice channel", channel_types=[discord.ChannelType.voice.value]) create_mentionable_select_menu("target", "A member or a role") ``` And to read the choices: | Menu | Read with | What you get | | --- | --- | --- | | Text | `interaction.data["values"]` | `list[str]` of the `value`s | | Users | `parse_values(interaction).users("id")` | `discord.Member` (or `discord.User` in DMs) | | Roles | `parse_values(interaction).roles("id")` | `discord.Role` | | Channels | `parse_values(interaction).channels("id")` | discord.py channels | | Mentionables | `parse_values(interaction).mentionables("id")` | members and roles mixed | `channel_types` limits the channels offered: `text` (0), `voice` (2), `category` (4), `news` (5), `forum` (15)… ### 7. Prefill an entity select ```python menu = create_user_select_menu("guests", "Guests", max_values=5, default_values=[ctx.user]) menu = create_role_select_menu("roles", "Your roles", max_values=10, default_values=ctx.user.roles[1:]) ``` `default_values` accepts discord.py objects or IDs. `ctx.user.roles[1:]` skips `@everyone`. ### 8. Full example: self-assignable roles Each member picks their notification roles. The menu only offers the roles you listed: nobody can give themselves a moderator role. ```python ROLES = { "123456789012345678": ("Announcements", "📢"), "234567890123456789": ("Events", "🎉"), "345678901234567890": ("Updates", "🔧"), } @slash.command(description="Pick your notification roles") async def notifications(ctx): current = {str(r.id) for r in ctx.user.roles} options = [select_option(name, rid, emoji=emoji, default=rid in current) for rid, (name, emoji) in ROLES.items()] menu = create_select_menu("notifs", "Your notifications", options=options, min_values=0, max_values=len(options)) await ctx.respond(components=[create_action_row(menu)], ephemeral=True) @router.select("notifs") async def notifs(interaction): await defer_interaction(interaction, update=True) # several API calls: take our time member = interaction.user wanted = set(interaction.data["values"]) to_add = [interaction.guild.get_role(int(r)) for r in wanted if not member.get_role(int(r))] to_remove = [interaction.guild.get_role(int(r)) for r in ROLES if r not in wanted and member.get_role(int(r))] await member.add_roles(*to_add) await member.remove_roles(*to_remove) await send_followup(interaction, f"{len(to_add)} role(s) added, {len(to_remove)} removed.", ephemeral=True) ``` For this to work, the bot needs the **Manage Roles** permission, and its own role must be **above** the roles it hands out in the server role list. Otherwise: `403 Forbidden (50013)`. ### 9. A menu in a V2 card In a container, a menu goes in `.row(...)` like buttons: ```python card = container("## Preferences").add("Pick your language:").row( create_select_menu("language", options=[("Français", "fr"), ("English", "en")]) ) await ctx.respond(components=[card]) ``` ### 10. A menu in a modal Menus also work in forms. See [Modals](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/modales/): `ModalBuilder(...).select("id", "Title", options)`. ### Common errors | What you see | Why | Fix | | --- | --- | --- | | "This interaction failed" after picking | No response within 3 seconds, or the `custom_id` matches no `@router.select(...)` | Check the exact spelling of the ID; for slow work, `defer_interaction(interaction, update=True)` first | | The menu goes back to empty after a choice | Normal Discord behaviour | Send the menu back with `default=True` on the chosen option (section 4) | | `TypeError: string indices must be integers` or a single letter received | You treated `values` as a string | `values` is a list: `interaction.data["values"][0]` | | `400 Bad Request (50035)` `Must be 25 or fewer in length` | More than 25 options | Split into several menus, or use a slash command with autocomplete | | `400 Bad Request (50035)` on `min_values`/`max_values` | `max_values` exceeds the number of options, or `min_values` > `max_values` | `max_values=len(options)` at most | | `400 Bad Request (50035)` `The specified option value is already used` | Two options share a `value` | Each `value` must be unique in the menu | | `400 Bad Request (50035)` on `components.0.components` | A menu shares its row with another component | One menu = one row of its own | | `parse_values(...).users("id")` returns an empty list | Wrong `custom_id`, or a text menu read as an entity menu | Pass exactly the menu's `custom_id`, and use `.users` only for a user select | | `403 Forbidden (50013)` when giving a role | The bot lacks "Manage Roles" or its role is too low | Move the bot's role above the roles involved | The [Common errors](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/erreurs/) page details Discord's error codes. ## Components V2 Containers, sections, thumbnails, galleries, files and separators. Components V2 replace embeds: a card (container) holds Markdown text, images, files and buttons, in the order you choose. ### A card in a few lines ```python from discord_interactions import container, create_button, section card = ( container(accent_color=0x5865F2) .add("## Minecraft server") .add(section("**Online**", "12 players connected").thumbnail("https://example.com/logo.png")) .separator() .row(create_button("join", "Join", style="success")) ) await ctx.respond(components=[card]) ``` A string passed to `add()` becomes a text block. `build()` is optional: `ctx.respond` and every sending function accept the builder directly. > **Note:** > As soon as a V2 component is present, the `IS_COMPONENTS_V2` flag is added for you. Text passed as `content` becomes a leading text block, and embeds are rejected with a clear message, because Discord forbids them in this mode. ### Building blocks | Builder | Role | | --- | --- | | `container()` | The card, with border color and spoiler | | `textDisplay()` or a string | Markdown text, 4000 characters in total per message | | `section()` | 1 to 3 texts with a button or a thumbnail on the right | | `thumbnail()` | Square image used as a section accessory | | `mediaGallery()` | 1 to 10 images or videos | | `fileComponent()` | Attached file shown inside the card | | `separator()` | Divider and spacing, small or large | | `.row()` | Row of buttons or a select menu | ### Images and files ```python import discord from discord_interactions import container, mediaGallery file = discord.File("report.pdf") card = container("## Monthly report").add(mediaGallery("https://example.com/chart.png")).file("report.pdf") await ctx.respond(components=[card], files=[file]) ``` A file sent with `files=` is referenced as `attachment://name`. `.file("report.pdf")` adds that prefix for you. ### Separators ```python container("Title").separator().add("Thin divider") container("Title").separator(spacing="large").add("Large gap") container("Title").separator(divider=False).add("Space without a line") ``` ### discord.js style The camelCase names from discord.js work too, if you come from JavaScript: ```python from discord_interactions import ContainerBuilder, textDisplay card = ( ContainerBuilder() .setAccentColor(0x57F287) .addTextDisplayComponents(textDisplay("Hello")) .addSeparatorComponents() .build() ) ``` Prefer the short form in new code: it reads better and produces the same output. ### Update a card A card is replaced like any message: rebuild it and pass it to `update_message`. ```python def status_card(online): state = "🟢 Online" if online else "🔴 Offline" return container("## Server", state).row(create_button("refresh", "Refresh")) @router.on("refresh") async def refresh(interaction): await update_message(interaction, components=[status_card(await ping_server())]) ``` ### A button next to a text A section can carry a button instead of a thumbnail: ideal for a list of items with one action each. ```python card = container("## Your reminders") for reminder in reminders: button = create_button("delete", "Delete", style="danger", data={"id": reminder.id}) card.add(section(f"**{reminder.title}**", reminder.date).button(button)) ``` ### Common errors | What you see | Why | Fix | | --- | --- | --- | | `ValueError: Les embeds sont interdits avec les composants V2` | An `embed=` in a message that holds a container | Put the embed content in the container | | `ValueError: Une section doit avoir un accessoire` | `section(...)` without `.thumbnail(...)` or `.button(...)` | Add an accessory, or pass the text directly to `.add("text")` | | `ValueError: Une section accepte 3 TextDisplay maximum` | More than 3 texts in a section | Merge the lines into a single text | | The image does not show | URL not public, or attached file misnamed | A public `https://` URL; for a file, the same name in `files=` and `.file(...)` | | `400 (50035)` on total length | More than 4000 characters of text in total, or more than 40 components | Split into several messages or pages | ## Modals Forms with text, select menus, radio buttons, checkboxes and file uploads. A modal is a form that opens on top of Discord. `ModalBuilder` builds it field by field, `parse_values` reads the answers. ### Opening a modal ```python from discord_interactions import ModalBuilder @slash.command(description="Open a ticket") async def ticket(ctx): modal = ( ModalBuilder("ticket", "Open a ticket") .text_input("subject", "Subject", max_length=80) .paragraph("details", "Details", "Describe the issue in a few sentences") ) await ctx.send_modal(modal) ``` Every field sits in a Label: a title (45 characters) and an optional description (100 characters). A modal holds 5 components at most. ### Receiving the answers ```python @router.modal("ticket") async def received(interaction, values): subject = values["subject"] details = values.get("details", "No details") await respond_to_interaction(interaction, f"Ticket “{subject}” created.", ephemeral=True) ``` The router recognizes the modal by its `custom_id` and passes a `ModalSubmit` to the handler. ### Every field | Method | Field | Received value | | --- | --- | --- | | `text_input`, `paragraph` | Short or long text | `str` | | `select` | Text menu | `list[str]` | | `user_select`, `role_select`, `channel_select`, `mentionable_select` | Entity menus | `list` of IDs, objects through `.users()`, `.roles()`, `.channels()` | | `radio` | Radio buttons, one choice | `str` or `None` | | `checkboxes` | Checkboxes, several choices | `list[str]` | | `checkbox` | Single checkbox | `bool` | | `file_upload` | File upload | `list` of IDs, files through `.attachments()` | | `text` | Introduction text | none | ```python modal = ( ModalBuilder("signup", "Sign up") .text("Fill in the form, it takes 30 seconds.") .radio("slot", "Slot", [("Saturday", "sat"), ("Sunday", "sun")]) .checkboxes("activities", "Activities", ["Tournament", "Workshop", "Quiz"]) .checkbox("reminder", "Get a reminder", default=True) ) ``` ### File uploads ```python modal = ModalBuilder("portfolio", "Portfolio").file_upload( "images", "Images", max_values=4, file_types=["image"] ) @router.modal("portfolio") async def portfolio(interaction, values): await defer_interaction(interaction) files = [await piece.to_file() for piece in values.attachments("images")] await send_followup(interaction, files=files) ``` `file_types` accepts `"image"`, `"video"`, `"audio"` or extensions such as `".pdf"`. > **Warning:** > A modal must be opened as the direct response to an interaction, within 3 seconds, and never after a `defer`. ### Full example: a button that opens a form The most common case: a "Report" button opens a modal, and the answer goes to a channel. ```python from discord_interactions import ModalBuilder, create_action_row, create_button, respond_to_interaction, send_message, send_modal MOD_CHANNEL = 123456789012345678 @slash.command(description="Report panel") async def panel(ctx): await ctx.respond("Something wrong?", components=[create_action_row(create_button("report", "Report", style="danger"))]) @router.on("report") async def open_form(interaction): modal = ModalBuilder("report_form", "Report a problem").paragraph( "reason", "What is happening?", placeholder="Be specific", max_length=500 ) await send_modal(interaction, modal) @router.modal("report_form") async def received(interaction, values): await send_message(interaction.client.get_channel(MOD_CHANNEL), f"{interaction.user.mention}: {values['reason']}") await respond_to_interaction(interaction, "Thanks, the team has been notified.", ephemeral=True) ``` ### Prefill a field `value=` fills the field when the modal opens: handy to edit an existing profile. ```python modal = ( ModalBuilder("profile", "Your profile") .text_input("nickname", "Nickname", value=old_nickname, max_length=32) .paragraph("bio", "Bio", value=old_bio, required=False) ) ``` ### Validate an input A modal only checks length. For anything else (a number, a date), check it yourself and answer with an error message: ```python @router.modal("age") async def age(interaction, values): if not values["age"].isdigit(): await respond_to_interaction(interaction, "Age must be a number, try again.", ephemeral=True) return await respond_to_interaction(interaction, f"Saved: {int(values['age'])} years old.", ephemeral=True) ``` Discord cannot keep the modal open with an error message: you have to open it again, for instance with a "Try again" button. ### Carry data in the modal Like a button, a modal can carry a small dict, which comes back in `values.data`: ```python modal = ModalBuilder("rate", "Rate the member", data={"target": member.id}).text_input("score", "Score out of 10", max_length=2) @router.modal("rate") async def rate(interaction, values): target = values.data["target"] ``` ### Common errors | What you see | Why | Fix | | --- | --- | --- | | The modal does not open, `40060 already acknowledged` | A `defer` or a response was sent before the modal | `send_modal` must be the very first response | | The modal does not open, `10062 Unknown interaction` | Slow code before `send_modal` | Open the modal right away, do the work after submission | | "This interaction failed" on submit | No `@router.modal(...)` for this `custom_id`, or no response within 3 s | Check the ID, and respond in the modal handler | | `KeyError: 'details'` | Typo in the field ID | Same ID as in `ModalBuilder`; `values.get("details", "default")` for an optional field | | `ValueError: Une modale accepte 5 composants maximum` | More than 5 fields | Split into two modals, or replace text fields with checkboxes | | `400 (50035)` on `label` | Field title longer than 45 characters | Shorten it, and put details in `description` | ## Slash commands Declare commands, their typed options, groups and autocomplete. `SlashManager` declares, runs and syncs your commands. Every option is typed and validated, and users, channels, roles and files arrive as discord.py objects. ### Declaring a command ```python from discord_interactions.slash import Integer, SlashManager, String, option slash = SlashManager(client) @slash.command(description="Repeats a text") @option(String("text", "Text to repeat", max_length=200)) @option(Integer("times", "Repetitions", required=False, default=1, min_value=1, max_value=5)) async def repeat(ctx, text, times): await ctx.respond("\n".join([text] * times)) ``` The command is named after the function; pass `name="..."` to pick another name, for example one with a dash. ### Options | Factory | Received value | Checks | | --- | --- | --- | | `String` | `str` | length, choices, regex, autocomplete | | `Integer` | `int` | bounds, step, choices, autocomplete | | `Number` | `float` | bounds, rounding | | `Boolean` | `bool` | | | `User` | `discord.Member` or `discord.User` | reject bots, require voice | | `Channel` | channel | channel types | | `Role` | `discord.Role` | reject @everyone or managed roles | | `Mentionable` | member or role | | | `Attachment` | `discord.Attachment` | file types, extensions, size | Every option also accepts `validator=` (returns `True`, `False` or an error message) and `transformer=` (converts the value before the call). ```python @option(String("hex", "Color", pattern=r"^#[0-9A-Fa-f]{6}$", pattern_error="Expected format: #RRGGBB")) @option(Attachment("image", "Image", file_types=["image"], max_size=8_000_000)) ``` ### Responding | Method | Effect | | --- | --- | | `ctx.respond(...)` | Initial response, then an automatic followup | | `ctx.defer(ephemeral=...)` | Shows the thinking state to answer later | | `ctx.edit(...)` | Edits the original response | | `ctx.send_modal(modal)` | Opens a modal | `@slash.command(ephemeral=True)` makes every response ephemeral by default, and `auto_defer=True` acknowledges before running the function. ### Groups ```python config = slash.group("config", "Bot configuration") channels = config.subgroup("channels", "Bot channels") @config.command(description="Show the configuration") async def show(ctx): ... @channels.command(description="Log channel") @option(Channel("channel", "Channel")) async def logs(ctx, channel): ... ``` Result: `/config show` and `/config channels logs`. Option, cooldown and permission decorators work on subcommands. ### Autocomplete ```python from discord_interactions.slash import filter_choices, from_list async def cities(ctx): country = ctx.options.get("country") return filter_choices([(c, c) for c in CITIES[country]], ctx.value, fuzzy=True) @slash.command(description="Weather") @option(String("country", "Country", autocomplete=from_list(["France", "Belgium"]))) @option(String("city", "City", autocomplete=cities)) async def weather(ctx, country, city): ... ``` `ctx.value` holds the current input, `ctx.options` the other options already filled. ### Sync Commands are synced on startup. With `default_guilds=[...]`, they are synced to those guilds, which is instant. Without it, they are global. > **Warning:** > Syncing replaces every command of the bot. Use a test bot while developing. ### More option examples **A fixed list of choices**: the user cannot type anything else. ```python @slash.command(description="Change theme") @option(String("theme", "Theme", choices=[("Light", "light"), ("Dark", "dark")])) async def theme(ctx, theme): await ctx.respond(f"Theme: {theme}", ephemeral=True) # receives "light" or "dark" ``` **A member**: you receive a `discord.Member` directly. ```python @slash.command(description="Say hi to someone") @option(User("member", "Who?", allow_bots=False)) async def greet(ctx, member): await ctx.respond(f"{ctx.user.mention} says hi to {member.mention}!") ``` **An optional option** with a default value: ```python @slash.command(description="Roll dice") @option(Integer("sides", "Number of sides", required=False, default=6, min_value=2, max_value=100)) async def die(ctx, sides): await ctx.respond(f"🎲 {random.randint(1, sides)}") ``` **A file** attached to the command: ```python @slash.command(description="Inspect an image") @option(Attachment("image", "The image", file_types=["image"], max_size=8_000_000)) async def inspect(ctx, image): await ctx.respond(f"{image.filename}: {image.width}×{image.height} px, {image.size // 1024} KB") ``` **Slow work**: `auto_defer=True` shows "thinking…" while it runs. ```python @slash.command(description="Recent messages", auto_defer=True) async def stats(ctx): total = sum([1 async for _ in ctx.channel.history(limit=1000)]) # takes a while await ctx.respond(f"{total} recent messages in this channel.") ``` ### Common errors | What you see | Why | Fix | | --- | --- | --- | | The command does not show up in Discord | Slow global sync, or bot invited without the `applications.commands` scope | `default_guilds=[ID]` during development; reinvite the bot with that scope | | "This interaction failed" after the command | The function crashed (see the console) or took more than 3 s | Fix the printed error; `auto_defer=True` for slow work | | `TypeError: ... got an unexpected keyword argument` | An option name does not match a function parameter | `String("text", ...)` requires a `text` parameter | | `TypeError: ... missing 1 required positional argument` | Optional option without a default value | `required=False, default=...` in the option | | `400 (50035)` on sync, on `name` | Command or option name with a capital letter, space or accent | Lowercase, digits, `-` and `_`; readable text goes in `description` | | `400 (50035)` on `description` | Empty description or longer than 100 characters | 1 to 100 characters | | `400 (50035)` on `options` | A required option placed after an optional one | Declare required options first | ## Cooldowns and permissions Rate-limit commands and control who can use them, and where. Decorators go under `@slash.command()` and also apply to group subcommands. ### Cooldowns ```python @slash.command(description="Reward") @cooldown(1, 30) async def work(ctx): ... ``` `@cooldown(rate, per)` allows `rate` uses every `per` seconds. The default scope is the user; `type=` changes it. | Scope | Decorator | | --- | --- | | User | `@user_cooldown(1, 5)` | | Member (user within a guild) | `@member_cooldown(1, 5)` | | Guild | `@guild_cooldown(1, 60)` | | Channel | `@channel_cooldown(1, 10)` | | Everyone | `@global_cooldown(10, 60)` | #### Shared and dynamic ```python economy = SharedCooldown("economy", rate=5, per=60) @slash.command(description="Balance") @economy async def balance(ctx): ... @slash.command(description="Generation") @DynamicCooldown(rate=1, per_func=lambda i: 5 if is_premium(i.user.id) else 30) async def generate(ctx): ... ``` When a cooldown blocks, `CommandOnCooldown` is raised. The default message shows the wait; customize it with `@slash.on_error`. ```python @slash.on_error async def errors(ctx, error): if isinstance(error, CommandOnCooldown): await ctx.respond(f"Wait {error.retry_after:.0f} more seconds.", ephemeral=True) return True return False ``` ### Permissions | Decorator | Effect | | --- | --- | | `@default_permissions(manage_messages=True)` | Hides the command in Discord from members without the permission | | `@has_permissions(...)` | Checks the user's permissions in the channel | | `@bot_has_permissions(...)` | Checks the bot's permissions in the channel | | `@guild_only()` | Guilds only | | `@owner_only()` | Bot owners, read from the application | | `@require_roles(id1, id2)` | One of the roles, or all with `require_all=True` | | `@check(function)` | Custom async check | Checked permissions are the channel's effective permissions, computed by Discord, overwrites included. ### User installs A user-installable command works everywhere: guilds, DMs with the bot and group chats. ```python @slash.command(description="Private note", ephemeral=True) @user_installable() async def note(ctx): ... ``` Also enable “User Install” in the Installation tab of the developer portal. For finer control, combine `@integration_types(...)` and `@contexts(...)`. ## Routing and custom_id Send every click to its function, carry data and sign it. Every button, menu or modal carries a `custom_id`. `InteractionRouter` reads the part before `:` (the `base_id`) and calls the right function. ### The router ```python from discord_interactions import InteractionRouter router = InteractionRouter() @router.on("like") async def like(interaction, data): ... @router.modal("profile") async def profile(interaction, values): ... @client.event async def on_interaction(interaction): await router.handle(interaction) ``` Depending on its signature, the handler receives `(interaction)`, `(interaction, data)` or `(interaction, data, base_id)`. For a modal, `data` is a `ModalSubmit`. | Decorator | Interactions | | --- | --- | | `@router.on(id)`, `@router.button(id)`, `@router.select(id)` | Buttons and menus | | `@router.modal(id)` | Modal submissions | | `@router.fallback` | Buttons and menus without a dedicated route | `handle()` returns `True` when a handler took the interaction, so several routers can be chained. ### Embedded data ```python create_button("page", "Next", data={"p": 3}) # custom_id: "page:eyJwIjozfQ" base_id, data = parse_custom_id("page:eyJwIjozfQ") # ("page", {"p": 3}) ``` Data is compact JSON in url-safe base64. Everything fits in 100 characters: keep short keys and IDs rather than objects. > **Tip:** > Two buttons of the same message cannot share a `custom_id`. When two buttons carry identical data, add a key that tells them apart. ### Signed custom_id A modified client can send any `custom_id`. For a sensitive action (purchase, withdrawal, moderation), sign it: ```python button = create_signed_button("buy", SECRET, data={"price": 150}, ttl_seconds=60, label="Buy") @client.event async def on_interaction(interaction): base_id, data, valid, reason = parse_signed_custom_id(interaction.data["custom_id"], SECRET) if not valid: ... ``` `reason` is `ok`, `expired`, `bad_signature`, `bad_payload`, `missing_separator` or `missing_signature`. The HMAC-SHA256 signature is truncated to 96 bits to fit the 100-character limit. ## Messages and updates Send, reply, defer, edit, then change the components of an existing message. Every sending function shares the same parameters: `content`, `components`, `files`, `allowed_mentions`, `ephemeral`, `flags`. ### Responding to an interaction | Function | When | | --- | --- | | `respond_to_interaction(i, ...)` | Initial response, within 3 seconds | | `update_message(i, ...)` | After a click: edits the component's message | | `defer_interaction(i)` | Long task: answer within 15 minutes | | `send_followup(i, ...)` | Following messages | | `edit_original_response(i, ...)` | Change the first response | | `respond(i, ...)` | Initial response or followup, depending on the state | ```python await defer_interaction(interaction, ephemeral=True) result = await long_task() await send_followup(interaction, f"Result: {result}", ephemeral=True) ``` ### Sending outside an interaction `send_message` accepts a channel, a thread, a `commands.Context`, or a member for a direct message. ```python message = await send_message(channel, components=[container("## Announcement")]) await send_message(channel, "Thanks everyone", reply_to=message) await send_message(member, "Your ticket is closed.") await edit_message(message, components=[container("## Announcement over")]) ``` ### Allowed mentions ```python await ctx.respond(text, allowed_mentions={"parse": ["users"]}) await ctx.respond(text, allowed_mentions={"roles": [role]}) await ctx.respond(text, allowed_mentions={"users": False, "roles": False, "everyone": False}) ``` The discord.js style, the API payload and `discord.AllowedMentions` are all accepted. ### Changing the components of a message These functions reload the message, change its components at any depth (rows, sections, containers), then edit it. ```python await defer_interaction(interaction, update=True) await update_component(interaction.message, "confirm", {"disabled": True, "label": "Confirmed"}) await remove_component(interaction.message, "cancel") await row_update(interaction.message, "confirm", lambda button: {**button, "style": 2}) ``` | Function | Effect | | --- | --- | | `update_component(message, selector, fields)` | Replaces fields of the matching components | | `remove_component(message, selector)` | Removes components, and the rows left empty | | `row_update(message, row, function)` | Transforms every component of a row | | `disable_all(message, delay_ms)` | Disables everything, now or after a delay | The selector is an exact `custom_id` or a `(component) -> bool` function. ### Automatic expiry ```python timer = disable_all_by_message_id(channel, message_id, delay_ms=30_000) timer.refresh(30_000) # restart on every activity timer.cancel() ``` ### Which function should I use? | You want to… | Function | | --- | --- | | Answer a slash command | `ctx.respond(...)` | | Answer a click with a new message | `respond_to_interaction(interaction, ...)` | | Edit the message that holds the clicked button | `update_message(interaction, ...)` | | Answer after a long computation | `defer_interaction(...)` then `send_followup(...)` | | Send a 2nd, 3rd message after the response | `send_followup(...)` or `respond(...)` | | Send to a channel without an interaction (task, event) | `send_message(channel, ...)` | | Send a direct message | `send_message(member, ...)` | | Edit a message already sent | `edit_message(message, ...)` | ### Common errors | What you see | Why | Fix | | --- | --- | --- | | `40060 already acknowledged` | Two initial responses to the same interaction | The second as `send_followup`, or `respond(...)` which picks for you | | `10062 Unknown interaction` | Response after 3 seconds | `defer_interaction` first | | `10008 Unknown Message` | The message was deleted before the edit | Wrap the edit in `try` / `except discord.NotFound` | | `50007 Cannot send messages to this user` | The member closed DMs or blocked the bot | Catch `discord.Forbidden` and answer in the channel | | `50013 Missing Permissions` | The bot cannot write in this channel | Check the channel permissions for the bot's role | | Cannot edit an ephemeral message later | An ephemeral message can only be edited through its interaction, for 15 minutes | `edit_original_response(interaction, ...)` while the interaction is valid | ## Common errors What "This interaction failed", 10062, 40060, 50035 and 50013 mean, and how to fix them. Most errors in an interactions bot come from three Discord rules: **respond fast**, **respond once**, **send a valid message**. This page starts from what you see and gives the fix in code. ### Reading a Discord error When Discord rejects a call, discord.py raises a `discord.HTTPException`. Three pieces matter: ```text discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In data.components.0.components.5: Must be 5 or fewer in length. ``` | Piece | Meaning | | --- | --- | | `400 Bad Request` | HTTP status: 400 = invalid message, 403 = forbidden, 404 = not found | | `error code: 50035` | Discord's code, more precise than the status | | `data.components.0.components.5` | **Where** the problem is: 1st row (`0`), 6th component (`5`) | Indexes start at 0. Here the first row has a 6th button, while the limit is 5. ### "This interaction failed" The red message under a button, a menu or a command. Discord received **no response within 3 seconds**. **Cause 1: the interaction never reaches your function.** ```python @client.event async def on_interaction(interaction): handled = await router.handle(interaction) if not handled and interaction.type == discord.InteractionType.component: print("No route for", interaction.data["custom_id"]) ``` If that line prints, the ID in `@router.on("...")` does not match the component's `custom_id`: a typo, a capital letter, or an old message sent before you renamed the ID. **Cause 2: your function crashes before responding.** The Python error shows in the bot's console, not in Discord. Look at the terminal. **Cause 3: your function is too slow.** A database query, an external API or an AI call easily exceeds 3 seconds. Acknowledge first, answer later: ```python @router.on("report") async def report(interaction): await defer_interaction(interaction, ephemeral=True) # instant: "thinking…" text = await build_report() # can take up to 15 minutes await send_followup(interaction, text, ephemeral=True) ``` For a slash command: `await ctx.defer()` then `await ctx.respond(...)`, or directly `@slash.command(auto_defer=True)`. For a button that must **edit** its message: `defer_interaction(interaction, update=True)` then `edit_original_response(interaction, ...)`. ### 10062: Unknown interaction ```text discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction ``` The response arrived after the 3 seconds: the interaction expired. Same fix as cause 3 above. If it happens while your code is fast, check that the same bot is not running twice (two instances fight over interactions). ### 40060: Interaction has already been acknowledged ```text discord.errors.HTTPException: 400 Bad Request (error code: 40060): Interaction has already been acknowledged. ``` Your function responds **twice** to the same interaction. An interaction accepts one initial response; the next ones are followups. ```python # Wrong: two initial responses await respond_to_interaction(interaction, "Step 1") await respond_to_interaction(interaction, "Step 2") # 40060 # Right await respond_to_interaction(interaction, "Step 1") await send_followup(interaction, "Step 2") # Even simpler: respond picks for you await respond(interaction, "Step 1") await respond(interaction, "Step 2") ``` `ctx.respond(...)` in a slash command already does this: calling it twice is safe. Another classic cause: two routers or two `on_interaction` handling the same click. Keep a single entry point. ### 50035: Invalid Form Body The message breaks one of Discord's limits. The `In data...` line says which. The most common: | Discord message | Limit | Fix | | --- | --- | --- | | `components.N.components: Must be 5 or fewer in length` | 5 buttons per row | `create_auto_rows(buttons)` | | `components: Must be 5 or fewer in length` | 5 rows per message (outside V2) | Pagination, or a menu instead of buttons | | `custom_id ... duplicated` | Unique `custom_id`s in a message | Add data that tells them apart | | `label: Must be 80 or fewer in length` | 80 characters per button | Shorten the text | | `options: Must be 25 or fewer in length` | 25 options per menu | Several menus, or autocomplete | | `placeholder: Must be 150 or fewer in length` | 150 characters | Shorten | | `content: Must be 2000 or fewer in length` | 2000 characters of text | Split, or use a V2 container (4000) | | `value: This field is required` | Menu option without a `value` | `select_option("Text", "value")` | | `The specified component type is invalid in this context` | Misplaced component (a button outside a row, a V2 component in a modal) | Put buttons in `create_action_row` or `.row()` | | `Invalid emoji` | Unknown emoji, or from a server the bot is not in | Unicode emoji, or `"<:name:id>"` from one of the bot's servers | | `Invalid Form Body` on `url` | Invalid URL (link button, image) | Full `https://` URL | > **Tip:** > To see exactly what goes to Discord, print the payload: `print(build_message_payload(components=[...]))`. You will see the raw structure and can count rows and buttons. ### 50013: Missing Permissions ```text discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions ``` The **bot** is not allowed to do this in that channel. Common causes: - Giving a role: it needs "Manage Roles" **and** its role must be above the given role in the server role list. - Sending in a channel: a channel overwrite removes "Send Messages" from the bot. - Kicking or banning someone whose role is higher than the bot's. Check before acting with `@bot_has_permissions(...)`: the user then gets a clear message instead of a failure. ```python @slash.command(description="Give a role") @bot_has_permissions(manage_roles=True) async def give(ctx, member, role): ... ``` ### 50001: Missing Access The bot cannot see the channel (no "View Channel" permission) or is no longer in the server. ### Slash commands do not show up | Situation | Fix | | --- | --- | | Global commands never visible | Invite the bot with the `applications.commands` scope in addition to `bot` | | New command invisible | Without `default_guilds`, global sync can take a while. During development: `SlashManager(client, default_guilds=[SERVER_ID])` | | Command greyed out or missing for some users | `@default_permissions(...)` hides it from members without the permission; server admins can also restrict it in Settings > Integrations | | Old commands duplicated | They were registered globally **and** on the server. Sync once without them, or remove them | ### Errors raised by the module These happen **before** sending, with a French message: | Error | Cause | | --- | --- | | `ValueError: custom_id trop long (…)` | `data=` too large for 100 characters | | `ValueError: Un bouton Premium demande sku_id` | `style="premium"` without `sku_id` | | `ValueError: Une section accepte 3 TextDisplay maximum` | More than 3 texts in `section()` | | `ValueError: Une section doit avoir un accessoire (bouton ou thumbnail)` | `section(...)` without `.thumbnail(...)` or `.button(...)` | | `ValueError: Une modale accepte 5 composants maximum` | More than 5 fields in `ModalBuilder` | | `ValueError: Les embeds sont interdits avec les composants V2 : utilise un container` | An `embed=` in a message that holds a container | | `ValueError: embed et embeds sont exclusifs` | `embed=` and `embeds=` together | | `TypeError: Destination non supportée` | `send_message` received something other than a channel, a member or a context | ### Slash command errors The module turns refusals into exceptions you can customise with `@slash.on_error`. Without a handler, the user gets an ephemeral English message. ```python from discord_interactions.slash import ( BotMissingPermissions, CheckFailure, CommandOnCooldown, InvalidOption, MissingPermissions, NotInGuild, ) @slash.on_error async def errors(ctx, error): if isinstance(error, CommandOnCooldown): message = f"Slow down: try again in {error.retry_after:.0f} s." elif isinstance(error, MissingPermissions): message = "You are missing: " + ", ".join(error.missing_permissions) elif isinstance(error, BotMissingPermissions): message = "I am missing: " + ", ".join(error.missing_permissions) elif isinstance(error, NotInGuild): message = "This command only works in a server." elif isinstance(error, InvalidOption): message = f"Invalid value: {error}" elif isinstance(error, CheckFailure): message = error.message else: return False # unexpected error: default handling (log + generic message) await ctx.respond(message, ephemeral=True) return True ``` Returning `False` lets the module handle the error: it is logged with the full traceback, and the user sees a generic message. ### See what happens Enable logs to follow every command and error in the console: ```python import logging logging.basicConfig(level=logging.INFO) logging.getLogger("discord_interactions").setLevel(logging.DEBUG) ``` ## 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](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/introduction/). 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. ```python from discord_interactions import container, create_button, respond_to_interaction, update_message from 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. ```python 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_id`s. ### Support tickets A permanent button opens a modal; on submit, the bot creates a private thread with the person. ```python import discord from discord_interactions import ModalBuilder, container, create_button, respond_to_interaction, send_message, send_modal from 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. ```python 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. ```python 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. ```python 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=[]) ``` ## Using with an AI Give the whole documentation to Claude, ChatGPT, Cursor or Copilot so they write correct code. An AI does not know this module, or knows an old version: it will invent functions or fall back to `discord.ui.View`. The fix: give it the full documentation, prepared for it. ### Files for AI | File | Content | Size | When to use it | | --- | --- | --- | --- | | [`/llms-small.txt`](https://discordpy.levraiberet.ovh/llms-small.txt) | The rules, a minimal bot and every function signature | ~13,000 tokens | **The default choice**: fits any AI, even free plans | | [`/llms-full.txt`](https://discordpy.levraiberet.ovh/llms-full.txt) | Every guide, the whole reference and every example | ~54,000 tokens | Claude, paid ChatGPT, Gemini: the most complete | | [`/llms-full-fr.txt`](https://discordpy.levraiberet.ovh/llms-full-fr.txt) | The same in French | ~55,000 tokens | If you want answers using the French terms | | [`/llms.txt`](https://discordpy.levraiberet.ovh/llms.txt) | The rules and a link to every page | ~6,000 tokens | The AI browses the web and opens only what it needs | | [`/AGENTS.md`](https://discordpy.levraiberet.ovh/AGENTS.md) | The rules, ready to drop into a project | ~1,000 tokens | Claude Code, Cursor, Copilot, Codex (see below) | | [`/reference.json`](https://discordpy.levraiberet.ovh/reference.json) | The whole API as JSON: signature, summary, example, URLs | | Tools and scripts | Every page of these docs also exists as Markdown: add `index.md` to its URL (for example [`…/api/create_button/index.md`](https://discordpy.levraiberet.ovh/docs/en/0.3.0/api/create_button/index.md)). It is the version an AI reads best, without menus or layout. All these files are regenerated with every release of the docs: they always describe the latest version of the module. ### With Claude or ChatGPT (in the browser) Download `llms-small.txt` (or `llms-full.txt` for Claude), attach it to your conversation, then ask what you need: ```text Here is the documentation of the discord-interactions-py module (attached). Only use this module for components, not discord.ui. Write a /poll command with two Yes / No buttons that count votes and update the message. ``` If the AI can browse the web, the address is enough: `Read https://discordpy.levraiberet.ovh/llms-small.txt before answering.` ### With Claude Code, Cursor or Copilot (in your project) Add an instructions file at the root of your project, which the tool reads automatically: | Tool | File | | --- | --- | | Claude Code | `CLAUDE.md` | | Cursor | `.cursor/rules/discord.mdc` | | GitHub Copilot | `.github/copilot-instructions.md` | | Codex, Windsurf, others | `AGENTS.md` | The [`AGENTS.md`](https://discordpy.levraiberet.ovh/AGENTS.md) file is ready: the ten rules of the module, a minimal bot and the docs address to read before writing code. Download it under the name your tool expects: ```bash curl -o AGENTS.md https://discordpy.levraiberet.ovh/AGENTS.md ``` If the instructions file already exists, append to it instead of overwriting it: ```bash curl https://discordpy.levraiberet.ovh/AGENTS.md >> CLAUDE.md ``` In Cursor you can also add the docs as a source: **Settings > Features > Docs > Add new doc**, with the address `https://discordpy.levraiberet.ovh/llms-full.txt`. Give it a name, then type `@` followed by that name in the chat to load it. ### Why it works better Every file starts with ten rules written for an AI: import name, single router, 3-second deadline, a single response, Discord limits, no `discord.ui`. These are exactly the mistakes an AI makes without them. Then come the exact signatures of every function and, in the full version, the guides and one example per function. The AI has nothing left to guess. > **Tip:** > If the AI's code fails, paste the full console message (with the Discord error code, such as `50035`): the [Common errors](https://discordpy.levraiberet.ovh/docs/en/0.3.0/guides/erreurs/) page is part of the file, so it can find the cause. ## Upgrading to 0.3 What changes between 0.2 and 0.3, and what to adapt. Code written for 0.2 runs on 0.3: every public import still exists. Four points need your attention. ### 1. Python 3.9 and discord.py 2.6 ```bash pip install -U levraiberet-discord-interactions ``` ### 2. Entity options arrive as objects In 0.2, `User`, `Channel`, `Role`, `Mentionable` and `Attachment` gave an ID. In 0.3, you receive the discord.py object directly. ```python # 0.2 async def profile(ctx, member): member = ctx.bot.get_user(int(member)) or await ctx.bot.fetch_user(int(member)) # 0.3 async def profile(ctx, member): await ctx.respond(member.display_name) ``` ### 3. Default components are lighter Fields at their default value are no longer sent (`"disabled": False`, `"required": True`). Discord applies the same values; only code inspecting the generated dicts can notice. ### 4. Error handlers can hand over An `@slash.on_error` returning `False` lets the default handling respond. Any other return value, `None` included, keeps the 0.2 behavior. ### Fixed without any change - Autocompletes declared through `String(..., autocomplete=...)` are called. - `DynamicCooldown` works, and two simultaneous calls no longer bypass a cooldown. - Option, cooldown and permission decorators work on group subcommands. - `content` with components V2 is converted instead of being rejected by Discord. - `owner_only()` without a list reads the application's owners. ### Deprecated `PseudoContainerBuilder` and the `pseudo*` functions imitate containers with embeds. Replace them with `container()`: they will be removed in 0.4. ## Reference: Buttons ### create_button Creates a button. Values passed in `data` travel inside the `custom_id` and come back on click. `from discord_interactions import create_button` ```python def create_button( custom_id: str = '', label: str = '', style: str | int = 1, emoji: str | Dict[str, Any] | Any | None = None, data: Dict[str, Any] | None = None, disabled: bool = False, url: str | None = None, sku_id: int | str | None = None, component_id: int | None = None, ) -> Dict[str, Any] ``` - `custom_id`: Base identifier, sent back on click. Must be unique within the message. - `label`: Button text (80 characters max). - `style`: Style: a name (`"primary"`, `"success"`, `"danger"`) or a `ButtonStyle` number. - `emoji`: Unicode emoji, custom emoji `"<:name:id>"`, dict or `discord.PartialEmoji`. - `data`: JSON dict embedded in the `custom_id` (100 characters in total). - `disabled`: Greyed out and not clickable. - `url`: External link: the button becomes a Link button. - `sku_id`: SKU to purchase: the button becomes a Premium button. - `component_id`: Optional numeric identifier, unique within the message. ```python from discord_interactions import create_action_row, create_button button = create_button( "buy", "Buy", style="success", emoji="<:coin:123456789012345678>", data={"item": 42}, ) await ctx.respond("Shop", components=[create_action_row(button)]) ``` ### create_link_button Button that opens a URL. No event reaches the bot. `from discord_interactions import create_link_button` ```python def create_link_button( url: str, label: str = '', emoji: str | Dict[str, Any] | Any | None = None, disabled: bool = False, ) -> Dict[str, Any] ``` - `url`: Address opened on click (512 characters max). ```python from discord_interactions import create_action_row, create_link_button link = create_link_button("https://discord.com/developers/docs", "Discord documentation") await ctx.respond(components=[create_action_row(link)]) ``` ### create_premium_button Purchase button for one of your application's SKUs (Discord monetization). `from discord_interactions import create_premium_button` ```python def create_premium_button(sku_id: int | str, disabled: bool = False) -> Dict[str, Any] ``` - `sku_id`: SKU identifier. ```python from discord_interactions import container, create_premium_button await ctx.respond(components=[container("## Premium pass").row(create_premium_button(1234567890123456789))]) ``` ## Reference: Select menus ### create_channel_select_menu Channel select menu, filterable by type. `from discord_interactions import create_channel_select_menu` ```python def create_channel_select_menu( custom_id: str, placeholder: str | None = 'Select channels', min_values: int | None = 1, max_values: int | None = 1, disabled: bool = False, default_values: Sequence[Any] | None = None, channel_types: Sequence[int] | None = None, required: bool | None = None, component_id: int | None = None, ) -> Dict[str, Any] ``` - `channel_types`: Accepted types, for example `ChannelTypes.TEXT_CHANNELS`. ```python from discord_interactions import ChannelTypes, create_action_row, create_channel_select_menu menu = create_channel_select_menu("logs", "Log channel", channel_types=ChannelTypes.TEXT_CHANNELS) await ctx.respond(components=[create_action_row(menu)]) ``` ### create_entity_select_menu Generic entity select menu: users (5), roles (6), mentionables (7) or channels (8). `from discord_interactions import create_entity_select_menu` ```python def create_entity_select_menu( custom_id: str, select_type: int, placeholder: str | None = 'Select', min_values: int | None = 1, max_values: int | None = 1, disabled: bool = False, default_values: Sequence[Any] | None = None, channel_types: Sequence[int] | None = None, required: bool | None = None, component_id: int | None = None, ) -> Dict[str, Any] ``` - `select_type`: Menu type: 5, 6, 7 or 8. - `default_values`: Pre-selected entities: IDs, discord.py objects or `{"id", "type"}` dicts. - `channel_types`: Channel types offered (channel menus only). ```python from discord_interactions import ComponentType, create_action_row, create_entity_select_menu # Generic version: select_type picks the kind of menu. # Same as create_role_select_menu("staff", "Staff role"). menu = create_entity_select_menu("staff", ComponentType.RoleSelect, placeholder="Staff role") await ctx.respond(components=[create_action_row(menu)]) ``` ### create_mentionable_select_menu Select menu mixing users and roles. `from discord_interactions import create_mentionable_select_menu` ```python def create_mentionable_select_menu( custom_id: str, placeholder: str | None = 'Select mentionables', min_values: int | None = 1, max_values: int | None = 1, disabled: bool = False, default_values: Sequence[Any] | None = None, required: bool | None = None, component_id: int | None = None, ) -> Dict[str, Any] ``` ```python from discord_interactions import create_action_row, create_mentionable_select_menu, parse_values # A menu offering both members and roles menu = create_mentionable_select_menu("ping", "Who should be notified?", max_values=5) await ctx.respond(components=[create_action_row(menu)]) @router.select("ping") async def ping(interaction): targets = parse_values(interaction).mentionables("ping") # members and roles mixed await respond_to_interaction(interaction, " ".join(t.mention for t in targets)) ``` ### create_role_select_menu Role select menu. `from discord_interactions import create_role_select_menu` ```python def create_role_select_menu( custom_id: str, placeholder: str | None = 'Select roles', min_values: int | None = 1, max_values: int | None = 1, disabled: bool = False, default_values: Sequence[Any] | None = None, required: bool | None = None, component_id: int | None = None, ) -> Dict[str, Any] ``` ```python from discord_interactions import create_action_row, create_role_select_menu, parse_values # 1. Send: a menu listing the server's roles menu = create_role_select_menu("auto_roles", "Pick your roles", min_values=0, max_values=3) await ctx.respond("Which roles do you want?", components=[create_action_row(menu)]) # 2. Receive: read the chosen roles @router.select("auto_roles") async def auto_roles(interaction): roles = parse_values(interaction).roles("auto_roles") await interaction.user.add_roles(*roles) await respond_to_interaction(interaction, f"{len(roles)} role(s) added.", ephemeral=True) ``` ### create_select_menu Text select menu (25 options max). Options accept dicts, tuples or strings. `from discord_interactions import create_select_menu` ```python def create_select_menu( custom_id: str, placeholder: str | None = 'Select an option', options: Sequence[Any] | None = None, min_values: int | None = 1, max_values: int | None = 1, disabled: bool = False, required: bool | None = None, component_id: int | None = None, ) -> Dict[str, Any] ``` - `custom_id`: Identifier sent back with the selected values. - `placeholder`: Text shown while nothing is selected. - `options`: Options: `select_option(...)`, dicts, tuples `(label, value, description, emoji, default)` or strings. - `min_values`: Minimum number of choices (0 to 25). - `max_values`: Maximum number of choices (1 to 25). - `disabled`: Greyed out menu (messages only). - `required`: Choice required (modals only). ```python from discord_interactions import create_action_row, create_select_menu, select_option menu = create_select_menu( "language", placeholder="Your language", options=[ select_option("Python", "py", emoji="🐍"), select_option("Rust", "rs", emoji="🦀"), "JavaScript", ], ) await ctx.respond(components=[create_action_row(menu)]) ``` ### create_user_select_menu User or member select menu. `from discord_interactions import create_user_select_menu` ```python def create_user_select_menu( custom_id: str, placeholder: str | None = 'Select users', min_values: int | None = 1, max_values: int | None = 1, disabled: bool = False, default_values: Sequence[Any] | None = None, required: bool | None = None, component_id: int | None = None, ) -> Dict[str, Any] ``` ```python from discord_interactions import create_action_row, create_user_select_menu menu = create_user_select_menu("team", "Pick your teammates", max_values=4, default_values=[ctx.user]) await ctx.respond(components=[create_action_row(menu)]) ``` ### default_value Pre-selected value of an entity select menu. `from discord_interactions import default_value` ```python def default_value(value: Any, kind: str) -> Dict[str, str] ``` - `value`: ID, discord.py object or ready-made dict. - `kind`: `"user"`, `"role"` or `"channel"`. ```python from discord_interactions import create_action_row, create_role_select_menu, default_value # Pre-select values when the menu opens (here: the role already configured) current_role = 123456789012345678 menu = create_role_select_menu( "welcome_role", "Role given to newcomers", default_values=[default_value(current_role, "role")], ) await ctx.respond(components=[create_action_row(menu)]) ``` ### select_option Option for a select menu, a radio group or a checkbox group. `from discord_interactions import select_option` ```python def select_option( label: str, value: str | None = None, description: str | None = None, emoji: str | Dict[str, Any] | Any | None = None, default: bool | None = None, ) -> Dict[str, Any] ``` - `label`: Displayed text (100 characters max). - `value`: Value sent to the bot; defaults to the label. - `description`: Secondary text under the label. - `emoji`: Emoji shown before the option (select menus only). - `default`: Pre-selected option. ```python from discord_interactions import create_action_row, create_select_menu, select_option # label = text shown, value = what your code receives menu = create_select_menu( "pizza", placeholder="Your pizza", options=[ select_option("Margherita", "marg", description="Tomato, mozzarella", emoji="🍅"), select_option("Four cheese", "4c", default=True), # already selected select_option("Veggie"), # value = label when omitted ], ) await ctx.respond(components=[create_action_row(menu)]) ``` ## Reference: Builders ### ActionRowBuilder Action row builder. `from discord_interactions import ActionRowBuilder` ```python class ActionRowBuilder(*components: Any) -> None ``` - `def addComponents(*components: Any) -> ActionRowBuilder` - `def to_dict() -> Dict[str, Any]` - `def id(component_id: int)` - `def build() -> Dict[str, Any]` ```python from discord_interactions import ActionRowBuilder, create_button row = ActionRowBuilder(create_button("yes", "Yes", style="success")).addComponents( create_button("no", "No", style="danger") ) await ctx.respond("Are you sure?", components=[row.build()]) ``` ### ContainerBuilder Chainable container V2 builder. Every method returns the builder; finish with `build()`. `from discord_interactions import ContainerBuilder` ```python class ContainerBuilder( *components: Any, accent_color: int | None = None, spoiler: bool = False, ) -> None ``` - `components`: Initial components; a string becomes a text block. - `accent_color`: Border color. - `spoiler`: Hidden until clicked. - `def setAccentColor(color: int | None) -> ContainerBuilder` - `def setSpoiler(spoiler: bool = True) -> ContainerBuilder` - `def add(*components: Any) -> ContainerBuilder`: Adds components or texts, in order. - `def addTextDisplayComponents(*text_displays: Any) -> ContainerBuilder` - `def addSeparatorComponents(separator: Any | None = None) -> ContainerBuilder` - `def addSectionComponents(*sections: Any) -> ContainerBuilder` - `def addMediaGalleryComponents(*galleries: Any) -> ContainerBuilder` - `def addFileComponents(*files: Any) -> ContainerBuilder` - `def addActionRowComponents(action_row: Any) -> ContainerBuilder` - `def text(content: str) -> ContainerBuilder`: Adds a text block. - `def separator(divider: bool = True, spacing: int | str = 1) -> ContainerBuilder`: Adds a separator. - `def gallery(*urls: Any) -> ContainerBuilder`: Adds a gallery from URLs. - `def file(filename: str, spoiler: bool = False) -> ContainerBuilder`: Adds an attached file. - `def row(*components: Any) -> ContainerBuilder`: Adds a row of buttons or a select menu. - `def to_dict() -> Dict[str, Any]` - `def id(component_id: int)` - `def build() -> Dict[str, Any]`: Returns the container dict. ```python from discord_interactions import ContainerBuilder, textDisplay card = ( ContainerBuilder() .setAccentColor(0x57F287) .addTextDisplayComponents(textDisplay("## discord.js style")) .addSeparatorComponents() .addTextDisplayComponents(textDisplay("camelCase names are available too.")) .build() ) ``` ### FileBuilder Attached file builder. `from discord_interactions import FileBuilder` ```python class FileBuilder(filename: str = '', spoiler: bool = False) -> None ``` - `def setFile(filename: str) -> FileBuilder` - `def setSpoiler(spoiler: bool = True) -> FileBuilder` - `def to_dict() -> Dict[str, Any]` - `def id(component_id: int)` - `def build() -> Dict[str, Any]` ```python import discord from discord_interactions import ContainerBuilder, FileBuilder # The file is sent as an attachment, then shown in the container through attachment:// file = discord.File("export.csv") card = ContainerBuilder().addTextDisplayComponents("## Export").addFileComponents( FileBuilder().setFile("export.csv") ) await ctx.respond(components=[card.build()], files=[file]) ``` ### MediaGalleryBuilder Gallery builder; `add()` appends an image with alt text or spoiler. `from discord_interactions import MediaGalleryBuilder` ```python class MediaGalleryBuilder(*urls: Any) -> None ``` - `def addItem(url: Any, description: str | None = None, spoiler: bool = False) -> MediaGalleryBuilder` - `def to_dict() -> Dict[str, Any]` - `def id(component_id: int)` - `def build() -> Dict[str, Any]` ```python from discord_interactions import ContainerBuilder, MediaGalleryBuilder gallery = ( MediaGalleryBuilder() .addItem("https://example.com/before.png", description="Before") .addItem("https://example.com/after.png", description="After") ) await ctx.respond(components=[ContainerBuilder().addMediaGalleryComponents(gallery).build()]) ``` ### SectionBuilder Section builder: texts on the left, button or thumbnail on the right. `from discord_interactions import SectionBuilder` ```python class SectionBuilder() -> None ``` - `def addTextDisplayComponents(*text_displays: Any) -> SectionBuilder` - `def setButtonAccessory(button: Any) -> SectionBuilder` - `def setThumbnailAccessory(thumbnail: Any, description: str | None = None) -> SectionBuilder` - `def accessory(component: Any) -> SectionBuilder` - `def to_dict() -> Dict[str, Any]` - `def id(component_id: int)` - `def build() -> Dict[str, Any]` ```python from discord_interactions import ContainerBuilder, SectionBuilder, create_button # A section = 1 to 3 texts on the left + a button or a thumbnail on the right row = ( SectionBuilder() .addTextDisplayComponents("**Starter pack**", "500 coins") .setButtonAccessory(create_button("buy_pack", "Buy", style="success")) ) await ctx.respond(components=[ContainerBuilder().addSectionComponents(row).build()]) ``` ### SeparatorBuilder Separator builder. `from discord_interactions import SeparatorBuilder` ```python class SeparatorBuilder(divider: bool = True, spacing: int | str = 1) -> None ``` - `def setDivider(divider: bool) -> SeparatorBuilder` - `def setSpacing(spacing: int | str) -> SeparatorBuilder` - `def to_dict() -> Dict[str, Any]` - `def id(component_id: int)` - `def build() -> Dict[str, Any]` ```python from discord_interactions import ContainerBuilder, SeparatorBuilder, SeparatorSpacing card = ( ContainerBuilder() .addTextDisplayComponents("## Part 1") .addSeparatorComponents(SeparatorBuilder().setSpacing(SeparatorSpacing.Large)) .addTextDisplayComponents("## Part 2") ) ``` ### TextDisplayBuilder Text block builder. `from discord_interactions import TextDisplayBuilder` ```python class TextDisplayBuilder(content: str = '') -> None ``` - `def setContent(content: str) -> TextDisplayBuilder` - `def to_dict() -> Dict[str, Any]` - `def id(component_id: int)` - `def build() -> Dict[str, Any]` ```python from discord_interactions import ContainerBuilder, TextDisplayBuilder text = TextDisplayBuilder().setContent("**Bold**, *italic* and `code`: Markdown works.") await ctx.respond(components=[ContainerBuilder().addTextDisplayComponents(text).build()]) ``` ### ThumbnailBuilder Thumbnail builder. `from discord_interactions import ThumbnailBuilder` ```python class ThumbnailBuilder( url: Any = '', description: str | None = None, spoiler: bool = False, ) -> None ``` - `def setURL(url: Any) -> ThumbnailBuilder` - `def setDescription(description: str | None) -> ThumbnailBuilder` - `def setSpoiler(spoiler: bool = True) -> ThumbnailBuilder` - `def to_dict() -> Dict[str, Any]` - `def id(component_id: int)` - `def build() -> Dict[str, Any]` ```python from discord_interactions import SectionBuilder, ThumbnailBuilder # Thumbnail on the right of a section, for example a member's avatar avatar = ThumbnailBuilder().setURL(member.display_avatar.url).setDescription("Avatar") row = SectionBuilder().addTextDisplayComponents(f"## {member.display_name}").setThumbnailAccessory(avatar) ``` ### actionRow Shortcut for `ActionRowBuilder(*components)`. `from discord_interactions import actionRow` ```python def actionRow(*components: Any) -> ActionRowBuilder ``` ```python from discord_interactions import actionRow, create_button await ctx.respond(components=[actionRow(create_button("a", "A"), create_button("b", "B")).build()]) ``` ### container Shortcut for `ContainerBuilder(...)`. `from discord_interactions import container` ```python def container( *components: Any, accent_color: int | None = None, spoiler: bool = False, ) -> ContainerBuilder ``` ```python from discord_interactions import container, create_button, section card = ( container(accent_color=0x5865F2) .add("## Minecraft server") .add(section("**Online**", "12 players").thumbnail("https://example.com/logo.png")) .separator() .row(create_button("join", "Join", style="success")) ) await ctx.respond(components=[card]) ``` ### fileComponent Shortcut for `FileBuilder(filename, spoiler)`. `from discord_interactions import fileComponent` ```python def fileComponent(filename: str, spoiler: bool = False) -> FileBuilder ``` ```python import discord from discord_interactions import container, fileComponent card = container("## Invoice").add(fileComponent("invoice.pdf")) await ctx.respond(components=[card], files=[discord.File("invoice.pdf")]) ``` ### mediaGallery Shortcut for `MediaGalleryBuilder(*urls)`. `from discord_interactions import mediaGallery` ```python def mediaGallery(*urls: Any) -> MediaGalleryBuilder ``` ```python from discord_interactions import container, mediaGallery gallery = mediaGallery("https://example.com/1.png", "https://example.com/2.png").add( "https://example.com/3.png", description="Preview", spoiler=True ) await ctx.respond(components=[container("## Screenshots").add(gallery)]) ``` ### section Shortcut for `SectionBuilder` with its texts. `from discord_interactions import section` ```python def section(*texts: Any) -> SectionBuilder ``` ```python from discord_interactions import create_button, section row = section("**Notifications**", "Get a message for every announcement.").button( create_button("notify", "Enable", style="secondary") ) ``` ### separator Shortcut for `SeparatorBuilder(divider, spacing)`. `from discord_interactions import separator` ```python def separator(divider: bool = True, spacing: int | str = 1) -> SeparatorBuilder ``` ```python from discord_interactions import container, separator card = container("Before").add(separator(spacing="large")).add("After").add(separator(divider=False)).add("End") ``` ### textDisplay Shortcut for `TextDisplayBuilder(content)`. `from discord_interactions import textDisplay` ```python def textDisplay(content: str = '') -> TextDisplayBuilder ``` ```python from discord_interactions import textDisplay # A text on its own, without a container: it looks like a normal message await ctx.respond(components=[textDisplay("Hello **everyone**").build()]) ``` ### thumbnail Shortcut for `ThumbnailBuilder(url, description, spoiler)`. `from discord_interactions import thumbnail` ```python def thumbnail( url: Any, description: str | None = None, spoiler: bool = False, ) -> ThumbnailBuilder ``` ```python from discord_interactions import section, thumbnail row = section("## Weather", "18 °C, sunny").accessory(thumbnail("https://example.com/sun.png")) ``` ## Reference: Components V2 ### create_action_row Action row (type 1): up to 5 buttons or a single select menu. `from discord_interactions import create_action_row` ```python def create_action_row( *components: Any, component_id: int | None = None, ) -> Dict[str, Any] ``` ```python from discord_interactions import create_action_row, create_button # Up to 5 buttons per row, or a single select menu row = create_action_row( create_button("prev", "◀"), create_button("next", "▶"), ) await ctx.respond("Page 1/3", components=[row]) ``` ### create_button_row Row of buttons. Same as `create_action_row`. `from discord_interactions import create_button_row` ```python def create_button_row(*buttons: Any) -> Dict[str, Any] ``` ```python from discord_interactions import create_button, create_button_row row = create_button_row(create_button("yes", "Yes"), create_button("no", "No")) await ctx.respond("Continue?", components=[row]) ``` ### create_container Container (type 17): the card grouping components V2. A string becomes a text block. `from discord_interactions import create_container` ```python def create_container( *components: Any, accent_color: int | None = None, spoiler: bool = False, component_id: int | None = None, ) -> Dict[str, Any] ``` - `accent_color`: Border color as an RGB integer (`0x5865F2`). - `spoiler`: Hidden until clicked. ```python from discord_interactions import create_container, create_separator, create_text_display_component card = create_container( create_text_display_component("## Rules"), create_separator(), create_text_display_component("1. Be respectful\n2. No spam"), accent_color=0xED4245, ) await ctx.respond(components=[card]) ``` ### create_file Attached file shown in the message (type 13). Send the file itself with `files=`. `from discord_interactions import create_file` ```python def create_file( filename: str, spoiler: bool = False, component_id: int | None = None, ) -> Dict[str, Any] ``` - `filename`: Name of the attached file; `attachment://` is added when missing. - `spoiler`: Hidden until clicked. ```python import discord from discord_interactions import container, create_file file = discord.File("report.pdf") card = container("## Monthly report").add(create_file("report.pdf")) await ctx.respond(components=[card], files=[file]) ``` ### create_media_gallery Gallery of 1 to 10 images or videos (type 12). `from discord_interactions import create_media_gallery` ```python def create_media_gallery(*items: Any, component_id: int | None = None) -> Dict[str, Any] ``` ```python from discord_interactions import create_container, create_media_gallery, create_media_item gallery = create_media_gallery( "https://example.com/1.png", # a URL is enough ("https://example.com/2.png", "With a caption"), # or (url, description) create_media_item("https://example.com/3.png", spoiler=True), # or a full item ) await ctx.respond(components=[create_container(gallery)]) ``` ### create_media_item Gallery item: media, alt text and spoiler. `from discord_interactions import create_media_item` ```python def create_media_item( url: str | Dict[str, Any], description: str | None = None, spoiler: bool = False, ) -> Dict[str, Any] ``` ```python from discord_interactions import create_media_gallery, create_media_item image = create_media_item("https://example.com/spoiler.png", description="Movie ending", spoiler=True) gallery = create_media_gallery(image) ``` ### create_modal_row Modal row in the legacy format (ActionRow + TextInput). `from discord_interactions import create_modal_row` ```python def create_modal_row(component: Any) -> Dict[str, Any] ``` ```python from discord_interactions import create_modal_row, create_text_input # Old modal format: each field in its own row row = create_modal_row(create_text_input("username", "Username")) ``` ### create_section Section (type 9): 1 to 3 texts with an accessory, button or thumbnail. `from discord_interactions import create_section` ```python def create_section( *texts: Any, accessory: Any, component_id: int | None = None, ) -> Dict[str, Any] ``` - `accessory`: Button or thumbnail shown on the right. ```python from discord_interactions import create_button, create_section row = create_section( "**Music**", "Now playing: Lo-fi", accessory=create_button("pause", "Pause", style="secondary"), ) ``` ### create_select_row Row holding a select menu. `from discord_interactions import create_select_row` ```python def create_select_row(select_menu: Any) -> Dict[str, Any] ``` ```python from discord_interactions import create_select_menu, create_select_row row = create_select_row(create_select_menu("size", options=["S", "M", "L"])) await ctx.respond(components=[row]) ``` ### create_separator Separator (type 14): divider line and vertical spacing. `from discord_interactions import create_separator` ```python def create_separator( divider: bool = True, spacing: int | str = 1, component_id: int | None = None, ) -> Dict[str, Any] ``` - `divider`: Draw a line; `False` leaves plain space. - `spacing`: `"small"` / 1 or `"large"` / 2. ```python from discord_interactions import create_separator line = create_separator() # thin line space = create_separator(divider=False, spacing=2) # large gap without a line ``` ### create_text_display_component Markdown text block (type 10), up to 4000 characters. `from discord_interactions import create_text_display_component` Aliases: `create_text_display` ```python def create_text_display_component( content: str, component_id: int | None = None, ) -> Dict[str, Any] ``` - `content`: Markdown text: `#` headings, lists, `-#` for subtle text. ```python from discord_interactions import create_text_display_component text = create_text_display_component("# Title\nThe text supports **Markdown**.") # {"type": 10, "content": "# Title\nThe text supports **Markdown**."} ``` ### create_thumbnail Thumbnail (type 11), used as the accessory of a section. `from discord_interactions import create_thumbnail` ```python def create_thumbnail( url: str | Dict[str, Any], description: str | None = None, spoiler: bool = False, component_id: int | None = None, ) -> Dict[str, Any] ``` - `url`: Image URL, `attachment://file.png` or media dict. - `description`: Alt text (1024 characters max). - `spoiler`: Blurred until clicked. ```python from discord_interactions import create_section, create_thumbnail row = create_section("## Profile", accessory=create_thumbnail(ctx.user.display_avatar.url)) ``` ### disable_all_components Copy of the components with every button and select disabled, at any depth. `from discord_interactions import disable_all_components` ```python def disable_all_components(components: Sequence[Any]) -> List[Dict[str, Any]] ``` ```python from discord_interactions import disable_all_components # After a vote: grey out every button of the message, without removing anything @router.on("vote") async def vote(interaction, data): disabled = disable_all_components(interaction.message.components) await update_message(interaction, components=disabled) ``` ## Reference: Modal fields ### create_checkbox Single yes or no checkbox. Always optional. `from discord_interactions import create_checkbox` ```python def create_checkbox( custom_id: str, default: bool = False, component_id: int | None = None, ) -> Dict[str, Any] ``` - `default`: Checked by default. ```python from discord_interactions import create_checkbox, create_label_component, create_modal rules = create_label_component("I accept the rules", component=create_checkbox("rules")) await send_modal(interaction, create_modal("signup", "Sign up", rules)) @router.modal("signup") async def signup(interaction, values): if not values["rules"]: # checkbox: True or False return await respond_to_interaction(interaction, "You must accept the rules.", ephemeral=True) ``` ### create_checkbox_group Checkbox group (1 to 10 options, multiple choices). `from discord_interactions import create_checkbox_group` ```python def create_checkbox_group( custom_id: str, options: Sequence[Any], placeholder: str | None = None, min_values: int | None = 0, max_values: int | None = None, disabled: bool = False, required: bool = False, component_id: int | None = None, ) -> Dict[str, Any] ``` - `min_values`: Minimum number of boxes; 0 makes the group optional. - `max_values`: Maximum number of boxes; all of them by default. ```python from discord_interactions import create_checkbox_group, create_label_component, create_modal interests = create_checkbox_group("interests", ["Games", "Music", "Code", "Drawing"], max_values=3) await send_modal(interaction, create_modal("profile", "Profile", create_label_component("Your interests", component=interests))) @router.modal("profile") async def profile(interaction, values): chosen = values["interests"] # list, for example ["Games", "Code"] ``` ### create_file_upload_component File upload inside a modal (0 to 10 files), filterable by type. `from discord_interactions import create_file_upload_component` ```python def create_file_upload_component( custom_id: str, min_values: int | None = None, max_values: int | None = None, required: bool = True, file_types: Sequence[str] | None = None, component_id: int | None = None, ) -> Dict[str, Any] ``` - `min_values`: Minimum number of files (0 to 10). - `max_values`: Maximum number of files (1 to 10). - `file_types`: Accepted types: `"image"`, `"video"`, `"audio"` or extensions such as `".pdf"` (10 max). ```python from discord_interactions import create_file_upload_component, create_label_component, create_modal screenshots = create_file_upload_component("screenshots", max_values=3, file_types=["image"]) await send_modal(interaction, create_modal("bug", "Report a bug", create_label_component("Screenshots", component=screenshots))) @router.modal("bug") async def bug(interaction, values): files = values.attachments("screenshots") # discord.Attachment objects await respond_to_interaction(interaction, f"{len(files)} screenshot(s) received.", ephemeral=True) ``` ### create_label_component Label (type 18): title and description around a modal field. The modern format recommended by Discord. `from discord_interactions import create_label_component` Aliases: `create_label` ```python def create_label_component( label: str, description: str | None = None, component: Any | None = None, component_id: int | None = None, ) -> Dict[str, Any] ``` - `label`: Field title (45 characters max). - `description`: Help text under the title (100 characters max). - `component`: Wrapped field: text input, select, radio group, checkboxes, checkbox or file upload. ```python from discord_interactions import create_label_component, create_modal, create_text_input field = create_label_component( "Your age", description="You must be 13 or older", # small grey text under the title component=create_text_input("age", max_length=3), ) modal = create_modal("signup", "Sign up", field) ``` ### create_modal Complete modal as a dict. Bare fields are wrapped in a Label automatically. `from discord_interactions import create_modal` ```python def create_modal( custom_id: str, title: str, *components: Any, strict_text_inputs: bool = False, ) -> Dict[str, Any] ``` - `custom_id`: Identifier sent back on submit. - `title`: Window title (45 characters max). - `strict_text_inputs`: Legacy format: keep text inputs only. ```python from discord_interactions import create_modal, create_text_input, send_modal # Each field automatically gets a title (its label) modal = create_modal( "contact", "Contact us", create_text_input("email", "Email", placeholder="you@example.com"), create_text_input("message", "Message", style=2, max_length=1000), ) await send_modal(interaction, modal) ``` ### create_radio_group Radio group (2 to 10 options, single choice). `from discord_interactions import create_radio_group` ```python def create_radio_group( custom_id: str, options: Sequence[Any], placeholder: str | None = None, disabled: bool = False, required: bool = True, component_id: int | None = None, ) -> Dict[str, Any] ``` - `options`: Options: `select_option(...)`, dicts, tuples or strings. - `required`: Choice required. ```python from discord_interactions import create_label_component, create_modal, create_radio_group rating = create_radio_group("rating", ["1", "2", "3", "4", "5"]) await send_modal(interaction, create_modal("review", "Your review", create_label_component("Rating out of 5", component=rating))) @router.modal("review") async def review(interaction, values): rating = int(values["rating"]) # a single choice: a string ``` ### create_text_input Modal text field, short or paragraph. `from discord_interactions import create_text_input` ```python def create_text_input( custom_id: str, label: str | None = None, style: str | int = 1, placeholder: str | None = None, min_length: int | None = None, max_length: int | None = None, required: bool = True, value: str | None = None, component_id: int | None = None, ) -> Dict[str, Any] ``` - `custom_id`: Key of the value in the submission. - `label`: Title in the legacy format (ActionRow). Removed automatically inside a Label. - `style`: `"short"` / `TextInputStyle.Short` or `"paragraph"` / `TextInputStyle.Paragraph`. - `placeholder`: Hint text (100 characters max). - `min_length`: Minimum length (0 to 4000). - `max_length`: Maximum length (1 to 4000). - `required`: Field required. - `value`: Pre-filled value. ```python from discord_interactions import TextInputStyle, create_label_component, create_text_input short = create_text_input("username", "Username", max_length=32) long = create_text_input("bio", "Bio", style=TextInputStyle.Paragraph, required=False) prefilled = create_text_input("city", "City", value="Paris") # value already typed ``` ## Reference: Types and constants ### ButtonStyle Button styles: `Primary` (1), `Secondary` (2), `Success` (3), `Danger` (4), `Link` (5) and `Premium` (6). `from discord_interactions import ButtonStyle` `Primary = 1`, `Secondary = 2`, `Success = 3`, `Danger = 4`, `Link = 5`, `Premium = 6` ```python from discord_interactions import ButtonStyle, create_button # Both forms are equivalent create_button("ok", "OK", style=ButtonStyle.Success) create_button("ok", "OK", style="success") # Primary (blurple), Secondary (grey), Success (green), Danger (red), Link, Premium ``` ### ComponentType Type numbers of every Discord component, from action row (1) to checkbox (23). `from discord_interactions import ComponentType` `ActionRow = 1`, `Button = 2`, `StringSelect = 3`, `TextInput = 4`, `UserSelect = 5`, `RoleSelect = 6`, `MentionableSelect = 7`, `ChannelSelect = 8`, `Section = 9`, `TextDisplay = 10`, `Thumbnail = 11`, `MediaGallery = 12`, `File = 13`, `Separator = 14`, `Container = 17`, `Label = 18`, `FileUpload = 19`, `RadioGroup = 21`, `CheckboxGroup = 22`, `Checkbox = 23` ```python from discord_interactions import ComponentType # Find out which kind of component triggered the interaction if interaction.data["component_type"] == ComponentType.Button: ... elif interaction.data["component_type"] == ComponentType.StringSelect: ... ``` ### SeparatorSpacing Separator spacing: `Small` (1) or `Large` (2). `from discord_interactions import SeparatorSpacing` `Small = 1`, `Large = 2` ```python from discord_interactions import SeparatorSpacing, separator small = separator(spacing=SeparatorSpacing.Small) large = separator(spacing=SeparatorSpacing.Large) ``` ### TextInputStyle Text input style: `Short` (single line) or `Paragraph` (multiple lines). `from discord_interactions import TextInputStyle` `Short = 1`, `Paragraph = 2` ```python from discord_interactions import TextInputStyle, create_text_input title = create_text_input("title", "Title", style=TextInputStyle.Short) # one line body = create_text_input("body", "Text", style=TextInputStyle.Paragraph) # several lines ``` ### create_component Raw component: `{"type": component_type, **fields}`. Handy for a type the module does not cover yet. `from discord_interactions import create_component` ```python def create_component(component_type: int, **fields: Any) -> Dict[str, Any] ``` - `component_type`: Discord type number (see `ComponentType`). ```python from discord_interactions import ComponentType, create_component # For a component the module does not cover yet: pass the API fields as they are text = create_component(ComponentType.TextDisplay, content="Built by hand") # {"type": 10, "content": "Built by hand"} ``` ## Reference: Building modals ### ModalBuilder Modern modal builder: every field sits in a Label with a title and description. 5 components max. `from discord_interactions import ModalBuilder` ```python class ModalBuilder( custom_id: str, title: str, data: Dict[str, Any] | None = None, ) -> None ``` - `custom_id`: Base identifier, routed by `InteractionRouter.modal()`. - `title`: Window title. - `data`: JSON data embedded in the `custom_id`. - `def add(component: Any, label: str | None = None, description: str | None = None) -> ModalBuilder`: Adds a raw component, wrapped in a Label when `label` is given. - `def text(content: str) -> ModalBuilder`: Adds an introduction text (Markdown). - `def text_input(custom_id: str, label: str, description: str | None = None, *, style: str | int = 1, placeholder: str | None = None, min_length: int | None = None, max_length: int | None = None, required: bool = True, value: str | None = None) -> ModalBuilder`: Adds a short text field. - `def paragraph(custom_id: str, label: str, description: str | None = None, **kwargs: Any) -> ModalBuilder`: Adds a long text field. - `def select(custom_id: str, label: str, options: Sequence[Any], description: str | None = None, *, placeholder: str | None = None, min_values: int | None = None, max_values: int | None = None, required: bool | None = None) -> ModalBuilder`: Adds a text select menu. - `def user_select(custom_id: str, label: str, description: str | None = None, *, placeholder: str | None = None, min_values: int | None = None, max_values: int | None = None, required: bool | None = None, default_values: Sequence[Any] | None = None) -> ModalBuilder`: Adds a user select menu. - `def role_select(custom_id: str, label: str, description: str | None = None, *, placeholder: str | None = None, min_values: int | None = None, max_values: int | None = None, required: bool | None = None, default_values: Sequence[Any] | None = None) -> ModalBuilder`: Adds a role select menu. - `def mentionable_select(custom_id: str, label: str, description: str | None = None, *, placeholder: str | None = None, min_values: int | None = None, max_values: int | None = None, required: bool | None = None, default_values: Sequence[Any] | None = None) -> ModalBuilder`: Adds a user and role select menu. - `def channel_select(custom_id: str, label: str, description: str | None = None, *, placeholder: str | None = None, min_values: int | None = None, max_values: int | None = None, required: bool | None = None, default_values: Sequence[Any] | None = None, channel_types: Sequence[int] | None = None) -> ModalBuilder`: Adds a channel select menu. - `def radio(custom_id: str, label: str, options: Sequence[Any], description: str | None = None, *, required: bool = True) -> ModalBuilder`: Adds a radio group. - `def checkboxes(custom_id: str, label: str, options: Sequence[Any], description: str | None = None, *, min_values: int | None = 0, max_values: int | None = None, required: bool = False) -> ModalBuilder`: Adds a checkbox group. - `def checkbox(custom_id: str, label: str, description: str | None = None, *, default: bool = False) -> ModalBuilder`: Adds a single checkbox. - `def file_upload(custom_id: str, label: str, description: str | None = None, *, min_values: int | None = None, max_values: int | None = None, required: bool = True, file_types: Sequence[str] | None = None) -> ModalBuilder`: Adds a file upload. - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions import ModalBuilder modal = ( ModalBuilder("ticket", "Open a ticket") .text_input("subject", "Subject", max_length=80) .select("category", "Category", ["Billing", "Technical", "Other"]) .paragraph("details", "Details", "Describe your problem", required=False) .file_upload("screenshots", "Screenshots", file_types=["image"], max_values=3, required=False) ) await ctx.send_modal(modal) ``` ## Reference: Reading values ### ModalSubmit Submitted values keyed by `custom_id`. Text and radio as `str`, checkbox as `bool`, everything else as `list`. `from discord_interactions import ModalSubmit` ```python class ModalSubmit(interaction: discord.Interaction) -> None ``` - `def get(custom_id: str, default: Any = None) -> Any`: Value of a field, or `default` when missing or empty. - `def type_of(custom_id: str) -> int | None` - `def to_dict() -> Dict[str, Any]`: Every value in a plain dict. - `def attachments(custom_id: str) -> List[discord.Attachment]`: Uploaded files, as `discord.Attachment`. - `def users(custom_id: str) -> List[discord.Member | discord.User]`: Selected users, as `discord.Member` or `discord.User`. - `def roles(custom_id: str) -> List[discord.Role]`: Selected roles, as `discord.Role`. - `def channels(custom_id: str) -> List[Any]`: Selected channels. - `def mentionables(custom_id: str) -> List[Any]`: Selected users and roles. ```python @router.modal("ticket") async def ticket(interaction, values): subject = values["subject"] category = values["category"][0] screenshots = values.attachments("screenshots") await respond_to_interaction(interaction, f"Ticket “{subject}” ({category}), {len(screenshots)} screenshot(s).") ``` ### get_modal_values Modal values as a `{custom_id: value}` dict. `from discord_interactions import get_modal_values` ```python def get_modal_values(interaction: discord.Interaction) -> Dict[str, Any] ``` ```python from discord_interactions import get_modal_values values = get_modal_values(interaction) # plain dict: {"subject": "...", "details": "..."} ``` ### parse_modal Reads the values of a submitted modal. Same as `parse_values`. `from discord_interactions import parse_modal` ```python def parse_modal(interaction: discord.Interaction) -> ModalSubmit ``` ```python from discord_interactions import parse_modal @client.event async def on_interaction(interaction): if interaction.type == discord.InteractionType.modal_submit: values = parse_modal(interaction) print(values.base_id, values.to_dict()) ``` ### parse_values Reads the values of a modal or a select menu, with entities and files resolved. `from discord_interactions import parse_values` ```python def parse_values(interaction: discord.Interaction) -> ModalSubmit ``` ```python from discord_interactions import parse_values @router.select("members") async def members(interaction): chosen = parse_values(interaction).users("members") await respond_to_interaction(interaction, ", ".join(m.mention for m in chosen), ephemeral=True) ``` ## Reference: Sending and replying ### defer_interaction Acknowledges now to answer later (15 minutes). On a component, `update=True` shows nothing. `from discord_interactions import defer_interaction` ```python async def defer_interaction( interaction: discord.Interaction, update: bool = False, ephemeral: bool = False, thinking: bool = True, ) -> None ``` - `update`: Silent acknowledgement for a component; the message is edited afterwards. - `ephemeral`: The thinking state and the answer are ephemeral. ```python from discord_interactions import defer_interaction, send_followup await defer_interaction(interaction, ephemeral=True) result = await long_computation() await send_followup(interaction, f"Result: {result}", ephemeral=True) ``` ### delete_original_response Deletes the original response, or a followup with `message_id`. `from discord_interactions import delete_original_response` ```python async def delete_original_response( interaction: discord.Interaction, message_id: str | int = '@original', ) -> None ``` ```python await ctx.respond("This message disappears in 5 seconds.") await asyncio.sleep(5) await delete_original_response(ctx.interaction) ``` ### edit_message Edits an existing message. Attachments are kept when `attachments` is omitted. `from discord_interactions import edit_message` ```python async def edit_message( message: discord.Message | discord.InteractionMessage | Any, content: str | None = None, embed: discord.Embed | None = None, embeds: List[discord.Embed] | None = None, components: Dict[str, Any] | Any | Sequence[Dict[str, Any] | Any] | None = None, allowed_mentions: Dict[str, Any] | discord.AllowedMentions | None = None, flags: int | None = None, files: Sequence[discord.File] | None = None, attachments: Sequence[Any] | None = None, **kwargs: Any, ) -> Any ``` - `message`: discord.py message, or any object with `channel` and `id`. - `attachments`: Attachments to keep; `[]` removes them all. ```python from discord_interactions import container, edit_message, send_message message = await send_message(channel, components=[container("## Vote open")]) await asyncio.sleep(3600) await edit_message(message, components=[container("## Vote closed")]) ``` ### edit_original_response Edits the original response, or a followup with `message_id`. `from discord_interactions import edit_original_response` ```python async def edit_original_response( interaction: discord.Interaction, content: str | None = None, embed: discord.Embed | None = None, embeds: List[discord.Embed] | None = None, components: Dict[str, Any] | Any | Sequence[Dict[str, Any] | Any] | None = None, allowed_mentions: Dict[str, Any] | discord.AllowedMentions | None = None, flags: int | None = None, files: Sequence[discord.File] | None = None, attachments: Sequence[Any] | None = None, message_id: str | int = '@original', ) -> Dict[str, Any] ``` ```python @slash.command(description="Download") async def download(ctx): await ctx.respond("Download: 0%") for pct in (25, 50, 75, 100): await asyncio.sleep(1) await edit_original_response(ctx.interaction, content=f"Download: {pct}%") ``` ### get_original_response Fetches the original response (API dict), for example to get its ID. `from discord_interactions import get_original_response` ```python async def get_original_response(interaction: discord.Interaction) -> Dict[str, Any] ``` ```python await ctx.respond("Poll started") message = await get_original_response(ctx.interaction) # raw API dict print(message["id"], message["channel_id"]) ``` ### respond Responds to the interaction, or sends a followup if it was already answered. `from discord_interactions import respond` ```python async def respond( interaction: discord.Interaction, content: str | None = None, **kwargs: Any, ) -> Any ``` ```python from discord_interactions import respond @router.on("steps") async def steps(interaction): await respond(interaction, "Step 1") # initial response await respond(interaction, "Step 2") # automatic followup, no 40060 error ``` ### respond_to_interaction Initial interaction response. With `update=True`, edits the message of the clicked component. `from discord_interactions import respond_to_interaction` ```python async def respond_to_interaction( interaction: discord.Interaction, content: str | None = None, embed: discord.Embed | None = None, embeds: List[discord.Embed] | None = None, components: Dict[str, Any] | Any | Sequence[Dict[str, Any] | Any] | None = None, allowed_mentions: Dict[str, Any] | discord.AllowedMentions | None = None, ephemeral: bool = False, update: bool = False, flags: int | None = None, files: Sequence[discord.File] | None = None, with_response: bool = False, **kwargs: Any, ) -> Any ``` - `interaction`: Interaction to answer (within 3 seconds). - `ephemeral`: Visible to the author only. - `update`: Edit the original message instead of sending a new one. - `with_response`: Return Discord's response object. ```python from discord_interactions import respond_to_interaction await respond_to_interaction(interaction, "Saved", ephemeral=True) await respond_to_interaction(interaction, components=[new_card], update=True) ``` ### send_followup Followup message after a response or a defer. `from discord_interactions import send_followup` ```python async def send_followup( interaction: discord.Interaction, content: str | None = None, embed: discord.Embed | None = None, embeds: List[discord.Embed] | None = None, components: Dict[str, Any] | Any | Sequence[Dict[str, Any] | Any] | None = None, allowed_mentions: Dict[str, Any] | discord.AllowedMentions | None = None, ephemeral: bool = False, flags: int | None = None, files: Sequence[discord.File] | None = None, ) -> Dict[str, Any] ``` ```python @router.on("report") async def report(interaction): await defer_interaction(interaction, ephemeral=True) text = await build_report() # slow await send_followup(interaction, text, ephemeral=True) ``` ### send_message Sends a message to a channel, a thread, a context, a member's DMs, or as an interaction response. `from discord_interactions import send_message` ```python async def send_message( destination: Any, content: str | None = None, embed: discord.Embed | None = None, embeds: List[discord.Embed] | None = None, components: Dict[str, Any] | Any | Sequence[Dict[str, Any] | Any] | None = None, allowed_mentions: Dict[str, Any] | discord.AllowedMentions | None = None, tts: bool = False, files: Sequence[discord.File] | None = None, flags: int | None = None, file: discord.File | None = None, reply_to: Any | None = None, poll: Any | None = None, ephemeral: bool = False, **kwargs: Any, ) -> discord.Message | None ``` - `destination`: Channel, thread, `commands.Context`, member, user or interaction. - `content`: Message text. - `components`: Message components. - `files`: Attached files. - `file`: A single attached file. - `reply_to`: Message to reply to. - `poll`: Discord poll. - `ephemeral`: For an interaction: visible to the author only. ```python from discord_interactions import container, send_message message = await send_message(channel, components=[container("## Announcement")]) await send_message(channel, "Reply to the previous message", reply_to=message) await send_message(member, "Direct message") ``` ### send_modal Opens a modal. Accepts a `ModalBuilder`, a `create_modal` dict or the three separate arguments. `from discord_interactions import send_modal` ```python async def send_modal( interaction: discord.Interaction, custom_id: str | Dict[str, Any] | Any, title: str | None = None, components: Sequence[Dict[str, Any] | Any] | None = None, ) -> None ``` - `custom_id`: Identifier, or directly a `ModalBuilder` / modal dict. - `title`: Title (when `custom_id` is a string). - `components`: Fields (when `custom_id` is a string). ```python from discord_interactions import ModalBuilder, send_modal await send_modal(interaction, ModalBuilder("feedback", "Your feedback").paragraph("text", "Feedback")) ``` ### update_message Edits the message of the clicked component. Shortcut for `respond_to_interaction(..., update=True)`. `from discord_interactions import update_message` ```python async def update_message(interaction: discord.Interaction, **kwargs: Any) -> Any ``` ```python from discord_interactions import update_message @router.on("confirm") async def confirm(interaction): await update_message(interaction, content="Order confirmed.", components=[]) ``` ## Reference: Updating components ### DisableAllHandle Disable timer: `refresh()`, `cancel()`, `force_disable()`, `is_active()`. `from discord_interactions import DisableAllHandle` ```python class DisableAllHandle(message: Any, delay_ms: int = 0) ``` - `def refresh(new_delay_ms: int) -> None`: Restarts the timer with a new delay. - `def cancel() -> None`: Cancels the disabling. - `async def force_disable() -> bool`: Disables immediately. - `def is_active() -> bool` ```python handle = disable_all(message, delay_ms=30_000) handle.refresh(30_000) # push back handle.cancel() # cancel await handle.force_disable() # disable right now ``` ### add_component Inserts components into a builder or a container dict. `from discord_interactions import add_component` ```python def add_component( container: Any, components: Any | Sequence[Any], position: int | None = None, ) -> Any ``` - `position`: Insertion index; the end by default. ```python from discord_interactions import add_component, container, create_button card = container("## Tasks") add_component(card, create_button("add", "Add a task")) ``` ### disable_all Disables every component of a message, now or after a delay. `from discord_interactions import disable_all` ```python def disable_all(message: Any, delay_ms: int = 0) -> DisableAllHandle ``` - `delay_ms`: Delay in milliseconds. ```python from discord_interactions import disable_all timer = disable_all(message, delay_ms=30_000) timer.refresh(30_000) ``` ### disable_all_by_message_id Like `disable_all`, from a channel and a message ID. `from discord_interactions import disable_all_by_message_id` ```python def disable_all_by_message_id( channel: Any, message_id: int | str, delay_ms: int = 0, ) -> DisableAllHandle ``` ```python from discord_interactions import disable_all_by_message_id timer = disable_all_by_message_id(channel, message_id, delay_ms=60_000) @router.on("activity") async def activity(interaction): timer.refresh(60_000) # every click pushes the expiry back ``` ### disable_buttons Copy of the components with buttons and selects disabled; Link buttons stay active. `from discord_interactions import disable_buttons` ```python def disable_buttons( components: Dict[str, Any] | Sequence[Dict[str, Any]], ) -> List[Dict[str, Any]] ``` ```python from discord_interactions import disable_buttons rows = [create_action_row(create_button("yes", "Yes"), create_button("no", "No"))] await ctx.respond("Choose", components=rows) disabled = disable_buttons(rows) # copy with every button disabled await edit_original_response(ctx.interaction, components=disabled) ``` ### remove_component Removes the matching components; rows left empty disappear too. `from discord_interactions import remove_component` ```python async def remove_component( message: Any, selector: str | Callable[[Dict[str, Any]], bool], remove_empty_rows: bool = True, ) -> bool ``` - `remove_empty_rows`: Remove a row that became empty. ```python from discord_interactions import remove_component @router.on("cancel") async def cancel(interaction): await defer_interaction(interaction, update=True) await remove_component(interaction.message, "cancel") # removes the button, and the row if empty ``` ### row_update Transforms every component of one or more rows with a function. `from discord_interactions import row_update` ```python async def row_update( message: Any, row_selector: str | int | Callable[[Dict[str, Any], int], bool], updater: Callable[[Dict[str, Any]], Dict[str, Any] | None] | Callable[[Dict[str, Any]], Awaitable[Dict[str, Any] | None]], ) -> bool ``` - `row_selector`: Row index, `custom_id` of a component in the row, or a `(row, index) -> bool` function. - `updater`: Function (sync or async) returning the updated component, or `None` to remove it. ```python from discord_interactions import row_update def turn_off(button): button["style"] = 2 return button await row_update(interaction.message, 0, turn_off) ``` ### row_update_one Like `row_update`, but only when exactly one row matches. `from discord_interactions import row_update_one` ```python async def row_update_one( message: Any, row_selector: str | int | Callable[[Dict[str, Any], int], bool], updater: Callable[[Dict[str, Any]], Dict[str, Any] | None] | Callable[[Dict[str, Any]], Awaitable[Dict[str, Any] | None]], ) -> bool ``` ```python # Turns every button of the row containing "yes" grey await row_update_one(interaction.message, "yes", lambda button: {**button, "style": 2}) ``` ### update_component Reloads the message, then updates every matching component. `from discord_interactions import update_component` ```python async def update_component( message: Any, selector: str | Callable[[Dict[str, Any]], bool], updates: Dict[str, Any], ) -> bool ``` - `message`: Message holding the component. - `selector`: Exact `custom_id` or a `(component) -> bool` function. - `updates`: Fields to replace, for example `{"disabled": True}`. ```python from discord_interactions import defer_interaction, update_component await defer_interaction(interaction, update=True) await update_component(interaction.message, "confirm", {"disabled": True, "label": "Confirmed"}) ``` ### update_component_one Like `update_component`, but only when exactly one component matches. `from discord_interactions import update_component_one` ```python async def update_component_one( message: Any, selector: str | Callable[[Dict[str, Any]], bool], updates: Dict[str, Any], ) -> bool ``` ```python await update_component_one(interaction.message, "confirm", {"label": "Confirmed", "disabled": True}) ``` ## Reference: Payloads ### MessageFlags Message flags: `EPHEMERAL`, `IS_COMPONENTS_V2`, `SUPPRESS_EMBEDS`, `SUPPRESS_NOTIFICATIONS` and the other API flags. `from discord_interactions import MessageFlags` `CROSSPOSTED = 1`, `SUPPRESS_EMBEDS = 4`, `EPHEMERAL = 64`, `LOADING = 128`, `SUPPRESS_NOTIFICATIONS = 4096`, `IS_VOICE_MESSAGE = 8192`, `IS_COMPONENTS_V2 = 32768` ```python from discord_interactions import MessageFlags, send_message await send_message(channel, "Silent update", flags=MessageFlags.SUPPRESS_NOTIFICATIONS) ``` ### build_message_payload Builds a message payload for any endpoint. Adds `IS_COMPONENTS_V2` and turns `content` into a text block when needed. `from discord_interactions import build_message_payload` ```python def build_message_payload( content: str | None = None, embed: discord.Embed | None = None, embeds: Sequence[discord.Embed] | None = None, components: Dict[str, Any] | Any | Sequence[Dict[str, Any] | Any] | None = None, allowed_mentions: Dict[str, Any] | discord.AllowedMentions | None = None, flags: int | None = None, tts: bool = False, ephemeral: bool = False, attachments: Sequence[Any] | None = None, files: Sequence[discord.File] | None = None, poll: Any | None = None, message_reference: Any | None = None, ) -> Dict[str, Any] ``` - `content`: Message text; with components V2 it becomes a leading TextDisplay. - `components`: Components: dicts or builders. - `allowed_mentions`: Allowed mentions, see `parse_allowed_mentions`. - `flags`: Extra flags (`MessageFlags`). - `ephemeral`: Visible to the target user only. - `files`: Attached files (`discord.File`). - `poll`: Discord poll (`discord.Poll` or dict). - `message_reference`: Message to reply to. ```python from discord_interactions import build_message_payload, container payload = build_message_payload("Hello", components=[container("Card")], ephemeral=True) # {"components": [{"type": 10, "content": "Hello"}, {...}], "flags": 32832} ``` ### parse_allowed_mentions Normalizes allowed mentions: discord.py object, API payload, discord.js style or boolean switches. `from discord_interactions import parse_allowed_mentions` ```python def parse_allowed_mentions( allowed_mentions: Dict[str, Any] | discord.AllowedMentions | None, ) -> Dict[str, Any] | None ``` ```python from discord_interactions import parse_allowed_mentions parse_allowed_mentions({"parse": ["users"]}) # {"parse": ["users"]} parse_allowed_mentions({"users": False, "roles": False, "everyone": False}) # {"parse": []}: no mention notifies anyone ``` ## Reference: Routing ### InteractionRouter Routes buttons, select menus and modals to handlers by the `base_id` of their `custom_id`. `from discord_interactions import InteractionRouter` Aliases: `ButtonRouter` ```python class InteractionRouter() -> None ``` - `def on(base_id: str) -> Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]`: Decorator: handler for a button or a select menu. - `def modal(base_id: str) -> Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]`: Decorator: handler for a modal; receives a `ModalSubmit`. - `def fallback(func: Callable[..., Awaitable[Any]]) -> Callable[..., Awaitable[Any]]`: Decorator: handler for buttons and menus without a dedicated route. - `async def handle(interaction: discord.Interaction) -> bool`: Processes an interaction; returns `True` when a handler took it. ```python from discord_interactions import InteractionRouter, update_message router = InteractionRouter() @router.on("vote") async def vote(interaction, data): await update_message(interaction, content=f"Vote recorded: {data['choice']}") @router.modal("profile") async def profile(interaction, values): ... @client.event async def on_interaction(interaction): await router.handle(interaction) ``` ## Reference: Signed custom_id ### build_signed_custom_id `custom_id` signed with HMAC-SHA256, with optional expiry. Cannot be forged without the secret. `from discord_interactions import build_signed_custom_id` ```python def build_signed_custom_id( base_id: str, data: Dict[str, Any] | None, secret: str, ttl_seconds: int | None = None, max_length: int = 100, ) -> str ``` - `secret`: The bot's secret key. - `ttl_seconds`: Validity in seconds. ```python from discord_interactions import build_signed_custom_id, parse_signed_custom_id custom_id = build_signed_custom_id("withdraw", {"amount": 500}, secret=SECRET, ttl_seconds=120) base_id, data, valid, reason = parse_signed_custom_id(custom_id, SECRET) ``` ### create_auto_rows Places buttons and select menus into valid rows automatically. `from discord_interactions import create_auto_rows` ```python def create_auto_rows( components: Sequence[Dict[str, Any]], max_buttons_per_row: int = 5, ) -> List[Dict[str, Any]] ``` - `max_buttons_per_row`: Buttons per row (5 max). ```python from discord_interactions import create_auto_rows, create_button buttons = [create_button("letter", c, data={"c": c}) for c in "ABCDEFGHIJKL"] await ctx.respond("Pick a letter", components=create_auto_rows(buttons)) # 5 + 5 + 2 ``` ### create_signed_button Button with a signed `custom_id`. `from discord_interactions import create_signed_button` ```python def create_signed_button( base_id: str, secret: str, data: Dict[str, Any] | None = None, ttl_seconds: int | None = None, label: str = '', style: int | str = 'Primary', emoji: str | Dict[str, Any] | None = None, disabled: bool = False, max_custom_id_length: int = 100, ) -> Dict[str, Any] ``` ```python from discord_interactions import create_action_row, create_signed_button button = create_signed_button( "withdraw", SECRET, data={"amount": 500}, ttl_seconds=120, label="Withdraw 500", style="danger" ) await ctx.respond(components=[create_action_row(button)], ephemeral=True) ``` ### parse_signed_custom_id Verifies a signed `custom_id`. Returns `(base_id, data, valid, reason)`. `from discord_interactions import parse_signed_custom_id` ```python def parse_signed_custom_id( custom_id: str, secret: str, enforce_expiry: bool = True, ) -> Tuple[str, Dict[str, Any], bool, str] ``` - `enforce_expiry`: Reject an expired `custom_id`. ```python @router.on("withdraw") async def withdraw(interaction): _, data, valid, reason = parse_signed_custom_id(interaction.data["custom_id"], SECRET) if not valid: await respond_to_interaction(interaction, f"Button rejected ({reason}).", ephemeral=True) return await debit(interaction.user.id, data["amount"]) ``` ### respond_or_followup Initial response when possible, otherwise a followup. `from discord_interactions import respond_or_followup` ```python async def respond_or_followup( interaction: discord.Interaction, *, content: str | None = None, embed: discord.Embed | None = None, embeds: List[discord.Embed] | None = None, components: Iterable[Any] | None = None, ephemeral: bool = False, flags: int | None = None, **kwargs: Any, ) -> Any ``` ```python from discord_interactions import respond_or_followup await respond_or_followup(interaction, content="Done.", ephemeral=True) ``` ## Reference: Shortcuts ### quick_button One-line button. `from discord_interactions import quick_button` ```python def quick_button( base_id: str, label: str, *, style: str | int = 'Primary', emoji: str | Dict[str, Any] | None = None, data: Dict[str, Any] | None = None, disabled: bool = False, url: str | None = None, ) -> Dict[str, Any] ``` ```python from discord_interactions import quick_button, quick_row await ctx.respond(components=[quick_row(quick_button("yes", "Yes", style="Success"), quick_button("no", "No"))]) ``` ### quick_container Complete container in one call: title, lines, thumbnail, section button or row of buttons. `from discord_interactions import quick_container` ```python def quick_container( *, title: str | None = None, lines: Iterable[str] | None = None, color: int | None = 5793266, button: Dict[str, Any] | None = None, button_text: str = 'Action', buttons: Sequence[Dict[str, Any]] | None = None, separator_between_lines: bool = False, thumbnail: str | None = None, ) -> Dict[str, Any] ``` - `title`: Title shown as `##`. - `lines`: Text blocks. - `color`: Border color. - `button`: Accessory button of a section. - `button_text`: Text of the button's section. - `buttons`: Row of buttons at the bottom. - `separator_between_lines`: Separator between each line. - `thumbnail`: Thumbnail next to the title. ```python from discord_interactions import quick_button, quick_container card = quick_container( title="Status", lines=["**API** operational", "**Database** operational"], buttons=[quick_button("refresh", "Refresh")], ) ``` ### quick_row Row of buttons: `quick_row(b1, b2)` or `quick_row([b1, b2])`. `from discord_interactions import quick_row` ```python def quick_row(*buttons: Dict[str, Any] | Sequence[Dict[str, Any]]) -> Dict[str, Any] ``` ```python row = quick_row(quick_button("a", "A"), quick_button("b", "B"), quick_button("c", "C")) ``` ### quick_send_container Sends a `quick_container` directly. `from discord_interactions import quick_send_container` ```python async def quick_send_container( destination: Any, *, title: str | None = None, lines: Iterable[str] | None = None, color: int | None = 5793266, button: Dict[str, Any] | None = None, buttons: Sequence[Dict[str, Any]] | None = None, separator_between_lines: bool = False, content: str | None = None, **kwargs: Any, ) ``` ```python from discord_interactions import quick_button, quick_send_container await quick_send_container( channel, title="Maintenance tonight", lines=["From 10 pm to 11 pm", "The bot will be offline"], button=quick_button("remind", "Remind me"), ) ``` ## Reference: custom_id ### build_custom_id `base_id:data` as compact JSON in url-safe base64. Raises past 100 characters. `from discord_interactions import build_custom_id` ```python def build_custom_id( base_id: str, data: Dict[str, Any] | None = None, max_length: int = 100, ) -> str ``` - `base_id`: Readable part, used for routing. - `data`: JSON dict to embed. - `max_length`: Maximum allowed length. ```python from discord_interactions import build_custom_id, parse_custom_id custom_id = build_custom_id("page", {"p": 3}) base_id, data = parse_custom_id(custom_id) # ("page", {"p": 3}) ``` ### decode_data Decodes `custom_id` data; returns `{}` when invalid. `from discord_interactions import decode_data` ```python def decode_data(encoded: str) -> Dict[str, Any] ``` ```python decode_data("eyJwIjozfQ") # {"p": 3} decode_data("not base64") # {}: never raises ``` ### encode_data Encodes a dict as compact JSON in url-safe base64 without padding. `from discord_interactions import encode_data` ```python def encode_data(data: Dict[str, Any]) -> str ``` ```python from discord_interactions import decode_data, encode_data text = encode_data({"p": 3}) # "eyJwIjozfQ" decode_data(text) # {"p": 3} ``` ### get_base_custom_id Part of a `custom_id` before the first `:`. `from discord_interactions import get_base_custom_id` ```python def get_base_custom_id(custom_id: str) -> str ``` ```python from discord_interactions import get_base_custom_id get_base_custom_id("buy:eyJhIjo0Mn0") # "buy" ``` ### parse_custom_id Splits a `custom_id` into `(base_id, data)`. Also reads the legacy format. `from discord_interactions import parse_custom_id` ```python def parse_custom_id(custom_id: str) -> Tuple[str, Dict[str, Any]] ``` ```python from discord_interactions import parse_custom_id base_id, data = parse_custom_id(interaction.data["custom_id"]) # "page:eyJwIjozfQ" -> ("page", {"p": 3}) ``` ## Reference: HTTP ### CallbackType Interaction response types: message (4), deferred (5, 6), update (7), autocomplete (8), modal (9). `from discord_interactions import CallbackType` `PONG = 1`, `CHANNEL_MESSAGE = 4`, `DEFERRED_CHANNEL_MESSAGE = 5`, `DEFERRED_UPDATE_MESSAGE = 6`, `UPDATE_MESSAGE = 7`, `AUTOCOMPLETE_RESULT = 8`, `MODAL = 9`, `LAUNCH_ACTIVITY = 12` ```python from discord_interactions import CallbackType # API response types, for an HTTP call made by hand payload = {"type": CallbackType.CHANNEL_MESSAGE, "data": {"content": "Hello"}} # CHANNEL_MESSAGE (4), DEFERRED_CHANNEL_MESSAGE (5), UPDATE_MESSAGE (7), MODAL (9)... ``` ## Reference: Slash commands ### SlashCommand A declared command. Created by `@slash.command()`. `from discord_interactions import SlashCommand` ```python class SlashCommand( name: str, description: str, callback: Callable[..., Awaitable[Any]], options: List[OptionBase] = , name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, permissions: PermissionConfig = , cooldowns: List[CooldownBucket] = , guild_ids: Set[int] | None = None, parent: str | None = None, group: str | None = None, auto_defer: bool = False, defer_ephemeral: bool = False, ephemeral_by_default: bool = False, _enabled: bool = True, ) -> None ``` - `def to_dict() -> Dict[str, Any]` - `def to_subcommand_dict() -> Dict[str, Any]` - `def prepare(values: Dict[str, Any]) -> Dict[str, Any]` - `async def invoke(ctx: SlashContext, **kwargs: Any) -> Any` ```python # You never create SlashCommand yourself: @slash.command builds it and keeps it @slash.command(description="Latency") async def ping(ctx): await ctx.respond("Pong") command = slash.get_command("ping") print(command.name, command.description) print(command.to_dict()) # what is sent to Discord ``` ### SlashCommandManager Entry point for slash commands: declaration, execution, autocomplete and sync. Alias: `SlashManager`. `from discord_interactions import SlashCommandManager` Aliases: `SlashManager` ```python class SlashCommandManager( client: discord.Client, *, owner_ids: Set[int] | None = None, auto_sync: bool = True, sync_on_ready: bool = True, default_guilds: List[int] | None = None, ) -> None ``` - `client`: `discord.Client` or `commands.Bot`. - `owner_ids`: Owners for `@owner_only()`; read from the application otherwise. - `auto_sync`: Sync commands on startup. - `sync_on_ready`: Sync on the `ready` event. - `default_guilds`: Guilds to sync to (instant) instead of globally. - `def find_command(data: Dict[str, Any]) -> Tuple[SlashCommand | None, List[Dict[str, Any]]]` - `def command(name: str | None = None, description: str = 'No description', *, options: List[OptionBase] | None = None, guild_ids: List[int] | None = None, auto_defer: bool = False, defer_ephemeral: bool = False, ephemeral: bool = False, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, **kwargs: Any) -> Callable[[~T], ~T]`: Decorator: declares a command. - `def group(name: str, description: str = 'No description', *, guild_ids: List[int] | None = None, **kwargs: Any) -> SlashGroup`: Creates a subcommand group. - `def add_middleware(middleware: Middleware) -> None`: Adds a ready-made middleware. - `def remove_middleware(name: str) -> bool` - `def middleware(name: str | None = None, *, priority: int = 100, commands: List[str] | None = None, exclude: List[str] | None = None) -> Callable`: Decorator: before, after or error middleware, depending on the signature. - `def on_error(func: Callable) -> Callable`: Decorator: error handler. Returning `False` lets the default handling run. - `def autocomplete(command_name: str, option_name: str) -> Callable`: Decorator: autocomplete for an option. - `def build_payload() -> List[Dict[str, Any]]`: Commands in API format, without sending anything. - `async def sync(guilds: List[int] | None = None) -> Dict[int | None, Any]`: Replaces the commands on Discord, globally or per guild. - `def get_command(name: str) -> SlashCommand | None` - `def get_all_commands() -> List[SlashCommand]` - `def get_group(name: str) -> SlashGroup | None` - `def remove_command(name: str) -> bool` ```python import discord from discord_interactions.slash import SlashManager client = discord.Client(intents=discord.Intents.default()) slash = SlashManager(client, default_guilds=[123456789012345678]) @slash.command(description="Bot latency") async def ping(ctx): await ctx.respond(f"Pong! {ctx.bot.latency * 1000:.0f} ms") client.run(TOKEN) ``` ### SlashGroup Command group: `/group subcommand` or `/group subgroup subcommand`. `from discord_interactions import SlashGroup` ```python class SlashGroup( name: str, description: str, commands: Dict[str, SlashCommand] = , subgroups: Dict[str, SlashGroup] = , name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, guild_ids: Set[int] | None = None, permissions: PermissionConfig = , ) -> None ``` - `def command(name: str | None = None, description: str = 'No description', *, options: List[OptionBase] | None = None, **kwargs: Any) -> Callable[[~T], ~T]`: Decorator: adds a subcommand. - `def subgroup(name: str, description: str = 'No description', **kwargs: Any) -> SlashGroup`: Creates a subgroup. - `def find(raw_options: List[Dict[str, Any]]) -> Tuple[SlashCommand | None, List[Dict[str, Any]]]` - `def to_dict() -> Dict[str, Any]` ```python config = slash.group("config", "Configuration") channels = config.subgroup("channels", "Bot channels") @channels.command(description="Log channel") @option(Channel("channel", "Channel")) async def logs(ctx, channel): await ctx.respond(f"Logs: {channel.mention}") ``` ### option Decorator: adds an option to the command. Writing order is kept. `from discord_interactions import option` ```python def option(opt: OptionBase) -> Callable[[~T], ~T] ``` ```python from discord_interactions.slash import Integer, String, option @slash.command(description="Repeat") @option(String("text", "Text", max_length=200)) @option(Integer("times", "Repetitions", required=False, default=1, min_value=1, max_value=5)) async def repeat(ctx, text, times): await ctx.respond("\n".join([text] * times)) ``` ### options Decorator: adds several options at once. `from discord_interactions import options` ```python def options(*opts: OptionBase) -> Callable[[~T], ~T] ``` ```python from discord_interactions.slash import Integer, String, options @slash.command(description="Create a reminder") @options( String("text", "What?"), Integer("minutes", "In how many minutes?", min_value=1), ) async def remind(ctx, text, minutes): ... ``` ## Reference: Context ### SlashContext Command context: interaction, author, channel, options and response methods. `from discord_interactions import SlashContext` ```python class SlashContext( interaction: discord.Interaction, command: SlashCommand | None = None, options: Dict[str, Any] | None = None, ) -> None ``` - `def get(name: str, default: Any = None) -> Any`: Value of an option, or `default`. - `async def respond(content: str | None = None, *, embed: discord.Embed | None = None, embeds: List[discord.Embed] | None = None, components: Sequence[Any] | None = None, ephemeral: bool | None = None, flags: int | None = None, tts: bool = False, files: Sequence[discord.File] | None = None, file: discord.File | None = None, allowed_mentions: Any | None = None) -> Dict[str, Any] | None`: Initial response, or an automatic followup when a response or defer already exists. - `async def followup(content: str | None = None, **kwargs: Any) -> Dict[str, Any]`: Sends a followup message. - `async def defer(*, ephemeral: bool | None = None) -> None`: Shows the thinking state to answer later. - `async def edit(content: str | None = None, *, embed: discord.Embed | None = None, embeds: List[discord.Embed] | None = None, components: Sequence[Any] | None = None, files: Sequence[discord.File] | None = None, attachments: Sequence[Any] | None = None, allowed_mentions: Any | None = None) -> Dict[str, Any]`: Edits the original response. - `async def delete() -> None`: Deletes the original response. - `async def send_modal(custom_id: Any, title: str | None = None, components: List[Any] | None = None) -> None`: Opens a modal. - `async def reply(content: str | None = None, **kwargs: Any) -> Dict[str, Any] | None` - `async def send(content: str | None = None, **kwargs: Any) -> Dict[str, Any] | None` - `async def think(ephemeral: bool = False) -> None` - `def set_ephemeral_default(value: bool) -> None` ```python @slash.command(description="Long task") async def report(ctx): await ctx.defer(ephemeral=True) await ctx.respond("Report ready") await ctx.edit("Report ready and sent") ``` ### create_context Creates a `SlashContext` (internal use or tests). `from discord_interactions.slash import create_context` ```python def create_context( interaction: discord.Interaction, command: SlashCommand | None = None, options: Dict[str, Any] | None = None, ) -> SlashContext ``` ```python from discord_interactions.slash import create_context # Build a context outside a slash command, to reuse ctx.respond, ctx.user... @client.event async def on_interaction(interaction): ctx = create_context(interaction) await ctx.respond(f"Hi {ctx.user.display_name}", ephemeral=True) ``` ## Reference: Options ### AttachmentOption Attachment option (created by `Attachment`). `from discord_interactions.slash import AttachmentOption` ```python class AttachmentOption( name: str, description: str, required: bool = True, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, default: Any = None, validator: Callable[[Any], bool | str] | None = None, transformer: Callable[[Any], Any] | None = None, allowed_extensions: List[str] | None = None, max_size: int | None = None, file_types: List[str] | None = None, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions.slash import AttachmentOption # file_types filters inside Discord, allowed_extensions and max_size are checked by the bot file = AttachmentOption("log", "Log file", allowed_extensions=[".txt", ".log"], max_size=2_000_000) ``` ### BooleanOption Boolean option (created by `Boolean`). `from discord_interactions.slash import BooleanOption` ```python class BooleanOption( name: str, description: str, required: bool = True, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, default: Any = None, validator: Callable[[Any], bool | str] | None = None, transformer: Callable[[Any], Any] | None = None, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions.slash import BooleanOption private = BooleanOption("private", "Reply visible only to you", required=False, default=True) ``` ### ChannelOption Channel option (created by `Channel`). `from discord_interactions.slash import ChannelOption` ```python class ChannelOption( name: str, description: str, required: bool = True, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, default: Any = None, validator: Callable[[Any], bool | str] | None = None, transformer: Callable[[Any], Any] | None = None, channel_types: List[int] | None = None, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions import ChannelTypes from discord_interactions.slash import ChannelOption voice = ChannelOption("voice", "Voice channel", channel_types=ChannelTypes.VOICE_CHANNELS) ``` ### Choice Fixed choice of an option. `from discord_interactions import Choice` ```python class Choice( name: str, value: Any, name_localizations: Dict[str, str] | None = None, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions.slash import Choice, String, option @slash.command(description="Bot language") @option(String("language", "Language", choices=[ Choice("English", "en", name_localizations={"fr": "Anglais"}), Choice("Français", "fr"), ])) async def language(ctx, language): ... ``` ### IntegerOption Integer option (created by `Integer`). `from discord_interactions.slash import IntegerOption` ```python class IntegerOption( name: str, description: str, required: bool = True, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, default: Any = None, validator: Callable[[Any], bool | str] | None = None, transformer: Callable[[Any], Any] | None = None, min_value: int | None = None, max_value: int | None = None, choices: List[Choice] | None = None, autocomplete: Callable[..., Awaitable[List[Tuple[str, Any]]]] | None = None, step: int | None = None, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions.slash import IntegerOption age = IntegerOption("age", "Your age", min_value=13, max_value=120) @slash.command(description="Age", options=[age]) async def set_age(ctx, age): ... ``` ### MentionableOption Mentionable option (created by `Mentionable`). `from discord_interactions.slash import MentionableOption` ```python class MentionableOption( name: str, description: str, required: bool = True, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, default: Any = None, validator: Callable[[Any], bool | str] | None = None, transformer: Callable[[Any], Any] | None = None, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions.slash import MentionableOption target = MentionableOption("target", "Member or role to notify") ``` ### NumberOption Decimal option (created by `Number`). `from discord_interactions.slash import NumberOption` ```python class NumberOption( name: str, description: str, required: bool = True, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, default: Any = None, validator: Callable[[Any], bool | str] | None = None, transformer: Callable[[Any], Any] | None = None, min_value: float | None = None, max_value: float | None = None, choices: List[Choice] | None = None, autocomplete: Callable[..., Awaitable[List[Tuple[str, Any]]]] | None = None, precision: int | None = None, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions.slash import NumberOption rating = NumberOption("rating", "Rating out of 5", min_value=0, max_value=5, precision=1) ``` ### OptionBase Common base of options. `from discord_interactions.slash import OptionBase` ```python class OptionBase( name: str, description: str, required: bool = True, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, default: Any = None, validator: Callable[[Any], bool | str] | None = None, transformer: Callable[[Any], Any] | None = None, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions.slash import OptionBase # Common base class: every option has validator and transformer def uppercase(value): return value.upper() def not_empty(value): return bool(value.strip()) or "The text cannot be empty" # String("code", "Promo code", transformer=uppercase, validator=not_empty) ``` ### RoleOption Role option (created by `Role`). `from discord_interactions.slash import RoleOption` ```python class RoleOption( name: str, description: str, required: bool = True, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, default: Any = None, validator: Callable[[Any], bool | str] | None = None, transformer: Callable[[Any], Any] | None = None, exclude_everyone: bool = True, exclude_managed: bool = False, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions.slash import RoleOption role = RoleOption("role", "Role", exclude_everyone=True, exclude_managed=True) ``` ### StringOption Text option (created by `String`). `from discord_interactions.slash import StringOption` ```python class StringOption( name: str, description: str, required: bool = True, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, default: Any = None, validator: Callable[[Any], bool | str] | None = None, transformer: Callable[[Any], Any] | None = None, min_length: int | None = None, max_length: int | None = None, choices: List[Choice] | None = None, autocomplete: Callable[..., Awaitable[List[Tuple[str, Any]]]] | None = None, pattern: str | None = None, pattern_error: str | None = None, _regex: Pattern[str] | None = None, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions.slash import StringOption # Long form of String(...), handy to pass options= to @slash.command @slash.command(description="Username", options=[StringOption("username", "Your username", min_length=3, max_length=16)]) async def username(ctx, username): ... ``` ### UserOption User option (created by `User`). `from discord_interactions.slash import UserOption` ```python class UserOption( name: str, description: str, required: bool = True, name_localizations: Dict[str, str] | None = None, description_localizations: Dict[str, str] | None = None, default: Any = None, validator: Callable[[Any], bool | str] | None = None, transformer: Callable[[Any], Any] | None = None, allow_bots: bool = True, require_in_voice: bool = False, ) -> None ``` - `def to_dict() -> Dict[str, Any]` ```python from discord_interactions.slash import UserOption # Rejects bots and requires the member to be in a voice channel invite = UserOption("member", "Who to invite", allow_bots=False, require_in_voice=True) ``` ### ChannelTypes Channel types and ready-made groups: `TEXT_CHANNELS`, `VOICE_CHANNELS`, `THREAD_CHANNELS`, `ALL_TEXT`. `from discord_interactions import ChannelTypes` `GUILD_TEXT = 0`, `DM = 1`, `GUILD_VOICE = 2`, `GROUP_DM = 3`, `GUILD_CATEGORY = 4`, `GUILD_ANNOUNCEMENT = 5`, `ANNOUNCEMENT_THREAD = 10`, `PUBLIC_THREAD = 11`, `PRIVATE_THREAD = 12`, `GUILD_STAGE_VOICE = 13`, `GUILD_DIRECTORY = 14`, `GUILD_FORUM = 15`, `GUILD_MEDIA = 16`, `TEXT_CHANNELS = [0, 5]`, `VOICE_CHANNELS = [2, 13]`, `THREAD_CHANNELS = [10, 11, 12]`, `ALL_TEXT = [0, 5, 11, 12, 15]` ```python from discord_interactions.slash import Channel, ChannelTypes, option @slash.command(description="Join a voice channel") @option(Channel("voice", "Voice channel", channel_types=[ChannelTypes.GUILD_VOICE])) async def join(ctx, voice): await voice.connect() ``` ### OptionType API option types. `from discord_interactions.slash import OptionType` `SUBCOMMAND = 1`, `SUBCOMMAND_GROUP = 2`, `STRING = 3`, `INTEGER = 4`, `BOOLEAN = 5`, `USER = 6`, `CHANNEL = 7`, `ROLE = 8`, `MENTIONABLE = 9`, `NUMBER = 10`, `ATTACHMENT = 11` ```python from discord_interactions.slash import OptionType # Raw API types (STRING = 3, INTEGER = 4, USER = 6...) if option["type"] == OptionType.USER.value: ... ``` ### Attachment Attachment option. `file_types` filters on Discord's side, `allowed_extensions` and `max_size` on the bot's side. `from discord_interactions import Attachment` ```python def Attachment( name: str, description: str, *, required: bool = True, allowed_extensions: List[str] | None = None, max_size: int | None = None, file_types: List[str] | None = None, localizations: Dict[str, Tuple[str, str]] | None = None, ) -> AttachmentOption ``` - `allowed_extensions`: Accepted extensions, checked by the bot. - `max_size`: Maximum size in bytes. - `file_types`: Types offered by Discord: `"image"`, `"video"`, `"audio"` or extensions. ```python from discord_interactions.slash import Attachment, option @slash.command(description="Analyze an image") @option(Attachment("image", "Image", file_types=["image"], max_size=8_000_000)) async def analyze(ctx, image): await ctx.respond(f"{image.filename}: {image.width}×{image.height}") ``` ### Boolean True or false option. `from discord_interactions import Boolean` ```python def Boolean( name: str, description: str, *, required: bool = True, default: bool | None = None, localizations: Dict[str, Tuple[str, str]] | None = None, ) -> BooleanOption ``` ```python from discord_interactions.slash import Boolean, option @slash.command(description="Welcome message") @option(Boolean("public", "Visible to everyone?", required=False, default=False)) async def welcome(ctx, public): await ctx.respond("Welcome!", ephemeral=not public) ``` ### Channel Channel option, filterable by type. `from discord_interactions import Channel` ```python def Channel( name: str, description: str, *, required: bool = True, channel_types: List[int] | None = None, localizations: Dict[str, Tuple[str, str]] | None = None, ) -> ChannelOption ``` - `channel_types`: Accepted types, for example `ChannelTypes.TEXT_CHANNELS`. ```python import discord from discord_interactions.slash import Channel, option @slash.command(description="Announcement channel") @option(Channel("channel", "Text channel", channel_types=[discord.ChannelType.text.value])) async def announcements(ctx, channel): await ctx.respond(f"Announcements in {channel.mention}.") ``` ### Integer Integer option with bounds, step, choices and autocomplete. `from discord_interactions import Integer` ```python def Integer( name: str, description: str, *, required: bool = True, default: Any = None, min_value: int | None = None, max_value: int | None = None, choices: List[Choice | Tuple[str, int]] | None = None, autocomplete: Callable[..., Awaitable[List[Tuple[str, Any]]]] | None = None, step: int | None = None, validator: Callable[[int], bool | str] | None = None, transformer: Callable[[int], Any] | None = None, localizations: Dict[str, Tuple[str, str]] | None = None, ) -> IntegerOption ``` - `min_value`: Minimum value. - `max_value`: Maximum value. - `step`: The value must be a multiple of this step. ```python from discord_interactions.slash import Integer, option @slash.command(description="Delete messages") @option(Integer("count", "How many?", min_value=1, max_value=100)) async def clear(ctx, count): deleted = await ctx.channel.purge(limit=count) await ctx.respond(f"{len(deleted)} messages deleted.", ephemeral=True) ``` ### Mentionable User or role option. `from discord_interactions import Mentionable` ```python def Mentionable( name: str, description: str, *, required: bool = True, localizations: Dict[str, Tuple[str, str]] | None = None, ) -> MentionableOption ``` ```python from discord_interactions.slash import Mentionable, option @slash.command(description="Mention") @option(Mentionable("target", "A member or a role")) async def ping(ctx, target): await ctx.respond(f"Hey {target.mention}") ``` ### Number Decimal option with bounds and rounding. `from discord_interactions import Number` ```python def Number( name: str, description: str, *, required: bool = True, default: Any = None, min_value: float | None = None, max_value: float | None = None, choices: List[Choice | Tuple[str, float]] | None = None, autocomplete: Callable[..., Awaitable[List[Tuple[str, Any]]]] | None = None, precision: int | None = None, validator: Callable[[float], bool | str] | None = None, transformer: Callable[[float], Any] | None = None, localizations: Dict[str, Tuple[str, str]] | None = None, ) -> NumberOption ``` - `precision`: Number of decimals kept. ```python from discord_interactions.slash import Number, option @slash.command(description="Convert euros") @option(Number("euros", "Amount", min_value=0, precision=2)) async def convert(ctx, euros): await ctx.respond(f"{euros} € = {euros * 1.08:.2f} $") ``` ### Role Role option. The value arrives as `discord.Role`. `from discord_interactions import Role` ```python def Role( name: str, description: str, *, required: bool = True, exclude_everyone: bool = True, exclude_managed: bool = False, localizations: Dict[str, Tuple[str, str]] | None = None, ) -> RoleOption ``` - `exclude_everyone`: Reject @everyone. - `exclude_managed`: Reject roles managed by an integration. ```python from discord_interactions.slash import Role, User, option @slash.command(description="Give a role") @option(User("member", "Who?")) @option(Role("role", "Which role?", exclude_managed=True)) async def give(ctx, member, role): await member.add_roles(role) await ctx.respond(f"{role.mention} given to {member.mention}.") ``` ### String Text option with length, choices, regex and autocomplete. `from discord_interactions import String` ```python def String( name: str, description: str, *, required: bool = True, default: Any = None, min_length: int | None = None, max_length: int | None = None, choices: List[Choice | Tuple[str, str]] | None = None, autocomplete: Callable[..., Awaitable[List[Tuple[str, Any]]]] | None = None, pattern: str | None = None, pattern_error: str | None = None, validator: Callable[[str], bool | str] | None = None, transformer: Callable[[str], Any] | None = None, localizations: Dict[str, Tuple[str, str]] | None = None, ) -> StringOption ``` - `name`: Option name (32 characters, lowercase). - `description`: Description (100 characters). - `required`: Option required. - `default`: Value when the option is omitted. - `min_length`: Minimum length. - `max_length`: Maximum length. - `choices`: Fixed choices: `Choice` or `(name, value)` tuples. - `autocomplete`: Autocomplete function. - `pattern`: Regex checked by the bot. - `pattern_error`: Message when the regex fails. - `validator`: Validation function: `True`, `False` or an error message. - `transformer`: Function applied to the value before the call. - `localizations`: `{locale: (name, description)}`. ```python from discord_interactions.slash import String, from_list, option @slash.command(description="Color") @option(String("hex", "Color code", pattern=r"^#[0-9A-Fa-f]{6}$", pattern_error="Format #RRGGBB")) @option(String("name", "Name", autocomplete=from_list(["Red", "Green", "Blue"]))) async def color(ctx, hex, name): ... ``` ### User User option. The value arrives as `discord.Member` (or `discord.User` outside guilds). `from discord_interactions import User` ```python def User( name: str, description: str, *, required: bool = True, allow_bots: bool = True, require_in_voice: bool = False, localizations: Dict[str, Tuple[str, str]] | None = None, ) -> UserOption ``` - `allow_bots`: Accept bots. - `require_in_voice`: The member must be in a voice channel. ```python from discord_interactions.slash import User, option @slash.command(description="Profile") @option(User("member", "Member", allow_bots=False)) async def profile(ctx, member): await ctx.respond(f"{member.display_name} joined on {member.joined_at:%Y-%m-%d}") ``` ## Reference: Permissions ### PermissionConfig Every restriction of a command, filled by the decorators. `from discord_interactions.slash import PermissionConfig` ```python class PermissionConfig( user_permissions: int = 0, bot_permissions: int = 0, default_member_permissions: int | None = None, dm_permission: bool = True, contexts: List[int] | None = None, integration_types: List[int] | None = None, nsfw: bool = False, checks: List[Callable[[discord.Interaction], Awaitable[bool]]] = , owner_only: bool = False, owner_ids: Set[int] = , guild_only: bool = False, allowed_guilds: Set[int] | None = None, blocked_guilds: Set[int] = , allowed_users: Set[int] | None = None, blocked_users: Set[int] = , required_roles: Set[int] | None = None, required_any_role: Set[int] | None = None, allowed_channels: Set[int] | None = None, blocked_channels: Set[int] = , allowed_categories: Set[int] | None = None, allowed_hours: Set[int] | None = None, ) -> None ``` - `def to_api_dict() -> dict` ```python from discord_interactions.slash import PermissionConfig, check_permissions # The same rules as the decorators, reusable on a button staff_config = PermissionConfig(guild_only=True, required_any_role={111111111111111111}) ``` ### IntegrationType Installation types: `GUILD_INSTALL`, `USER_INSTALL`. `from discord_interactions import IntegrationType` `GUILD_INSTALL = 0`, `USER_INSTALL = 1` ```python from discord_interactions.slash import IntegrationType IntegrationType.GUILD_INSTALL # 0: installed on a server IntegrationType.USER_INSTALL # 1: installed on the user's account ``` ### InteractionContext Usage contexts: `GUILD`, `BOT_DM`, `PRIVATE_CHANNEL`. `from discord_interactions import InteractionContext` `GUILD = 0`, `BOT_DM = 1`, `PRIVATE_CHANNEL = 2` ```python from discord_interactions.slash import InteractionContext InteractionContext.GUILD # 0: servers InteractionContext.BOT_DM # 1: DMs with the bot InteractionContext.PRIVATE_CHANNEL # 2: DMs and group DMs, for a user-installed command ``` ### Permissions Discord permission flags, up to `PIN_MESSAGES` and `BYPASS_SLOWMODE`. `from discord_interactions.slash import Permissions` `CREATE_INSTANT_INVITE = 1`, `KICK_MEMBERS = 2`, `BAN_MEMBERS = 4`, `ADMINISTRATOR = 8`, `MANAGE_CHANNELS = 16`, `MANAGE_GUILD = 32`, `ADD_REACTIONS = 64`, `VIEW_AUDIT_LOG = 128`, `PRIORITY_SPEAKER = 256`, `STREAM = 512`, `VIEW_CHANNEL = 1024`, `SEND_MESSAGES = 2048`, `SEND_TTS_MESSAGES = 4096`, `MANAGE_MESSAGES = 8192`, `EMBED_LINKS = 16384`, `ATTACH_FILES = 32768`, `READ_MESSAGE_HISTORY = 65536`, `MENTION_EVERYONE = 131072`, `USE_EXTERNAL_EMOJIS = 262144`, `VIEW_GUILD_INSIGHTS = 524288`, `CONNECT = 1048576`, `SPEAK = 2097152`, `MUTE_MEMBERS = 4194304`, `DEAFEN_MEMBERS = 8388608`, `MOVE_MEMBERS = 16777216`, `USE_VAD = 33554432`, `CHANGE_NICKNAME = 67108864`, `MANAGE_NICKNAMES = 134217728`, `MANAGE_ROLES = 268435456`, `MANAGE_WEBHOOKS = 536870912`, `MANAGE_GUILD_EXPRESSIONS = 1073741824`, `USE_APPLICATION_COMMANDS = 2147483648`, `REQUEST_TO_SPEAK = 4294967296`, `MANAGE_EVENTS = 8589934592`, `MANAGE_THREADS = 17179869184`, `CREATE_PUBLIC_THREADS = 34359738368`, `CREATE_PRIVATE_THREADS = 68719476736`, `USE_EXTERNAL_STICKERS = 137438953472`, `SEND_MESSAGES_IN_THREADS = 274877906944`, `USE_EMBEDDED_ACTIVITIES = 549755813888`, `MODERATE_MEMBERS = 1099511627776`, `VIEW_CREATOR_MONETIZATION_ANALYTICS = 2199023255552`, `USE_SOUNDBOARD = 4398046511104`, `CREATE_GUILD_EXPRESSIONS = 8796093022208`, `CREATE_EVENTS = 17592186044416`, `USE_EXTERNAL_SOUNDS = 35184372088832`, `SEND_VOICE_MESSAGES = 70368744177664`, `SET_VOICE_CHANNEL_STATUS = 281474976710656`, `SEND_POLLS = 562949953421312`, `USE_EXTERNAL_APPS = 1125899906842624`, `PIN_MESSAGES = 2251799813685248`, `BYPASS_SLOWMODE = 4503599627370496` ```python from discord_interactions.slash import Permissions # Permission flags, combined with | rights = Permissions.KICK_MEMBERS | Permissions.BAN_MEMBERS print(int(rights)) ``` ### allowed_channels Restricts the command to some channels. `from discord_interactions.slash import allowed_channels` ```python def allowed_channels(*channel_ids: int) -> Callable ``` ```python from discord_interactions.slash import allowed_channels @slash.command(description="Play") @allowed_channels(123456789012345678) # only in #games async def play(ctx): ... ``` ### allowed_guilds Restricts the command to some guilds. `from discord_interactions.slash import allowed_guilds` ```python def allowed_guilds(*guild_ids: int) -> Callable ``` ```python from discord_interactions.slash import allowed_guilds @slash.command(description="Beta command") @allowed_guilds(123456789012345678) async def beta(ctx): ... ``` ### blocked_channels Forbids the command in some channels. `from discord_interactions.slash import blocked_channels` ```python def blocked_channels(*channel_ids: int) -> Callable ``` ```python from discord_interactions.slash import blocked_channels @slash.command(description="Music") @blocked_channels(123456789012345678) # never in #announcements async def music(ctx): ... ``` ### bot_has_permissions Requires bot permissions in the channel. `from discord_interactions import bot_has_permissions` ```python def bot_has_permissions(**perms) -> Callable ``` ```python from discord_interactions.slash import bot_has_permissions @slash.command(description="Clear the channel") @bot_has_permissions(manage_messages=True, read_message_history=True) async def clear(ctx): ... ``` ### check Adds a custom async check `(interaction) -> bool`. `from discord_interactions import check` ```python def check(check_func: Callable[[discord.Interaction], Awaitable[bool]]) -> Callable ``` ```python from discord_interactions.slash import check async def account_linked(interaction): return await db.is_linked(interaction.user.id) @slash.command(description="Game profile") @check(account_linked) async def profile(ctx): ... ``` ### check_permissions Checks every restriction. Returns `(allowed, message)`. `from discord_interactions.slash import check_permissions` ```python async def check_permissions( interaction: discord.Interaction, config: PermissionConfig, ) -> tuple[bool, str | None] ``` ```python from discord_interactions.slash import PermissionConfig, check_permissions staff_config = PermissionConfig(guild_only=True, required_any_role={111111111111111111}) @router.on("close_ticket") async def close_ticket(interaction, data): allowed, error = await check_permissions(interaction, staff_config) if not allowed: return await respond_to_interaction(interaction, error, ephemeral=True) ... ``` ### contexts Where the command can be used: guilds, DMs with the bot, private groups. `from discord_interactions.slash import contexts` ```python def contexts(*values: int) -> Callable ``` ```python from discord_interactions.slash import InteractionContext, contexts @slash.command(description="Note") @contexts(InteractionContext.GUILD, InteractionContext.BOT_DM) async def note(ctx): ... ``` ### default_permissions Hides the command from members lacking these permissions, directly in Discord. `from discord_interactions import default_permissions` ```python def default_permissions(**perms) -> Callable ``` ```python from discord_interactions.slash import default_permissions @slash.command(description="Ban") @default_permissions(ban_members=True) # hidden from members without this permission async def ban(ctx, member): ... ``` ### dm_only Command usable in direct messages only. `from discord_interactions.slash import dm_only` ```python def dm_only() -> Callable ``` ```python from discord_interactions.slash import dm_only @slash.command(description="Private settings") @dm_only() async def private(ctx): ... ``` ### guild_only Command usable in guilds only. `from discord_interactions import guild_only` ```python def guild_only() -> Callable ``` ```python from discord_interactions.slash import guild_only @slash.command(description="Server members") @guild_only() async def members(ctx): await ctx.respond(f"{ctx.guild.member_count} members") ``` ### has_permissions Requires user permissions in the channel: `@has_permissions(manage_messages=True)`. `from discord_interactions import has_permissions` ```python def has_permissions(**perms) -> Callable ``` ```python from discord_interactions.slash import default_permissions, has_permissions @slash.command(description="Purge the channel") @default_permissions(manage_messages=True) @has_permissions(manage_messages=True) async def purge(ctx): ... ``` ### integration_types Installation types: guild, user, or both. `from discord_interactions.slash import integration_types` ```python def integration_types(*values: int) -> Callable ``` ```python from discord_interactions.slash import IntegrationType, integration_types @slash.command(description="Translate") @integration_types(IntegrationType.GUILD_INSTALL, IntegrationType.USER_INSTALL) async def translate(ctx, text): ... ``` ### nsfw Command restricted to NSFW channels. `from discord_interactions import nsfw` ```python def nsfw() -> Callable ``` ```python from discord_interactions.slash import nsfw @slash.command(description="Restricted content") @nsfw() async def restricted(ctx): ... ``` ### owner_only Command restricted to the bot owners. `from discord_interactions import owner_only` ```python def owner_only(owner_ids: Set[int] | None = None) -> Callable ``` - `owner_ids`: Allowed IDs; the application's owners by default. ```python from discord_interactions.slash import owner_only @slash.command(description="Stop the bot") @owner_only() # owners read from the Discord application async def stop(ctx): await ctx.respond("Stopping.") await ctx.bot.close() ``` ### require_roles Requires one of the given roles, or all of them with `require_all=True`. `from discord_interactions import require_roles` ```python def require_roles(*role_ids: int, require_all: bool = False) -> Callable ``` ```python from discord_interactions.slash import require_roles MOD, ADMIN = 123456789012345678, 234567890123456789 @slash.command(description="Warn a member") @require_roles(MOD, ADMIN) # either one is enough async def warn(ctx, member): ... ``` ### time_restricted Restricts the command to some hours (UTC). `from discord_interactions.slash import time_restricted` ```python def time_restricted(hours: List[int]) -> Callable ``` ```python from discord_interactions.slash import time_restricted @slash.command(description="Support") @time_restricted(list(range(8, 20))) # from 8 am to 8 pm UTC async def support(ctx): ... ``` ### user_installable Command installable by users and usable everywhere. `from discord_interactions import user_installable` ```python def user_installable() -> Callable ``` ```python from discord_interactions.slash import user_installable @slash.command(description="Private note", ephemeral=True) @user_installable() async def note(ctx): await ctx.respond("Available everywhere, even in direct messages.") ``` ## Reference: Cooldowns ### CooldownBucket Sliding window of a cooldown. `acquire()` checks and consumes in one step. `from discord_interactions.slash import CooldownBucket` ```python class CooldownBucket( rate: int, per: float, type: CooldownType = CooldownType.USER, bucket_key: Callable[[discord.Interaction], str] | None = None, ) -> None ``` - `def acquire(interaction: discord.Interaction) -> Tuple[bool, float]` - `async def check(interaction: discord.Interaction) -> Tuple[bool, float]` - `async def trigger(interaction: discord.Interaction) -> None` - `async def reset(interaction: discord.Interaction) -> None` - `def reset_all() -> None` - `def retry_after(interaction: discord.Interaction) -> float` ```python from discord_interactions.slash import CooldownBucket, CooldownType # A cooldown on a button (the decorators only work on commands) click = CooldownBucket(rate=1, per=5, type=CooldownType.USER) @router.on("draw") async def draw(interaction, data): allowed, wait = click.acquire(interaction) if not allowed: return await respond_to_interaction(interaction, f"Wait {wait:.0f} s.", ephemeral=True) ... ``` ### DynamicCooldown Cooldown whose duration is computed on every call. `from discord_interactions import DynamicCooldown` ```python class DynamicCooldown( rate: int = 1, per: float = 5.0, type: CooldownType = CooldownType.USER, bucket_key: Callable[[discord.Interaction], str] | None = None, per_func: Callable[[discord.Interaction], float] = lambda, ) -> None ``` - `per_func`: Function `(interaction) -> seconds`. - `def apply(func: Callable) -> Callable` - `def acquire(interaction: discord.Interaction) -> Tuple[bool, float]` - `async def check(interaction: discord.Interaction) -> Tuple[bool, float]` - `async def trigger(interaction: discord.Interaction) -> None` - `async def reset(interaction: discord.Interaction) -> None` - `def reset_all() -> None` - `def retry_after(interaction: discord.Interaction) -> float` ```python from discord_interactions.slash import DynamicCooldown def duration(interaction): return 5.0 if is_premium(interaction.user.id) else 30.0 @slash.command(description="Generate") @DynamicCooldown(rate=1, per_func=duration) async def generate(ctx): ... ``` ### SharedCooldown Cooldown shared between several commands. `from discord_interactions import SharedCooldown` ```python class SharedCooldown( name: str, rate: int = 1, per: float = 5.0, type: CooldownType = CooldownType.USER, bucket_key: Callable[[discord.Interaction], str] | None = None, ) -> None ``` - `def apply(func: Callable) -> Callable` ```python from discord_interactions.slash import SharedCooldown economy = SharedCooldown("economy", rate=5, per=60) @slash.command(description="Balance") @economy async def balance(ctx): ... ``` ### CooldownType Cooldown scopes. `from discord_interactions.slash import CooldownType` `USER = 'user'`, `CHANNEL = 'channel'`, `GUILD = 'guild'`, `MEMBER = 'member'`, `GLOBAL = 'global'`, `CATEGORY = 'category'`, `ROLE = 'role'`, `CUSTOM = 'custom'` ```python from discord_interactions.slash import CooldownType, cooldown @slash.command(description="Report") @cooldown(1, 30, type=CooldownType.GUILD) async def report(ctx): ... ``` ### channel_cooldown Per-channel cooldown. `from discord_interactions.slash import channel_cooldown` ```python def channel_cooldown(rate: int = 1, per: float = 5.0) -> Callable ``` ```python @slash.command(description="Question of the day") @channel_cooldown(1, 60) # once a minute in each channel async def question(ctx): ... ``` ### cooldown Rate-limits a command: `@cooldown(1, 5)` allows one use every 5 seconds per user. `from discord_interactions import cooldown` ```python def cooldown( rate: int = 1, per: float = 5.0, type: CooldownType = CooldownType.USER, bucket_key: Callable[[discord.Interaction], str] | None = None, ) -> Callable ``` - `rate`: Number of uses in the window. - `per`: Window length in seconds. - `type`: Scope: user, member, guild, channel, category, role, global or custom. - `bucket_key`: Custom key `(interaction) -> str`. ```python from discord_interactions.slash import CooldownType, cooldown @slash.command(description="Daily reward") @cooldown(1, 86_400, type=CooldownType.MEMBER) async def daily(ctx): await ctx.respond("+100 coins") ``` ### global_cooldown Cooldown shared by everyone. `from discord_interactions.slash import global_cooldown` ```python def global_cooldown(rate: int = 1, per: float = 5.0) -> Callable ``` ```python @slash.command(description="Generate an image") @global_cooldown(10, 60) # 10 generations per minute for the whole bot async def image(ctx): ... ``` ### guild_cooldown Per-guild cooldown. `from discord_interactions import guild_cooldown` ```python def guild_cooldown(rate: int = 1, per: float = 5.0) -> Callable ``` ```python @slash.command(description="Start an event") @guild_cooldown(1, 600) # once every 10 minutes on the server async def event(ctx): ... ``` ### member_cooldown Per-member cooldown (user within a guild). `from discord_interactions.slash import member_cooldown` ```python def member_cooldown(rate: int = 1, per: float = 5.0) -> Callable ``` ```python @slash.command(description="Work") @member_cooldown(1, 3600) # per person and per server async def work(ctx): ... ``` ### user_cooldown Per-user cooldown. `from discord_interactions import user_cooldown` ```python def user_cooldown(rate: int = 1, per: float = 5.0) -> Callable ``` ```python from discord_interactions.slash import user_cooldown @slash.command(description="Daily reward") @user_cooldown(1, 86_400) # once a day per person async def daily(ctx): ... ``` ## Reference: Autocomplete ### AutocompleteContext Autocomplete context: current input (`value`), option and other filled options. `from discord_interactions import AutocompleteContext` ```python class AutocompleteContext( interaction: discord.Interaction, value: str, option_name: str, focused: bool = True, options: Dict[str, Any] = , ) -> None ``` ```python async def cities(ctx): ctx.value # what the user is typing ctx.options # the other options already filled in ctx.user, ctx.guild, ctx.locale return [(c, c) for c in CITIES if c.lower().startswith(ctx.value.lower())][:25] ``` ### AutocompleteRegistry Internal registry of autocomplete functions. `from discord_interactions.slash import AutocompleteRegistry` ```python class AutocompleteRegistry() ``` - `def register(command_name: str, option_name: str, handler: Callable[..., Awaitable[List[Tuple[str, Any]]]]) -> None`: Register an autocomplete handler for a specific command option. - `def register_options(command_path: str, command: Any) -> None` - `def register_global(option_name: str, handler: Callable[..., Awaitable[List[Tuple[str, Any]]]]) -> None`: Register a global autocomplete handler that applies to all commands with an option of this name. - `def get_handler(command_name: str, option_name: str) -> Callable[..., Awaitable[List[Tuple[str, Any]]]] | None`: Get the handler for a command option. - `async def handle(interaction: discord.Interaction) -> None` ```python from discord_interactions.slash import AutocompleteRegistry, from_list # Only useful without SlashManager (which already has one) registry = AutocompleteRegistry() registry.register("game", "name", from_list(["Chess", "Go"])) registry.register_global("language", from_list(["fr", "en"])) # any option named "language" @client.event async def on_interaction(interaction): if interaction.type.value == 4: # autocomplete await registry.handle(interaction) ``` ### autocomplete_handler Marks a function as the autocomplete of a command. `from discord_interactions.slash import autocomplete_handler` ```python def autocomplete_handler( command: str | None = None, option: str | None = None, ) -> Callable ``` ```python from discord_interactions.slash import autocomplete_handler # Tags the function (target command and option); registration is done with slash.autocomplete @slash.autocomplete("search", "query") @autocomplete_handler(command="search", option="query") async def suggestions(ctx): results = await index.search(ctx.value) return [(r.title, r.id) for r in results] ``` ### chain Combines several autocompletes, without duplicates. `from discord_interactions.slash import chain` ```python def chain( *handlers: Callable[..., Awaitable[List[Tuple[str, Any]]]], ) -> Callable[..., Awaitable[List[Tuple[str, Any]]]] ``` ```python from discord_interactions.slash import chain, from_list favorites = from_list(["Paris", "Lyon"]) everything = from_list(CITIES) suggestions = chain(favorites, everything) # favorites first, then the rest ``` ### conditional Picks an autocomplete depending on the context. `from discord_interactions.slash import conditional` ```python def conditional( condition: Callable[[AutocompleteContext], bool], if_true: Callable[..., Awaitable[List[Tuple[str, Any]]]], if_false: Callable[..., Awaitable[List[Tuple[str, Any]]]], ) -> Callable[..., Awaitable[List[Tuple[str, Any]]]] ``` ```python from discord_interactions.slash import conditional, from_list suggestions = conditional( lambda ctx: ctx.locale.startswith("fr"), from_list(["Bonjour", "Salut"]), from_list(["Hello", "Hi"]), ) ``` ### filter_choices Filters and ranks choices against the input: exact, prefix, contains, then fuzzy. `from discord_interactions.slash import filter_choices` ```python def filter_choices( choices: Sequence[Tuple[str, Any]], query: str, *, case_sensitive: bool = False, fuzzy: bool = False, max_results: int = 25, ) -> List[Tuple[str, Any]] ``` - `fuzzy`: Accept letters in order, even when not adjacent. - `max_results`: Number of results (25 max). ```python from discord_interactions.slash import filter_choices async def cities(ctx): return filter_choices([(c, c) for c in CITIES], ctx.value, fuzzy=True) ``` ### from_coroutine Autocomplete from an async function, with optional caching. `from discord_interactions.slash import from_coroutine` ```python def from_coroutine( coro_func: Callable[..., Awaitable[List[str]]], *, cache_ttl: float = 0, ) -> Callable[..., Awaitable[List[Tuple[str, Any]]]] ``` ```python from discord_interactions.slash import String, from_coroutine, option async def products(): # called with no argument return await db.product_names() # list of str @slash.command(description="Find a product") @option(String("product", "Product", autocomplete=from_coroutine(products, cache_ttl=60))) async def find(ctx, product): ... ``` ### from_dict Autocomplete from a `{label: value}` dict. `from discord_interactions import from_dict` ```python def from_dict( mapping: Dict[str, Any], ) -> Callable[..., Awaitable[List[Tuple[str, Any]]]] ``` ```python from discord_interactions.slash import String, from_dict, option TIMEZONES = {"Paris": "Europe/Paris", "Montreal": "America/Toronto", "Tokyo": "Asia/Tokyo"} @slash.command(description="Local time") @option(String("city", "City", autocomplete=from_dict(TIMEZONES))) async def time(ctx, city): # receives "Europe/Paris" ... ``` ### from_list Autocomplete from a list of strings. `from discord_interactions import from_list` ```python def from_list( items: List[str], *, value_transform: Callable[[str], Any] | None = None, ) -> Callable[..., Awaitable[List[Tuple[str, Any]]]] ``` ```python from discord_interactions.slash import String, from_list, option @slash.command(description="Pick a fruit") @option(String("fruit", "Fruit", autocomplete=from_list(["Apple", "Pear", "Peach", "Plum"]))) async def fruit(ctx, fruit): ... ``` ## Reference: Middlewares ### Middleware Before, after and error hooks, filterable per command. `from discord_interactions.slash import Middleware` ```python class Middleware( name: str, before: Callable[[SlashContext], Awaitable[bool | None]] | None = None, after: Callable[[SlashContext, Any, Exception | None], Awaitable[None]] | None = None, on_error: Callable[[SlashContext, Exception], Awaitable[bool | None]] | None = None, priority: int = 100, commands: List[str] | None = None, exclude_commands: List[str] | None = None, ) -> None ``` - `def should_apply(command_name: str) -> bool`: Check if this middleware should apply to a command. ```python @slash.middleware() async def banned(ctx): if ctx.user.id in BANNED: await ctx.respond("You cannot use this bot.", ephemeral=True) return False # blocks the command ``` ### MiddlewareStack Stack of middlewares sorted by priority. `from discord_interactions.slash import MiddlewareStack` ```python class MiddlewareStack() ``` - `def add(middleware: Middleware) -> None`: Add a middleware to the stack. - `def remove(name: str) -> bool`: Remove a middleware by name. - `async def run_before(ctx: SlashContext) -> bool`: Run all before middlewares. Returns False if any middleware blocks execution. - `async def run_after(ctx: SlashContext, result: Any, error: Exception | None) -> None`: Run all after middlewares. - `async def run_error(ctx: SlashContext, error: Exception) -> bool`: Run error handlers. Returns True if the error was handled. ```python from discord_interactions.slash import Middleware, MiddlewareStack # SlashManager already has one: slash.add_middleware / slash.remove_middleware stack = MiddlewareStack() stack.add(Middleware("log", before=log_command)) stack.remove("log") ``` ### MiddlewarePhase Middleware execution phases. `from discord_interactions.slash import MiddlewarePhase` `BEFORE = 'before'`, `AFTER = 'after'`, `ERROR = 'error'`, `SUCCESS = 'success'` ```python from discord_interactions.slash import MiddlewarePhase # When a middleware can step in MiddlewarePhase.BEFORE # before the command MiddlewarePhase.AFTER # after, successful or not MiddlewarePhase.ERROR # on error MiddlewarePhase.SUCCESS # only when successful ``` ### analytics_middleware Sends one usage event per command to your function. `from discord_interactions.slash import analytics_middleware` ```python def analytics_middleware( *, track_func: Callable[[str, Dict[str, Any]], Awaitable[None]], ) -> Middleware ``` ```python from discord_interactions.slash import analytics_middleware async def track(event, info): # event == "command_used" await db.increment(info["command"], success=info["success"]) slash.add_middleware(analytics_middleware(track_func=track)) ``` ### error_handler_middleware Global error handling with a message to the user. `from discord_interactions import error_handler_middleware` ```python def error_handler_middleware( *, send_error_to_user: bool = True, error_message: str = 'An error occurred while processing your command.', log_errors: bool = True, on_error: Callable[[SlashContext, Exception], Awaitable[None]] | None = None, ) -> Middleware ``` ```python from discord_interactions.slash import error_handler_middleware slash.add_middleware(error_handler_middleware(error_message="Oops, something went wrong.")) ``` ### logging_middleware Logs every command, its options and its duration. `from discord_interactions import logging_middleware` ```python def logging_middleware( *, log_func: Callable[[str], None] | None = None, include_options: bool = True, include_timing: bool = True, ) -> Middleware ``` ```python import logging from discord_interactions.slash import logging_middleware logging.basicConfig(level=logging.INFO) slash.add_middleware(logging_middleware()) ``` ### maintenance_middleware Maintenance mode: blocks commands except for some users. `from discord_interactions.slash import maintenance_middleware` ```python def maintenance_middleware( *, is_enabled: Callable[[], bool] = lambda, allowed_users: List[int] | None = None, message: str = 'The bot is currently under maintenance. Please try again..., ) -> Middleware ``` ```python from discord_interactions.slash import maintenance_middleware IN_MAINTENANCE = False slash.add_middleware(maintenance_middleware( is_enabled=lambda: IN_MAINTENANCE, allowed_users=[MY_ID], message="The bot is under maintenance, come back in a few minutes.", )) ``` ### ratelimit_middleware Global anti-spam: maximum commands per minute. `from discord_interactions.slash import ratelimit_middleware` ```python def ratelimit_middleware( *, max_commands_per_minute: int = 30, per: str = 'user', ) -> Middleware ``` ```python from discord_interactions.slash import ratelimit_middleware slash.add_middleware(ratelimit_middleware(max_commands_per_minute=20)) ``` ### timing_middleware Reports commands slower than a threshold. `from discord_interactions.slash import timing_middleware` ```python def timing_middleware( *, slow_threshold_ms: float = 3000, on_slow: Callable[[SlashContext, float], Awaitable[None]] | None = None, ) -> Middleware ``` ```python from discord_interactions.slash import timing_middleware async def slow(ctx, ms): print(f"/{ctx.command_name} took {ms:.0f} ms") slash.add_middleware(timing_middleware(slow_threshold_ms=1500, on_slow=slow)) ``` ## Reference: Localization ### Localization Translations for command names, descriptions and choices. `from discord_interactions import Localization` ```python class Localization(default_locale: str = 'en-US') ``` - `def load_from_dict(data: Dict[str, Dict[str, str]]) -> None`: Load translations from a dictionary. - `def load_from_json(path: str | pathlib.Path) -> None`: Load translations from a JSON file. - `def load_from_folder(folder: str | pathlib.Path) -> None`: Load translations from a folder with one JSON file per locale. - `def get(key: str, locale: str | None = None) -> str | TranslationSet`: Get a translation or TranslationSet. - `def t(key: str, locale: str, **kwargs) -> str`: Get a translated string with formatting. - `def localizations(key: str) -> Dict[str, str]`: Get the localizations dict for the Discord API. - `def command(name_key: str, description_key: str) -> Dict[str, Any]`: Get localization data for a command. - `def option(name_key: str, description_key: str) -> Dict[str, Any]`: Get localization data for an option. - `def choice(name_key: str) -> Dict[str, Any]`: Get localization data for a choice. ```python from discord_interactions.slash import Localization loc = Localization() loc.load_from_dict({ "en-US": {"ping.name": "ping", "ping.desc": "Check latency"}, "fr": {"ping.name": "ping", "ping.desc": "Vérifier la latence"}, }) @slash.command(**loc.command("ping.name", "ping.desc")) async def ping(ctx): ... ``` ### LocalizedString Translated string built on the fly: `L("Bonjour").en_US("Hello")`. `from discord_interactions.slash import LocalizedString` ```python class LocalizedString(default: str) ``` - `def to_dict() -> Dict[str, str]`: Get localizations for Discord API. ```python from discord_interactions.slash import LocalizedString description = LocalizedString("Bot latency").fr("Latence du bot").de("Bot-Latenz") @slash.command(description=description.value, description_localizations=description.to_dict()) async def ping(ctx): ... ``` ### TranslationSet Translations of one key in several locales. `from discord_interactions.slash import TranslationSet` ```python class TranslationSet( key: str, translations: Dict[str, str] = , default: str | None = None, ) -> None ``` - `def get(locale: str, fallback: str | None = None) -> str`: Get translation for a locale with fallback. - `def to_api_dict() -> Dict[str, str]`: Convert to Discord API format. ```python translations = loc.get("ping.desc") # TranslationSet (every language) translations.get("fr") # "Latence du bot" translations.get("fr-CA") # "Latence du bot" (falls back to "fr") translations.to_api_dict() # {"en-US": "...", "fr": "..."} for the API ``` ### create_common_localization `Localization` pre-filled with the common translations. `from discord_interactions.slash import create_common_localization` ```python def create_common_localization() -> Localization ``` ```python from discord_interactions.slash import create_common_localization # Common error messages, already translated (en, fr, de, es) loc = create_common_localization() text = loc.t("errors.cooldown", "en-US", seconds=12) # "This command is on cooldown. Please wait 12.0 seconds." ``` ### L Shortcut for `LocalizedString`. `from discord_interactions import L` ```python def L(default: str) -> LocalizedString ``` ```python from discord_interactions.slash import L description = L("Check latency").fr("Vérifier la latence").de("Latenz prüfen") @slash.command(description=description.value, description_localizations=description.to_dict()) async def ping(ctx): ... ``` ## Reference: Sync ### CommandSync Fine-grained sync: targeted read, create, update and delete of commands. `from discord_interactions.slash import CommandSync` ```python class CommandSync(client: discord.Client) ``` - `async def get_global_commands() -> List[Dict[str, Any]]`: Get all registered global commands. - `async def get_guild_commands(guild_id: int) -> List[Dict[str, Any]]`: Get all registered commands for a guild. - `async def bulk_overwrite_global(commands: List[Dict[str, Any]]) -> List[Dict[str, Any]]`: Bulk overwrite all global commands. - `async def bulk_overwrite_guild(guild_id: int, commands: List[Dict[str, Any]]) -> List[Dict[str, Any]]`: Bulk overwrite all guild commands. - `async def create_global_command(command: Dict[str, Any]) -> Dict[str, Any]`: Create a single global command. - `async def update_global_command(command_id: int, command: Dict[str, Any]) -> Dict[str, Any]`: Update a single global command. - `async def delete_global_command(command_id: int) -> None`: Delete a global command. - `async def create_guild_command(guild_id: int, command: Dict[str, Any]) -> Dict[str, Any]`: Create a single guild command. - `async def update_guild_command(guild_id: int, command_id: int, command: Dict[str, Any]) -> Dict[str, Any]`: Update a single guild command. - `async def delete_guild_command(guild_id: int, command_id: int) -> None`: Delete a guild command. - `async def sync_global(commands: List[Dict[str, Any]], mode: SyncMode = SyncMode.FULL) -> SyncResult`: Sync commands globally. - `async def sync_guild(guild_id: int, commands: List[Dict[str, Any]], mode: SyncMode = SyncMode.FULL) -> SyncResult`: Sync commands to a specific guild. - `async def sync_tree(manager: SlashCommandManager, guilds: List[int] | None = None, mode: SyncMode = SyncMode.FULL) -> Dict[int | None, SyncResult]`: Sync all commands from a SlashCommandManager. ```python from discord_interactions.slash import CommandSync, SyncMode # Manual sync (SlashManager(client, auto_sync=False)) @client.event async def on_ready(): sync = CommandSync(client) results = await sync.sync_tree(slash, guilds=[123456789012345678], mode=SyncMode.SMART) for guild, result in results.items(): print(guild, result.created, "created", result.updated, "updated") ``` ### SyncResult Sync report: created, updated, deleted, errors. `from discord_interactions.slash import SyncResult` ```python class SyncResult( synced: int = 0, created: int = 0, updated: int = 0, deleted: int = 0, errors: List[str] = None, ) -> None ``` ```python result = await CommandSync(client).sync_global(slash.build_payload()) if result.success: print(f"{result.synced} commands synced") else: print("Errors:", result.errors) ``` ### SyncMode Sync strategies. `from discord_interactions.slash import SyncMode` `FULL = 'full'`, `SMART = 'smart'`, `APPEND = 'append'` ```python from discord_interactions.slash import SyncMode SyncMode.FULL # replaces everything: commands missing from the code are deleted SyncMode.SMART # only sends what changed SyncMode.APPEND # adds and updates, never deletes ``` ## Reference: Errors ### AutocompleteError An autocomplete failed. `from discord_interactions.slash import AutocompleteError` ```python def AutocompleteError(option_name: str, reason: str) ``` ```python from discord_interactions.slash import AutocompleteError async def cities(ctx): # An exception in autocomplete is written to the logs; # the user simply sees an empty list. if len(ctx.value) > 50: raise AutocompleteError("city", "Search too long") return await search_cities(ctx.value) ``` ### BotMissingPermissions Missing bot permissions. `from discord_interactions.slash import BotMissingPermissions` ```python def BotMissingPermissions(missing: List[str], command_name: str) ``` ```python @slash.on_error async def errors(ctx, error): if isinstance(error, BotMissingPermissions): await ctx.respond("Please give me: " + ", ".join(error.missing_permissions), ephemeral=True) return True return False ``` ### CheckFailure A `@check` failed. `from discord_interactions.slash import CheckFailure` ```python def CheckFailure(check_name: str, message: str | None = None) ``` ```python @slash.on_error async def errors(ctx, error): if isinstance(error, CheckFailure): await ctx.respond(error.message, ephemeral=True) return True return False ``` ### CommandDisabled Command disabled. `from discord_interactions.slash import CommandDisabled` ```python def CommandDisabled(command_name: str, reason: str | None = None) ``` ```python from discord_interactions.slash import CommandDisabled @slash.command(description="Casino") async def casino(ctx): if not casino_open: raise CommandDisabled("casino", "The casino is closed for the night.") ``` ### CommandNotFound Unknown command. `from discord_interactions.slash import CommandNotFound` ```python def CommandNotFound(command_name: str) ``` ```python from discord_interactions.slash import CommandNotFound # The module never raises it itself: use it in your own dispatching async def run(name, ctx): command = slash.get_command(name) if command is None: raise CommandNotFound(name) await command.invoke(ctx) ``` ### CommandOnCooldown Command on cooldown; `retry_after` gives the wait in seconds. `from discord_interactions import CommandOnCooldown` ```python def CommandOnCooldown(cooldown_type: str, retry_after: float, command_name: str) ``` ```python @slash.on_error async def errors(ctx, error): if isinstance(error, CommandOnCooldown): await ctx.respond(f"Try again in {error.retry_after:.0f} s.", ephemeral=True) return True return False ``` ### InvalidOption Option value rejected by validation. `from discord_interactions.slash import InvalidOption` ```python def InvalidOption(option_name: str, reason: str) ``` ```python @slash.command(description="Profile color") @option(String("hex", "Color", validator=lambda v: v.startswith("#") or "Must start with #")) async def color(ctx, hex): ... # "red" raises InvalidOption: "Invalid value for 'hex': Must start with #" ``` ### MaxConcurrency Too many simultaneous runs. `from discord_interactions.slash import MaxConcurrency` ```python def MaxConcurrency(command_name: str, max_concurrent: int, per: str) ``` ```python from discord_interactions.slash import MaxConcurrency running = set() @slash.command(description="Generate an image") async def generate(ctx): if ctx.user.id in running: raise MaxConcurrency("generate", 1, "user") # one generation at a time running.add(ctx.user.id) try: ... finally: running.discard(ctx.user.id) ``` ### MiddlewareError A middleware failed. `from discord_interactions.slash import MiddlewareError` ```python def MiddlewareError(middleware_name: str, reason: str) ``` ```python from discord_interactions.slash import Middleware, MiddlewareError async def check_account(ctx): if not await account_exists(ctx.user.id): raise MiddlewareError("account", "Create your account first with /signup.") return True slash.add_middleware(Middleware("account", before=check_account)) ``` ### MissingPermissions Missing user permissions. `from discord_interactions.slash import MissingPermissions` ```python def MissingPermissions(missing: List[str], command_name: str) ``` ```python @slash.on_error async def errors(ctx, error): if isinstance(error, MissingPermissions): await ctx.respond("You are missing: " + ", ".join(error.missing_permissions), ephemeral=True) return True return False ``` ### NotInGuild Command restricted to guilds. `from discord_interactions.slash import NotInGuild` ```python def NotInGuild(command_name: str) ``` ```python from discord_interactions.slash import NotInGuild @slash.on_error async def errors(ctx, error): if isinstance(error, NotInGuild): await ctx.respond("Use this command in a server.", ephemeral=True) return True return False ``` ### NotOwner Command restricted to owners. `from discord_interactions.slash import NotOwner` ```python def NotOwner() ``` ```python from discord_interactions.slash import NotOwner @slash.on_error async def errors(ctx, error): if isinstance(error, NotOwner): await ctx.respond("This command is reserved for the bot owner.", ephemeral=True) return True return False ``` ### NSFWChannelRequired Command restricted to NSFW channels. `from discord_interactions.slash import NSFWChannelRequired` ```python def NSFWChannelRequired(command_name: str) ``` ```python from discord_interactions.slash import NSFWChannelRequired @slash.on_error async def errors(ctx, error): if isinstance(error, NSFWChannelRequired): await ctx.respond("Only in an NSFW channel.", ephemeral=True) return True return False ``` ### SlashCommandError Base of every slash command error. `from discord_interactions import SlashCommandError` ```python def SlashCommandError() ``` ```python from discord_interactions.slash import SlashCommandError @slash.on_error async def errors(ctx, error): if isinstance(error, SlashCommandError): # every error raised by the module await ctx.respond(str(error), ephemeral=True) return True return False ``` ## Reference: Other ### COMMON_TRANSLATIONS Common ready-made translations. `from discord_interactions.slash import COMMON_TRANSLATIONS` ```python from discord_interactions.slash import COMMON_TRANSLATIONS print(COMMON_TRANSLATIONS["en-US"]["errors.guild_only"]) # "This command can only be used in a server." ``` ### LOCALES Locale codes supported by Discord. `from discord_interactions.slash import LOCALES` ```python from discord_interactions.slash import LOCALES # Language codes accepted by Discord "fr" in LOCALES # True "fr-FR" in LOCALES # False: Discord uses "fr" ```