Crea un plugin
La referencia completa del SDK para desarrolladores de plugins — Python en sandbox, entregado como zip, distribuido a través del marketplace.
Los plugins son procesos Python en sandbox. Escribe un handler, declara tus capacidades, envía un zip — lo ejecutamos en un contenedor Docker restringido y transmitimos eventos de Discord mediante JSON-RPC.
En esta página Eventos de Discord · Comandos de barra · Botones y menús · Diálogos modales · Tareas en segundo plano · Programaciones cron
Eventos de Discord
Usa @plugin.on_event(name) para eventos de Discord sin procesar. Se envían dieciséis tipos de eventos a los plugins:
| Evento | Aspectos destacados del payload |
|---|---|
| message_create | message_id, channel_id, author_id, author_bot, content, created_at |
| message_edit | message_id, channel_id, content |
| message_delete | message_id, channel_id |
| member_join | user_id, username, guild_id |
| member_leave | user_id, username, guild_id |
| member_update | user_id, roles |
| reaction_add | message_id, channel_id, user_id, emoji |
| reaction_remove | message_id, channel_id, user_id, emoji |
| voice_state_update | user_id, before_channel_id, after_channel_id, self_mute, self_deaf |
| interaction_create | interaction_id, interaction_type, command_name, options, custom_id, values, modal_values |
| channel_create | channel_id, name, type |
| channel_delete | channel_id, name |
| channel_update | channel_id, name |
| role_create | role_id, name |
| role_delete | role_id, name |
| role_update | role_id, name |
Field availability can differ slightly by delivery path (for example author_bot), so read optional fields defensively with event.get(...).
Nota: para comandos de barra, clics en botones y envíos de modales, usa los decoradores dedicados a continuación — son más sencillos que analizar interaction_create.
Message text is capability-gated: without events:message_content the whole payload is reduced to IDs and timestamps — content, author fields and attachments are omitted (interaction fields like options and custom_id are always preserved). The events still fire either way. All 16 payloads also ship typed shapes you can import for autocomplete: from yourbot_sdk.events import MessageCreate, MemberJoin, …
Canal de entrega
- Delivered events arrive at least once: your handler can be called twice for the same event, so make side effects idempotent or guard with
ctx.ephemeral.dedup(…). Under extreme load the platform sheds gateway events rather than buffering them, so don't build flows that assume every Discord event reaches you. - If a handler raises, the event is marked failed and is not retried. The full traceback lands in your plugin logs.
- 5 consecutive crashes within 5 minutes quarantines the plugin (see the Production tab).
- Handlers for the same server run on a small thread pool and can execute concurrently. Module-level state shared across handlers must be thread-safe (use
threading.Lock).
Comandos de barra
Dos pasos: declara el comando en manifest.json y luego gestiónalo con @plugin.on_slash_command. La plataforma sincroniza el registro del comando con Discord automáticamente cuando se publica tu versión.
Atajo de capacidad: declarar cualquier slash_commands añade automáticamente interaction:respond a capabilities_required — no necesitas listarlo tú mismo. La declaración explícita en el ejemplo siguiente es inofensiva pero redundante.
Name rules: command names must be unique within your manifest and may not use names reserved by built-in YourBot plugins (see the definitive list; yourbot validate checks it locally). Uploads that break these rules are rejected at publish time. If another installed plugin already uses one of your names on a server, the plugin installed first keeps the name there and yours is skipped.
Interaction timing. The platform acknowledges each slash command for you before your handler runs (users see a "thinking…" placeholder), and your respond() fills it in — you have up to 15 minutes, not Discord's raw 3 seconds. The exception is modals: a modal must be the first response, so a command that opens one must set "defer_on_dispatch": false in its manifest entry and then call send_modal within 3 seconds.
Declaración en manifest.json
{
"id": "my_plugin",
"name": "My Plugin",
"version": "1.0.0",
"capabilities_required": ["interaction:respond"],
"slash_commands": [
{
"name": "greet",
"description": "Say hello to someone",
"options": [
{
"name": "user",
"description": "Who to greet",
"type": 6,
"required": true
},
{
"name": "message",
"description": "Custom greeting",
"type": 3,
"required": false
},
{
"name": "tone",
"description": "How formal?",
"type": 3,
"required": false,
"choices": [
{"name": "Casual", "value": "casual"},
{"name": "Formal", "value": "formal"}
]
}
]
}
]
}
Tipos de opciones de Discord que usarás con frecuencia:
| Tipo | Significado |
|---|---|
| 3 | Cadena |
| 4 | Entero |
| 5 | Booleano |
| 6 | Usuario (se resuelve en un ID de usuario) |
| 7 | Canal |
| 8 | Rol |
| 10 | Número (flotante) |
Controlador
@plugin.on_slash_command("greet")
def greet(ctx: Context, event: dict):
options = {opt["name"]: opt["value"] for opt in event.get("options", [])}
target_user_id = options.get("user")
custom_msg = options.get("message", "Hey there!")
ctx.interaction.respond(
content=f"<@{target_user_id}> {custom_msg}",
)
Because the platform already acknowledged the interaction, respond() here edits the "thinking…" placeholder — take the time you need (up to 15 minutes). Additional messages go through followup().
Autocomplete is not forwarded. The platform does not currently deliver Discord autocomplete interactions to plugins, so declare static choices on your options (see the tone option above) instead of autocomplete handlers.
Botones y menús
Las clases de componentes generan el JSON de componentes de Discord por ti. Aceptan valores en forma de cadena, no enumeraciones.
Button
from yourbot_sdk import Button, ActionRow
Button(
label="Click me",
custom_id="btn_hi",
style="primary", # "primary" | "secondary" | "success" | "danger" | "link"
emoji="🎉",
disabled=False,
)
# Link buttons use url instead of custom_id
Button(label="Docs", url="https://yourbot.gg/dev/docs", style="link")
SelectMenu
from yourbot_sdk import SelectMenu, SelectOption, ActionRow
menu = SelectMenu(
custom_id="pick_role",
options=[
SelectOption(label="Gamer", value="role_gamer", description="Get pinged for game nights"),
SelectOption(label="Music", value="role_music"),
SelectOption(label="Art", value="role_art", emoji="🎨"),
],
placeholder="Pick your interests…",
min_values=1,
max_values=2,
)
ActionRow
Discord muestra los componentes en filas. Envuelve uno o más componentes en un ActionRow y pásalo como components=[…]:
@plugin.on_slash_command("menu")
def menu_cmd(ctx: Context, event: dict):
row = ActionRow(
Button("Yes", custom_id="yes", style="success"),
Button("No", custom_id="no", style="danger"),
)
ctx.interaction.respond(content="Pick one:", components=[row])
@plugin.on_component("yes")
def yes_clicked(ctx: Context, event: dict):
ctx.interaction.respond(content="✅", ephemeral=True)
@plugin.on_component("no")
def no_clicked(ctx: Context, event: dict):
ctx.interaction.respond(content="❌", ephemeral=True)
Dynamic custom_ids: prefix matching
@plugin.on_component("exact_id") matches the whole string. When your custom_id encodes state (page numbers, vote targets), register with prefix= instead and parse the rest yourself. Exactly one of custom_id= or prefix= must be given.
@plugin.on_component(prefix="page:")
def handle_page(ctx: Context, event: dict):
cid = event["custom_id"] # e.g. "page:next:5"
_, direction, index = cid.split(":", 2)
...
Buttons posted by an older version of your plugin stay clickable on Discord forever. If you encode state in custom_id, embed a schema version too (e.g. "v2:vote:42") so stale buttons can be detected and politely refused.
Updating a message in place v0.7.0
Inside a component handler, pass update_message=True to respond() to edit the message the button or menu is attached to (game boards, pagination, live leaderboards) instead of sending a new reply:
@plugin.on_component(prefix="counter:")
def bump(ctx: Context, event: dict):
count = int(event["custom_id"].split(":")[1]) + 1
ctx.interaction.respond(
content=f"Count: **{count}**",
components=[ActionRow(Button("+1", custom_id=f"counter:{count}"))],
update_message=True,
)
- Component interactions only. The platform rejects it for slash commands and modal submits.
- The fields you pass replace the message's current content/embeds/components, so pass everything the updated message should contain.
ephemeralis ignored (the message keeps its original visibility). You can call it repeatedly within the 15-minute interaction window.
Diálogos modales
Los modales recopilan texto del usuario. Abre uno con ctx.interaction.send_modal y gestiona el envío con @plugin.on_modal_submit:
Required manifest flag: Discord only accepts a modal as the first response, and the platform normally acknowledges slash commands for you before your handler runs. A command that opens a modal must opt out of that acknowledgement on its slash_commands entry:
{ "name": "feedback", "description": "Send feedback", "defer_on_dispatch": false }
With the flag set, call send_modal promptly (within Discord's 3-second window). Without it the modal is rejected with an API error.
from yourbot_sdk import TextInput
@plugin.on_slash_command("feedback")
def feedback_cmd(ctx: Context, event: dict):
ctx.interaction.send_modal(
title="Send Feedback",
custom_id="feedback_form",
fields=[
TextInput(
label="Subject",
custom_id="subject",
style="short", # "short" | "paragraph"
placeholder="Quick summary",
required=True,
max_length=100,
),
TextInput(
label="Details",
custom_id="details",
style="paragraph",
required=False,
max_length=2000,
),
],
)
@plugin.on_modal_submit("feedback_form")
def feedback_submitted(ctx: Context, event: dict):
values = event["modal_values"] # {"subject": "...", "details": "..."}
ctx.kv.set(f"feedback:{event['interaction_id']}", values)
ctx.interaction.respond(content="Thanks for the feedback!", ephemeral=True)
Tareas en segundo plano
How schedules reach production: declare each @plugin.cron task in your manifest's "cron" array (see below) and the platform fires it per installed server — UTC, a 5-minute floor, up to 5 entries. @plugin.schedule (fixed intervals) runs only in local yourbot dev; for interval-style work in production use a cron spec or the event-driven pattern on Pool mode.
@plugin.schedule(seconds) ejecuta una corrutina en un intervalo fijo, comenzando después de que haya transcurrido el primer intervalo. El intervalo mínimo es de 30 segundos.
@plugin.schedule(300) # every 5 minutes
def heartbeat(ctx: Context):
count = ctx.kv.increment("heartbeats")
ctx.log(f"heartbeat #{count}")
Runs never overlap — the next interval is counted from when the previous run finishes, so a slow handler delays later runs rather than stacking them.
Programaciones cron
@plugin.cron(spec) ejecuta una tarea según una programación cron de 5 campos en UTC. Úsalo cuando quieras que un trabajo se ejecute a una hora determinada (p. ej., lunes a las 09:00) en lugar de en un intervalo fijo desde el arranque.
Formato de especificación: "minute hour day-of-month month day-of-week" — cada campo admite *, */N, N, N,M,…, N-M, N-M/S. El día de la semana va de 0=domingo a 6=sábado.
@plugin.cron("0 9 * * 1") # every Monday at 09:00 UTC
def weekly_report(ctx: Context):
ctx.log("Sending weekly report")
@plugin.cron("*/15 * * * *") # every 15 minutes
def refresh_cache(ctx: Context):
ctx.kv.increment("cache_refreshes")
@plugin.cron("30 0 1 * *") # 00:30 UTC on the 1st of each month
def monthly_rollup(ctx: Context):
...
To run in production, each task also needs a manifest entry whose name matches the function (the platform reads schedules from the manifest, not your code):
"cron": [
{"spec": "0 9 * * 1", "name": "weekly_report"},
{"spec": "*/15 * * * *", "name": "refresh_cache"}
]
- Specs firing more often than every 5 minutes are rejected at upload, and a manifest carries at most 5 cron entries.
yourbot validateapplies the same checks and warns when a decorated task has no matching manifest entry (it would never run in production). - Delivery rides the normal event pipeline per installed server: your handler gets a tenant-scoped
ctx, delivery is at-least-once (rare replays possible — keep handlers idempotent or guard withctx.ephemeral.dedup), and a missed tick is not replayed. - Las especificaciones no válidas lanzan
ValueErroren el momento del registro — verás el error durante el arranque, no silenciosamente en el primer fallo.
SDK v0.8.4 · Última actualización: julio de 2026 · Volver al Portal de desarrolladores