← Documentação  /  Guia do Desenvolvedor

Construir um plugin

A referência completa do SDK para desenvolvedores de plugins — Python em sandbox, distribuído como zip, disponibilizado através do 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 são processos Python em sandbox. Escreva um handler, declare suas capacidades, envie um zip — executamos em um container Docker bloqueado e transmitimos eventos do Discord para ele via JSON-RPC.

Eventos do Discord

Use @plugin.on_event(name) para eventos brutos do Discord. Dezesseis tipos de eventos são despachados para plugins:

EventoDestaques da carga
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(...).

Nota: para slash commands, cliques em botões e envios de modal, use os decoradores dedicados abaixo — são mais fáceis do que analisar 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

Dois passos: declare o comando em manifest.json e depois manipule-o com @plugin.on_slash_command. A plataforma sincroniza o registro de comando com Discord automaticamente quando sua versão é publicada.

Atalho de capacidade: declarar qualquer slash_commands adiciona automaticamente interaction:respond a capabilities_required — você não precisa listá-lo você mesmo. A declaração explícita no exemplo abaixo é inofensiva, mas 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.

Declaração em 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 opção do Discord que você usará comumente:

TipoSignificado
3String
4Integer
5Boolean
6Usuário (resolve para um ID de usuário)
7Canal
8Função
10Número (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.

Botões & menus

As classes de componentes criam JSON de componentes do Discord para você. Elas recebem valores em estilo string, não 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 mostra componentes em linhas. Envolva um ou mais componentes em um ActionRow e passe 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.
  • ephemeral is ignored (the message keeps its original visibility). You can call it repeatedly within the 15-minute interaction window.

Diálogos modais

Modais coletam entrada de texto do usuário. Abra um com ctx.interaction.send_modal e trate o envio com @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)

Tarefas em 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) executa uma coroutine em um intervalo fixo, começando após o primeiro intervalo ter decorrido. O intervalo mínimo é 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.

Cronogramas Cron

@plugin.cron(spec) executa uma tarefa em um cronograma cron de 5 campos em UTC. Use isto quando você quer que um trabalho dispare em um horário de relógio de parede (p.ex. Segunda 09:00) em vez de um intervalo fixo desde o boot.

Formato de Spec: "minuto hora dia-do-mês mês dia-da-semana" — cada campo suporta *, */N, N, N,M,…, N-M, N-M/S. Dia-da-semana é 0=Domingo até 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 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.
  • Specs inválidas levantam ValueError no registro — você verá o erro durante o boot, não silenciosamente na primeira falta.

SDK v0.8.4 · Última atualização em julho de 2026 · Voltar ao Dev Portal