Skip to main content
Version: v0.31.0

Building a Plugin

Build a plugin that reacts to incoming WhatsApp messages, declare exactly the permissions it needs, test it locally, and package it into the .zip an operator installs. This guide walks the full path using the official faq-bot plugin as the worked example — an auto-reply bot that answers inbound messages from keyword and regex rules.

Prerequisites
  • Node.js 22 (the package builder targets node22).
  • The plugins repository's dependencies: run npm ci once in your clone. It installs esbuild for the packager, tsx for the tests and TypeScript for npm run typecheck.
  • A working OpenWA install you can upload to. See Installation.
  • A grasp of the plugin runtime — what a hook is, what the sandbox guarantees. Read Plugin architecture first.
  • An admin API key with no allowedSessions or allowedChats restriction. Plugin install, base-config and enable routes require the ADMIN role and answer 403 to a key restricted to sessions or, since v0.23.6, to chats; a session-restricted key can only set the per-session override (PUT /api/plugins/{id}/config/{sessionId}) for a session in its scope.

By the end you will have a built faq-bot.zip that an operator can install, configure, and enable.

How a plugin is structured​

A plugin is a folder with a manifest and a default-exported class. OpenWA reads the manifest, loads the compiled entry, and drives your class through a lifecycle (load → enable → run hooks → disable). At minimum you ship two things: manifest.json (what the platform reads) and a built dist/index.js (what it runs).

The faq-bot source folder looks like this:

faq-bot/
├─ manifest.json # metadata, permissions, hooks, config schema
├─ index.ts # default-exports the IPlugin class
├─ rules.ts # rule parsing + matching (plain TS, no host API)
├─ cooldown.ts # per-chat cooldown gate (plain TS, no host API)
├─ jid.ts # channel / broadcast-list JID check (plain TS, no host API)
├─ send-outcome.ts # did a failed send possibly go out (plain TS, no host API)
├─ index.test.ts # unit tests (node --test + tsx)
├─ rules.test.ts
├─ CHANGELOG.md # Keep a Changelog; top version must equal the manifest
├─ README.md # human-readable docs
└─ dist/index.js # built artifact — produced by the packager, gitignored

You write TypeScript; the packager bundles it to a single CommonJS dist/index.js. The platform require()s that file — never your .ts sources.

Step 1 — Write the manifest​

manifest.json is the single source of truth. OpenWA reads the fields it knows and ignores unknown ones. Here is faq-bot's manifest, trimmed to the load-bearing fields:

{
"id": "faq-bot",
"name": "FAQ / Auto-Reply Bot",
"version": "0.2.22",
"type": "extension",
"main": "dist/index.js",
"description": "Auto-replies to inbound WhatsApp messages from configurable FAQ keyword/regex rules.",
"author": "Yudhi Armyndharis <yudhi@rmyndharis.com>",
"license": "MIT",
"permissions": ["messages:send"],
"sessionScoped": true,
"sessions": ["*"],
"hooks": ["message:received"],
"status": "stable",
"minOpenWAVersion": "0.7.0",
"testedOpenWAVersion": "0.31.0"
}

The fields that decide whether the install succeeds and what your code is allowed to do:

FieldRequiredPurpose
idyesUnique identifier, /^[a-z0-9][a-z0-9._-]*$/i. Cannot be a reserved id (see below); the reservation check is case-insensitive, so Auto-Reply is refused too.
nameyesShown in the dashboard plugin card.
versionyesSemVer. Must equal the top released heading in CHANGELOG.md — the packager rejects a mismatch.
typeyesOnly "extension" is user-installable. Any other value fails the build.
mainyesThe require()-able entry inside the package. Always dist/index.js.
permissionsnoThe capabilities your code may call. Enforced at runtime — see Step 3.
sessionsnoThe session scope the plugin may act on. ["*"] = all sessions. Static — config edits can't widen it.
sessionScopednoDefault true: the plugin only runs for sessions an operator activated it for. false makes it global (always runs, no per-number notion).
hooksnoThe events you register handlers for.
configSchemanoA declarative form the dashboard renders for operator config. See Step 2.
configUinoA self-contained HTML config editor (inline JS/CSS) served in a sandboxed iframe. When present, the dashboard shows it alone in place of the generated configSchema form. Its message contract is under Write a configUi editor.
net.allownoOutbound-HTTP host allowlist for net:fetch (host:port entries; a bare host also works, and "*" allows any public host). Absent means deny all. Pair with net.allowConfigHosts for operator-opened hosts.
statusno"stable", "beta", or "development". Shown as a badge.
minOpenWAVersionnoSince v0.24.0, must be a MAJOR.MINOR.PATCH version no newer than the host. An incompatible or malformed value refuses installation with 400; at boot the plugin is skipped and logged as plugin_load_failed.
i18nnoDashboard localization, keyed by BCP-47 locale tag. The gateway ships fifteen locales, including id since v0.24.0; the packager warns on codes it does not support.
providesnoFeature tags rendered on the dashboard plugin card.
sdkVersionnoIntegration SDK major the plugin targets (e.g. "1"). Integration Fabric only — see Author an Integration Fabric adapter.
ingressnoInbound webhook routes to claim (requires webhook:ingress). Integration Fabric only.
Reserved ids

These ids are taken by built-ins and will be rejected at install: whatsapp-web.js, baileys, auto-reply, translation. Pick a unique id.

Step 2 — Define the config schema​

Most plugins need operator-supplied settings — keywords, replies, an API key. Declare them in configSchema and the dashboard renders an authenticated form; the operator's input is saved through PUT /api/plugins/{id}/config and handed to your code as ctx.config.

faq-bot declares four fields:

"configSchema": {
"type": "object",
"properties": {
"rules": {
"type": "textarea",
"required": true,
"title": "Rules (JSON)",
"description": "JSON array of { mode: 'contains'|'exact'|'regex', pattern, reply }."
},
"fallbackReply": {
"type": "string",
"default": "",
"title": "Fallback reply",
"description": "Sent when no rule matches. Leave empty to stay silent."
},
"fallbackCooldownSec": {
"type": "number",
"default": 600,
"title": "Fallback cooldown (seconds per chat)",
"description": "Minimum seconds between fallback replies to the same chat. 0 = reply every time."
},
"respondInGroups": {
"type": "boolean",
"default": false,
"title": "Also respond in group chats"
}
}
}

Each property is a field. The type drives the widget (string, number, boolean, textarea for multi-line, plus object/array for nesting). Useful extras: default seeds the form, title/description label it, enum renders a <select>, and secret: true masks a value such as an API key.

On OpenWA ≥ 0.10.0 a declared default does more than seed the form: the host merges schema defaults into the stored config at load time, so a field with a declared default arrives in ctx.config even if the operator never opened or saved the form. Explicit values — including null — are never overwritten, and a required field without a default still needs real operator input. Keep your code's fallbacks equal to the schema defaults so the plugin behaves identically on older hosts.

The schema drives the form, not validation

configSchema only tells the dashboard how to draw the form. The platform does not validate operator input against it. Your code reads ctx.config as Record<string, unknown> and must validate defensively. faq-bot does exactly this — parseConfig coerces every field and throws on bad input:

export function parseConfig(raw: Record<string, unknown>): {
config: FaqConfig;
rules: CompiledRule[];
skipped: string[];
} {
const rulesJson = String(raw.rules ?? '').trim();
if (!rulesJson) throw new Error('faq-bot: rules is required (a JSON array)');

const parsed = parseRules(rulesJson); // throws on structurally invalid rules

const rawCooldown =
typeof raw.fallbackCooldownSec === 'string' && !raw.fallbackCooldownSec.trim()
? undefined
: raw.fallbackCooldownSec;
const cooldown = Number(rawCooldown ?? 600);
return {
rules: parsed.rules,
skipped: parsed.skipped,
config: {
fallbackReply: String(raw.fallbackReply ?? ''),
fallbackCooldownSec: Number.isFinite(cooldown) ? cooldown : 600,
respondInGroups: raw.respondInGroups === true,
},
};
}

A throw here surfaces the plugin as ERROR in the dashboard instead of misbehaving silently.

Write a configUi editor​

A plugin that needs more than the generated form ships its own editor: declare "configUi": { "entry": "config/index.html", "height": 600 }, where entry is a path inside the package and height is optional. The dashboard shows the editor alone in place of the generated configSchema form. It fetches the entry from GET /api/plugins/{id}/config-ui with the API key, which never enters the editor, and renders it as the srcdoc of an iframe with sandbox="allow-scripts", so the editor runs on an opaque origin with no access to the dashboard. Keep it self-contained, with its JavaScript and CSS inline, because it talks to the dashboard only through postMessage:

MessageDirectionMeaning
{ type: 'config:get' }editor to dashboardThe editor is ready for its values.
{ type: 'config:value', config, schema, locale, theme }dashboard to editorThe reply to config:get.
{ type: 'config:save', config }editor to dashboardThe values to store.
{ type: 'config:saved' }dashboard to editorThe write succeeded.
{ type: 'config:error', message }dashboard to editorThe write failed.
  • config holds only the fields your configSchema declares, with secrets already masked; a key the schema does not declare never reaches the editor. In a per-session editor it is that session's resolved slice: the override where one is set, the base value otherwise.
  • schema is the configSchema with field titles and descriptions localized from the manifest i18n block, locale is the dashboard language code (es, zh-CN), and theme is light or dark, already resolved from the dashboard's setting. Since v0.24.0 the reply carries locale and the localized schema; before, it carried config, schema and theme. All of them are sent once, with the handshake, so an editor that follows the operating system's appearance should also watch prefers-color-scheme.
  • The dashboard makes the authenticated PUT itself, so the secret mask and restore rules apply to config:save (*** or an empty string keeps a stored secret, unless a per-session save moves a host key to another origin, and null removes it since v0.26.0), and a write that answers success: false reaches the editor as config:error with the message. In a list of rows with a secret column, a masked row is matched to its stored row by its other fields. Since v0.31.0, in a save of the same length in which a row moved (rows reordered, or a row removed ahead of a kept one and another added), a row whose other fields were edited, with its mask untouched, is saved without its secret, and the same holds for rows that differ only by their secret once one of them is edited or removed in such a save, so an editor has to ask for those secrets again.
  • If no config:get arrives within 5 seconds of the editor loading, the dashboard shows a handshake error.

Step 3 — Declare permissions and sessions​

A plugin reaches WhatsApp, the engine, the network, and its own key-value store only through ctx.messages, ctx.engine, ctx.net, and ctx.storage. Each call is gated by a declared permission; calling a capability you did not declare throws a PluginCapabilityError. Declare the minimum and nothing more.

PermissionUnlocksWhen you need it
messages:sendctx.messages.sendText, ctx.messages.replySending or replying to messages.
engine:readctx.engine.getContacts, getGroupInfo, getChats, getChatHistory, canonicalChatId, …Reading contacts, groups, chats, chat history, or resolving a @lid to a canonical id (read-only). On Baileys, getContacts returns only contacts saved on the phone (v0.23.6+); getContactById still resolves an unsaved peer, with isMyContact: false. Since v0.31.0 getChats lists a Baileys chat held under a privacy id (@lid) that has no saved, verified or push name with name: "" and, when the session can map the id, a phone: title such a chat by phone, else by its id.
net:fetchctx.net.fetchOutbound HTTP. Also requires a net.allow host allowlist in the manifest. The response body arrives as UTF-8 text and a redirect is not followed; see the ctx.net.fetch contract.
webhook:ingressctx.registerWebhookIntegration Fabric — receive inbound webhooks from an external system.
conversation:sendctx.conversations.send, ctx.handover.set, ctx.mappings.*Integration Fabric — send normalized replies, flip handover, manage the chat↔external-conversation map.
search:providectx.registerSearchProviderServe the gateway's GET /api/search queries. Required since v0.12.2 — a provider without it is refused with a sandbox_search_provider_denied warning. What the caller sees when your provider misbehaves: a result shape that fails the host's validation answers 502, and a handler that throws, passes the 10-second search timeout, or runs in a worker that is no longer alive answers 503.
storage:usectx.storage.get, set, delete, listPersisting state across restarts in the per-plugin key-value store. Required since v0.17.0 — before that the four verbs dispatched with no permission check at all.

faq-bot only ever replies, so it declares one permission and one scope:

"permissions": ["messages:send"],
"sessions": ["*"]

sessions: ["*"] grants the capability scope across all sessions. The scope is static — editing config at runtime cannot widen it. To run a plugin only for the sessions an operator chooses, leave sessionScoped at its default (true); the operator then picks the active sessions via PUT /api/plugins/{id}/sessions, and ctx.config resolves to that session's slice inside the hook.

Least privilege

Declare only what you call. A plugin that asks for net:fetch it never uses is a red flag in review and a wider blast radius if compromised. faq-bot reads inbound messages and replies — nothing else — so messages:send is all it declares.

storage:use is required from v0.17.0

If your plugin calls ctx.storage, add one line to the manifest — "storage:use" inside permissions. A plugin that persists state and declares messages:send only becomes:

"permissions": ["messages:send", "storage:use"]

The permission is not checked at load. The refusal arrives at the next storage call, so an upgraded gateway looks fine until your plugin tries to store, and because every storage verb is async the denial arrives as a rejected promise rather than a synchronous throw. A plugin that stores during onEnable does not merely lose the write: the host records the error, sets the plugin to ERROR, unregisters its hooks, and leaves it disabled.

An unrecognised permission string is ignored by older gateways, so a manifest carrying storage:use still installs on a pre-0.17.0 host. For operators that means upgrading the plugins first and the gateway second — see the plugin catalog for the official version floors.

Step 4 — Implement the hook​

Your plugin is a default-exported class implementing IPlugin. The lifecycle methods you care about:

  • onEnable(ctx) — runs when the operator enables the plugin. Register your hooks here and fail fast on invalid config.
  • onConfigChange(ctx, newConfig) — runs when the base config of an enabled plugin changes (a per-session override does not trigger it; since v0.27.0 it also runs immediately after onEnable if the base config was updated while onLoad/onEnable was running); newConfig is the base config after the change. Re-validate so a bad edit surfaces immediately.
  • healthCheck() is optional: GET /api/plugins/{id}/health runs it and reports its healthy flag and message. faq-bot reports its rule count, or the reason its config does not parse.

Register a handler with ctx.registerHook(event, handler, priority?). The handler receives a HookContext and returns a HookResult — { continue: true } lets the event flow to the next plugin and the host; { continue: false } stops the handlers registered after yours. The optional third argument orders the handlers subscribed to one event: they run ascending, lower first, and an omitted priority defaults to 100, as does one that is not a finite number (v0.23.6+). When your plugin registers several handlers for one event, they run together at the lowest priority among them (v0.23.6+; before, at the priority of the first one registered). Pass one explicitly — without it the order is whatever order the plugins happened to register in, which differs between a restart and a manual enable. faq-bot passes 80: late enough that a plugin which only logs or translates the message has already seen it, early enough to answer before a bot that replies to everything. See Lifecycle hooks for the chain in full.

Here is faq-bot's plugin class. It lives in index.ts next to the FaqConfig type and the parseConfig helper, which the excerpt leaves out (see Step 2), and it imports the four host-independent modules beside it: ./rules.ts for matching, ./cooldown.ts for the cooldown gates, ./jid.ts for the channel and broadcast-list check, and ./send-outcome.ts for the check on a failed send:

import type { IPlugin, PluginContext, HookContext, IncomingMessage } from '../types/openwa';
import { parseRules, matchRule, CompiledRule } from './rules.ts';
import { allowCooldown } from './cooldown.ts';
import { isBroadcastJid } from './jid.ts';
import { sendOutcomeUnknown } from './send-outcome.ts';

// FaqConfig and parseConfig (Step 2) are defined here in index.ts.

// Responder band: keyword rules are more specific than a bot that answers everything, less specific than
// a command prefix.
const HOOK_PRIORITY = 80;

// Minimum gap before the SAME inbound text is answered again in the same chat. Hardcoded, like the retry
// cadence in the other plugins: it exists to stop a runaway exchange, not to be tuned. A rule whose own
// reply matches its own pattern is a fixed point, and an autoresponder on the other end then answers each
// of this plugin's replies forever, at full message rate, repeating one canned message as it goes.
// Keyed on the text rather than the rule or the chat, so two different questions are both answered even
// when they match the same rule.
const MATCHED_REPLY_COOLDOWN_MS = 10_000;
const RETRY_BACKOFF_MS = 60_000;
const MAX_RETRY_ENTRIES = 5_000;

// A message sent longer ago than this is never answered. From OpenWA 0.23.6 a Baileys session delivers,
// after it reconnects, what WhatsApp queued while it was disconnected, each message with its original send
// time, so a long outage ended in a burst of canned replies quoting old messages, often in chats already
// answered from the phone. Five minutes is far above clock skew between WhatsApp and the gateway and
// matches the host's own auto-reply age limit.
const LATE_AFTER_MS = 5 * 60_000;

export default class FaqBot implements IPlugin {
private ctx: PluginContext | null = null;
private readonly fallbackAt = new Map<string, number>();
/** `${sessionId}:${chatId}:${pattern}` -> last answer for that rule, for MATCHED_REPLY_COOLDOWN_MS. */
private readonly matchedAt = new Map<string, number>();
private readonly replyAttempts = new Map<string, object>();
private readonly retryNotBefore = new Map<string, number>();

async onEnable(ctx: PluginContext): Promise<void> {
this.ctx = ctx;
this.warnSkipped(ctx); // fail-fast + surface any invalid regex rules at enable
ctx.registerHook(
'message:received',
async (hook: HookContext) => ({ continue: !(await this.onMessage(ctx, hook)) }),
HOOK_PRIORITY,
);
}

async onConfigChange(ctx: PluginContext): Promise<void> {
this.warnSkipped(ctx); // re-validate on change (fail-fast feedback + fresh skipped warning)
}

async healthCheck(): Promise<{ healthy: boolean; message?: string }> {
if (!this.ctx) return { healthy: false, message: 'faq-bot: not enabled' };
try {
const { rules } = parseConfig(this.ctx.config);
return { healthy: true, message: `faq-bot: ${rules.length} rule(s)` };
} catch (e) {
return { healthy: false, message: e instanceof Error ? e.message : String(e) };
}
}

private warnSkipped(ctx: PluginContext): void {
const { skipped } = parseConfig(ctx.config);
if (skipped.length) {
// Truncate each pattern before joining. The host caps a log line at 8 KiB and drops the overflow,
// so one pathological rule could push the list past the cap and take every other skipped pattern
// with it — losing exactly the diagnostic this line exists to give.
const preview = skipped.map(p => (p.length > 80 ? `${p.slice(0, 80)}…` : p)).join(', ');
ctx.logger.warn(`faq-bot: skipped ${skipped.length} rule(s) with an invalid regex: ${preview}`);
}
}

// Claim before sending, so a slow reply cannot outlive the host's hook budget.
private async onMessage(ctx: PluginContext, hook: HookContext): Promise<boolean> {
if (hook.source !== 'Engine' || !hook.sessionId) return false;
const m = (hook.data ?? {}) as Partial<IncomingMessage>;
// A sticker, image or voice note arrives with an empty body. No rule can match it, so the fallback
// would answer a picture with "I did not understand" and claim the event away from a plugin that
// could actually handle media. chat-flow guards the same way.
if (m.fromMe || typeof m.body !== 'string' || !m.body.trim() || !m.chatId || !m.id) return false;
// Since host 0.23.2 a shared contact card arrives with its full vCard as the body and a poll with
// its question, and since 0.23.5 a Baileys 'order' carries the order note and a 'product' card the
// product title, so a non-empty body no longer means a human typed it. A vCard is free text (name,
// org, notes, numbers) and readily matches a `contains` or `regex` rule; with `fallbackReply` set,
// an unmatched card would answer and claim the event. 'unknown' stays admitted: business button and
// list replies land there on whatsapp-web.js (Baileys delivers them as 'text' from 0.23.6, as
// 'unknown' before) and are real answers to a question this bot asked. A Baileys whole-catalog share
// also arrives as 'unknown' with the catalog title as the body, and cannot be told apart from those.
if (m.isForwarded) return false;
if (
m.type === 'contact' ||
m.type === 'poll' ||
m.type === 'order' ||
m.type === 'product' ||
m.type === 'location'
) {
return false;
}

// Re-parse per event so a per-session config override (resolved by the host for this hook fire) is
// honored — a snapshot cached at enable would ignore overrides set via the dashboard after enable.
let cfg: { config: FaqConfig; rules: CompiledRule[] };
try {
cfg = parseConfig(ctx.config);
} catch (e) {
ctx.logger.warn(`faq-bot: skipping message, config invalid: ${e instanceof Error ? e.message : String(e)}`);
return false;
}

if (m.isGroup && !cfg.config.respondInGroups) return false;
// `isGroup` is a boolean over a five-way discriminator, so it cannot see a WhatsApp Channel: a
// `@newsletter` post arrives flagged as a non-group chat and reads exactly like a 1:1 message.
// Nothing filters it upstream (the host diverts only status broadcasts), so a channel this account
// merely FOLLOWS drew a reply into a chat it can never post to, burning the per-chat slot and
// logging a send failure per post. Broadcast-list ids are the same shape. Matched on the JID rather
// than `msg.kind`, which the host only stamps from 0.10.8, below every floor in this catalogue.
if (isBroadcastJid(m.chatId)) return false;

const sessionId = hook.sessionId;
const rule = matchRule(cfg.rules, m.body);
// `timestamp` is unix seconds; a missing, zero, negative or unrepresentable one counts as sent now.
const sent = new Date((m.timestamp ?? 0) * 1000);
const late = sent.getTime() > 0 && Date.now() - sent.getTime() > LATE_AFTER_MS;
try {
if (rule) {
// Keyed on the INBOUND TEXT, not on the rule. A runaway exchange repeats the same message: the
// other end's autoresponder sends one canned reply, this plugin answers, and that same canned
// reply arrives again. Keying on the rule instead would have suppressed a customer's second,
// genuinely different question whenever it happened to match the same rule ("berapa harga paket
// A?" then "kalau harga paket B?"), which costs far more than the loop it prevents.
// Claimed either way, too old to answer included: the message matched a rule, so it is this
// plugin's, and the standard allows a claim to resolve to silence.
if (late) return true;
const key = `${sessionId}:${m.chatId}:${m.body.trim().toLowerCase().slice(0, 200)}`;
const attemptKey = `matched:${key}`;
const notBefore = this.retryNotBefore.get(attemptKey);
if (notBefore !== undefined && Date.now() < notBefore) return true;
if (!allowCooldown(this.matchedAt, key, Date.now(), MATCHED_REPLY_COOLDOWN_MS)) return true;
this.dispatchReply(ctx, sessionId, m.chatId, m.id, rule.reply, attemptKey, this.matchedAt, key);
return true;
}
if (cfg.config.fallbackReply && !late) {
const key = `${sessionId}:${m.chatId}`;
const attemptKey = `fallback:${key}`;
const notBefore = this.retryNotBefore.get(attemptKey);
if (notBefore !== undefined && Date.now() < notBefore) return false;
const cooldownMs = Math.max(0, cfg.config.fallbackCooldownSec) * 1000;
if (allowCooldown(this.fallbackAt, key, Date.now(), cooldownMs)) {
this.dispatchReply(ctx, sessionId, m.chatId, m.id, cfg.config.fallbackReply, attemptKey, this.fallbackAt, key);
return true;
}
}
} catch (err) {
ctx.logger.error('faq-bot: reply failed', err);
}
return false; // nothing delivered — a later plugin may still have an answer
}

private dispatchReply(
ctx: PluginContext,
sessionId: string,
chatId: string,
messageId: string,
text: string,
attemptKey: string,
cooldownMap: Map<string, number>,
cooldownKey: string,
): void {
const attempt = {};
this.replyAttempts.set(attemptKey, attempt);
void ctx.messages.reply(sessionId, chatId, messageId, text).then(() => {
if (this.replyAttempts.get(attemptKey) !== attempt) return;
this.replyAttempts.delete(attemptKey);
this.retryNotBefore.delete(attemptKey);
}, err => {
if (this.replyAttempts.get(attemptKey) === attempt) {
this.replyAttempts.delete(attemptKey);
// The cooldown slot stays when the send may have gone out (OpenWA 0.31.0 says so in the error), so a
// reply that was perhaps delivered is not sent again once the backoff ends.
if (!sendOutcomeUnknown(err)) cooldownMap.delete(cooldownKey);
this.retryNotBefore.set(attemptKey, Date.now() + RETRY_BACKOFF_MS);
if (this.retryNotBefore.size > MAX_RETRY_ENTRIES) {
const now = Date.now();
for (const [k, until] of this.retryNotBefore) if (until <= now) this.retryNotBefore.delete(k);
for (const k of this.retryNotBefore.keys()) {
if (this.retryNotBefore.size <= MAX_RETRY_ENTRIES) break;
this.retryNotBefore.delete(k);
}
}
}
ctx.logger.error('faq-bot: reply failed', err);
});
}
}

Four of the names this class relies on are not in the excerpt: the FaqConfig type and parseConfig beside it in index.ts (shown in Step 2), isBroadcastJid from ./jid.ts, a pure check that a chat id is a channel, a broadcast list or a status chat, and sendOutcomeUnknown from ./send-outcome.ts, a pure check of whether the error text of a failed send says the message may still have gone out (see the last pattern below). The fifth, allowCooldown, is imported from ./cooldown.ts and is the gate behind both fallbackReply and the ten-second window on a repeated rule match. It records the last time per key, refuses an action inside the configured window, and caps its own map (MAX_COOLDOWN_ENTRIES = 5000, LRU eviction) so it can't grow unbounded. Like rules.ts it takes no PluginContext, which is exactly why it is its own module, a pure function you can test without the host:

// cooldown.ts — in-memory per-key cooldown with an LRU cap. Pure — no ctx.
const MAX_COOLDOWN_ENTRIES = 5000;

/**
* Decide whether an action may go to `key` now. On allow, records `nowMs` (re-inserting so the map
* evicts least-recently-used) and caps the map by dropping the LRU entry. A `cooldownMs` of 0 always allows.
*/
export function allowCooldown(map: Map<string, number>, key: string, nowMs: number, cooldownMs: number): boolean {
const last = map.get(key);
if (last !== undefined && nowMs - last < cooldownMs) return false;
map.delete(key); // re-insert so iteration order tracks recency (LRU by touch)
map.set(key, nowMs);
if (map.size > MAX_COOLDOWN_ENTRIES) {
const oldest = map.keys().next().value as string | undefined;
if (oldest !== undefined) map.delete(oldest);
}
return true;
}

Five patterns worth copying:

  • Guard the event first. Ignore your own outbound messages (m.fromMe), non-text payloads, and group chats you were not configured for. A hook fires for every matching event — filter early. On Baileys, since v0.23.6 a session that reconnects after being offline (a gateway restart included) replays the inbound messages WhatsApp queued in the meantime into message:received, where earlier releases dropped them; a responder that should not answer that backlog can compare the message's timestamp (Unix seconds) with the current time and skip anything older than it is willing to answer; faq-bot answers nothing sent more than five minutes ago (LATE_AFTER_MS). Also since v0.23.6, Baileys reports a business list prompt, and a reply to a button, template or list prompt, as type: "text" where earlier releases reported unknown, and a list prompt or list reply now carries text in body (the prompt's description or title, the chosen row's title), so a responder keyed on type or on a non-empty body receives them too. A native-flow button reply with no body text of its own was already type: "text" but arrived with an empty body; since v0.23.6 it carries the button label from its parameters in body when those parameters also carry the button's id, so a responder keyed on a non-empty body receives it as well. One that should not answer any of these can skip a message carrying button or buttons; only a reply without an id and a list prompt with no answerable row carry neither (see Payload fields that are easy to miss). See Lifecycle hooks.
  • Re-parse ctx.config inside the handler, per event. The host resolves ctx.config to the firing session's slice — the base config with that session's override merged over it — so per-event parsing means a config edit or a per-session override takes effect on the next message, with no restart. Since v0.26.0 an override that points a net.allowConfigHosts key at another origin than the base config does not inherit the base config's secret fields, so ctx.config holds none of them there until the override brings its own (see Scope a plugin to specific sessions). onEnable/onConfigChange still parse once, but only to fail fast on invalid input.
  • return after the rule match. A matched rule returns at once, claiming the message and, unless it is stale or a repeat, replying; only an unmatched message reaches the fallback branch. The two config fields from Step 2 — fallbackReply and fallbackCooldownSec — drive that branch.
  • Catch your own errors. A handler that throws is logged by the host and the chain continues with the previous data — but you lose the chance to log context. Wrap the capability call and log through ctx.logger.
  • Claim what is yours, and claim it before the send settles. onMessage resolves true for a message this plugin owns, and the handler inverts it: { continue: !(await this.onMessage(ctx, hook)) }. A claim returns { continue: false }, which tells the host this message is mine, don't let another bot answer it too; it stops the plugin handlers after yours and nothing else, because the gateway still persists the message and still dispatches it to webhooks and the websocket. faq-bot decides that synchronously and does not wait for delivery: it starts the reply with void ctx.messages.reply(...), returns true at once, and handles a failed send in the promise's rejection handler. That keeps a slow send from outliving the hook's 5-second budget, past which the host resolves the handler fail-open as { continue: true } and the next bot would answer too. A send that fails later is logged, and the message stays claimed. The failure starts a 60-second retry backoff for that text (a rule) or that chat (the fallback), so a broken send is not retried on every inbound message, and it releases the cooldown slot unless the error says the message may have gone out (see below). A failed send is not proof that nothing went out. From OpenWA 0.31.0 a send cut short while it ran, by a Baileys connection that was replaced or stopped or by a whatsapp-web.js page reload, rejects with a 409 whose text says the message "may or may not have been sent". A send that times out on the host (since v0.11.0) is also rejected without being cancelled. Only the error text reaches the plugin, so sendOutcomeUnknown matches those texts and keeps the cooldown slot instead of releasing it, which stops the fallback from repeating a reply that was perhaps delivered within its cooldown. A matched rule claims the message even when it sends nothing, whether it sits inside the 10-second same-text window, was sent more than five minutes ago (LATE_AFTER_MS) or falls in a retry backoff, because it is this plugin's message and the standard allows a claim to resolve to silence. Every other path returns { continue: true }: a guard bail, an invalid config, no rule match and no fallback reply to send, a fallback still inside its cooldown or its retry backoff, a message too old for the fallback, and a synchronous throw while starting the send. Claiming a message you will not answer silences the chat: the plugins behind you skip it and the contact gets nothing.
Don't cache ctx.config at enable

A config snapshot taken in onEnable silently ignores per-session overrides (PUT /api/plugins/{id}/config/{sessionId}) set after enable — the plugin keeps answering with the base config for every session. Re-parse ctx.config per event as faq-bot does, or — for a stateful coordinator that must hold parsed state — cache keyed by a config signature and rebuild when the signature changes. Which official plugins support overrides is cataloged in the plugin catalog.

ctx.messages.reply(sessionId, chatId, quotedMessageId, text) sends a quoted reply through the host's message service, with the messages:send permission checked on the call. The quotedMessageId is the inbound message's id, so the answer threads under the customer's question.

The message flow​

Step 5 — Test locally​

Keep your matching and parsing logic in plain TypeScript modules with no dependency on the host context, then unit-test them directly. faq-bot puts rule parsing and matching in rules.ts and config coercion in parseConfig, so the tests need no running gateway:

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { parseConfig } from './index.ts';

const rules = JSON.stringify([{ mode: 'contains', pattern: 'hi', reply: 'hello' }]);

test('parseConfig requires rules', () => {
assert.throws(() => parseConfig({}), /rules is required/);
assert.throws(() => parseConfig({ rules: ' ' }), /rules is required/);
});

test('parseConfig parses rules and applies option defaults', () => {
const { config, rules: parsed } = parseConfig({ rules });
assert.equal(parsed.length, 1);
assert.equal(config.fallbackReply, '');
assert.equal(config.fallbackCooldownSec, 600);
assert.equal(config.respondInGroups, false);
});

The two excerpts above are part of faq-bot's suite of 59 tests: 27 in index.test.ts (config coercion, message claiming, the guards for media, contact, poll, order, product, location, forwarded, channel and broadcast messages, the fallback cooldown, the retry backoff after a failed send and the cooldown a send of unknown outcome keeps, the ten-second window on a repeated text, and the five-minute limit on a replayed message) and 32 in rules.test.ts (mode matching, the ReDoS guard). Run just this plugin's tests with Node's built-in runner over tsx, then type-check the whole repo:

npx tsx --test "faq-bot/*.test.ts" # run faq-bot's tests only
npm run typecheck # tsc --noEmit, repo-wide

Expected output:

1..59
# tests 59
# suites 0
# pass 59
# fail 0

npm test runs the same runner across every plugin in the repo, so its total is higher; scope to your plugin's glob while iterating.

Push host-independent logic out of the class

Everything in rules.ts — mode matching, regex compilation, the ReDoS guard — is a pure function. That is deliberate: pure functions are trivial to test without mocking PluginContext. Reserve the class for wiring the lifecycle and calling capabilities.

Step 6 — Package the .zip​

The packager validates the manifest, bundles index.ts to dist/index.js, zips the result, and prints the size and sha256. It imports esbuild, so run npm ci once in your clone first. Run it from the plugins repo root with your plugin's folder name:

node package.mjs faq-bot

Expected output:

✓ Packaged faq-bot v0.2.22 → faq-bot.zip (33.1 KB)
sha256: d934…c816

Under the hood the packager:

  1. Validates the manifest — required fields present, type is extension, and version equals the top CHANGELOG.md heading. Any mismatch aborts the build.
  2. Bundles index.ts to a single CommonJS dist/index.js with esbuild (platform: node, target: node22).
  3. Zips manifest.json + dist/ into faq-bot.zip at the repo root. Besides the bundle, dist/ carries a package.json that pins CommonJS (so Node loads the CJS bundle even when the repo root is ESM), and a plugin that declares configUi.entry gets that static editor directory zipped in as well.
  4. Reports size and sha256, and fails if the package exceeds 5 MB.
Package limits

OpenWA rejects a package at install if it exceeds any of: 5 MB compressed, 200 files, or 20 MB uncompressed. Bundle to a single dist/index.js (the packager does this) rather than shipping node_modules.

Author an Integration Fabric adapter​

The faq-bot plugin above is outbound-only: it reacts to message:received and replies. An Integration Fabric adapter goes further — it receives inbound webhooks from an external system (a helpdesk, CRM, or chatbot) and relays them to WhatsApp, all inside the same sandboxed plugin with no separate server. The full guide is at Integration Fabric; this section covers the manifest and code shape.

Declare the SDK version and an ingress route in the manifest, and request the two Integration Fabric permissions:

{
"sdkVersion": "1",
"permissions": ["conversation:send", "webhook:ingress"],
"ingress": [
{
"route": "webhook",
"mode": "async",
"signature": { "scheme": "hmac-sha256", "header": "X-Signature", "contentTemplate": "{timestamp}.{rawBody}", "encoding": "hex", "timestampHeader": "X-Timestamp", "toleranceSec": 300 },
"verify": "core",
"maxBodyBytes": 1048576
}
]
}

For hmac-sha256, contentTemplate is the text the HMAC is computed over, with the tokens {rawBody}, {timestamp} and {id} (the integration instance id, not a delivery id). It defaults to {rawBody}, and it, encoding and prefix must reproduce exactly what your provider signs. Include {timestamp} whenever you declare timestampHeader: otherwise the timestamp is only checked for freshness, not signed, so a captured delivery can be re-sent with a fresh timestamp, and the host logs ingress_unsigned_timestamp for the route.

The host validates this when it loads the plugin, and since v0.31.0 also when a package is installed or updated, so a manifest it would refuse answers 400 before anything is written and, for an update, before the running plugin is stopped (earlier releases stopped it first, and rolled back when the new package then failed to load or enable, or the gateway began shutting down meanwhile). The SDK major must match, webhook:ingress must be declared, routes must be unique, each route must be a single URL path segment (no /, \, ?, #, % or ASCII control character, and not . or ..), a toleranceSec replay window must be a number greater than zero (a quoted number such as "300" still loads), and a declared dedupOn must be "header" or "body". Since v0.31.0 ingress must also be a list, and an hmac-sha256 contentTemplate, a header or timestampHeader (on hmac-sha256 and shared-secret routes), a dedupHeader and a conversationId.header must each be a string; the 400 names the field. A route that declares "scheme": "none" is refused at load unless the operator sets ALLOW_UNSIGNED_INGRESS=true, because a provisioned unsigned route is a public endpoint anyone who can reach the host may use to trigger WhatsApp sends; the three signed schemes are hmac-sha256, shared-secret, and standard-webhooks. The handler's req.verified is true when the route's scheme authenticated the delivery and false on a none route (and on hmac-sha256 and standard-webhooks routes, false when an empty body is accompanied by a non-empty query string, which the body HMAC does not cover, v0.28.0+), and a queued or replayed delivery keeps the verdict recorded when it was accepted (v0.26.0+), so a plugin update that later signs a route does not relabel a payload that was never authenticated; a delivery stored before v0.26.0 reads the route as it stands. Since v0.24.0 a signature.scheme outside those three and none is refused too, as is an hmac-sha256 encoding other than hex or base64 (the other schemes ignore encoding). A declared response.ack is validated too: its status must be a final status, an integer in 200-599; its body and every header value must be strings; its header names must be HTTP tokens; and a header value may hold no ASCII control character other than a tab and nothing above U+00FF, since Node cannot write one. The host verifies the HMAC over the raw request bytes (a re-serialized body would not match), so the route is not bound to a DTO — unknown provider fields pass through. Only application/json and application/x-www-form-urlencoded bodies keep the raw bytes, so since v0.24.0 a request that carries a body of any other type answers 415 before the signature is checked; an empty body is not refused.

Stricter ingress checks from v0.23.6

The single-segment route, the numeric toleranceSec, the string ack body and header values, the 200 floor on the ack status and the wider header-value rule are new in v0.23.6; earlier releases loaded a manifest that broke them. Such a manifest is now refused at install with 400. A plugin already installed with one stops loading when the gateway is upgraded: the boot log reports it as plugin_load_failed, it drops out of GET /api/plugins, every /api/plugins/{id} route except POST /api/plugins/{id}/disable and DELETE /api/plugins/{id} answers 404, as does a delivery to its ingress URLs, and only its stored registry entry, which those two still act on, is marked error. Its config and its integration instances are kept: the routes under /api/integration/plugins/{id}/instances still work on them, except creating a new one, which answers 404. Install a corrected version through POST /api/plugins/install or POST /api/plugins/install-url; POST /api/plugins/{id}/update cannot be used, because the plugin is not loaded. The reinstalled plugin loads as installed, so enable it with POST /api/plugins/{id}/enable; otherwise, if it had been enabled, the stored enable decision brings it back only at the next restart.

Stricter ingress checks from v0.31.0

A manifest whose ingress is not a list, or whose hmac-sha256 contentTemplate, header or timestampHeader (on hmac-sha256 and shared-secret routes), dedupHeader or conversationId.header is not a string, was not checked by earlier releases, so it could fail to load, fail at runtime or be read as if the field were absent. It is now refused at install and update with a 400 that names the field, and an installed plugin that declares one fails to load at the next boot the way the v0.23.6 case above does: its status is error and the log names the field and, where one applies, the route. Install a corrected package; POST /api/plugins/{id}/update cannot be used on a plugin that is not loaded.

The host deduplicates provider retries on the route's delivery-id header (the declared dedupHeader, webhook-id for standard-webhooks, otherwise x-delivery), or on a hash of the raw body when the provider sends none; since v0.23.6 a blank header counts as none, and since v0.25.0 so does one longer than 255 characters. A provider that mints a fresh delivery id on every retry attempt defeats the header, so a route can declare "dedupOn": "body" (v0.23.6+) to key every delivery on the body hash, as supabase-otp-hook does. An earlier gateway does not know the field: the manifest still loads there, but the route keeps deduplicating on the header, so each retry from such a provider counts as a new delivery. Setting minOpenWAVersion to 0.23.6 cannot keep the plugin off a gateway without dedupOn: a gateway before v0.24.0 does not check the field at install or load, and every gateway that does check it already knows dedupOn. Keep the default when the provider's retries legitimately differ in the signed body, since body would then deduplicate nothing. On a header-dedup route (dedupOn: "header" or default), setting "dedupBodyMismatchAsNew": true (v0.28.0+) accepts a delivery whose dedup header matches an existing row within the retention window when its SHA-256 body hash differs (storing it under ${deliveryId}:${payloadHash} while req.deliveryId passed to the handler remains the original delivery id, and incrementing openwa_ingress_dedup_body_mismatches_total), while identical bodies with the same header still deduplicate. The trade runs the other way too: under body, two deliveries to the route with byte-identical bodies are one delivery for as long as the dedup row is kept (INGRESS_DEDUP_RETENTION_DAYS, default 7 days), so the second gets the route's ack and never reaches the handler, and the handler's req.deliveryId is that hash rather than the provider's id. The header is not covered by the credential, so on a shared-secret route and on an hmac-sha256 route that signs no timestamp, a copy of a delivery sent with a different header value is accepted as new unless the route declares dedupOn: "body". Since v0.24.0 the loader logs ingress_replayable_route for a shared-secret route, and for an hmac-sha256 route that declares no timestampHeader and has no {timestamp} in its contentTemplate, unless the route sets dedupOn: "body".

In onEnable, claim the route with ctx.registerWebhook. The host renders the synchronous HTTP response itself from the route's response.ack block (default 202 accepted), and the handler usually runs after the provider has been answered. The one exception is inline dispatch (the queue disabled, or Redis unreachable) on a route without a response block: there the answer waits until the handler returns or fails (see What the provider receives). A retry the host has already recorded gets that same ack and is not dispatched again (v0.23.6+; before, it was answered 200 duplicate). A repeat is therefore not distinguishable by its response: a route whose declared ack is non-2xx gives every retry that status, so a provider that retries on it no longer stops after its first retry, and the gateway keeps no record of which deliveries were repeats: the ingress_events dedup row is written by the first delivery of each id, and a repeat adds no row or field. Your handler's return value never reaches the provider, and the status in it is inert. What carries weight is a throw: a handler that throws, or blows the dispatch budget, fails the delivery (since v0.28.0 a queued delivery with QUEUE_ENABLED=true gets SIMULATE_TYPING_MAX_MS + 5 seconds, capped at 25 seconds, while inline dispatch (a reconciler replay with the queue off included) keeps the fixed 5-second budget (INGRESS_DISPATCH_TIMEOUT_MS is a constant in the gateway, not a setting); start an outbound send with void ctx.messages.sendText(...) without await when the handler does not need the send result): a queued delivery is retried and dead-lettered once INGRESS_MAX_ATTEMPTS attempts have failed (3 by default, the first dispatch included), and an inline delivery (the queue disabled, or Redis unreachable) is dead-lettered on its first failure and then, with the queue disabled, replayed by the ingress reconciler on later sweeps (INGRESS_RECONCILE_INTERVAL_MS) until a replay succeeds or its replay budget runs out (with the queue enabled and Redis unreachable the sweep leaves it alone until Redis answers), while a handler that returns normally is recorded as delivered whatever status it names. Declare the synchronous contract in the manifest's response block instead (response.ack for the status, body and headers; response.preflight for a host-side check such as session-alive), the way supabase-otp-hook does. A session-alive preflight answers 503 session not ready when the instance's bound session has no live engine or has failed; since v0.23.6 that answer carries Retry-After: 5, so a provider that retries a 503 only when the header is present comes back. The rejected delivery writes no dedup row, so the retry counts as a new delivery. While the gateway is still restoring the plugin after a start (v0.26.0+), a route that declares a response block is refused the same way, with 503 plugin restoring and Retry-After: 5, and writes no dedup row either. A route without a response block is acked and recorded as usual and its handler runs once the plugin is up: a queued delivery is held without spending an attempt, and with the queue off the row stays pending until the ingress reconciler dispatches it, on the first pass after the restore once the row is older than INGRESS_RECONCILE_GRACE_MS (60 seconds by default). With the reconciler disabled (INGRESS_RECONCILE_INTERVAL_MS=0) nothing would replay a held row, so the delivery is dispatched at once and, with no worker yet, files a dead letter to redrive. Of the declared ack headers, Content-Type is honored only as application/json or text/plain (v0.23.6+; v0.20.0 through v0.23.5 sent every ack as text/plain), and any other type goes out as text/plain. Since v0.23.6 the host also drops a declared header it controls itself: Content-Length, Transfer-Encoding, Content-Encoding, Trailer, Set-Cookie, Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Content-Security-Policy, X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security and Referrer-Policy. The handler itself:

async onEnable(ctx: PluginContext): Promise<void> {
ctx.registerWebhook('webhook', async (req) => {
// req.verified is true — the host already checked the HMAC and dedup.
const providerMsg = JSON.parse(req.body ?? '{}');

// Resolve the WhatsApp chat for this external conversation.
const mapping = await ctx.mappings.getByProvider(req.instanceId, providerMsg.conversation_id);
// Nothing to relay, and a retry cannot invent a mapping. Return without throwing so the delivery is
// not retried into the DLQ. The provider never sees this return value: the host answers the route's
// ack itself.
if (!mapping) {
ctx.logger.warn(`no chat mapped to conversation ${providerMsg.conversation_id}`);
return;
}

// Send the agent's reply as a normalized message.
await ctx.conversations.send({
sessionId: mapping.sessionId,
instanceId: req.instanceId,
chatId: mapping.chatId,
type: 'text',
text: providerMsg.body,
source: { provider: 'helpdesk', externalConversationId: providerMsg.conversation_id },
});
});
}

The envelope type selects the send path: text, image/video/audio/file (with mediaUrl and caption from text), voice (a PTT voice note), or location. A location envelope needs latitude (-90 to 90) and longitude (-180 to 180), with text as its description; without valid coordinates the send fails with a PluginCapabilityError. replyTo is refused with a PluginCapabilityError on a location envelope and on a media envelope that carries a mediaUrl. Since v0.23.6 a non-empty mediaUrl must be an absolute http:// or https:// URL with a host: any other value fails the send with url must be an absolute http(s) URL, where earlier releases passed it to the engine, which decoded it as base64. A media envelope whose mediaUrl is missing or empty is not refused; it goes out as a plain text message carrying text (a quoted reply when replyTo is set). For a session with an egress proxy, the host fetches the URL through that proxy (v0.23.6+) unless the operator sets SESSION_PROXY_URL_FETCH=false. On a plain text send, linkPreview: true asks the engine to attach a URL preview card — Baileys generates one only on request, so an adapter relaying a link delivers a bare URL without it, while whatsapp-web.js previews by default and takes false to suppress. Since v0.30.3 an envelope that leaves linkPreview out, or gives anything but a boolean, takes the session's linkPreview config default when one is set, and so does a plain ctx.messages.sendText. It is ignored on media, location, and quoted sends. On Baileys the page fetched for that card also leaves through the session's egress proxy under the same switch (v0.23.6+); when the proxy cannot reach it, the text is sent without a preview rather than failing. Use ctx.mappings.upsert to record a new chat↔conversation link, and ctx.handover.set to flip a conversation to human so other bots stop replying while an agent handles it. Since v0.23.6 a 1:1 chat's @lid and phone forms count as one chat for handover: a takeover recorded under either form silences other bots on both, ctx.handover.set applies the state to every mapping the instance holds for the chat in that session, and a mapping upserted under the chat's other form starts in the handover state the instance already holds. A takeover or closed conversation recorded on a lid form before the upgrade therefore also applies to the phone form until the adapter hands the chat back to the bot. The chat's forms are its phone form and every @lid an engine has reported for that number (a lid it has not reported yet matches only itself, and since v0.26.0 a mapping kept from an earlier release, including one restored from a backup made on an earlier release, counts only once an engine reports the pair again; before, every mapped lid counted), so on a number WhatsApp recycled to a new owner the earlier owner's lid still counts, and a handover decision on either owner's chat applies to both. Since v0.30.2 ctx.mappings.get and ctx.mappings.getByProvider report that state as well: handoverState is the one the instance holds for the chat in that session across those forms (human outranks closed, which outranks bot), so a read of one row no longer misses a takeover recorded under the other, while providerConversationId, sessionId and chatId are those of the row read. The capability model, the handover gate, and the payload fields that are easy to miss are documented in Plugin architecture.

Install, configure, and enable​

With faq-bot.zip built, an operator installs it in three admin-authenticated calls. Plugin routes sit under the /api prefix and require the ADMIN role.

Upload the package:

curl -X POST "http://localhost:2785/api/plugins/install" \
-H "X-API-Key: YOUR_API_KEY" \
-F "file=@faq-bot.zip"

Set its config (the rules value is a JSON string, so its quotes are escaped):

curl -X PUT "http://localhost:2785/api/plugins/faq-bot/config" \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "config": { "rules": "[{\"mode\":\"contains\",\"pattern\":\"price\",\"reply\":\"Plans start at $10/mo.\"}]" } }'

Enable it:

curl -X POST "http://localhost:2785/api/plugins/faq-bot/enable" \
-H "X-API-Key: YOUR_API_KEY"

If the plugin fails to enable, that call still answers HTTP 200, with { "success": false, "message": "<the error>" }; check success, not the status code. Send "price" from another phone to a connected session and the bot replies "Plans start at $10/mo." as a quoted reply. The operator can also do all three steps from the dashboard's Plugins tab.

YOUR_API_KEY is an admin key from your OpenWA configuration. See Authentication for how to obtain one.

Troubleshooting​

SymptomCauseFix
version drift: manifest is X but CHANGELOG top is YThe manifest version and the top CHANGELOG.md heading disagree.Make them match. The top heading must read ## [X.Y.Z] — YYYY-MM-DD.
type must be "extension" to be installablemanifest.type is not extension.Set "type": "extension". Only extensions are user-installable.
Install rejected — id reservedThe id is one of whatsapp-web.js, baileys, auto-reply, translation.Rename to a unique id.
Install rejected — over limitPackage exceeds 5 MB / 200 files / 20 MB.Bundle to a single dist/index.js; drop node_modules from the zip.
Plugin shows ERROR in the dashboardYour config parser threw (for example, invalid rules JSON), or its sandbox worker crashed or stopped answering (see the note below).Fix the operator config; check ctx.logger output. A thrown config error is the parser doing its job; after a worker failure, enable the plugin again once the cause is fixed.
PluginCapabilityError at runtimeYou called a capability without declaring its permission.Add the matching permission (messages:send, engine:read, net:fetch, webhook:ingress, conversation:send, storage:use) to the manifest.
missing the 'storage:use' permission on a ctx.storage callThe plugin persists state but its manifest predates v0.17.0, where storage:use became required.Add "storage:use" to the manifest permissions array and reload the plugin. If the store happens in onEnable, the plugin shows ERROR until you do.
Hook handlers are time-boxed

A sandboxed plugin's hook runs under a host timeout (5 s), and when it runs out the chain continues without the plugin's result. Since v0.24.0, a plugin whose worker then also stops answering a liveness ping, as one stuck in a synchronous loop does, is terminated and set to ERROR; a slow but asynchronous handler is not. Keep handlers fast — match, decide, send. Do not block on long external work inside a message:received handler.

Next steps​