Repository navigation
en dev star guides plugin views chat message
Note
AstrBot includes a card renderer in ChatUI.
Plugins can create HTML cards from commands, message handlers, UI callbacks, or local LLM tools. Creation is not limited to tool calls. Declare each card in metadata.yaml, then yield or return event.view_result().
Download the reading-list example plugin and send /reading in ChatUI to use the real card, or ask the model to call open_reading_list. The smaller counter example below explains registration and callbacks.
filter.ui_action currently handles view actions only. Existing buttons continue to use filter.button_action and ButtonInteraction.
Add to metadata.yaml:
views:
- name: counter
target: chat_message
title: Counter
version: 1
actions: ["view_demo:increment"]main.py:
from pydantic import BaseModel, ConfigDict, Field
from astrbot.api.event import AstrMessageEvent, filter
from astrbot.api.star import Star
class IncrementInput(BaseModel):
"""Validated counter input."""
model_config = ConfigDict(extra="forbid", strict=True)
amount: int = Field(ge=1, le=10)
class ViewDemo(Star):
"""Create a card directly from a command."""
@filter.command("counter")
async def counter(self, event: AstrMessageEvent):
"""Create a counter.
Args:
event: Incoming command.
Yields:
A new card.
"""
yield event.view_result(
name="counter", data={"count": 0}, text="Counter created at zero.",
)
@filter.ui_action("view_demo:increment")
async def increment(self, event: AstrMessageEvent):
"""Update the card without invoking the model.
Args:
event: Authenticated UI event.
Yields:
The replacement card data.
"""
interaction = event.get_ui_interaction()
if interaction is None:
return
payload = IncrementInput.model_validate(interaction.data)
yield event.view_result(
data={"count": interaction.view.data["count"] + payload.amount},
)Keep the usual plugin metadata.yaml. The entry must be views/<name>/index.html, with relative scripts, styles, and assets inside that directory.
Providing name creates a new card, including from a UI callback. Omitting name replaces the current interaction's card data and requires a UI event. Creation requires nonempty text as a fallback. A local tool can directly return event.view_result(name=..., data=..., text=...). The model receives text, and display data goes to the card. Import ViewSpec and ViewResult from astrbot.api.interactive_ui when you need the Python types.
AstrBot sends new cards as InteractiveView components. Adapters translate authenticated user actions into UIInteraction components. Both types are available from astrbot.api.message_components. Custom adapters can enable support_ui_interaction in their registration and event metadata after implementing card rendering and action handling for their platform. Platforms without this capability use the text fallback.
To handle a click, look up the card by ID, verify its adapter instance, session, user, and allowed action, then reserve the action in the shared store. Use the saved snapshot for UIInteraction.view and set the event's ui_plugin_module to the card's owning plugin module before dispatch.
Use this index.html with an adjacent app.js:
<!doctype html>
<html lang="en">
<head><meta charset="utf-8" /><title>Counter</title></head>
<body>
<p id="count"></p>
<button id="increment" type="button">Add one</button>
<p id="error" role="alert"></p>
<script type="module" src="./app.js"></script>
</body>
</html>const bridge = window.AstrBotPluginView;
await bridge.ready();
const view = bridge.view;
const button = document.querySelector("#increment");
const error = document.querySelector("#error");
view.subscribe(({ data }) => {
document.querySelector("#count").textContent = String(data.count);
});
bridge.onContext(({ locale }) => {
document.documentElement.lang = locale;
});
button.onclick = async () => {
button.disabled = true;
error.textContent = "";
try {
await view.action("view_demo:increment", { amount: 1 });
} catch (failure) {
error.textContent = failure.message;
} finally {
button.disabled = false;
}
};All targets use the same /api/plugin/page/bridge-sdk.js. Await bridge.ready() for context. bridge.view.subscribe() immediately supplies a snapshot and reports snapshot changes; it returns an unsubscribe function. Use the common bridge.onContext() for theme and locale updates. bridge.view.action() supplies instance, revision, and request identifiers automatically. Its Promise settles after callback execution and state commit, independently of any subsequent model generation. Errors have code and message fields.
The bridge injects --astrbot-color-* CSS tokens and updates data-theme automatically. See Following user-selected colors for the token list. Theme changes do not start generation or change the card revision.
body { color: var(--astrbot-color-text); background: transparent; }
button { color: var(--astrbot-color-primary); border-color: var(--astrbot-color-border); }Bundled Vue or React applications can also be used. Cards run in a sandbox without access to the parent DOM, dashboard credentials, management APIs, or iframe local storage.
event.get_ui_interaction() returns a UIInteraction, or None for ordinary messages and buttons:
| Field | Meaning |
|---|---|
action_id |
Business action name |
interaction_id |
Stable identifier for this submission |
data |
Untrusted input to validate in the plugin |
source |
Currently view
|
source_message_id |
Source message ID, possibly absent before persistence |
view.id, view.name
|
Instance ID and registered name |
view.version |
Data/action contract version |
view.revision |
Persisted data revision |
view.data |
Backend-loaded snapshot, not supplied by the action request |
Actor and conversation information remains on AstrMessageEvent. Treat view.data as read-only; yield event.view_result(data=...) to replace it. Display data is limited to one MiB and action input to 64 KiB. Both must be JSON-compatible.
Handlers can also yield ordinary message results or explicitly request a model response with event.request_llm(prompt=...). A handler chain can update its source card once and request the model once. These results are staged until successful callback completion; already sent messages and external side effects cannot be rolled back. Callbacks have a 120-second execution budget. An ID-less @filter.ui_action() receives only the owning plugin's view actions.
- Main chat, standalone chat, and threads share the card renderer. Reloading restores data without executing the original command, tool, or callback.
- A card instance stays bound to the first message that stores it. Sending it to another conversation uses the text fallback. AstrBot backups include card state and action receipts.
- Increment
versionfor incompatible contracts. Older incompatible cards fall back to text; there is no automatic migration. Successful data replacement incrementsrevision. - The backend checks session ownership, source message, plugin availability, session plugin configuration, and declared actions. Plugins must still enforce business permissions.
- Concurrent actions reserve the instance exclusively. Stale input gets
REVISION_CONFLICTand the latest snapshot. Completed duplicate requests replay their outcome; reusing an ID with different input fails. - Use
interaction_idfor external business idempotency. An unknown outcome is never automatically executed again. The first version does not recover interrupted callbacks, archive old bundles, push background task updates, or route button events. Model generation uses the existing run lifecycle and is not automatically restarted after process failure. - Session deletion removes its view records. Removed or edited-away source messages can no longer authorize a card.
The chat scope covers GET /api/v1/chat/views/{view_id}, POST .../actions, and GET .../actions/{interaction_id}. Frontend plugins should use the SDK rather than manage authentication themselves.
- 首页
- 文档入口
- Top Level
- community events
- config
- deploy
- dev
- others
- platform
- 接入 OneBot v11 协议实现
- 接入钉钉 DingTalk
- 接入 Discord
- 接入 Kook
- 接入飞书
- 接入 LINE
- 接入 Matrix
- 接入 Mattermost
- 接入 Misskey 平台
- 接入 QQ 官方机器人平台
- 通过 QQ官方机器人 接入 QQ (Webhook)
- 通过 QQ官方机器人 接入 QQ (Websockets)
- 接入 Satori 协议
- 接入 server-satori (基于 Koishi)
- 接入 Slack
- 接入消息平台
- 接入 Telegram
- 接入 VoceChat
- AstrBot 接入企业微信
- 接入企业微信智能机器人平台
- AstrBot 接入微信公众平台
- 接入个人微信
- providers
- use
- Home
- Docs Entry
- Top Level
- config
- deploy
- Deploy AstrBot on 1Panel
- Deploy AstrBot on BT Panel
- Deploy AstrBot on CasaOS
- Deploy AstrBot from Source Code
- Community-Provided Deployment Methods
- Deploy via Compshare
- Deploy with AstrBot Desktop Client
- Deploy AstrBot with Docker
- Deploy AstrBot with Kubernetes
- Deploy AstrBot with AstrBot Launcher
- Other Deployments
- Script Deployment
- Installation via System Package Manager
- Preface
- dev
- AstrBot Configuration File
- API Scope–Endpoint Reference
- AstrBot HTTP API
- AstrBot Plugin Market JSON Specification
- AstrBot Plugin Market JSON Specification
- Developing a Platform Adapter
- plugin
- AI
- Agents
- Sessions and Conversations
- Models
- Other APIs
- Tools
- Documentation moved
- Text to Image
- Handling Message Events
- Plugin Configuration
- Plugin Internationalization
- Documentation moved
- Shared Bridge API
- Interactive message component
- Standalone plugin page
- Backend Web APIs
- Workbench page
- Sending Messages
- Session Control
- Minimal Example
- Plugin Storage
- AstrBot Plugin Development Guide 🌠
- Publishing Plugins to the Plugin Marketplace
- ospp
- others
- platform
- Connect OneBot v11 Protocol Implementations
- Connect to DingTalk
- Connecting to Discord
- Connect to KOOK
- Connecting to Lark
- Connecting to LINE
- Connecting to Matrix
- Connecting to Mattermost
- Connecting to Misskey Platform
- Connect QQ Official Bot
- Connect QQ via QQ Official Bot (Webhook)
- Connect QQ via QQ Official Bot (Websockets)
- Connect to Satori Protocol
- Connect server-satori (Koishi)
- Connecting to Slack
- Messaging Platforms
- Connecting to Telegram
- Connect to VoceChat
- Connect AstrBot to WeCom
- Connect to WeCom AI Bot Platform
- Connect AstrBot to WeChat Official Account Platform
- Connect Personal WeChat
- providers
- Connect 302.AI
- Agent Runners
- Built-in Agent Runner
- Connect to Coze
- Connect to Alibaba Cloud Bailian Application
- Connect to DeerFlow
- Connect to Dify
- Connect AIHubMix
- coze
- dashscope
- DeepSeek STT Integration
- DeepSeek TTS Integration
- dify
- Model input images
- Large Language Model Providers
- Connect MiraRouter
- NewAPI
- Connect PPIO Cloud
- Connect LM Studio to Use DeepSeek-R1 and Other Models
- Integrating Ollama
- Connect ShengSuanYun
- Connecting to SiliconFlow
- Connecting Model Services
- Connecting to TokenPony
- use
- Agent Execution Mode {#agent-runner}
- Agent Sandbox Environment
- astrbot sandbox
- AstrBot CLI {#cli-commands}
- Docker-based Code Interpreter
- Built-in Commands
- computer
- Context Compression
- Session Configuration Mappings (formerly Custom Rules)
- AstrBot Knowledge Base
- MCP
- AstrBot Plugins {#astrbot-star}
- Proactive Capabilities
- Skills {#anthropic-skills}
- Subagents {#agent-handsoff-and-subagent}
- Unified Webhook Mode
- Web Search
- DeepSeek Search API
- SerpApi
- WebUI