Commands
For feedback and menu layout policies, see Customize built-in presentation.
A command is a function that runs when a user sends something like /hello or /remind 10 drink water. This page starts with the simplest command and adds params, options, permissions and rich replies step by step.
The remind command here is a development example. For a ready-to-use persistent reminder with follow-up questions, see Create reminders without AI.
The simplest command
Create commands/hello/index.ts in the plugin root:
// commands/hello/index.ts
import { defineCommand } from 'zhin.js/command';
export default defineCommand({
description: 'Say hello',
execute: () => 'Hello from zhin.',
});Save, send /hello, and the bot replies Hello from zhin..
- The file path is the command name. Only
index.ts(orindex.tsx) is the entry; other files in the folder can be helpers. - Whatever
executereturns is the reply. descriptionshows up in the command list and help — always write one.
Single-file style
If you don't want folders, register the same definition in plugin.ts; the result is identical:
import { definePlugin } from 'zhin.js';
import { defineCommand } from 'zhin.js/command';
export default definePlugin({
name: 'my-bot',
setup({ addCommand }) {
addCommand('hello', defineCommand({
description: 'Say hello',
execute: () => 'Hello from one file.',
}));
},
});Both styles share the same command table and conflict detection. As commands grow, move them into commands/; editing one then reloads only that file.
Fixed replies and pattern triggers
When the reply never changes, use reply instead of execute. To let a plain sentence (not /name) trigger the command, add a match regular expression:
// commands/demo/index.ts
import { defineCommand } from 'zhin.js/command';
export default defineCommand({ description: 'Status', match: /^demo$/, reply: 'All good' });- Use either
replyorexecute.replycan be text, message segments or JSX. matchtests the whole message text after the command prefix and surrounding whitespace are removed, and only for text-only messages. The command name (/demo) keeps working.- Command names are matched first; patterns are tried only when no name matches. If several patterns fit, the first command in the command list (sorted by name) runs.
- The result is in
context.match, with named groups inmatch.groups:
export default defineCommand({
description: 'Weather',
match: /^weather (?<city>\S+)$/u,
execute: ({ match }) => `Looking up the weather in ${match?.groups?.city}`,
});- The
gandyflags are rejected: they make a pattern remember its last position, so the same message would match only every other time.
Common tasks
Accept parameters
Declare params in order under params; the params passed to execute gets the right types automatically:
// commands/remind/index.ts → /remind 10 drink water
import { defineCommand } from 'zhin.js/command';
export default defineCommand({
description: 'Create a reminder',
params: {
minutes: { type: 'integer', min: 1, max: 1440, description: 'Minutes' },
note: { type: 'text', default: 'Take a break', description: 'What to remind' },
},
execute({ params }) {
// params.minutes: number, params.note: string
return `OK, I'll remind you in ${params.minutes} min: ${params.note}`;
},
});/remind 10 drink water:minutesis10,noteisdrink water./remind 10:notefalls back toTake a break./remind abc: the bot replies with the validation error automatically;executedoesn't run.
Common constraints:
| Option | Effect |
|---|---|
default: … | Value when nothing is given |
optional: true | May be omitted; the value is then undefined |
min / max | Range for numbers or text length |
choices: [...] | Only these values are allowed |
pattern | Check text with a regex |
validate(value, session) | Custom check returning true, false or an error message |
rest: true | Collect all remaining input as an array; must be the last param |
All param types: Reference · Param types.
Add options
Options are switches like --count 2 or -q that can appear anywhere:
export default defineCommand({
description: 'Create a reminder',
params: {
minutes: { type: 'integer', min: 1 },
},
options: {
count: { type: 'integer', alias: 'c', default: 1, min: 1, max: 10 },
quiet: { type: 'boolean', default: false },
},
execute({ params, options }) {
// options.count: number, options.quiet: boolean
if (options.quiet) return; // no reply
return `Reminding ${options.count} time(s)`;
},
});--count 2, --count=2 and -c 2 are equivalent; --quiet means true, --quiet=false means false.
Generated help
Once a command declares params or options, /remind --help shows help generated from the declaration, including the current platform's command prefix.
Aliases and shortcuts
export default defineCommand({
description: 'Like',
alias: ['zan'], // /zan runs this command
shortcut: { 'max likes': { count: 10 } }, // sending exactly "max likes" is like passing count=10
params: { count: { type: 'integer', default: 1 } },
execute: ({ params }) => `Liked ${params.count} time(s)`,
});Aliases may be multi-word (e.g. 'gh issue'). A shortcut fires only when the trimmed message exactly equals the key. Aliases, shortcuts and real command names must not collide; conflicts fail at startup.
Restrict who can use it
Declare rules with permit; the bot refuses when they aren't met:
export default defineCommand({
description: 'Wipe data',
permit: ['owner'], // the bot owner (chat role owner) only
execute: () => 'Wiped',
});| Rule | Meaning |
|---|---|
owner / admin / trusted / role(admin,trusted) | The sender's chat role along this conversation's scope chain (owner ⊃ admin ⊃ trusted) |
owner@global / owner@adapter / admin@endpoint / role(owner@global,admin) | Level-qualified: the role must come from that level or a higher one (sender.chatRoleLevels). Commands that affect the whole host (restart, project configuration, running commands…) use owner@global; a conversation-level owner owns that conversation only |
platform:owner / platform:admin / platform-role:<id> / platform-permission:<name> | The sender's platform standing (sender.platform, reported by the adapter) |
bot:owner / bot:admin / bot-role:<id> / bot-permission:<name> | The bot account's own standing in this conversation (cached per conversation; unknown means unmet) |
adapter(icqq) | Only on one platform |
group() / private() / channel() | Restrict conversation kind; an empty value or * matches any ID of that kind |
group(123) / private(…) / channel(…) / user(…) | Compare the corresponding conversation or sender ID, without restricting the complete account, parent or thread |
All rules in the array must pass (AND); commas inside one rule mean any of (OR). Users without permission don't see the command's help either, and the command menu lists only commands the sender can run in this conversation.
Commands share the rules and the evaluator with Agent tools / skills (three dimensions: the sender's zhin role, the sender's platform standing and the bot's own platform standing). A platform action the bot performs usually names both:
export default defineCommand({
description: 'Mute a member',
permit: ['group()', 'platform:admin', 'bot:admin'], // the sender is a group admin, and so is the bot
execute: async () => { /* … */ },
});When unmet the command takes its denial reply: platform:* / bot:* conditions say what is missing (e.g. 「无法执行此指令。机器人不是本群管理员(或无法确认其身份)。」), zhin role conditions say where roles come from (「没有权限执行此指令。此功能需要 zhin 角色。请联系本机器人的主人授予,或由主人在 Console「聊天角色」页授予。」; a platform group owner / admin is also told that platform standing is not a zhin role; the reply never names the missing role or who holds it), owner@global says a global chat owner is needed and where one is granted (the same text as the checks inside restart / config, describeGlobalOwnerRequired(); its bind <code> needs no command prefix, like claim <code>), private() answers 「此指令只能在私聊中使用,请私聊机器人发送。」, and the other conversation conditions keep the generic 「没有权限执行此指令。」. These texts have one source, describeCommandDenial() in @zhin.js/permission; subscription commands that decide with canManageConversation() reply with describeConversationManagerDenial() (zhin.js/command).
Roles come from the actual message (sender.chatRole, set by the Runtime) and grants live in the project database: manage them in the Roles tab of the Console object pages or with the role grant chat command. A platform group owner / admin is not a zhin role — commands for zhin functions use admin / owner, commands for platform functions use platform:*. See Chat roles; the old role(master), scene_admin and platform(adapter,perm) spellings map as listed in Upgrading to chat roles.
For the same check in middleware or event handlers, use checkPermissions:
import { checkPermissions } from 'zhin.js';
if (!(await checkPermissions(context, ['group(team)', 'role(trusted)']))) return;It reuses the same rules but does not replace AI tool approval or execution security policies.
Limit repeated execution and show progress
Add execution to individual expensive commands. Commands without it keep their existing behavior. This complete example can live in commands/slow/index.ts:
import { setTimeout as delay } from 'node:timers/promises';
import { defineCommand } from 'zhin.js/command';
export default defineCommand({
description: 'Demonstrate cooldown and concurrency for a slow task',
execution: { cooldownMs: 10_000, maxConcurrent: 1, progressAfterMs: 1_500 },
async execute({ signal }) {
await delay(3_000, undefined, { signal });
return 'Demo task completed';
},
});Send slow as a real user in the original conversation, adjusting the actual account prefix and plugin namespace. A progress notice may arrive after 1.5 seconds, followed by the result. This is a local delay demonstration with no business-service calls. A pending notice is stopped when business work ends; an already-started notice drains before the final reply, preserving message order.
Budgets are isolated by command capability, real sender and complete conversation identity: Endpoint, kind, ID, parent and thread. Aliases and shortcuts share the same budget. This is not a plugin-wide or all-user concurrency cap.
cooldownMsstarts when business execution is accepted. Failure and cancellation still consume it. Help, invalid arguments, permission denial and admission refusal do not. Maximum: one day.maxConcurrentremains occupied until business work, rendering, outbound middleware and final sending actually settle. A retirement or hot-reload cancellation signal does not release a still-running operation. Generations share the budget. Maximum: 1000.progressAfterMsis off by default. When set, each operation can emit at most one notice for that command during business waiting. It uses the original conversation's unified reply path. Failed or uncertain notice delivery is not retried. Maximum: one hour.
All values must be positive integers, with at least one policy specified. Cooldown refusals include the remaining time when recorded. Busy operations have no predictable completion time. Diagnostics use limited, distinct from permission denial and platform delivery failure; a refused command is not handed to an Agent for another execution attempt.
Policies require a genuine Core inbound operation and complete identity. Direct CommandIndex calls outside that operation cannot manufacture a source to bypass admission. Continue to await input.$reply(...) for additional replies; work started by arbitrary future timers is outside an already-finished operation. Cooldown does not replace idempotency, permissions or reconciliation, never retries unknown, and does not create a cancellation button for an operation that cannot be cancelled.
Reply with images, cards or several messages
execute may return:
| Return value | Effect |
|---|---|
| A string | Text reply |
JSX (<card>, <html><Card>...</Card></html>, <button onClick>, etc.) | Sends rich messages, visual image cards, or interactive buttons adapted to each platform |
component('status-card', props) | Renders a component; image-capable platforms show it as an image |
raw({ type: 'html', data: { html, width } }) | A platform segment sent as-is |
| An array of the above | Multiple segments |
undefined | No reply (e.g. you already replied with input.$reply()) |
Save a command as .tsx (e.g. commands/poll/index.tsx) to return JSX directly—including native <card>, visual image cards (<html><Card>...</Card></html>), and interactive <button onClick> (which renders native buttons on supported platforms and automatically degrades to numbered replies on text platforms):
// commands/poll/index.tsx
import { defineCommand } from 'zhin.js/command';
import { Card, CardHeader, Badge } from '@zhin.js/components';
export default defineCommand({
description: 'Start a release confirmation poll',
execute: () => (
<>
<card title="Release Confirmation" content="Ship v1.1.0 now?" />
<html>
<Card>
<CardHeader title={<strong>Release Checklist</strong>} badge={<Badge>Ready</Badge>} />
<p>Build and unit tests have passed.</p>
</Card>
</html>
<button onClick={async (clickMsg) => `Confirmed by ${clickMsg.sender?.name ?? clickMsg.sender?.id}!`}>
Confirm
</button>
</>
),
});What a .tsx file costs in memory
Node strips types from .ts files natively but cannot compile JSX. The first time the instance loads a .tsx file of your project, it registers the tsx loader to compile it; a project without .tsx files never registers it. Once registered, the instance process keeps the tsx modules and the esbuild child process tsx compiles with, about 16 MB together (about 15 MB of it the esbuild child).
For a production deployment short on memory, write the command as .ts instead: render a component by name with component('status-card', props) (example below) or send a message segment with raw(). If the rendered component itself is a components/*.tsx file of the project, loading it registers the tsx loader just the same; to avoid tsx entirely, move the component into a separate plugin package compiled to .js before publishing, which needs no tsx at run time.
You can also invoke a registered component by name:
// commands/card/index.ts
import { defineCommand } from 'zhin.js/command';
import { component } from 'zhin.js/component';
export default defineCommand({
description: 'Status card',
execute: () => component('status-card', { title: 'my-bot', lines: [] }),
});Multi-turn interactive prompts (context.interaction)
When a command needs to ask follow-up questions mid-execution (type: 'confirm' | 'select' | 'text' | 'number', or interaction.select() / pick-style choices), use interaction from the execute argument:
// commands/deploy/index.ts
import { defineCommand } from 'zhin.js/command';
export default defineCommand({
description: 'Interactive deploy wizard',
async execute({ interaction }) {
if (!interaction) return 'Interactive prompts are not supported in this environment';
const env = await interaction.ask({
type: 'select',
title: 'Choose the target environment:',
options: [
{ label: 'Staging (staging)', value: 'staging' },
{ label: 'Production (prod)', value: 'prod' },
],
});
const replicas = await interaction.ask({
type: 'number',
title: 'Enter replica count (1-10):',
min: 1,
max: 10,
integer: true,
default: 2,
});
const notes = await interaction.ask({
type: 'text',
title: 'Enter release notes:',
default: 'Routine maintenance update',
});
const confirmed = await interaction.ask({
type: 'confirm',
title: `Deploy to ${env} (${replicas} replicas, notes: ${notes})?`,
default: false,
});
return confirmed ? `Deploying to ${env} (${replicas} replicas)` : 'Deployment cancelled';
},
});While a prompt waits (ADR 0061 decision 11, revised, #1250):
- Cancel:
select, multiselect,numberandlistprompts accept取消,退出,算了,cancel,exitandquitin every language (full-width, case and trailing punctuation are ignored; the vocabulary isisCancelWord()in@zhin.js/core), and the prompt saysreply "cancel" to exit. An option that is itself labelled取消stays an option. Inconfirmthese words still answerfalse; aconfirmanswer may be Chinese or English whatever the prompt's language:确认/确定/是/好/同意/yes/y/ok/confirmanswertrue,否/不/拒绝/no/n/canceland the like answerfalse(isConfirmWord()/isCancelWord()with{ yesNo: true }). Alistreply that is exactly one cancel word cancels (it is not read as the one-item list['取消']); a cancel word among several items stays an item. Atextprompt cancels on these words only when its rules (minLength,pattern, …) reject them; without rules it takes any text as its answer. - Sending something else leaves: when the asked person sends a message that matches a command (and is not a valid answer) or carries an image / file / voice / video, the prompt ends. A mention of the bot alone does not leave: some platforms deliver group messages only when the bot is mentioned, others mark a reply to the bot as a mention, so every answer may carry one; an invalid answer such as "@bot 3" gets the question again (then throttled reminders). Only when the text after the leading mention matches a command (such as "@bot /help") does the prompt end. An answer already taken while the question was still being sent is never displaced by a later message. Command matching honours a command's
adapterrestriction (not its permissions). The bot first says "Left the previous question" once (at most once a minute per person), then handles the new message normally. Other members' messages in a group are not affected. - Invalid answers: the first invalid answer re-sends the question; after that the bot reminds at most twice per prompt ("Still waiting for your choice: reply with an option number, or reply "cancel" to exit"), at least 20 seconds apart, instead of waiting silently.
- How it ends: on cancel, interruption or a newer prompt,
ask()throws an error whosenameisUserInteractionCancelledError(reason:cancelled/interrupted; a newer prompt throwsUserInteractionSupersededError); a timeout throwsUserInteractionTimeoutError(or returnsdefaultwhen one is set). Catch it only to clean up: the framework already told the user ("Cancelled", "Input timed out" or "Left the previous question"), and the inbound outcome isinteraction_cancelled/interaction_timeout(INFO log, not a failure, neverinternal_error). Match onerror.name.
Know who sent it and where
export default defineCommand({
description: 'Who and where',
execute: ({ adapter, endpoint, scene, sender }) =>
`${sender?.name ?? sender?.id} @ ${scene?.type}:${scene?.id} via ${adapter}/${endpoint} roles=${sender?.role.join(',')}`,
});sender is the sender (with roles), scene is the group / DM / channel, and adapter and endpoint are the platform and account. All fields: Reference · execute argument.
Use services from your plugin
Services provided in setup with context.resources.provide(token, value) are available in commands via use(token):
export default defineCommand({
description: "Show today's pick",
async execute({ use }) {
const { db } = use(lotteryRuntimeToken);
// ...query and return
},
});use throws when the service is missing. See definePlugin · Provide resources to your own commands and tools.
Type the config
A command in a convention folder does not know which plugin it belongs to, so config is unknown by default. Use defineCommand.withConfig: fix the config type first, then define the command:
import { defineCommand } from 'zhin.js/command';
import type { EchoConfig } from '../../../src/index.js'; // keep in sync with schema.json
export default defineCommand.withConfig<EchoConfig>()({
params: { text: { type: 'string' } },
execute({ params, config }) {
return `${config.prefix ?? ''}${params.text}`; // params.text: string, config: EchoConfig
},
});The function defineCommand.withConfig<EchoConfig>() returns can be reused: write export const defineEchoCommand = defineCommand.withConfig<EchoConfig>() once in src/ and call it from each command file.
The older defineCommand<EchoConfig>({...}) still works, but TypeScript cannot infer the remaining type arguments once one is given explicitly, so params falls back to Record<string, CommandParameterValue>. Use withConfig when you want params and options inferred.
Subcommands
Nested folders are subcommands; segments are joined with spaces:
| File | Command |
|---|---|
commands/hello/index.ts | hello |
commands/qq/endpoint/list/index.ts | qq endpoint list |
commands/qq/endpoint/add/[[name]]/index.ts | qq endpoint add [name] |
The plugin name is never prepended automatically. If two plugins' commands collide, give one of them commandNamespace: admin and all its commands become admin xxx.
When only a few commands overlap with another plugin, list them in that plugin instance's disabledCommands and keep the rest under their own names:
plugins:
60s: "@zhin.js/plugin-60s"
60s:
disabledCommands: [fanyi, weather] # local command paths, without commandNamespace or parametersA parent path such as netease also removes netease login, netease status and its other subcommands. Disabled commands are left out of routing and do not occupy their routes, so another plugin may use the same name. Entries that match no command are ignored.
An unresolved clash between two plugins no longer stops the instance from starting:
- When two command names clash, the plugin declared first in the configuration keeps the route. The later command is not registered, and neither are its aliases and shortcuts; its subcommands (such as
foo bar) are not affected and still work. - When only an alias or a shortcut clashes, only that alias or shortcut is skipped and the command itself is registered. A command name takes precedence over another plugin's alias: when a plugin declared later adds a command named like an earlier plugin's alias (for example A's
adminhas the aliasbanand B adds a commandban),bannow runs B's command. The "Needs attention" inbox marks this case as danger. - A plugin switched off for an adapter, account or conversation does not occupy its routes there. So on an endpoint where the plugin that keeps a route is switched off, the command that was skipped answers instead.
Each clash is logged once as a warning (op=command_route_conflict) and is listed in the Console "Needs attention" inbox and in zhin doctor, with both plugin names and the command or alias. Fix it as described above: rename one of them, add a commandNamespace, or remove one with disabledCommands. A plugin hot reload that replaces its own commands is not a clash.
Two commands, aliases or shortcuts of the same plugin that collide are that plugin's own bug (for example commands/foo declares a parameter and commands/foo/[id] also exists). This still fails with Duplicate Command route when the plugin loads, so the plugin's own tests catch it.
Params as folders
A param can also be the last path segment, Next.js style. Types and defaults are still declared in params:
| Folder | Meaning | Shown in help | params declaration |
|---|---|---|---|
[name]/index.ts | Required | <name> | params: { name: { type: 'string' } } |
[[name]]/index.ts | Optional | [name] | params: { name: { type: 'string', default: '' } } |
[...name]/index.ts | Collect all remaining input | <...name> | params: { name: { type: 'text' } }, value is an array |
[[...name]]/index.ts | Optional collect-all | [...name] | Same; empty array when omitted |
Declaring several params in commands/remind/index.ts is usually better than a folder per param. Folder params suit "command followed by an object name", such as qq endpoint remove <name>. Details: Reference · Folder param rules.
Accept images, mentions and other non-text params
Param types can be message segments such as image or mention:
// commands/upload/[asset]/index.ts → /upload [image] caption text
import { defineCommand } from 'zhin.js/command';
export default defineCommand({
params: {
asset: { type: 'image', description: 'Image to upload' },
},
execute: ({ params, args, segments }) => ({
uploaded: params.asset, // the image MediaRef
captionWords: args, // remaining text, split on whitespace
remainingSegments: segments, // remaining content, keeping images, mentions, etc.
}),
});Matching happens directly on message segments; images and mentions are never flattened to text first. These params don't support defaults.
Set a command prefix
By default there is no prefix: every message is tried as a command. Once a connection sets commandPrefix, only messages starting with it are treated as commands; the rest go to normal chat or the AI:
configVersion: 2
plugins:
qq: "@zhin.js/adapter-qq"
qq:
commandPrefix: '/' # only messages like "/qq endpoint list" trigger commands
endpoints:
- name: main
commandPrefix: '' # override for a single accountThe Sandbox created by npm create zhin-app --adapter sandbox is set to /.
Browse loaded commands
With the Command Feature enabled, the built-in command menu responds out of the box to 菜单, 帮助, help, and menu (as well as /help, /menu, and @Bot 菜单)—no separate help plugin is needed. When total commands are ≤ 8, the first page automatically flattens root commands so users can see them at a glance; with more than 8 commands, it browses by plugin layer and page. If the current account uses commandPrefix: '/', you can also prefix these messages with /:
| Message (without a prefix) | Result |
|---|---|
菜单 / 帮助 / help / menu | Commands, descriptions, and immediate child plugins of the root plugin (automatically flattens root commands when total ≤ 8) |
菜单 rss | Commands and immediate children of the plugin instance named rss |
菜单 foo.bar | Commands and children of nested plugin bar under foo |
菜单 --page 2 | The second page of the root menu |
菜单 rss --page 2 | The second page of the rss instance menu |
remind --help | A command's parameters, options, and usage, without executing it |
Plugin names here are instance keys, not npm package names. Start with 菜单 or help and follow the child plugin names it returns. Only plugins whose subtree has a command you may run are listed: adapters and command-less service plugins are left out (菜单 <instance key> still shows them). The root menu is titled with the project's display name (metadata.displayName), or plain "Command menu".
You can customize the primary menu keyword at the top level of the project's zhin.config.yml, alongside plugins:
menuKeyword: helpSet menuKeyword: false or menuKeyword: '' to disable the built-in menu.
Similar-command hints
When a private message, an @mention of the Bot or a prefixed message matches no command but its first words closely resemble a registered command name or alias (for example rss lst, RSS-List, gues), the framework replies "No such command. Did you mean: …" through the normal reply pipeline instead of handing the message to the AI. Matching ignores case, spaces, - and _; by default it accepts one edit for names of at least 5 characters (3 CJK characters), and shorter names only when they are identical after removing separators. After the name the message may carry at most the command's declared arguments plus one word. Only commands the sender may run are listed. When no name is that close but the first word is the whole first word of a multi-word command (for example qrcode hello for qrcode gen / qrcode scan, at least 3 characters), the commands under that word are listed.
commandSuggestion: false # disable
# commandSuggestion: { maxDistance: 2, limit: 5 }With @zhin.js/html-renderer installed, the menu emits a styled HTML card through the unified outbound pipeline. Image-capable platforms receive a menu image; native HTML platforms follow their declared HTML policy. If rendering fails or the platform requires text or cannot accept the generated image, the original text menu is preserved. Without a renderer, it remains plain text. Browsing, prefixes and custom keywords are unchanged.
Each page contains at most 30 entries, counting commands and child plugins together. The menu shows totals, the current page and explicit previous/next messages, using the current prefix and keyword. Text fallback uses the same page; it never sends every page at once. Page numbers must be positive integers; out-of-range requests report the actual page count. Long names and descriptions in the image are limited to two lines; command help retains the full declaration.
On endpoints declaring both native Markdown and native keyboard support, a multi-page menu also includes a Markdown page indicator and Previous / Next buttons. Previous is disabled on the first page, Next on the last; a single-page menu omits the controls. Each click sends the requested page through the unified reply pipeline, preserving the custom keyword, prefix and plugin target. Callback bindings stay within the original conversation and generation; expired or retired-generation buttons cannot invoke old handlers. Endpoints missing either capability retain the textual navigation. Telegram's disabled button wire format requires Bot API 10.3+; see DisabledButton.
The default artwork, ornaments and icons are embedded; they need no external downloads. Customize the presentation at the project root:
menuStyle:
title: My Bot · Command Atlas
subtitle: A little help for your everyday
accentColor: '#e7c993'
# Optional: your own artwork; omit to use the built-in landscape.
backgroundImage: https://example.com/my-menu.webpbackgroundImage accepts HTTP(S) URLs or PNG/JPEG/WebP base64 data URLs, not file paths or executable CSS. Remote artwork must be reachable from the bot host; its availability is independent of the HTML renderer. Use a data URL for fully offline custom artwork. accentColor accepts a six-digit hex color; invalid optional values use the defaults. These settings change image presentation only.
Platform types and the operation Session
Load installed adapter declarations once in the project, for example by including "node" and "@zhin.js/adapter-icqq" in compilerOptions.types while preserving existing entries. Business commands do not import Adapter classes. Installing a package alone does not make TypeScript scan its declarations.
import { defineCommand } from 'zhin.js/command';
export default defineCommand({
adapter: 'icqq',
params: { text: { type: 'text' } },
options: { silent: { type: 'boolean', default: false } },
async execute({ session, params, options }) {
if (!session) return;
session.adapter; // IcqqAdapter
session.endpoint; // IcqqEndpoint, extending the actual ICQQ Client
session.scene; // Narrow kind before using scene-specific fields
session.sender; // Separate platformRoles and authorizationRoles
session.event; // The original SDK callback object
if (!options.silent) await session.reply(params.text);
},
});Parameter, option, withConfig, and factory inference remains intact. Direct execution without a real IM input has no Session. Canonical message handlers and inbound middleware share the same operation view; unrelated native callbacks do not fabricate one.
Stopping or reconnecting the account cancels the captured signal. Framework replies cannot switch to a replacement connection. Retaining an SDK reference does not make direct native calls cancellable; use the unified send chain.
What happens on bad input
| Situation | Bot behavior |
|---|---|
| The message isn't a command | No response; passed on to later middleware, normal chat or the AI |
| Right command, missing or wrong params | Replies with the reason and help |
| No permission | Replies with a refusal, without help |
| Success | Replies with execute's return value |
execute throws a UserFacingError | Replies with its format(locale) (default message) through the normal reply chain |
execute throws anything else | Nothing about the error is sent; it is logged |
Expected, user-caused refusals (such as "there is already a game running in this channel") can throw UserFacingError (import { UserFacingError } from 'zhin.js/command'), or a subclass overriding format(locale) for localization. Its text is sent to the user as is: never put stack traces, internal ids or raw upstream errors in it. A UserFacingError thrown by an inbound middleware (defineMiddleware) or an event handler (defineHandler) is answered the same way in that conversation (a middleware replies as its own author; a handler replies in the message / notice / request conversation and dispatch continues with the next handler); any other error is only logged, never sent to the user.
Param errors are reported only when the input is clearly a given command: remind nope gets an error, while reminder 3 or ordinary chat isn't treated as a command. Permission checks run before param validation.
Reference
Param types
| Kind | type | Value |
|---|---|---|
| Text | string / word / text | A string; text reads the remaining continuous text, keeping quotes and newlines |
| Number | number / integer / float | A number; integer requires an integer, float a decimal |
| Boolean | boolean | true / false |
| Segment | mention / image / face / reply / forward / dice / rps | Fields of the matching segment |
Param declaration rules
- Params consume input in declaration order. Required params can't follow optional ones;
rest: truemust be last. textreads continuous text and belongs after other ordinary params.- Defaults may be dynamic functions; dynamic defaults and shortcut prefills are validated too.
- Invalid static defaults, bad param order and duplicate option aliases fail at load time; dynamic defaults are validated at dispatch.
- Options may appear between params; negative numbers aren't mistaken for options; nothing after
--is parsed as an option. Withparamsoroptionsdeclared, unknown or repeated options fail validation. - Commands without declared params can parse free input themselves from
args(remaining words) andsegments(remaining segments).
Real examples: QR code uses text, image size and defaults; code runner uses a folder param for the language plus code and timeout options.
execute argument
execute(context) receives a read-only object:
| Field | Description |
|---|---|
params | Declared params, typed from the declaration |
options | Declared options; undefined when unset without a default |
args | Words left after the command name (split on whitespace) |
segments | Remaining segments, keeping images, mentions and other non-text content |
config | This plugin's config |
input | The message that triggered the command; may be absent for Host or programmatic calls |
session | Bound single-operation platform session (adapter, endpoint, scene, sender, event, reply) |
$client | Typed platform endpoint client when adapter is specified |
interaction | Multi-turn interactive prompt API (ask / sequence), see Multi-turn interactive prompts |
adapter | Adapter instance id, e.g. root/icqq |
endpoint | Account / connection name |
scene | { id, type, name? }: group, DM or channel |
sender | { id, name?, role: string[] }: the sender and their roles |
has(token) | Check if an optional capability or Host token is available before calling use(token) |
use(token) | Get a service provided by the plugin; throws when missing |
locale | Active locale for the message or conversation (e.g. 'zh-CN', 'en') |
formatCommand(localPath) | Format a command display string using the current account's commandPrefix and plugin commandNamespace |
signal | AbortSignal for the current operation or generation, cancelled on hot reload or account disconnect |
owner | The plugin that owns the command |
generation | Current version number (increments on each hot reload) |
Unit testing a command
With createFakeMessage and runCommand from @zhin.js/testing, you can unit-test a command in 10 lines—runCommand automatically parses positional args and fills option defaults from your command declaration:
import { createFakeMessage, createFakePlugin, runCommand } from '@zhin.js/testing';
import remind from '../commands/remind/index.js';
it('parses positional args and fills option defaults', async () => {
const fake = createFakePlugin();
const input = createFakeMessage({ sender: { id: 'u1', name: 'Alice' } });
const reply = await runCommand(fake, remind, { input, args: ['10', 'drink water'] });
expect(reply).toBe("OK, I'll remind you in 10 min: drink water");
});See Testing Plugins for the full guide.
input isn't always a message (it may come from a Host call), so type-check before reading the sender; for non-message sources $reply does nothing. input is typed as CommandMessage by default, structurally compatible with the runtime Message (layering prevents @zhin.js/command from depending on @zhin.js/core).
alias / permit / shortcut / match / reply
| Field | Behavior |
|---|---|
alias | Replaces all static parts of the command name; folder params follow |
permit | Built-in rules: adapter|group|private|channel|user(...), owner|admin|trusted[@level] / role(...), platform:… / platform-role:… / platform-permission:…, bot:… / bot-role:… / bot-permission:…. Failure returns denied (denial names the first unmet rule and the reason); no auth subject also means denied, and programmatic CommandIndex.execute can't bypass it |
shortcut | { trigger text: prefilled params }, fires on an exact match after trimming |
match | Pattern trigger: runs when a text-only message, without the command prefix and surrounding whitespace, fits; the result is in context.match. Command names win; see Fixed replies and pattern triggers |
reply | Fixed reply; use instead of execute |
Conflicts are judged on the full word sequence: b and b list can coexist.
Folder param rules
- One folder param per command, and it must be the last segment.
commands/[note]/index.tsmatches a top-level single-word input;commands/remind/[note]/index.tsformsremind <note>. - A param with a
defaultmust use double brackets[[name]]; a folder param without a matchingparamsentry throwsCommandPathSyntaxError. - TypeScript can't see folder shapes: for
[[id]]without a default, declareparams.id.optional: true; for[...items], declareparams.items.rest: true. Put the folder param first inparams. - For collect-all params the element granularity follows the type:
textcollects by segment (plain text is one element);word/stringsplit on whitespace; numbers and booleans split into words and convert each;mention/imagecollect by segment. - Static folder names are lowercase kebab-case (
hello/,lottery-today/) or names containing non-ASCII characters without ASCII capitals (e.g.赞我/); param folders are ASCII only. - Static wins:
list/index.tsalways beats[name]/index.ts; among dynamic routes, more static segments win. - Routes that are still identical after
commandNamespacefail at startup; give conflicting plugins different namespaces.
Going deeper
How a command runs
Matching uses a fixed priority: static commands before dynamic ones, and more specific dynamic paths first. After a match, remaining text is split into args, and the full remaining segments stay in segments. For example qq endpoint remove mybot matches qq endpoint remove <name> with empty args and params.name === 'mybot'.
commandPrefix is read from the adapter instance the message belongs to (default ''); when the instance configures endpoints, the source account's commandPrefix wins. Implementation: packages/im/core/src/plugin-runtime/im/message-dispatcher.ts.
Programmatic CommandIndex.dispatch({ input, source, snapshot }) returns status: unmatched | invalid | denied | executed: unmatched has matched: false; invalid carries issues: { field, message }[] and help; denied means permission refused; only executed has a business return value. A Host can pass a real PermissionSubject for authorization.
Run a command from middleware or a button callback
To turn a button callback (or any inbound message) into a command, take the command table from the current context inside a middleware / handler and pass the message itself as source; leave out snapshot, commandPrefix and operation, which default to the message's own:
// middlewares/vote-buttons/index.ts
import { defineMiddleware } from 'zhin.js/middleware';
import { commandFeatureId, type CommandIndex } from '@zhin.js/command';
export default defineMiddleware({
async handle(context, next) {
const payload = context.input.content;
if (!payload.startsWith('vote ')) return next();
const result = await context.project<CommandIndex>(commandFeatureId).dispatch({ input: payload, source: context.input });
if (!result.matched) return next();
if (result.status === 'denied') return result.denial?.reason ?? 'You cannot do that';
if (result.status === 'invalid') return result.help;
return result.value; // the command's reply, refusal text (UserFacingError) included; undefined when it used $reply
},
});- The command runs as the message's real sender:
permitand execution policies are checked as usual, andinput.senderand reply ownership come from the original message; the middleware cannot substitute someone else. - The command table is bound to the generation snapshot of the message's operation. Caching a command table across hot reloads, or passing another
snapshot, is refused (Message author binding belongs to another generation operation/not the command projection of the message's generation): callcontext.project()in the current middleware / handler every time. - Plugins switched off per endpoint / conversation (ADR 0050) do not exist here either:
dispatchfilters out their commands for the message's endpoint and returnsunmatched, exactly as if the user had sent the command text (also when you pass the message's ownsnapshotexplicitly). - Help text and
formatCommand()inside the command use the message's command prefix (for example/), also withoutcommandPrefix. - The
valuedispatchreturns is the reply for the user: the middleware must send it (returnresult.value, as above), or the user gets nothing. When the command refuses with a UserFacingError (refused: true),dispatchrecords the message's outcome asrefused(with the command's refusal code), as for a command sent directly. - Any plugin's command can be dispatched, and so can Root commands (the project's own
commands/and host commands such asbind/claim/config/restart/role): they run as usual with the same operation resources (for example the inference client) as when the user sends them directly, with or without the Agent installed. - The exception is the Agent management commands that need the dispatch lease (
models/health/tree/fork/compact/reset): forwarded by a plugin, the Host withholds the lease and the command does not run;dispatchreturnsstatus: 'executed',refused: true,refusalReason: 'direct_command_required', andvalueasks the user (in their language) to send the command directly, prefix included (for example "Send /reset directly."); the outcome isrefused/direct_command_required. Reply withresult.value, as above. Only a lease this Host instance issued counts: passing your ownoperationthat claims to provide one, or a port you minted by callingcreateHostOperationResources()yourself, does not run the command either.memory/memory forgetneed no lease and run as usual. - A command run this way has no
context.interaction(multi-turn prompts); for flows that ask follow-up questions, let the user send the command text directly. - You do not always need middleware: a JSX
<button onClick>callback carries its ownpermit(see Buttons); QQ officialmode: 'command'buttons have the platform prefillpayloadas the user's message, which goes through the normal command matching and authorization chain (other platforms' adapters do not support this kind of button yet).
Endpoint management commands for adapters
Generate list / add / remove commands for an adapter
createEndpointCommands(spec, defineCommand) generates <adapter> endpoint list / add / remove and shares the owning Adapter and persistence with Console. Declare platform-specific QR or login commands separately rather than hiding them in a generic bindFlow callback.
listreads account configuration and runtime status from the owning Adapter, without another Endpoint Map.add <id> <key=value...>saves disabled configuration only. Start the account manually in Console.remove <id>cancels the target incarnation and closes its connection. History remains; recreating the same name gets a new identity.- Before the first change, an administrator must review existing accounts and confirm migration in Console. Chat commands cannot confirm it.
- Later changes use encrypted persistence without modifying startup files or
.env, or restarting Root. Missing runtime or database support rejects writes without a file fallback. - They need the chat role
owner. Refresh on revision conflict; verify an unknown commit through authoritative state before any further action, without automatically retrying it.
// src/telegram-endpoint-commands.ts
import { createEndpointCommands } from 'zhin.js/adapter';
import { defineCommand } from 'zhin.js/command';
export const telegramEndpointCommands = createEndpointCommands({
adapterKey: 'telegram',
adapterDisplayName: 'Telegram',
fields: [{ key: 'token', required: true, env: true,
description: 'Telegram bot token' }],
}, defineCommand);
// commands/telegram/endpoint/list/index.ts
export default telegramEndpointCommands.list;
// add/[id]/index.ts exports .add; remove/[id]/index.ts exports .removeadapterKey is the registered Adapter name within the current owner. The framework resolves its directory from the real command operation’s owner, generation and AdapterIndex, never from display names. Register the actual AdapterRegistry type once; no RuntimeState token or separate Client token is needed.
fields is a closed list matching the platform schema. Nested fields use explicitly declared dotpaths such as smtp.port; type accepts string | number | boolean, defaulting to string. Arbitrary object merging is not supported. env: true or secret: true marks sensitive fields for masked responses and Host-private persistence; it does not enable .env writes. add reads key=value arguments and splits at the first =.
The real entry uses the common isEndpointOperator owner check (chat role owner). Additional platform permissions must not replace or widen that gate.
Next steps
- Middleware & components: keyword replies, message cards and JSX.
- Convention directories: where other capabilities go.
- Agent tools: let the AI call your features too.