discord-interactions.py

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#

from discord_interactions import InteractionRouter router = InteractionRouter()  @router.on("like")async def like(interaction, data): ...  @router.modal("profile")async def profile(interaction, values): ...  @client.eventasync 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#

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.

Signed custom_id#

A modified client can send any custom_id. For a sensitive action (purchase, withdrawal, moderation), sign it:

button = create_signed_button("buy", SECRET, data={"price": 150}, ttl_seconds=60, label="Buy")  @client.eventasync 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.

Type a name: create_button, ModalBuilder, cooldown.