Component: Command
Command components are triggered by user messages that start with a command prefix (set in the Plugins & commands tab of the bot, / by default). Commands belong to the bot: only plugins enabled on the bot (or on the route the message matches) have their commands matched, and enabled built-in system commands take precedence over same-named plugin commands. Here's an example of triggering a command:
Adding Command Components
A single plugin can contain any number of commands. Execute the command lbp comp Command in the plugin directory and follow the prompts to enter the command configuration.
➜ HelloPlugin > lbp comp Command
Generating component Command...
Command name: info
Command description: Show information of the query
Component Command generated successfully.
组件 Command 生成成功。This will generate info.yaml and info.py files in the components/commands/ directory. The .yaml file defines the basic information for the !info command, and the .py file is the command handler:
➜ HelloPlugin > tree
...
├── components
│ ├── __init__.py
│ ├── commands
│ │ ├── __init__.py
│ │ ├── info.py
│ │ └── info.yaml
...Manifest File: Command Component
apiVersion: v1 # Do not modify
kind: Command # Do not modify
metadata:
name: info # Command name, users will trigger this command with !info
label: # Command display name, shown in LangBot UI, supports multilingual
en_US: Info
zh_Hans: Info
description: # Command description, shown in LangBot UI, supports multilingual. Optional.
en_US: 'Show information of the query'
zh_Hans: '发送此次消息的详细信息'
spec:
execution:
python:
path: info.py # Command handler, do not modify
attr: Info # Command handler class name, matches the class name in info.pyHow commands match and apply
- Commands apply only to
message.received. They match by "prefix + registered command name" before route rules; a matched command runs directly instead of going to a Chat, an Agent or a plugin processor. - A command uses the message policy of the route the message would otherwise match (group response rules, access control, rate limit, content filter, long text, @mention, quote). When no route matches, the bot default policy applies.
- Command messages also fire
*MessageReceived; after admission and before execution,*CommandSentfires and plugins can intercept it. See Message Lifecycle Events. - Query-bound APIs such as
context.reply()andget_bot_uuid()work while a command runs. - Commands do not take part in message aggregation.
/stopstill stops an AI reply in progress.
Command Configuration
A command can declare a configuration form in its manifest spec.config, using the same format as a Runner's spec.config:
spec:
config:
- name: style
type: string
label:
en_US: Style
zh_Hans: 风格
default: plainOn the bot's Plugins tab, users click Command settings on a plugin's row and fill in the configuration of each of its commands for that bot. At execution time, read these values from context.config; missing fields use their default. Plugins without saved command settings use the defaults. Command settings only appears for plugins with at least one command that declares spec.config.
Commands without spec.config need no changes: enable the plugin on the bot and they work as before, with context.config as an empty dict. Plugin-level settings are still available through self.get_plugin_config().
Plugin Processing
The following code is generated by default (components/command/<command_name>.py). You need to register and implement subcommand processing logic in the initialize method of the Info class.
# Auto generated by LangBot Plugin SDK.
# Please refer to https://langbot.app/docs/en/plugin/dev/tutor.html for more details.
from __future__ import annotations
from typing import Any, AsyncGenerator
from langbot_plugin.api.definition.components.command.command import Command, Subcommand
from langbot_plugin.api.entities.builtin.command.context import ExecuteContext, CommandReturn
class Info(Command):
async def initialize(self):
await super().initialize()
"Fill with your code here"Adding subcommands:
...
class Info(Command):
async def initialize(self):
await super().initialize()
@self.subcommand(
name="", # Empty string represents root command
help="Show information of the query", # Command help information
usage="info", # Command usage example, displayed in command help
aliases=["i"], # Command aliases
)
async def send(self, context: ExecuteContext) -> AsyncGenerator[CommandReturn, None]:
print(context)
reply_text = f"Query ID: {context.query_id}\n"
reply_text += f"command: {context.command}\n"
reply_text += f"command_text: {context.command_text}\n"
reply_text += f"params: {context.params}\n"
reply_text += f"crt_params: {context.crt_params}\n"
reply_text += f"privilege: {context.privilege}\n"
reply_text += f"session: {context.session.launcher_type.value}_{context.session.launcher_id}\n"
yield CommandReturn(
text=reply_text,
)
@self.subcommand(
name="field",
help="Show information of the field",
usage="info field",
aliases=["f"],
)
async def field(self, context: ExecuteContext) -> AsyncGenerator[CommandReturn, None]:
print(context)
field_name = context.crt_params[0]
field_value = getattr(context, field_name)
yield CommandReturn(
text=f"{field_name}: {field_value}",
)In this code, the send function is registered as a subcommand through the @self.subcommand decorator, prints the command context (ExecuteContext) information, and concatenates it into a reply message.
Subcommand Registration
name is the subcommand name. Leaving it empty means handling the main command. If not empty, it matches the second parameter as the command. For example:
!infomatches the subcommand with name=""!info fieldmatches the subcommand with name="field"!info field valuematches the subcommand with name="field", withvalueas the subcommand parameter- Specialy,
name="*"matches all unmatched first-level subcommands, and passes each section afterinfoas parameters, for example!info 123,!info abc. You can get['123']or['abc']fromcontext.crt_params, depending on the user's input.
In subcommand functions, you can read command parameters through the context variable.
The effect of the above command is shown in the image:
Command Context
class ExecuteContext(pydantic.BaseModel):
"""Single command execution context"""
query_id: int
"""Request ID"""
session: provider_session.Session
"""Session object for this message"""
command_text: str
"""Complete command text"""
command: str
"""Command name"""
crt_command: str
"""Current command
In multi-level commands, crt_command is the current command, command is the root command.
Example: !plugin on Webwlkr
When processing plugin, command is plugin, crt_command is plugin
When processing on, command is plugin, crt_command is on
"""
params: list[str]
"""Command parameters
Parameter list after splitting the entire command by spaces
"""
crt_params: list[str]
"""Current command parameters
In multi-level commands, crt_params are current command parameters, params are root command parameters.
Example: !plugin on Webwlkr
When processing plugin, params is ['on', 'Webwlkr'], crt_params is ['on', 'Webwlkr']
When processing on, params is ['on', 'Webwlkr'], crt_params is ['Webwlkr']
"""
privilege: int
"""Session privilege level"""
config: dict[str, Any]
"""Command settings of this plugin on the current bot, filled from spec.config"""
...Command Return Values
Command return values (CommandReturn) currently support returning text, images (image_url, image links), and errors.
yield CommandReturn(
text=reply_text,
)
yield CommandReturn(
image_url=image_url,
)Command processing supports returning multiple messages, so please use yield statements to return messages.
For specific return values, please refer to the definition of CommandReturn: langbot_plugin.api.entities.builtin.command.context.CommandReturn
One installation, many usages
A single command is triggered concurrently by several conversations:
- Read config per call; never read it in
initialize()and cache it on the instance. - Never leave command arguments, return values or conversation data on instance fields or module-level variables;
ExecuteContextis valid only for the current execution. - Concurrent triggering means instance fields get interleaved writes — do not use them to hold "current conversation" style state. Data that must survive calls belongs in Host storage, keyed with the conversation identity.
- If you keep per-installation process-local caches, release them in
on_installation_revoked(binding).
See Certified plugins and shared runtime for the full specification.
Platform command menus
On the bot's Plugins tab, enable Register on platform and select commands from its enabled plugins. Save the bot before using Sync now. Registration replaces the entire platform list, including manually configured commands. Disabling it clears the previously managed lists. Other adapters do not expose this panel.
The effective list follows the order of the plugin list: the first plugin providing a
command name wins, the same rule used to match commands. Descriptions come from metadata.description in the Workspace language,
with localized variants registered where supported. Invalid names or descriptions
are excluded with a reason shown in the panel. Telegram allows 100 commands, names
matching [a-z0-9_]{1,32}, and descriptions of 1–256 characters. Discord allows 100
global chat-input commands, names of 1–32 characters using its Unicode naming rules,
and descriptions of 1–100 characters. Discord commands have one optional string
argument, args.
Telegram commands use normal incoming messages; include / in the bot prefixes.
Discord interactions are deferred before dispatch and converted to message.received,
with prefix validation bypassed. Replies use interaction followups.
Menus synchronize on bot startup, settings saves, and plugin changes. Unchanged
payloads skip remote writes. GET /api/v1/platform/bots/{uuid} returns
platform_command_sync and filtering diagnostics. The resource.manage endpoint
POST /api/v1/bots/{uuid}/platform-commands/sync and MCP tool
sync_bot_platform_commands synchronize saved settings. This release registers
Telegram's default scope and Discord's global command scope.
Limits: Telegram BotCommand, setMyCommands, Discord application commands, Discord interaction responses.
What's Next
You have learned the basic information about command registration and command execution. Next, you can:
- See the complete
ExecuteContextAPI reference. - Check out Plugin Common APIs.
