← Documentation  /  Guide du développeur

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.

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

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.

Tableaux de bord des plugins

Chaque plugin peut exposer une page de paramètres/données sur le tableau de bord côté utilisateur. Deux modes — choisissez-en un :

  • Mode manifeste — déclarez des widgets en JSON, écrivez des gestionnaires de données Python. Thème appliqué automatiquement, aucun HTML à écrire.
  • Mode Iframe — contrôle total HTML/CSS/JS. À utiliser lorsque vous avez besoin d'une interface personnalisée (glisser-déposer, graphiques non couverts par le manifeste, formulaires personnalisés).

Both modes live in the same file: dashboard_manifest.json, shipped in your version zip (the zip root or any folder works). You can also author it in the Dev Portal's Dashboard Editor, which writes the same JSON for you.

Mode manifeste

Declare "mode": "manifest" and a list of pages with widgets. rpc_method values are the names you registered with @plugin.on_dashboard(…):

{
  "mode": "manifest",
  "pages": [
    {
      "id": "overview",
      "title": "Overview",
      "widgets": [
        {
          "id": "active_users",
          "type": "stat_card",
          "label": "Active users",
          "icon": "📊",
          "width": "quarter",
          "rpc_method": "get_active_users"
        },
        {
          "id": "messages_chart",
          "type": "chart",
          "chart_type": "line",
          "title": "Messages per day",
          "refresh_seconds": 30,
          "rpc_method": "get_messages_chart"
        },
        {
          "id": "settings_form",
          "type": "form",
          "title": "Settings",
          "rpc_method": "get_settings",
          "save_rpc_method": "save_settings",
          "fields": [
            {"key": "channel_id", "label": "Welcome channel", "type": "text"},
            {"key": "message",    "label": "Welcome text",    "type": "textarea"}
          ]
        }
      ]
    }
  ]
}
  • Widths: "quarter", "third", "half", "two_thirds", "full" (default).
  • Auto-refresh: "refresh_seconds": 30 re-fetches periodically; a manual refresh button appears on every widget.
  • period accepte 1h, 24h, 7d, 30d, 90d. Agrégats : sum (par défaut), avg, max, min.
  • Form field types: text (default), textarea, number, select, multi_select, toggle, color, date, range. Every field renders label and help_text. placeholder applies to text, textarea and number. required is enforced on every type except toggle, color and range. select and multi_select need "options": [{"value": "...", "label": "..."}]. number and range accept min, max and step.
  • Extra RPC args: "rpc_params": {"stat": "total"} is merged into the params your handler receives.
  • Shared handlers: a widget may set "path" (e.g. "kpis.0" or "activity") to extract its slice from a bigger RPC response, so one get_overview handler can drive a whole page of widgets.
  • Access control: pages and widgets accept "permission": "viewer" | "manager" | "owner"; manifest values can only raise the bar, never lower it. Saves always require at least manager, enforced server-side regardless of what your UI shows.

Prefer Python over raw JSON? yourbot_sdk.dashboard ships fluent builders (Manifest, Page, StatCard, Chart.line(…), Form, …) that emit exactly this JSON.

Types de widgets pris en charge

TypeLe gestionnaire retourne
stat_card{"value": 1234, "change": "+12%", "trend": "up", "color": "green"} (trend: up / down / flat; color: green / red / gold / cyan)
chart{"labels": [...], "series": [{"name": "...", "data": [...]}]}
table{"rows": [{...}, ...], "total": 100, "page_size": 20} — Pourquoi déclarer ? "columns": [{"key": "...", "label": "..."}] on the widget (required); headers and cell order come from it. Your handler receives params["page"] (1-indexed) when the viewer pages with Prev/Next
list{"items": [{"label": "...", "value": "..."}, ...]}
progress_bar{"value": 75, "max": 100, "label": "…"}
text{"content": "Plain text content"}
markdown{"markdown": "# Heading\n- bullet"} (safe markdown, raw HTML is stripped)
alert{"level": "info", "message": "…"} — level: info / warning / error / success
formget → {"values": {...}}; save → {"ok": true} ou {"ok": false, "error": "…"}

Gestionnaires Python

@plugin.on_dashboard("get_active_users")
def active_users(ctx: Context, params: dict):
    n = ctx.kv.count(prefix="active_user:")
    return {"value": n, "change": "+12%", "trend": "up"}

@plugin.on_dashboard("get_messages_chart")
def messages_chart(ctx: Context, params: dict):
    return ctx.metrics.query("messages", period="7d")

@plugin.on_dashboard("get_settings")
def get_settings(ctx: Context, params: dict):
    return {"values": {
        "channel_id": ctx.kv.get("welcome_channel") or "",
        "message":    ctx.kv.get("welcome_message") or "Welcome!",
    }}

@plugin.on_dashboard("save_settings")
def save_settings(ctx: Context, params: dict):
    # Form saves arrive as params["values"], keyed by each field's "key".
    values = params.get("values") or {}
    message = str(values.get("message", "")).strip()
    if len(message) > 500:
        return {"ok": False, "error": "Keep the welcome text under 500 characters"}
    ctx.kv.set("welcome_channel", values.get("channel_id", ""))
    ctx.kv.set("welcome_message", message)
    return {"ok": True}
  • 8-second timeout per handler call; the widget shows an error past it.
  • Fresh Context per call: every dashboard RPC gets a ctx scoped to the server the viewer is looking at, even in pool mode (one shared worker serves every server that installed your plugin). params carries discord_srv_id (a string on widget reads, an int on form saves and iframe RPCs — compare with str(params.get("discord_srv_id"))) plus the viewer's identity: discord_user_id, viewer_user_id, viewer_username and username.
  • Read caching: widget responses are cached ~5 seconds per (plugin, server, method, params); each table page caches separately and writes bypass the cache.
  • Serialized: only one dashboard RPC runs at a time per worker, and handlers share the process with your event handlers.
  • Cold start: if no worker is running for your plugin yet, the widget shows “Starting plugin…” and retries up to 5 times at 1.5-second intervals.

Mode Iframe

Iframe mode turns on when your dashboard_manifest.json declares "mode": "iframe" and every page names an HTML file via "src" (the validator rejects iframe pages without one). Ship those files in a dashboard/ directory; the platform serves them on a per-plugin sandboxed origin inside an iframe and gives you a JS bridge (YourBotSDK) for backend RPC, theming and lifecycle.

{
  "mode": "iframe",
  "pages": [
    {"id": "overview", "title": "Overview", "src": "index.html"}
  ]
}
my_plugin/
├── manifest.json
├── dashboard_manifest.json   # the JSON above
├── __main__.py
└── dashboard/
    ├── index.html       # page "src", served relative to dashboard/
    ├── style.css
    └── app.js

The sandbox CSP allows same-origin assets only, so bundle every stylesheet, script, image and font inside dashboard/ and reference them with relative paths. The one exception is the bridge script itself: /static/yourbot-sdk.js is served on the sandboxed origin, so load it directly. Pages may embed third-party <iframe>s only for domains you list in proxy_domains_requested.

HTML minimal

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>body { color: var(--yourbot-text); background: transparent; }</style>
</head>
<body>
  <h1>My plugin</h1>
  <div id="stat">Loading…</div>

  <script src="/static/yourbot-sdk.js"></script>
  <script>
    YourBotSDK.ready(async function () {
      const ctx = YourBotSDK.getContext();
      // ctx = { plugin_id, server_id, page_id, user: {id, display_name, role} }

      const res = await YourBotSDK.metrics.total("messages_sent", "30d");
      document.getElementById("stat").textContent = (res.total || 0) + " messages";

      YourBotSDK.resize();   // ask the iframe host to resize to fit content
    });
  </script>
</body>
</html>

YourBot SDK

Every method returns a Promise. The bridge only forwards allow-listed RPC namespaces (kv, metrics, sql, dashboard). The kv, metrics and sql calls run host-side against the same per-install storage your Python handlers see: they never wake your plugin code, but they need a live pool worker for your plugin and they enforce the same capabilities as plugin-side calls (storage:kv for kv, storage:sql for sql, none for metrics). Reads need the viewer role; writes (kv.set, kv.setMany, kv.delete, kv.increment, kv.decrement, metrics.record, sql.execute and save_* dashboard handlers) need manager.

AppelObjectif
YourBotSDK.ready(fn)Exécute fn après la complétion du handshake du pont.
YourBotSDK.getContext()Synchronisation — retourne le serveur / plugin / utilisateur / thème.
YourBotSDK.getUser()Sync — the viewer: {id, display_name, role}; role is viewer, manager or owner.
YourBotSDK.getTheme()Sync — the current theme's CSS variable values as a map.
YourBotSDK.on(event, fn) / off(event, fn)Listen for "ready", "theme" or "navigate". The theme event arrives once, at the handshake.
YourBotSDK.resize(height?)Demander à l'iframe hôte de redimensionner. Détecte automatiquement le contenu si aucune hauteur n'est fournie.
YourBotSDK.navigateTo(pageId)Passer à une autre page dans le manifeste de votre tableau de bord.
YourBotSDK.rpc(method, params)Appeler un gestionnaire Python @plugin.on_dashboard.
YourBotSDK.kv.get / set / delete / list / listValues / getMany / setMany / increment / decrement / countDirect KV access (needs storage:kv). Resolves to result objects: get → {ok, value}; set / setMany / delete → {ok}; list → {ok, keys} (limit cap 1000); listValues → {ok, values} (limit cap 100); getMany → {ok, values} (max 50 keys); increment / decrement → {ok, value}; count → {ok, count}.
YourBotSDK.metrics.query / total / recordPull metrics for charts or record a data point. total → {ok, total}, so unwrap before rendering. No capability required; record needs a manager viewer.
YourBotSDK.sql.query / executeSQL access (needs storage:sql). query → {ok, rows, truncated} (limit cap 1000); execute → {ok, rowcount}.
YourBotSDK.openPlatformPopup(path, features?)Open a platform path (e.g. /buy/…) in a popup resolved against the parent dashboard's origin. Returns the popup window, or null before the handshake. Pass a path, not a full URL.

Bridge calls are rate-limited (600/min) and rejected errors carry a machine-readable .code (e.g. RPC_TIMEOUT). If no worker is running for your plugin yet, kv / metrics / sql calls fail with a “no running worker” error until it starts.

Variables de thème

L'iframe hérite ces propriétés CSS personnalisées du tableau de bord afin que votre widget s'intègre sans avoir à rétro-ingéniérer les couleurs :

:root {
  --yourbot-bg;       --yourbot-surface;  --yourbot-surface-alt;
  --yourbot-border;   --yourbot-gold;     --yourbot-text;
  --yourbot-muted;    --yourbot-success;  --yourbot-error;
  --yourbot-warning;  --yourbot-info;
}

Legacy --maid-* aliases are also set for older dashboards. Delivery order matters: ready fires before the theme message lands, so inside a ready callback getTheme() is still empty and the CSS variables are not yet set. Register an on("theme") listener (it fires once, right after ready) and do theme-dependent work there; plain CSS that uses var(--yourbot-*) just works once the variables land.

Pack de styles prêt à l'emploi nouveau

Manifest widgets are themed automatically. For iframe dashboards the platform ships a small CSS + JS pack so your custom HTML matches the host without copying styles. Bundle both files into your zip under dashboard/sdk/ (grab the current copies from /static/sdk/ui.css?v=2 and /static/sdk/ui.js?v=2) and reference them relative to dashboard/:

<link rel="stylesheet" href="sdk/ui.css">
<script src="sdk/ui.js" defer></script>

Contenu du pack :

  • .maid-btn / .maid-btn-primary / .maid-btn-danger — boutons correspondant à la palette de la plateforme
  • .maid-input / .maid-textarea / .maid-select — champs de formulaire avec anneaux de focus sensibles au thème
  • .maid-card — conteneur stylisé avec emplacements en-tête/aide
  • .maid-badge / .maid-pill — indicateurs d'état avec couleurs sémantiques (ok / avert / erreur / info / muet)
  • .maid-table — tableau de données sensible au thème
  • .maid-stack / .maid-grid / .maid-row — utilitaires de mise en page
  • .maid-empty — conteneur d'état vide

Utilitaires JS (sous l'espace de noms window.MaidUI) :

YourBotUI.toast("Saved!", "ok");
YourBotUI.confirm("Delete this record?").then((yes) => { if (yes) /* ... */ });
YourBotUI.modal({ title: "Details", body: bodyElement, actions: [/* ... */] });
YourBotUI.tabs(container);                      // wire [data-yourbot-tab] tabs
YourBotUI.table(target, { columns, rows });     // themed, click-to-sort table
YourBotUI.copy("text to clipboard");

// Form saves: call your @plugin.on_dashboard("save_settings") handler.
// It receives the object as params["values"].
const values = YourBotUI.serializeForm(myFormElement);
await YourBotSDK.rpc("save_settings", { values });

YourBotUI.fetchJSON(url, init) is bridge-aware: inside a sandboxed iframe it routes /p/{plugin_id}/dashboard/rpc/{method} URLs through YourBotSDK.rpc (load yourbot-sdk.js first) and resolves to the endpoint's {ok, data} body, while on main-origin pages it fetches directly and adds the page's CSRF token to non-GET requests.

SDK v0.8.4 · Dernière mise à jour juillet 2026 · Retour au portail développeur