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.
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.
Nesta página Modo manifesto · Widget LFG · Handlers Python · Modo Iframe · JS API · Variáveis de tema · Iniciar Backfill
Painéis de plugin
Todo plugin pode expor uma página de configurações/dados no painel voltado para o usuário. Dois modos — escolha um:
- Modo manifesto — declare widgets em JSON, escreva handlers de dados Python. Tema grátis, sem HTML para escrever.
- Modo Iframe — controle total de HTML/CSS/JS. Use quando precisar de uma interface customizada (arrastar e soltar, gráficos que o manifesto não cobre, formulários customizados).
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.
Modo manifesto
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": 30re-fetches periodically; a manual refresh button appears on every widget. periodaceita1h,24h,7d,30d,90d. Agregações:sum(padrão),avg,max,min.- Form field types:
text(default),textarea,number,select,multi_select,toggle,color,date,range. Every field renderslabelandhelp_text.placeholderapplies to text, textarea and number.requiredis enforced on every type except toggle, color and range.selectandmulti_selectneed"options": [{"value": "...", "label": "..."}].numberandrangeacceptmin,maxandstep. - Extra RPC args:
"rpc_params": {"stat": "total"}is merged into theparamsyour 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 oneget_overviewhandler 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.
Tipos de widget suportados
| Tipo | Handler retorna |
|---|---|
| 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} — Por que declarar? "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 |
| form | get → {"values": {...}}; save → {"ok": true} ou {"ok": false, "error": "…"} |
Handlers 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).
paramscarriesdiscord_srv_id(a string on widget reads, an int on form saves and iframe RPCs — compare withstr(params.get("discord_srv_id"))) plus the viewer's identity:discord_user_id,viewer_user_id,viewer_usernameandusername. - 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.
Modo 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 mínimo
<!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.
| Chamar | Propósito |
|---|---|
| YourBotSDK.ready(fn) | Execute fn após o handshake da ponte. |
| YourBotSDK.getContext() | Sincronizar — retorna servidor / plugin / usuário / tema. |
| 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?) | Diga ao iframe do host para redimensionar. Detecta automaticamente o conteúdo se nenhuma altura for passada. |
| YourBotSDK.navigateTo(pageId) | Mude para outra página no seu manifesto de dashboard. |
| YourBotSDK.rpc(method, params) | Chame um manipulador Python @plugin.on_dashboard. |
| YourBotSDK.kv.get / set / delete / list / listValues / getMany / setMany / increment / decrement / count | Direct 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 / record | Pull 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 / execute | SQL 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.
Variáveis de tema
O iframe herda essas propriedades CSS customizadas do dashboard para que seu widget se integre sem que você precise fazer engenharia reversa das cores:
: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.
Pacote de estilo pronto para usar novo
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>
O que há no pacote:
.maid-btn/.maid-btn-primary/.maid-btn-danger— botões correspondentes à paleta da plataforma.maid-input/.maid-textarea/.maid-select— campos de formulário com anéis de foco conscientes do tema.maid-card— contêiner estilizado com slots de cabeçalho/ajuda.maid-badge/.maid-pill— indicadores de status com cores semânticas (ok / aviso / erro / info / silenciado).maid-table— tabela de dados consciente do tema.maid-stack/.maid-grid/.maid-row— auxiliares de layout.maid-empty— contêiner de estado vazio
Auxiliares JS (namespaced sob 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 · Última atualização em julho de 2026 · Voltar ao Dev Portal