← Documentation  /  Developer Guide

Build a plugin

The full SDK reference for plugin developers: sandboxed Python, shipped as a zip, distributed through the marketplace.

These docs are publicly viewable. To publish a plugin you'll need a free YourBot account: sign in to access the Dev Portal.
SDK v0.8.4

Plugins are sandboxed Python processes. Write a handler, declare your capabilities, ship a zip and we run it in a locked-down Docker container, streaming Discord events to it over JSON-RPC.

Discord events

Use @plugin.on_event(name) for raw Discord events. Sixteen event types are dispatched to plugins:

EventPayload highlights
message_createmessage_id, channel_id, author_id, author_bot, content, created_at
message_editmessage_id, channel_id, content
message_deletemessage_id, channel_id
member_joinuser_id, username, guild_id
member_leaveuser_id, username, guild_id
member_updateuser_id, roles
reaction_addmessage_id, channel_id, user_id, emoji
reaction_removemessage_id, channel_id, user_id, emoji
voice_state_updateuser_id, before_channel_id, after_channel_id, self_mute, self_deaf
interaction_createinteraction_id, interaction_type, command_name, options, custom_id, values, modal_values
channel_createchannel_id, name, type
channel_deletechannel_id, name
channel_updatechannel_id, name
role_createrole_id, name
role_deleterole_id, name
role_updaterole_id, name

Field availability can differ slightly by delivery path (for example author_bot), so read optional fields defensively with event.get(...).

Note: for slash commands, button clicks, and modal submits use the dedicated decorators below — they're easier than picking through 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, …

Delivery guarantees

  • 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).

Slash commands

Two steps: declare the command in manifest.json, then handle it with @plugin.on_slash_command. The platform syncs the command registration with Discord automatically when your version is published.

Capability shortcut: declaring any slash_commands automatically adds interaction:respond to capabilities_required — you don't have to list it yourself. The explicit declaration in the example below is harmless but redundant.

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.

Declaration in 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"}
          ]
        }
      ]
    }
  ]
}

Discord option types you'll commonly use:

TypeMeaning
3String
4Integer
5Boolean
6User (resolves to a user ID)
7Channel
8Role
10Number (float)

Handler

@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.

Buttons & menus

Component classes build Discord component JSON for you. They take string-style values, not enums.

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 shows components in rows. Wrap one or more components in an ActionRow and pass it as 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.
  • ephemeral is ignored (the message keeps its original visibility). You can call it repeatedly within the 15-minute interaction window.

Modal dialogs

Modals collect text input from the user. Open one with ctx.interaction.send_modal and handle the submission with @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)

Background tasks

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) runs a regular (synchronous) function on a fixed interval, starting after the first interval has elapsed. Do not declare it async def: nothing awaits it, so an async body would never execute. Keep intervals at 30 seconds or more; tighter loops burn your CPU allowance and get flagged in review.

@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.

Cron schedules

@plugin.cron(spec) runs a task on a 5-field cron schedule in UTC. Use this when you want a job to fire at a wall-clock time (e.g. Monday 09:00) instead of a fixed interval since boot.

Spec format: "minute hour day-of-month month day-of-week" — each field supports *, */N, N, N,M,…, N-M, N-M/S. Day-of-week is 0=Sunday through 6=Saturday.

@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 validate applies 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 with ctx.ephemeral.dedup), and a missed tick is not replayed.
  • Invalid specs raise ValueError at registration and fail yourbot validate — you'll see the error before upload, not silently at the first miss.

SDK v0.8.4 · Last updated July 2026 · Back to Dev Portal