Créer un plugin
La référence complète du SDK pour les développeurs de plugins — Python sandboxé, livré sous forme de zip, distribué via la marketplace.
Les plugins sont des processus Python isolés. Écrivez un gestionnaire, déclarez vos capacités, envoyez un zip — nous l'exécutons dans un conteneur Docker verrouillé et lui transmettons les événements Discord via JSON-RPC.
Sur cette page Événements Discord · Commandes slash · Boutons & menus · Boîtes de dialogue modales · Tâches en arrière-plan · Planifications cron
Événements Discord
Utilisez @plugin.on_event(name) pour les événements Discord bruts. Seize types d'événements sont transmis aux plugins :
| Événement | Points forts de la charge utile |
|---|---|
| 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(...).
Remarque : pour les commandes slash, les clics sur les boutons et les soumissions de modales, utilisez les décorateurs dédiés ci-dessous — ils sont plus simples que de parcourir 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 livraison
- 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).
Commandes slash
Deux étapes : déclarez la commande dans manifest.json, puis gérez-la avec @plugin.on_slash_command. La plateforme synchronise l'enregistrement de la commande avec Discord automatiquement lors de la publication de votre version.
Raccourci de capacité : déclarer des slash_commands ajoute automatiquement interaction:respond à capabilities_required — vous n'avez pas à le lister vous-même. La déclaration explicite dans l'exemple ci-dessous est sans danger mais redondante.
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.
Déclaration dans 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"}
]
}
]
}
]
}
Types d'options Discord que vous utiliserez couramment :
| Type | Signification |
|---|---|
| 3 | Chaîne |
| 4 | Entier |
| 5 | Booléen |
| 6 | Utilisateur (résout vers un ID utilisateur) |
| 7 | Canal |
| 8 | Rôle |
| 10 | Nombre (flottant) |
Gestionnaire
@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.
Boutons & menus
Les classes de composants génèrent le JSON des composants Discord pour vous. Elles acceptent des valeurs de type chaîne, pas des énumérations.
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 affiche les composants en rangées. Encapsulez un ou plusieurs composants dans un ActionRow et passez-le en tant que 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.
Boîtes de dialogue modales
Les modales collectent la saisie de texte de l'utilisateur. Ouvrez-en une avec ctx.interaction.send_modal et gérez la soumission avec @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)
Tâches en arrière-plan
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) exécute une coroutine à intervalle fixe, en démarrant après l'écoulement du premier intervalle. L'intervalle minimum est de 30 secondes.
@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.
Planifications cron
@plugin.cron(spec) exécute une tâche selon un planning cron à 5 champs en UTC. Utilisez ceci lorsque vous souhaitez qu'une tâche se déclenche à une heure précise (par ex. lundi à 09:00) plutôt qu'à un intervalle fixe depuis le démarrage.
Format de la spec : "minute heure jour-du-mois mois jour-de-la-semaine" — chaque champ supporte *, */N, N, N,M,…, N-M, N-M/S. Le jour de la semaine est 0=Dimanche jusqu'à 6=Samedi.
@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. - Les specs invalides lèvent une
ValueErrorà l'enregistrement — vous verrez l'erreur au démarrage, pas silencieusement au premier manquement.
SDK v0.8.4 · Dernière mise à jour juillet 2026 · Retour au portail développeur