Writing plugins
A plugin is a WebAssembly file with a JSON manifest inside. There are SDKs for C (sdk/c, with the 18 official plugins as examples and the xbnc_util.h helper) and for Rust (sdk/rust). Any language that compiles to WebAssembly without WASI works if it follows the interface.
Manifest
| Field | Required | What it is |
|---|---|---|
id | yes | 1–32 characters a-z 0-9 _ -, starting with a letter. Cannot be status, notes, watch, events, xbnc, bnc, plugin or plugins. It is the name of its service (*id). |
name | yes | Visible name, 1–60 characters. |
version | yes | Version, 1–20 characters. |
description | no | What it does. |
usage | no | How it is used (up to 1000 characters). The panel shows it under “How to use it” and xBNC answers with it if the plugin does not answer a command. |
author | no | Author. |
homepage | no | Page of the plugin (https://). |
abi | no | Interface version (1). |
permissions | no | List of send, raw, timer, presence and http. |
http_domains | with http | 1 to 10 domains it asks permission to connect to. |
timer_secs | no | With timer: receive the timer every 5–60 seconds instead of every minute. |
settings | no | Up to 20 settings: {key, type (bool, int, text or lines), label, help, default, min, max}. The panel shows them as a form. |
translations | no | By language code (es, pt, fr…): name, description, usage and, per setting, label and help. The texts at the root of the manifest are the base, in English. |
{
"id": "hello",
"name": "Hello",
"version": "1.0.0",
"description": "Answers !hello.",
"usage": "In a channel: !hello",
"author": "your-name",
"permissions": ["send"],
"settings": [
{ "key": "greeting", "type": "text", "label": "Greeting", "default": "Hello!" },
{ "key": "lang", "type": "text", "label": "Language", "help": "Empty: your xBNC language.", "default": "" }
],
"translations": {
"es": {
"name": "Hola",
"description": "Responde a !hello.",
"usage": "En un canal: !hello",
"settings": { "greeting": { "label": "Saludo" } }
}
}
}
Interface (ABI 1)
The module exports:
| Export | Signature | What it does |
|---|---|---|
memory | memory | Linear memory of the plugin. |
xbnc_alloc | (len: i32) -> i32 | Reserves len bytes for the event and returns their address. |
xbnc_on_event | (ptr: i32, len: i32) -> i64 | Receives the event (UTF-8 JSON) and returns (address << 32) | length of the answer (JSON), or 0 if it does not answer. |
And it can only import from the xbnc module (neither WASI nor anything else):
| Import | What it does |
|---|---|
log(ptr, len) | Writes a line to the log (at most 10 per event and 500 characters). |
now_ms() -> i64 | Milliseconds since 1970. |
kv_get, kv_set, kv_del, kv_list | Key-value store of the plugin on that network: keys up to 200 bytes, values up to 64 KB, 16 MB and 200,000 keys in total, up to 2,000 writes per event (saved together). |
Events
{
"event": "message",
"network": "example", "nick": "y2k", "connected": true, "clients": 1, "lang": "en",
"config": { "trigger": "!roll" },
"state": null,
"command": "PRIVMSG", "conversation": "#xbnc", "channel": true,
"from": "bob", "from_mask": "bob!b@host", "text": "!roll 2d6",
"action": false, "outgoing": false
}
| Event | When | Own fields |
|---|---|---|
load | The plugin starts on the network (when turned on or when xBNC starts). | — |
connected | xBNC finishes connecting to the network. | — |
message | A message or notice in a channel or private conversation, yours too. | command, conversation, channel, from, from_mask, text, action, outgoing |
command | Someone writes /msg *id text. | text |
timer | Every minute, or every timer_secs (timer permission). | — |
join, part, kick, quit, nick, names | Movements in the channels (presence permission). | the data of each movement |
http | The answer to a web request (http permission). | id, status, body, error |
Common fields: network, nick (your current nick), connected, clients (connected clients), lang (your language code: en, es or any installed language), config (its settings) and state (what it saved).
Answer
{
"actions": [
{ "reply": "text in the same conversation" },
{ "tell": "text for you only, as *id" },
{ "privmsg": { "target": "#channel", "text": "..." } },
{ "notice": { "target": "nick", "text": "..." } },
{ "raw": "MODE #channel +o bob" },
{ "http": { "id": "weather", "method": "GET", "url": "https://api.open-meteo.com/..." } }
],
"state": { "whatever you want to keep": 1 }
}
- Single-line texts. Actions without permission or badly formed are dropped and noted in the log.
statereplaces the plugin's saved state on that network; it comes with every event and survives restarts. The instance is kept between events while the network is running.rawcan never send QUIT, PASS, USER, NICK, CAP, AUTHENTICATE, OPER, SERVER or SQUIT.http:('id', 'url', 'method', 'body'). https only, to approved domains; methods GET, POST, PUT and DELETE; body up to 16 KB (text or JSON); up to 3 requests at a time and 30 per minute per plugin and network. The answer arrives as anhttpevent withid,status,body(up to 256 KB) and, if it failed,error.
Limits
| Limit | Value |
|---|---|
| File size | 4 MB |
| Memory | 16 MB |
| CPU per event | about 20 million instructions (50 million when starting) |
| Answer | 64 KB and 20 actions; 5 messages per event |
| Saved state | 64 KB |
| Key-value store | 16 MB and 200,000 keys per plugin and network |
| Failures in a row before it stops on a network | 5 |
C SDK
sdk/c/xbnc_plugin.h takes care of the interface. Main functions:
| Function | What it does |
|---|---|
void on_event(const xbnc_event *ev) | The function you write: it receives each event. |
xbnc_get(ev, "field", buf, max) | Reads a text field of the event. |
xbnc_is(ev, "field") | Reads a yes/no field. |
xbnc_config(ev, "key", buf, max), xbnc_config_int, xbnc_config_bool | Reads a setting. |
xbnc_get_state(ev) | The saved state (JSON). |
xbnc_reply(text), xbnc_tell(text) | Answer in the conversation or to you only. |
xbnc_privmsg(target, text), xbnc_notice(target, text) | Message or notice to whoever you want. |
xbnc_raw(line) | IRC command (raw permission). |
xbnc_http_get(id, url), xbnc_http_post_json(id, url, json) | Web requests (http permission). |
xbnc_state(json) | Save the state. |
xbnc_kv_get, xbnc_kv_set, xbnc_kv_del, xbnc_kv_list (and the _str variants) | Key-value store. |
xbnc_log(text) | Write to the log. |
sdk/c/xbnc_util.h adds what the official plugins use: language of the answer (u_lang), reading commands with aliases (u_command), walking the store (u_next_key), dates, time zones with European daylight saving time and text building.
#include "xbnc_plugin.h"
void on_event(const xbnc_event *ev) {
static char kind[16], text[256], greeting[128];
xbnc_get(ev, "event", kind, sizeof kind);
if (!xbnc_streq(kind, xbnc_strlen(kind), "message")) return;
xbnc_get(ev, "text", text, sizeof text);
if (!xbnc_streq(text, xbnc_strlen(text), "!hello")) return;
xbnc_config(ev, "greeting", greeting, sizeof greeting);
xbnc_reply(greeting[0] ? greeting : "Hello!");
}
cd sdk/c
clang --target=wasm32 -O2 -nostdlib -fno-builtin -I. \
-Wl,--no-entry -Wl,--export-dynamic -Wl,--strip-debug -Wl,-z,stack-size=65536 \
-o hello.raw.wasm hello.c
xbncd plugin pack hello.raw.wasm hello.json -o hello.wasm
xbncd plugin check hello.wasm
sudo -u xbnc xbncd plugin install hello.wasm
# The official examples: make (or make bundle to copy them to the catalogue)
It needs clang and wasm-ld (LLVM 15 or later) and llvm-objcopy (or xbncd plugin pack).
Rust SDK
The xbnc-plugin crate (sdk/rust) provides the Plugin trait, the Event type (with kind(), text(), conversation(), is_channel(), outgoing(), config_str(), state()…), Response (with reply(), tell(), state()…) and the plugin! macro. Included example (sdk/rust/examples/stats.rs):
//! Example plugin: counts messages per channel and answers "!stats".
//! The counts survive restarts thanks to the persisted state.
//!
//! Build: cargo build -p xbnc-plugin --release --target wasm32-unknown-unknown --example stats
//! then: xbncd plugin pack target/wasm32-unknown-unknown/release/examples/stats.wasm \
//! sdk/rust/examples/stats.json -o stats.wasm
use xbnc_plugin::{plugin, Event, Plugin, Response};
#[derive(Default)]
struct Stats;
impl Plugin for Stats {
fn on_event(&mut self, ev: &Event) -> Response {
let mut r = Response::new();
let mut counts = ev.state().as_object().cloned().unwrap_or_default();
match ev.kind() {
"message" if ev.is_channel() && !ev.outgoing() => {
let chan = ev.conversation().to_lowercase();
let n = counts.get(&chan).and_then(|v| v.as_u64()).unwrap_or(0) + 1;
counts.insert(chan, n.into());
if ev.text().trim() == ev.config_str("trigger") {
r.reply(format!("{} messages counted in {}", n, ev.conversation()));
}
r.state(counts.into());
}
"command" => {
if counts.is_empty() {
r.tell("Nothing counted yet.");
}
let mut v: Vec<_> = counts.iter().collect();
v.sort_by_key(|e| std::cmp::Reverse(e.1.as_u64()));
for (chan, n) in v.into_iter().take(10) {
r.tell(format!("{chan}: {n}"));
}
}
_ => {}
}
r
}
}
plugin!(Stats);
Development mode
In Plugins → Development (superadministrators): with the mode on, xBNC watches /var/lib/xbnc/plugins/dev/. A .wasm saved there is checked and installed as soon as it changes and every network reloads it. If you put name.json next to name.wasm, it packs it for you (no need for xbncd plugin pack). A new plugin is turned on in the networks of whoever turned the mode on. The results and what the plugin writes are shown in the page's live log.
sudo cp hello.wasm hello.json /var/lib/xbnc/plugins/dev/
Publishing your own catalogue
Besides the official ones, xBNC can offer the plugins of a signed remote catalogue ([catalog] in xbnc.toml). The index is a JSON {"plugins": [{"id", "version", "url", "sha256", "size", "manifest"}]} and its Ed25519 signature in base64 is published in index.sig. Each plugin is checked against the signed SHA-256 before it is installed.
xbncd plugin catalog-keygen -o catalogue.key # once; the public key goes in [catalog] public_key
xbncd plugin catalog-entry hello.wasm https://plugins.example.org/hello.wasm # entry for the index
xbncd plugin catalog-sign --key catalogue.key index.json # writes index.json.sig
Translating xBNC
xBNC can speak any language. Every text it shows lives in one file per language: the web panel, the sign-in page and everything it says over IRC (*status, its help, notices and module messages). You translate one file and the language appears in every language selector of xBNC, without programming or compiling anything.
The files
| File | What it is |
|---|---|
locales/en.json | English. It is the base: it holds every text of xBNC. |
locales/es.json | Spanish. |
locales/<code>.json | Any other language: pt.json, fr.json, pt-BR.json… |
English and Spanish are built into the program. Other languages, and corrections, go in /etc/xbnc/locales/ (locales_dir in xbnc.toml, or the XBNC_LOCALES_DIR variable). xBNC reads them at start and on reload (sudo systemctl reload xbnc or /msg *status rehash).
{
"language": {
"code": "pt",
"name": "Português",
"english_name": "Portuguese",
"locale": "pt-PT",
"translators": ["Your name or nick"]
},
"irc": {
"connected_to": "Ligado a {0} como {1}.",
"help.group.channels": "Canais"
},
"panel": {
"Joined": "Dentro",
"Delete {username}": "Apagar {username}"
},
"installer": {
"finding_the_program": "A procurar o programa",
"installing_the_binary_to": "A instalar o programa em {0}"
}
}
| Part | What it is |
|---|---|
language | code: the language code (two or three letters, with a region if needed: pt, pt-BR); the file has the same name. name: the name of the language in the language itself, as shown in the selectors. locale: for dates and numbers. translators: shown by xbncd locales list. |
irc | What xBNC says over IRC. The key on the left is a name; translate only the text on the right. |
panel | The web panel. The key on the left is the English text; translate only the text on the right. |
installer | The installer and the scripts it uses. The key on the left is a name; translate only the text on the right. A language file in locales/ of the source code appears in the installer's language menu; the installer installs it and makes it xBNC's default language. |
Step by step
- Copy
en.jsonas<code>.json(for examplept.json). - Change the
languagepart: code, name, English name, locale and your name. - Translate the texts on the right. Never change the keys on the left.
- Check the file:
xbncd locales check pt.json(add--missingto see what is left). - Try the installer in your language: put the file in
locales/of the source code and runsudo ./scripts/install.sh --language pt, or choose it in the menu. - Try it on a server already installed: copy it to
/etc/xbnc/locales/and reload xBNC. It appears straight away on the sign-in page, in Your account, in Settings and with/msg *status language pt. - Send it to the project so it is included in the next version.
Rules for the texts
| In the English text | What to do |
|---|---|
{0}, {1}… (IRC) | Values xBNC fills in (a nick, a number…). Keep all of them; you can move them inside the sentence. |
{name}, {count}… (panel) | The same: keep them with exactly the same name. |
<b>…</b>, <u>…</u> (IRC) | Bold and underline in the IRC client. Keep them around the same words, each <b> with its </b>. |
Commands and settings (/msg *status help, set away delay 60) | Do not translate them: they are what people type. |
$1, $nick | Variables of the alias module: keep them as they are. |
Disabled|network state (panel key) | What follows the | is a hint about where the text is shown (for gender, for example). Translate only the text, without the hint. |
| Plurals | Texts ending in .one are used with 1 and those ending in .other with any other number (unit.network.one = “{{0}} network”). |
| Line breaks | Not allowed in IRC or installer texts. |
A text that breaks these rules is ignored and shown in English; xbncd locales check reports it as a problem. This also makes it impossible for a language file to inject IRC commands (line breaks are forbidden).
Correcting a built-in language
A file for a language that already exists (for example es.json in /etc/xbnc/locales/) only needs the texts you want to change: the rest stays as it is.
What a file does not translate
- Plugin replies. Their name, description and settings are translated in their manifest (
translations). What a plugin answers in a channel is written in the plugin itself; in a language it does not include, it answers in English. The official plugins speak English and Spanish. - The server log is in English.
Translating this wiki
The wiki is a project of its own, separate from the app (xbnc-wiki), so that anyone can read it without installing xBNC. It is generated with build.py from one content file per language (content/en.py is the base) and the xBNC source code. To translate it, copy en.py as <code>.py and translate the texts between quotes without touching the HTML tags or calls such as code(…). The tables of modules, plugins and commands translate themselves with xBNC's language files. When the wiki is built, each language appears in the selector at the top.
For developers
- In the panel, texts are written in English inside
t("…"),tk("…")ortx("…").npm run i18n:check(inweb/) lists what is missing fromen.json, andnode scripts/i18n-check.mjs --syncadds it. - In the server, the text is added to the
ircsection oflocales/en.jsonand used withself.t("key", &[]),tr!(self, "key", arg1, arg2)ori18n::tr(lang, "key", &[…]). The tests check that every key used exists and thates.jsontranslates all of them with the same placeholders.
The complete guide is in TRANSLATING.md, in the source code.