From 2cb947c0f2dde7f920145aa9ab45f5bd9896dfa5 Mon Sep 17 00:00:00 2001 From: xunxiing <110362831+xunxiing@users.noreply.github.com> Date: Wed, 13 May 2026 17:05:52 +0000 Subject: [PATCH] docs: automated sync from main repo --- docs/snapshots/index.md | 5 + docs/snapshots/v4.24.4/.gitignore | 6 + docs/snapshots/v4.24.4/SKILL.md | 138 ++++ .../v4.24.4/Storage & Utils/file_storage.md | 29 + .../v4.24.4/Storage & Utils/kv_storage.md | 21 + .../v4.24.4/Storage & Utils/plugin-i18n.md | 146 ++++ .../v4.24.4/Storage & Utils/text_to_image.md | 109 +++ docs/snapshots/v4.24.4/agent/Invoke-llm.md | 86 +++ .../v4.24.4/agent/agent-related-hooks.md | 88 +++ docs/snapshots/v4.24.4/agent/agent-runner.md | 17 + .../v4.24.4/agent/context-compression.md | 50 ++ docs/snapshots/v4.24.4/agent/conversation.md | 113 +++ docs/snapshots/v4.24.4/agent/cron.md | 57 ++ docs/snapshots/v4.24.4/agent/index.md | 56 ++ .../v4.24.4/agent/offical-tool-list/tools.md | 43 ++ .../v4.24.4/agent/persona-control.md | 106 +++ docs/snapshots/v4.24.4/agent/registe tools.md | 111 +++ docs/snapshots/v4.24.4/agent/sandbox.md | 48 ++ docs/snapshots/v4.24.4/agent/subagents.md | 70 ++ .../design_standards/architecture_overview.md | 21 + .../design_standards/best_practices.md | 43 ++ .../v4.24.4/design_standards/context_usage.md | 30 + .../v4.24.4/design_standards/core_concepts.md | 128 ++++ .../v4.24.4/design_standards/event_flow.md | 20 + .../v4.24.4/design_standards/sandbox.md | 20 + .../v4.24.4/design_standards/visual_utils.md | 89 +++ docs/snapshots/v4.24.4/index.md | 11 + docs/snapshots/v4.24.4/messages/components.md | 41 ++ docs/snapshots/v4.24.4/messages/events.md | 33 + docs/snapshots/v4.24.4/messages/model.md | 31 + docs/snapshots/v4.24.4/messages/umo.md | 22 + .../platform_adapters/adapter_interface.md | 374 ++++++++++ .../platform_adapters/message_conversion.md | 29 + .../platform_adapters/telegram_media_group.md | 40 ++ .../v4.24.4/plugin-development-workflow.md | 133 ++++ .../v4.24.4/plugin_config/command.md | 112 +++ .../snapshots/v4.24.4/plugin_config/schema.md | 154 ++++ .../v4.24.4/plugin_config/session_control.md | 106 +++ .../.github/workflows/release.yml | 107 +++ .../script/astrbot-plugin-demo/.gitignore | 207 ++++++ .../script/astrbot-plugin-demo/CHANGELOG.md | 16 + .../script/astrbot-plugin-demo/LICENSE | 661 ++++++++++++++++++ .../script/astrbot-plugin-demo/README.md | 14 + .../astrbot-plugin-demo/_conf_schema.json | 20 + .../script/astrbot-plugin-demo/main.py | 23 + .../script/astrbot-plugin-demo/metadata.yaml | 7 + docs/snapshots/v4.24.4/webui/plugin-pages.md | 131 ++++ scripts/state.json | 4 +- 48 files changed, 3924 insertions(+), 2 deletions(-) create mode 100644 docs/snapshots/index.md create mode 100644 docs/snapshots/v4.24.4/.gitignore create mode 100644 docs/snapshots/v4.24.4/SKILL.md create mode 100644 docs/snapshots/v4.24.4/Storage & Utils/file_storage.md create mode 100644 docs/snapshots/v4.24.4/Storage & Utils/kv_storage.md create mode 100644 docs/snapshots/v4.24.4/Storage & Utils/plugin-i18n.md create mode 100644 docs/snapshots/v4.24.4/Storage & Utils/text_to_image.md create mode 100644 docs/snapshots/v4.24.4/agent/Invoke-llm.md create mode 100644 docs/snapshots/v4.24.4/agent/agent-related-hooks.md create mode 100644 docs/snapshots/v4.24.4/agent/agent-runner.md create mode 100644 docs/snapshots/v4.24.4/agent/context-compression.md create mode 100644 docs/snapshots/v4.24.4/agent/conversation.md create mode 100644 docs/snapshots/v4.24.4/agent/cron.md create mode 100644 docs/snapshots/v4.24.4/agent/index.md create mode 100644 docs/snapshots/v4.24.4/agent/offical-tool-list/tools.md create mode 100644 docs/snapshots/v4.24.4/agent/persona-control.md create mode 100644 docs/snapshots/v4.24.4/agent/registe tools.md create mode 100644 docs/snapshots/v4.24.4/agent/sandbox.md create mode 100644 docs/snapshots/v4.24.4/agent/subagents.md create mode 100644 docs/snapshots/v4.24.4/design_standards/architecture_overview.md create mode 100644 docs/snapshots/v4.24.4/design_standards/best_practices.md create mode 100644 docs/snapshots/v4.24.4/design_standards/context_usage.md create mode 100644 docs/snapshots/v4.24.4/design_standards/core_concepts.md create mode 100644 docs/snapshots/v4.24.4/design_standards/event_flow.md create mode 100644 docs/snapshots/v4.24.4/design_standards/sandbox.md create mode 100644 docs/snapshots/v4.24.4/design_standards/visual_utils.md create mode 100644 docs/snapshots/v4.24.4/index.md create mode 100644 docs/snapshots/v4.24.4/messages/components.md create mode 100644 docs/snapshots/v4.24.4/messages/events.md create mode 100644 docs/snapshots/v4.24.4/messages/model.md create mode 100644 docs/snapshots/v4.24.4/messages/umo.md create mode 100644 docs/snapshots/v4.24.4/platform_adapters/adapter_interface.md create mode 100644 docs/snapshots/v4.24.4/platform_adapters/message_conversion.md create mode 100644 docs/snapshots/v4.24.4/platform_adapters/telegram_media_group.md create mode 100644 docs/snapshots/v4.24.4/plugin-development-workflow.md create mode 100644 docs/snapshots/v4.24.4/plugin_config/command.md create mode 100644 docs/snapshots/v4.24.4/plugin_config/schema.md create mode 100644 docs/snapshots/v4.24.4/plugin_config/session_control.md create mode 100644 docs/snapshots/v4.24.4/script/astrbot-plugin-demo/.github/workflows/release.yml create mode 100644 docs/snapshots/v4.24.4/script/astrbot-plugin-demo/.gitignore create mode 100644 docs/snapshots/v4.24.4/script/astrbot-plugin-demo/CHANGELOG.md create mode 100644 docs/snapshots/v4.24.4/script/astrbot-plugin-demo/LICENSE create mode 100644 docs/snapshots/v4.24.4/script/astrbot-plugin-demo/README.md create mode 100644 docs/snapshots/v4.24.4/script/astrbot-plugin-demo/_conf_schema.json create mode 100644 docs/snapshots/v4.24.4/script/astrbot-plugin-demo/main.py create mode 100644 docs/snapshots/v4.24.4/script/astrbot-plugin-demo/metadata.yaml create mode 100644 docs/snapshots/v4.24.4/webui/plugin-pages.md diff --git a/docs/snapshots/index.md b/docs/snapshots/index.md new file mode 100644 index 0000000..67ce680 --- /dev/null +++ b/docs/snapshots/index.md @@ -0,0 +1,5 @@ +# 文档快照 + +这里存放按 AstrBot Tag 归档的文档快照。 + +- [v4.24.4](/snapshots/v4.24.4/) diff --git a/docs/snapshots/v4.24.4/.gitignore b/docs/snapshots/v4.24.4/.gitignore new file mode 100644 index 0000000..3562259 --- /dev/null +++ b/docs/snapshots/v4.24.4/.gitignore @@ -0,0 +1,6 @@ +__pycache__/ +venv/ +.DS_Store +node_modules/ +.vitepress/cache +*dist diff --git a/docs/snapshots/v4.24.4/SKILL.md b/docs/snapshots/v4.24.4/SKILL.md new file mode 100644 index 0000000..a5b271c --- /dev/null +++ b/docs/snapshots/v4.24.4/SKILL.md @@ -0,0 +1,138 @@ +--- +name: skill-astrbot-dev +description: Reference + workflow notes for AstrBot plugin development (messages, platform adapters, plugin config, agent system). +metadata: + short-description: AstrBot dev reference +--- + +# skill-astrbot-dev + +This skill is the source-of-truth index for AstrBot developer docs in this repo (`docs/`). + +Goal: when this skill is selected, immediately ground on the minimum required docs + code entrypoints, +avoid duplicated reading, and always prefer code as the final authority. + +## When to use + +Use this skill when you ask for help with: + +- AstrBot plugin structure, decorators/hooks, lifecycle, schema, sessions +- Message model/event flow and message-chain conversion +- Platform adapter interface and message conversion patterns +- Agent topics (tools/providers/personas/subagents/sandbox/cron/context compression) + +## Mandatory workflow (use this every time) + +1. Start from a single entrypoint (avoid broad loading): + - Site index: `docs/index.md` + - Core concepts: `docs/design_standards/core_concepts.md` +2. Pick one topic folder and stay focused: + - Agent system: `docs/agent/` + - Plugin config: `docs/plugin_config/` + - Messages: `docs/messages/` + - Platform adapters: `docs/platform_adapters/` +3. For Agent Runner (v4.7.0+): `docs/agent/agent-runner.md` +4. If the user targets a specific AstrBot version, cross-check: + - `docs/snapshots//` +5. If docs and code disagree, treat code as truth: + - Core code lives under `astrbotcore/astrbot/core/` (read only the needed files) + +## STRONGLY ADVISED: use AstrBot SDK while writing plugins + +When writing plugin code, strongly advised to install AstrBot SDK locally and use it for API reference, +signature lookup, and IDE auto-completion. + +```powershell +python -m pip install -U astrbot +``` + +Use SDK symbols first when implementing hooks, provider/context calls, and agent runner integration. +This helps reduce guesswork and signature mismatch. + +If AstrBot source code in this repo is available, still treat repo code as higher priority than package docs. + +## Plugin project structure (strongly advised) + +A standard AstrBot plugin project should include: + +- `main.py`: entrypoint. Implement plugin startup and primary features here. +- `metadata.yaml`: plugin metadata (name, version, author, repo, description). +- `README.md`: installation, usage, feature overview, and dev links. +- `.gitignore`: ignore Python cache (`__pycache__`) and IDE config files. +- `LICENSE`: open-source license file. + +## `metadata.yaml` minimal template + +```yaml +name: astrbot_plugin_helloworld # 插件唯一识别名,最好以 astrbot_plugin_ 前缀开头 +display_name: helloworld # 展示名(v4.5.0+) +desc: AstrBot 插件示例。 # 插件简短描述 +version: v1.3.0 # 版本号:v1.1.1 或 v1.1 +author: Soulter # 作者 +repo: https://github.com/Soulter/helloworld # 插件的仓库地址 +astrbot_version: ">=4.16,<5" #声明插件要求的 AstrBot 版本范围。 +``` + +## Code rules for plugin implementation + +- Use `async def` for handlers/hooks/tool functions. +- Keep `main.py` focused on plugin entry and orchestration; extract complex logic into submodules. +- Add type hints for public methods and hook signatures. +- Do not hardcode provider IDs or secrets; expose configurable fields in `_conf_schema.json`. +- Prefer small, testable functions over large monolithic handler bodies. +- Keep README and metadata consistent with actual plugin behavior and version. + -If you are writing AstrBot core code instead of plugins, you must submit a PR to https://github.com/AstrBotDevs/AstrBot-docs if the changes require doc updates (for instance: new hooks, new APIs, new features, platform adapter changes, and so on). If you don't see the docs repo, please remind the user to clone the docs-repo and add it to the workspace. +Ensure that a `requirements.txt` file is created in the plugin directory and populated with the necessary dependencies. +plugin i18n is recommanded ,but is still in experiment state use it carefully +It's best to keep the plugin size under 32MB. +For large resources like high-resolution images, it is best to use a CDN instead of hardcoring. +### + +## Hooks: avoid missing / outdated references + +There are two different "hook" layers you must not mix up: + +- Plugin event hooks (decorators): `docs/plugin_config/hooks.md` +- Agent runner hooks (`BaseAgentRunHooks`): `docs/agent/agent-related-hooks.md` + +If you need a complete hook inventory (because context may be truncated), generate it locally: + +```powershell +python scripts/generate_hook_inventory.py +``` + +This writes to `docs/.tmp/hook_inventory/` (gitignored). Use it as a scratchpad for writing/updating docs; +do not reference `.tmp` paths as public documentation URLs. + +## High-signal code entrypoints (open only when needed) + +- Event hooks registration + signatures: `astrbotcore/astrbot/core/star/register/star_handler.py` +- Event types: `astrbotcore/astrbot/core/star/star_handler.py` +- Agent runners + hook call order: `astrbotcore/astrbot/core/agent/runners/` +- Agent hook interface: `astrbotcore/astrbot/core/agent/hooks.py` +- Main agent build (sandbox/cron/tools): `astrbotcore/astrbot/core/astr_main_agent.py` +- Skills system (AstrBot runtime skills): `astrbotcore/astrbot/core/skills/skill_manager.py` +- Subagents config loading: `astrbotcore/astrbot/core/subagent_orchestrator.py` + +## v4.5.7+ New Tool Definition Pattern + +推荐使用 dataclass 模式定义 Tool(见 `docs/design_standards/core_concepts.md` 第7节): + +```python +from pydantic.dataclasses import dataclass +from astrbot.core.agent.tool import FunctionTool + +@dataclass +class MyTool(FunctionTool): + name: str = "my_tool" + description: str = "工具描述" + parameters: dict = {...} + + async def call(self, context, **kwargs) -> str: + return "结果" +``` + +注册:`self.context.add_llm_tools(MyTool())` + +装饰器方式仍然支持,但推荐新项目使用 dataclass 模式。 + diff --git a/docs/snapshots/v4.24.4/Storage & Utils/file_storage.md b/docs/snapshots/v4.24.4/Storage & Utils/file_storage.md new file mode 100644 index 0000000..a248d0d --- /dev/null +++ b/docs/snapshots/v4.24.4/Storage & Utils/file_storage.md @@ -0,0 +1,29 @@ +--- +category: storage +--- + +# 文件存储规范 + +对于大文件、日志或插件特有的资源文件,AstrBot 建议遵循以下存储规范。 + +### 目录规范 + +所有插件特有的文件应存储在以下目录: +`data/plugin_data/{plugin_name}/` + +### 获取存储路径 + +建议在插件中使用以下方式获取路径,以确保兼容性: + +```python +from astrbot.core.utils.astrbot_path import get_astrbot_data_path + +# 获取插件专属数据目录 +plugin_data_path = get_astrbot_data_path() / "plugin_data" / self.name +plugin_data_path.mkdir(parents=True, exist_ok=True) # 确保目录存在 +``` + +### 注意事项 + +- 不要将大文件直接存储在 `docs/` 或插件根目录下。 +- 建议定期清理不再使用的临时文件。 diff --git a/docs/snapshots/v4.24.4/Storage & Utils/kv_storage.md b/docs/snapshots/v4.24.4/Storage & Utils/kv_storage.md new file mode 100644 index 0000000..62e98f3 --- /dev/null +++ b/docs/snapshots/v4.24.4/Storage & Utils/kv_storage.md @@ -0,0 +1,21 @@ +--- +category: storage +--- + +# 键值对存储 (KV Storage) + +AstrBot 为插件提供了简单易用的 KV 存储接口,适合存储配置、轻量级状态或用户数据。 + +### 核心接口 (>= v4.9.2) + +这些方法在插件类(继承自 `Star`)中可以直接调用: + +- `await self.put_kv_data(key: str, value: Any)`: 存储数据。 +- `await self.get_kv_data(key: str, default: Any = None) -> Any`: 获取数据。 +- `await self.delete_kv_data(key: str)`: 删除数据。 + +### 特点 + +- **隔离性**: 数据按插件 ID 隔离,不同插件之间的 Key 不会冲突。 +- **持久化**: 数据会自动持久化到 `data/metadata/kv_storage.db`(或相应目录)。 +- **异步**: 接口均为异步方法。 diff --git a/docs/snapshots/v4.24.4/Storage & Utils/plugin-i18n.md b/docs/snapshots/v4.24.4/Storage & Utils/plugin-i18n.md new file mode 100644 index 0000000..fb12abe --- /dev/null +++ b/docs/snapshots/v4.24.4/Storage & Utils/plugin-i18n.md @@ -0,0 +1,146 @@ +# 插件国际化 + +插件可以在自己的目录下提供 `.astrbot-plugin/i18n/*.json`,让 WebUI 根据当前语言显示插件名称、描述和配置项文案。 + +## 目录结构 + +```text +your_plugin/ + metadata.yaml + _conf_schema.json + .astrbot-plugin/ + i18n/ + zh-CN.json + en-US.json +``` + +语言文件名使用 WebUI 的 locale,例如 `zh-CN.json`、`en-US.json`。文件内容必须是 JSON object。 + +当当前语言没有对应翻译、某个字段缺失,或语言文件不存在时,AstrBot 会回退到默认文案: + +- 插件名称、卡片短描述和描述回退到 `metadata.yaml` 中的 `display_name`、`short_desc`、`desc`。 +- 配置项文案回退到 `_conf_schema.json` 中的 `description`、`hint`、`labels`。 + +## 元数据 + +`metadata` 用于覆盖插件在插件页展示的名称、卡片短描述和描述。 + +```json +{ + "metadata": { + "display_name": "天气助手", + "short_desc": "一句话天气查询。", + "desc": "查询天气并提供出行建议。" + } +} +``` + +## 配置项 + +`config` 用于覆盖 `_conf_schema.json` 中的配置文案。结构按配置项名称嵌套。 + +例如 `_conf_schema.json`: + +```json +{ + "enable": { + "description": "Enable", + "type": "bool", + "hint": "Whether to enable this plugin.", + "default": true + }, + "mode": { + "description": "Mode", + "type": "string", + "options": ["fast", "safe"], + "labels": ["Fast", "Safe"] + } +} +``` + +对应 `.astrbot-plugin/i18n/zh-CN.json`: + +```json +{ + "config": { + "enable": { + "description": "启用", + "hint": "是否启用这个插件。" + }, + "mode": { + "description": "模式", + "labels": ["快速", "安全"] + } + } +} +``` + +`options` 是配置保存值,不建议翻译。下拉框的展示文本请使用 `labels`。 + +## 嵌套配置 + +如果 `_conf_schema.json` 中有 `object` 类型配置,翻译也按同样的字段结构继续嵌套。 + +```json +{ + "config": { + "sub_config": { + "name": { + "description": "名称", + "hint": "显示在消息中的名称。" + } + } + } +} +``` + +## 模板列表 + +`template_list` 的模板名称和模板内字段也可以翻译。模板名称放在 `templates.<模板名>.name`,模板内字段继续往下嵌套。 + +```json +{ + "config": { + "rules": { + "description": "规则", + "templates": { + "default": { + "name": "默认模板", + "threshold": { + "description": "阈值", + "hint": "达到该值后触发规则。" + } + } + } + } + } +} +``` + +## 完整示例 + +下面是一个真实配置项的英文翻译示例: + +```json +{ + "metadata": { + "display_name": "HAPI Vibe Coding Remote", + "desc": "Connect to a HAPI service and control coding agent sessions from chat platforms." + }, + "config": { + "hapi_endpoint": { + "description": "HAPI service URL", + "hint": "Example: http://localhost:3006" + }, + "output_level": { + "description": "SSE delivery level", + "hint": "silence: permission requests only; simple: plain text messages and system events; summary: recent N messages when a task completes; detail: all messages in real time", + "labels": ["Silence", "Simple", "Summary", "Detail"] + } + } +} +``` + +## 约束 + +插件国际化只读取 `.astrbot-plugin/i18n` 目录。语言文件必须使用嵌套 JSON 结构,不支持点号扁平 key。 diff --git a/docs/snapshots/v4.24.4/Storage & Utils/text_to_image.md b/docs/snapshots/v4.24.4/Storage & Utils/text_to_image.md new file mode 100644 index 0000000..a3203a9 --- /dev/null +++ b/docs/snapshots/v4.24.4/Storage & Utils/text_to_image.md @@ -0,0 +1,109 @@ +# 文转图 (Text to Image) + +将文本或 HTML 模板渲染为图片。 + +## 插件方法(Star) + +### `text_to_image` + +```python +async def text_to_image(self, text: str, return_url: bool = True) -> str +``` + +- 内部调用:`html_renderer.render_t2i(...)` +- 使用当前激活模板:`t2i_active_template` +- `return_url=True` 返回可发送的 URL;`False` 返回本地文件路径 +- **网络渲染失败会自动 fallback 到本地渲染** + +```python +url = await self.text_to_image("你好,AstrBot") +yield event.image_result(url) +``` + +### `html_render` + +```python +async def html_render(self, tmpl: str, data: dict, return_url: bool = True, options: dict | None = None) -> str +``` + +- 内部调用:`html_renderer.render_custom_template(...)` +- 适合自定义 HTML + Jinja2 模板渲染 + +```python +tmpl = """ +
+

{{ title }}

+ +
+""" +url = await self.html_render(tmpl, {"title": "Todo", "items": ["吃饭", "睡觉"]}) +yield event.image_result(url) +``` + +## SDK 方法(`html_renderer`) + +```python +from astrbot.api import html_renderer +``` + +### 初始化 + +```python +await html_renderer.initialize() +``` + +### 默认文转图 + +```python +await html_renderer.render_t2i( + text: str, + use_network: bool = True, + return_url: bool = False, + template_name: str | None = None, +) +``` + +- `use_network=True` 先走网络渲染;失败时 fallback 到本地渲染 +- `return_url=False` 时返回本地路径 + +### 自定义模板渲染 + +```python +await html_renderer.render_custom_template( + tmpl_str: str, + tmpl_data: dict, + return_url: bool = False, + options: dict | None = None, +) +``` + +## 渲染选项(`html_render` / `render_custom_template`) + +`options` 透传给截图参数(Playwright 风格): + +- `timeout` +- `type`: `"jpeg" | "png"` +- `quality`(仅 jpeg) +- `omit_background`(仅 png) +- `full_page` +- `clip` +- `animations`: `"allow" | "disabled"` +- `caret`: `"hide" | "initial"` +- `scale`: `"css" | "device"` + +默认值(未传 `options` 时): + +```python +{"full_page": True, "type": "jpeg", "quality": 40} +``` + +## 模板管理方法 + +`TemplateManager` 提供模板 CRUD: + +- `list_templates()` +- `get_template(name)` +- `create_template(name, content)` +- `update_template(name, content)` +- `delete_template(name)` +- `reset_default_template()` diff --git a/docs/snapshots/v4.24.4/agent/Invoke-llm.md b/docs/snapshots/v4.24.4/agent/Invoke-llm.md new file mode 100644 index 0000000..6229426 --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/Invoke-llm.md @@ -0,0 +1,86 @@ +Provider 是模型能力入口(Chat/STT/TTS/Embedding) + +### 获取当前会话使用的 Chat Provider ID + +```python +prov_id = await ctx.get_current_chat_provider_id(umo) +``` +- `await get_current_chat_provider_id(umo: str) -> str`:返回当前会话的 chat provider ID + +### 简化 LLM 调用 + +```python +llm_resp = await ctx.llm_generate( + chat_provider_id=prov_id, + prompt="Hello!", + system_prompt="You are a helpful assistant.", +) +print(llm_resp.completion_text) +``` +- `await llm_generate(chat_provider_id, prompt, contexts=None, image_urls=None, system_prompt=None, tools=None) -> LLMResponse`: 简化的 LLM 调用接口,不自动执行 tool call + +### 工具循环 Agent + +```python +llm_resp = await ctx.tool_loop_agent( + event=event, + chat_provider_id=prov_id, + prompt="搜索 AstrBot 相关信息", + tools=ToolSet([SearchTool()]), + max_steps=30, + tool_call_timeout=60, +) +``` +- `await tool_loop_agent(event, chat_provider_id, prompt, contexts=None, image_urls=None, tools=None, system_prompt=None, max_steps=30, tool_call_timeout=120, **kwargs) -> LLMResponse` + - `event`: AstrMessageEvent,会话上下文来源 + - `chat_provider_id`: chat provider ID + - `prompt`: 用户 prompt + - `contexts`: 消息历史上下文(可选,追加到 prompt 后) + - `image_urls`: 图片 URL 列表(追加到 prompt) + - `tools`: ToolSet,AI 可调用的工具集 + - `system_prompt`: 系统提示(插到上下文最前面) + - `max_steps`: 最大 tool call 轮次,默认 30 + - `tool_call_timeout`: 单次工具调用超时(秒),默认 120 + - **`**kwargs`**: 扩展参数: + - `stream: bool` — 是否流式输出 + - `agent_hooks: BaseAgentRunHooks` — Agent 运行期钩子 + - `agent_context: AstrAgentContext` — 复用已有 agent 上下文 + - 其他 kwargs — 直接透传给 `runner.reset()` + +## 传统方法 + +### 当前会话正在使用的 Provider + +- `get_using_provider(umo: str | None = None) -> Provider | None`: 拿 chat provider 实例 +- `get_using_stt_provider(umo: str | None = None) -> STTProvider | None` +- `get_using_tts_provider(umo: str | None = None) -> TTSProvider | None` + +### 按 ID 读取 Provider + +- `get_provider_by_id(provider_id: str)`: 按 ID 获取 provider(可能是 chat/stt/tts/embedding/rerank) + +```python +prov = ctx.get_provider_by_id("your_provider_id") +``` +### 列表查询(用于配置页或校验) + +- `get_all_providers() -> list[Provider]` +- `get_all_stt_providers() -> list[STTProvider]` +- `get_all_tts_providers() -> list[TTSProvider]` +- `get_all_embedding_providers() -> list[EmbeddingProvider]` + +## Agent Runner 相关 + +```python +# 获取当前会话使用的 Agent Runner +runner = ctx.get_using_agent_runner(umo=event.unified_msg_origin) + +# 或者通过 ID 获取 +runner = ctx.get_agent_runner_by_id(runner_id="your_runner_id") +``` +```## + +- 会话内调用必须优先传 `umo`,否则会回退到默认配置,可能拿到错误 provider +- `get_provider_by_id` 返回的不一定是 chat provider,传给 `tool_loop_agent` 前要确保是 chat provider id +- 不要把 provider id 硬编码在代码里,优先从 `_conf_schema.json` 配置读取 +``` diff --git a/docs/snapshots/v4.24.4/agent/agent-related-hooks.md b/docs/snapshots/v4.24.4/agent/agent-related-hooks.md new file mode 100644 index 0000000..6db27f7 --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/agent-related-hooks.md @@ -0,0 +1,88 @@ +--- +category: agent +--- +# Agent Related Hooks + + Agent 请求/工具循环直接相关的 hooks。 + +## Plugin Hooks + +### LLM 请求阶段 + +- `@filter.on_waiting_llm_request()` +- `@filter.on_llm_request()` +- `@filter.on_llm_response()` + +```python +from astrbot.api.event import filter, AstrMessageEvent +from astrbot.api.provider import ProviderRequest, LLMResponse + +@filter.on_waiting_llm_request() +async def on_waiting(self, event: AstrMessageEvent) -> None: ... + +@filter.on_llm_request() +async def on_req(self, event: AstrMessageEvent, request: ProviderRequest) -> None: ... + +@filter.on_llm_response() +async def on_resp(self, event: AstrMessageEvent, response: LLMResponse) -> None: ... +``` + +### Tool 调用阶段 + +- `@filter.on_using_llm_tool()` +- `@filter.on_llm_tool_respond()` + +```python +from astrbot.api.event import filter, AstrMessageEvent +from astrbot.core.agent.tool import FunctionTool +from mcp.types import CallToolResult + +@filter.on_using_llm_tool() +async def on_tool_start(self, event: AstrMessageEvent, tool: FunctionTool, tool_args: dict | None) -> None: ... + +@filter.on_llm_tool_respond() +async def on_tool_end(self, event: AstrMessageEvent, tool: FunctionTool, tool_args: dict | None, tool_result: CallToolResult | None) -> None: ... +``` + +### 结果发送阶段 + +- `@filter.on_decorating_result()` +- `@filter.after_message_sent()` + +```python +from astrbot.api.event import filter, AstrMessageEvent + +@filter.on_decorating_result() +async def on_decorating(self, event: AstrMessageEvent) -> None: ... + +@filter.after_message_sent() +async def after_sent(self, event: AstrMessageEvent) -> None: ... +``` + +## Agent Runner Hooks + +用于 `context.tool_loop_agent(..., agent_hooks=...)` 的运行期扩展。 + +```python +from astrbot.core.agent.hooks import BaseAgentRunHooks +from astrbot.core.agent.run_context import ContextWrapper +from astrbot.core.agent.tool import FunctionTool +from astrbot.core.provider.entities import LLMResponse +import mcp + +class MyAgentHooks(BaseAgentRunHooks): + async def on_agent_begin(self, run_context: ContextWrapper) -> None: ... + async def on_tool_start(self, run_context: ContextWrapper, tool: FunctionTool, tool_args: dict | None) -> None: ... + async def on_tool_end(self, run_context: ContextWrapper, tool: FunctionTool, tool_args: dict | None, tool_result: mcp.types.CallToolResult | None) -> None: ... + async def on_agent_done(self, run_context: ContextWrapper, llm_response: LLMResponse) -> None: ... +``` + +## 主 Agent 默认映射关系 + +- `on_tool_start` -> `@filter.on_using_llm_tool()` +- `on_tool_end` -> `@filter.on_llm_tool_respond()` +- `on_agent_done` -> `@filter.on_llm_response()` + +## MUST + +- Hook 处理函数必须使用 `async def`。 diff --git a/docs/snapshots/v4.24.4/agent/agent-runner.md b/docs/snapshots/v4.24.4/agent/agent-runner.md new file mode 100644 index 0000000..803b389 --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/agent-runner.md @@ -0,0 +1,17 @@ +Agent Runner 是 AstrBot 中用于执行 Agent 的组件。 + +## 插件侧使用 + +```python +# 获取当前会话使用的 Agent Runner +runner = self.context.get_using_agent_runner(umo=event.unified_msg_origin) + +# 或者通过 provider_id 获取 +runner = self.context.get_agent_runner_by_id(runner_id="your_runner_id") +``` + +## 注意事项 + +- Agent Runner 会调用 Chat Provider 接口 +- 切换 Agent Runner 后,部分 AstrBot 功能(MCP、知识库、网页搜索)可能不可用(取决于 Runner 实现) +- AstrBot 内置 Agent Runner 支持全部功能 diff --git a/docs/snapshots/v4.24.4/agent/context-compression.md b/docs/snapshots/v4.24.4/agent/context-compression.md new file mode 100644 index 0000000..086ff43 --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/context-compression.md @@ -0,0 +1,50 @@ + +# 上下文控制与压缩 + + +## 1 `context.tool_loop_agent(...)` + +用于运行 Agent 工具循环,同时传入上下文压缩参数。 + +```python +await self.context.tool_loop_agent(event=event, chat_provider_id=prov_id, prompt="...", enforce_max_turns=20, truncate_turns=2, llm_compress_keep_recent=6) +``` + +可用压缩参数(都可选): + +- `enforce_max_turns: int`:最多保留多少轮对话(`-1` 不限制)。 +- `truncate_turns: int`:触发截断时一次丢弃多少轮。 +- `llm_compress_instruction: str | None`:LLM 压缩时的摘要指令。 +- `llm_compress_keep_recent: int`:LLM 压缩时保留最近多少条消息不摘要。 +- `llm_compress_provider: Provider | None`:用于压缩摘要的模型 provider。 +- `custom_token_counter: TokenCounter | None`:自定义 token 计数器。 +- `custom_compressor: ContextCompressor | None`:自定义压缩器。 + +## 2`context.get_provider_by_id(provider_id)` + +用于拿到压缩模型实例,再传给 `llm_compress_provider`。 + +```python +compress_prov = self.context.get_provider_by_id("openai/gpt-4o-mini") +``` + +## 3 `context.get_current_chat_provider_id(umo)` + +用于获取当前会话正在使用的对话 provider id,常用于给 `tool_loop_agent` 传 `chat_provider_id`。 + +```python +chat_provider_id = await self.context.get_current_chat_provider_id(event.unified_msg_origin) +``` + +## 4 `context.get_config(umo)` +用于读取当前会话配置,按需决定压缩参数。 +```python +cfg = self.context.get_config(event.unified_msg_origin) +``` +## 示例 +```python +umo = event.unified_msg_origin +chat_prov = await self.context.get_current_chat_provider_id(umo) +compress_prov = self.context.get_provider_by_id("your_compress_provider_id") +resp = await self.context.tool_loop_agent(event=event, chat_provider_id=chat_prov, prompt="总结最近讨论并给出下一步", enforce_max_turns=24, truncate_turns=2, llm_compress_instruction="保留任务结论、待办、关键约束", llm_compress_keep_recent=8, llm_compress_provider=compress_prov) +``` \ No newline at end of file diff --git a/docs/snapshots/v4.24.4/agent/conversation.md b/docs/snapshots/v4.24.4/agent/conversation.md new file mode 100644 index 0000000..902ab9a --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/conversation.md @@ -0,0 +1,113 @@ +--- +category: agent +--- + +# 会话与对话分支(Conversation) + +插件侧通过 `self.context.conversation_manager` 管理会话分支;会话标识使用 `event.unified_msg_origin`(`umo`)。 + +## 插件可用入口 + +```python +conv_mgr = self.context.conversation_manager +umo = event.unified_msg_origin +``` + +## ConversationManager 可用方法 + +- `register_on_session_deleted(callback: Callable[[str], Awaitable[None]]) -> None`:注册会话删除后的级联清理回调。 +- `new_conversation(unified_msg_origin: str, platform_id: str | None = None, content: list[dict] | None = None, title: str | None = None, persona_id: str | None = None) -> str`:新建分支并切换为当前分支。 +- `switch_conversation(unified_msg_origin: str, conversation_id: str) -> None`:切换当前分支。 +- `delete_conversation(unified_msg_origin: str, conversation_id: str | None = None) -> None`:删除指定分支;不传 `conversation_id` 时删除当前分支。 +- `delete_conversations_by_user_id(unified_msg_origin: str) -> None`:删除该会话下全部分支。 +- `get_curr_conversation_id(unified_msg_origin: str) -> str | None`:读取当前分支 ID。 +- `get_conversation(unified_msg_origin: str, conversation_id: str, create_if_not_exists: bool = False) -> Conversation | None`:读取分支对象。 +- `get_conversations(unified_msg_origin: str | None = None, platform_id: str | None = None) -> list[Conversation]`:列出分支。 +- `get_filtered_conversations(page: int = 1, page_size: int = 20, platform_ids: list[str] | None = None, search_query: str = "", **kwargs) -> tuple[list[Conversation], int]`:分页 + 条件过滤。 +- `update_conversation(unified_msg_origin: str, conversation_id: str | None = None, history: list[dict] | None = None, title: str | None = None, persona_id: str | None = None, token_usage: int | None = None) -> None`:更新历史/标题/persona/token_usage。 +- `add_message_pair(cid: str, user_message: UserMessageSegment | dict, assistant_message: AssistantMessageSegment | dict) -> None`:向指定分支追加一组 user/assistant 消息。 +- `get_human_readable_context(unified_msg_origin: str, conversation_id: str, page: int = 1, page_size: int = 10) -> tuple[list[str], int]`:获取分页后的可读上下文。 + +## 最小示例 + +```python +cid = await self.context.conversation_manager.get_curr_conversation_id(event.unified_msg_origin) +``` + +```python +cid = await self.context.conversation_manager.new_conversation(event.unified_msg_origin, title="新分支") +``` + +```python +await self.context.conversation_manager.update_conversation(event.unified_msg_origin, conversation_id=cid, title="重命名", persona_id="assistant_default") +``` + +```python +contexts, total_pages = await self.context.conversation_manager.get_human_readable_context(event.unified_msg_origin, cid, page=1, page_size=10) +``` + +## MUST + +- 所有分支操作必须使用当前会话的 `umo`,不要跨会话复用 `conversation_id`。 +- 更新历史时必须传 OpenAI 风格 `list[dict]` 消息结构。 + +--- + +## LLM 请求提示词注入 + +通过 `@filter.on_llm_request()` 拦截并修改 LLM 请求。 + +```python +from astrbot.api.event import filter, AstrMessageEvent +from astrbot.api.provider import ProviderRequest + +@filter.on_llm_request() +async def on_req(self, event: AstrMessageEvent, req: ProviderRequest): + # 修改系统提示词(仅稳定内容) + req.system_prompt += "\n\n[全局规则] 回答必须简洁。" +``` + +### ProviderRequest 关键属性 + +| 属性 | 类型 | 用途 | +|------|------|------| +| `system_prompt` | `str` | 系统提示词(请求最前) | +| `prompt` | `str \| None` | 本轮用户输入 | +| `extra_user_content_parts` | `list[ContentPart]` | 用户消息后的额外内容 | +| `contexts` | `list[dict]` | OpenAI 格式完整上下文 | + +### 1. 系统提示词(system_prompt) + +* **`system_prompt += ...`** + * 适合追加**稳定、长期有效**的角色设定或全局规则。 + * **警告**:每轮变化的内容(时间、好感度、记忆片段)会破坏模型服务端提示词缓存,导致成本和首 token 延迟增加 7-20 倍。 + +### 2. 动态内容(extra_user_content_parts) + +* **`req.extra_user_content_parts.append(...)`** + * 适合追加每轮变化的**动态上下文**(当前时间、状态面板、短期记忆)。 + * 追加在用户消息之后,**不影响缓存命中**。 + * 仅参与本轮请求、不持久化到历史:调用 `.mark_as_temp()`(`>= v4.24.0`)。 + +```python +from astrbot.core.agent.message import TextPart + +@filter.on_llm_request() +async def add_dynamic_context(self, event: AstrMessageEvent, req: ProviderRequest): + part = TextPart( + text=( + "\n" + f"当前时间:{datetime.now()}\n" + "好感度:72\n" + "" + ) + ) + part.mark_as_temp() # 不写入对话历史 + req.extra_user_content_parts.append(part) +``` + +### 3. 完整上下文替换(contexts) + +* **`req.contexts = [...]`** + * 直接替换 OpenAI 格式的消息历史。 + * 风险较高,需谨慎维护消息结构完整性。 \ No newline at end of file diff --git a/docs/snapshots/v4.24.4/agent/cron.md b/docs/snapshots/v4.24.4/agent/cron.md new file mode 100644 index 0000000..e9ead65 --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/cron.md @@ -0,0 +1,57 @@ +--- +category: agent +--- + +# Cron + +定时执行逻辑或唤醒 AI。AI 任务触发生成 `CronMessageEvent`(继承自 AstrMessageEvent)。 + +通过 `self.context.cron_manager` 调用。 + +## 注册 Python 函数(Basic Job) + +```python +await cron_mgr.add_basic_job( + name="任务名", + cron_expression="*/5 * * * *", + handler=self.your_method, + payload={"key": "value"}, + persistent=False, + description="任务描述", + handler_params={"extra": "data"}, + enabled=True, +) +``` + +- `name: str`: 任务唯一标识名 +- `cron_expression: str`: 标准 cron 表达式(5 段,`分 时 日 月 周`) +- `handler: Callable`: Python 异步处理函数 +- `payload: dict`: 传给 handler 的上下文数据 +- `persistent: bool`: 是否持久化(重启后保留,依赖 DB) +- `description: str`: 任务描述(v4.22.2 新增) +- `handler_params: dict`: 额外参数,合并到 payload(v4.22.2 新增) +- `enabled: bool`: 是否启用(v4.22.2 新增) + +## 注册 AI 唤醒(Active Agent Job) + +```python +await cron_mgr.add_active_job( + name="AI 定时任务", + cron_expression="0 8 * * *", + payload={"session": "UMO", "note": "指令"}, + run_once=False, + description="每日早报", +) +``` + +- `name: str`: 任务唯一标识名 +- `cron_expression: str`: 标准 cron 表达式 +- `payload: dict`: 包含 `session`(UMO)、`note`(唤醒指令) +- `run_once: bool`: 是否只执行一次 +- `description: str`: 任务描述(v4.22.2 新增) + +## 维护方法 + +- `delete_job(job_id: str)`: 删除任务 +- `list_jobs(job_type: str = None) -> list[CronJob]`: 列出任务(可选过滤 basic/active) +- `update_job(job_id: str, **kwargs) -> CronJob | None`: 更新任务(只支持部分字段) diff --git a/docs/snapshots/v4.24.4/agent/index.md b/docs/snapshots/v4.24.4/agent/index.md new file mode 100644 index 0000000..1c80977 --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/index.md @@ -0,0 +1,56 @@ +--- +category: agent +--- + +# Agent 系统概览 + +在 AstrBot 中,"Agent"指的是:**指令/系统提示(instructions)+ 工具(tools)+ 模型提供商(providers)+ 运行时能力(上下文管理 / 子智能体 / 沙盒 / 定时任务)** 的组合。 + +本目录把原先以 "LLM" 为中心的内容重组为 "Agent" 视角:LLM/VLM/Embedding 等都被视为 Provider 能力的一部分,工具与运行时能力决定了 Agent 的上限与安全边界。 + +## 你大概率会从这里开始 + +- 需要让模型调用工具:`docs/agent/registe tools.md` +- 需要选模型/Embedding/STT/TTS:`docs/agent/providers.md` +- 需要控制上下文与压缩:`docs/agent/context-compression.md` +- 需要 Hook(事件钩子/Agent 钩子):`docs/agent/agent-related-hooks.md` +- 需要子智能体:`docs/agent/subagents.md` +- 需要代码方式注册子智能体:`docs/agent/agent-registration.md` +- 需要沙盒(computer use):`docs/agent/sandbox.md` +- 需要定时任务(主动能力):`docs/agent/cron.md` +- **v4.7.0+ Agent Runner 架构(Dify/Coze/DeerFlow)**:`docs/agent/agent-runner.md` + +## 最短示例:工具循环 Agent + +```python +llm_resp = await self.context.tool_loop_agent( + event=event, + chat_provider_id=prov_id, + prompt="把这段需求拆成 3 个可执行步骤,并给出每步输出。", + tools=ToolSet([MyTool()]), + max_steps=10, + tool_call_timeout=60, + system_prompt="你是一个严谨的工程助手。", +) +``` + +### 关键参数(只记这几个就够用) + +- `chat_provider_id`:对话模型 provider id(LLM/VLM 的入口通常在这里) +- `tools`:可用工具集合(`FunctionTool` / handoff tool / 运行时注入工具) +- `max_steps`:限制循环次数,避免无限工具调用 +- `tool_call_timeout`:单个工具调用超时 +- `system_prompt`:定义 Agent 角色、边界与输出格式 + +### v4.22.2 扩展参数 + +`tool_loop_agent` 的 `**kwargs` 支持: +- `stream: bool` — 流式输出 +- `agent_hooks: BaseAgentRunHooks` — Agent 运行期钩子 +- `agent_context: AstrAgentContext` — 复用已有 agent 上下文 + +## 相关源码入口(以代码为准) + +- Agent runner(工具循环):`astrbotcore/astrbot/core/agent/runners/tool_loop_agent_runner.py` +- Agent hooks 接口:`astrbotcore/astrbot/core/agent/hooks.py` +- 主 Agent 构建(沙盒/定时工具注入/安全模式等):`astrbotcore/astrbot/core/astr_main_agent.py` diff --git a/docs/snapshots/v4.24.4/agent/offical-tool-list/tools.md b/docs/snapshots/v4.24.4/agent/offical-tool-list/tools.md new file mode 100644 index 0000000..595d9cd --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/offical-tool-list/tools.md @@ -0,0 +1,43 @@ +--- +category: agent +--- +# AstrBot 官方 Tool 列表 + + AstrBot Core 内置工具 + +## Computer Use + +- `astrbot_execute_shell`(`computer_use_runtime=sandbox|local`):执行 Shell 命令。 + - 示例参数:`{"command":"pwd","background":false}` +- `astrbot_execute_ipython`(`computer_use_runtime=sandbox`):在沙盒 IPython 执行代码。 + - 示例参数:`{"code":"print(1+1)","silent":false}` +- `astrbot_execute_python`(`computer_use_runtime=local`):在本地 Python 执行代码(仅管理员)。 + - 示例参数:`{"code":"print(1+1)","silent":false}` +- `astrbot_upload_file`(`computer_use_runtime=sandbox`):上传本地文件到沙盒。 + - 示例参数:`{"local_path":"C:/tmp/a.txt"}` +- `astrbot_download_file`(`computer_use_runtime=sandbox`):从沙盒下载文件。 + - 示例参数:`{"remote_path":"/workspace/out.txt","also_send_to_user":true}` + +## Knowledge Base + +- `astr_kb_search`(`kb_agentic_mode=true`):检索知识库内容。 + - 示例参数:`{"query":"AstrBot provider isolation"}` + +## Cron / Proactive Task + +- `create_future_task`(`add_cron_tools=true`):创建未来任务(周期或一次性)。 + - 示例参数:`{"note":"明早提醒我同步日报","cron_expression":"0 9 * * *"}` +- `delete_future_task`(`add_cron_tools=true`):删除未来任务。 + - 示例参数:`{"job_id":"cron_xxx"}` +- `list_future_tasks`(`add_cron_tools=true`):列出未来任务。 + - 示例参数:`{"job_type":"active_agent"}` + +## Proactive Message + +- `send_message_to_user`(平台支持主动消息时注入):主动向用户发送消息。 + - 示例参数:`{"messages":[{"type":"plain","text":"任务已完成"}]}` + +## Dynamic Handoff Tool + +- `transfer_to_`(`subagent_orchestrator.main_enable=true`):将任务移交给子智能体。 + - 示例参数:`{"input":"请处理这段文本并给出结构化结论"}` diff --git a/docs/snapshots/v4.24.4/agent/persona-control.md b/docs/snapshots/v4.24.4/agent/persona-control.md new file mode 100644 index 0000000..a36ba7e --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/persona-control.md @@ -0,0 +1,106 @@ +# Persona 管理与解析指南 + +`PersonaManager` 负责加载、缓存并提供所有人格的 CRUD 接口,兼容 AstrBot 4.x 前的 v3 格式。插件入口: + +```python +pm = self.context.persona_manager +conv_mgr = self.context.conversation_manager +umo = event.unified_msg_origin +``` + +--- + +## 核心操作 + +### 1. 读取 +* **`get_persona(persona_id: str) -> Persona`** + * 异常:不存在抛 `ValueError` +* **`get_all_personas() -> list[Persona]`** + +### 2. 新建 +* **`create_persona(persona_id, system_prompt, begin_dialogs=None, tools=None, skills=None, folder_id=None, sort_order=0) -> Persona`** + * `begin_dialogs`: 必为偶数条(user/assistant 交替)。 + * `tools` / `skills`: `None` = 全部可用,`[]` = 全部禁用。 + * 异常:ID 已存在抛 `ValueError` + +```python +await pm.create_persona( + persona_id="astrbot_plugin_writer", + system_prompt="你是一个技术写作助手。", + begin_dialogs=["你是谁?", "我是你的写作助手。"] +) +``` + +### 3. 更新 +* **`update_persona(persona_id, system_prompt=None, begin_dialogs=None, tools=None, skills=None) -> Persona`** + * 注意:无 `folder_id` 与 `sort_order` 参数。若仅改 prompt,需先读旧值回填 tools/skills,避免被重置为默认。 + * 异常:ID 不存在抛 `ValueError` + +```python +old = await pm.get_persona("astrbot_plugin_writer") +await pm.update_persona( + persona_id="astrbot_plugin_writer", + system_prompt="你是一个精炼的技术写作助手。", + tools=old.tools, + skills=old.skills, +) +``` + +### 4. 删除 +* **`delete_persona(persona_id: str) -> None`** + * 异常:ID 不存在抛 `ValueError` + +--- + +## 文件夹管理(core) + +* **查询**:`get_folder`, `get_folders`, `get_all_folders`, `get_folder_tree`, `get_personas_by_folder` +* **修改**:`create_folder`, `update_folder`, `delete_folder` +* **排序与移动**:`move_persona_to_folder`, `batch_update_sort_order` + +--- + +## 人格解析与优先级 + +系统按以下顺序解析,**命中即停止**: +1. **会话级**:`session_service_config.persona_id`(`umo` 作用域) +2. **对话分支级**:`conversation.persona_id` +3. **全局默认**:`provider_settings.default_personality` + +### 1. 设置会话级 Persona +读写 `session_service_config` 必须**先读后写**,避免覆盖同键下的 `llm_enabled` / `tts_enabled`: + +```python +from astrbot.api import sp + +cfg = await sp.get_async(scope="umo", scope_id=umo, key="session_service_config", default={}) or {} +cfg["persona_id"] = "assistant_default" +await sp.put_async(scope="umo", scope_id=umo, key="session_service_config", value=cfg) +``` + +### 2. 设置对话分支级 Persona + +```python +cid = await conv_mgr.get_curr_conversation_id(umo) +await conv_mgr.update_conversation(umo, conversation_id=cid, persona_id="assistant_default") +``` + +### 3. 显式禁用人格注入 +支持会话级或分支级: + +```python +await conv_mgr.update_conversation(umo, conversation_id=cid, persona_id="[%None]") +``` + +### 4. 获取默认人格 +* **`get_default_persona_v3(umo: str | MessageSession | None = None) -> Personality`** + * 解析会话配置并返回 v3 人格对象。未指定或不存在则回退至 `DEFAULT_PERSONALITY`。 + +--- + +## 运行时机制与注意项 + +* **注入逻辑**:命中后,`persona.prompt` 注入为系统提示词;`_begin_dialogs_processed` 注入为上下文前置消息。 +* **Webchat 回退机制**:若未命中 persona 且不为 `"[%None]"`,会自动追加 ChatUI 的默认人格提示词。 +* **会话隔离**:必须使用当前 `umo` 操作,严禁跨会话复用 `conversation_id`。 +* **UI 暴露**:可通过插件的 `_conf_schema.json` 暴露人设选择配置项。 \ No newline at end of file diff --git a/docs/snapshots/v4.24.4/agent/registe tools.md b/docs/snapshots/v4.24.4/agent/registe tools.md new file mode 100644 index 0000000..539a0f9 --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/registe tools.md @@ -0,0 +1,111 @@ +--- +category: agent +--- + +# Tools(函数调用) + +Tool 是让大语言模型调用外部能力(检索、计算、执行命令、文件处理)的机制。 + +## 两种定义方式 + +- 类方式:继承 FunctionTool +- 装饰器方式:@filter.llm_tool(...) + +## 方式一:类定义 Tool(推荐,v4.5.7+) + +`python +from pydantic import Field +from pydantic.dataclasses import dataclass + +from astrbot.core.agent.run_context import ContextWrapper +from astrbot.core.agent.tool import FunctionTool, ToolExecResult +from astrbot.core.astr_agent_context import AstrAgentContext + + +@dataclass +class BilibiliTool(FunctionTool[AstrAgentContext]): + name: str = "bilibili_videos" + description: str = "搜索 Bilibili 视频" + parameters: dict = Field( + default_factory=lambda: { + "type": "object", + "properties": { + "keywords": { + "type": "string", + "description": "搜索关键词", + } + }, + "required": ["keywords"], + } + ) + + async def call( + self, + context: ContextWrapper[AstrAgentContext], + **kwargs, + ) -> ToolExecResult: + return ToolExecResult(result="搜索结果...") +` + +**ToolExecResult 返回值格式(v4.22.2):** + +`python +from astrbot.core.agent.tool import ToolExecResult + +return ToolExecResult(result="文本结果") +return ToolExecResult(is_error=True, result="错误信息") +return ToolExecResult(result="", image_url="https://...") # 图片结果 +` + +## 注册到全局工具池 + +`python +class MyPlugin(Star): + def __init__(self, context: Context): + super().__init__(context) + self.context.add_llm_tools(BilibiliTool()) +` + +注册后主对话模型自动感知并调用该 Tool。 + +## 方式二:装饰器(兼容旧版) + +`python +from astrbot.api.event import filter, AstrMessageEvent + +@filter.llm_tool(name="get_weather") +async def get_weather(self, event: AstrMessageEvent, location: str): + """获取天气信息。 + + Args: + location(string): 地点 + """ + resp = self.get_weather_from_api(location) + yield event.plain_result("天气信息: " + resp) +` + +Docstring 中 Args 格式必须是 参数名(类型): 描述。 + +支持的类型:string、 +umber、object、oolean、rray、rray[string](v4.5.7+)。 + +## 内部 Tool(不注册全局) + +仅在单次 ool_loop_agent 调用中可见,不进入全局工具池: + +`python +from astrbot.core.agent.tool import ToolSet + +llm_resp = await self.context.tool_loop_agent( + event=event, + chat_provider_id=await self.context.get_current_chat_provider_id(event.unified_msg_origin), + prompt="请调用 bilibili_videos 工具搜索 AstrBot 教程", + tools=ToolSet([BilibiliTool()]), +) +` + +## Tips + +- parameters 必须是合法 JSON Schema +- 装饰器方式必须写规范 docstring(尤其 Args),否则 schema 解析失败 +- 推荐新项目使用类定义方式,参数类型检查更严格 \ No newline at end of file diff --git a/docs/snapshots/v4.24.4/agent/sandbox.md b/docs/snapshots/v4.24.4/agent/sandbox.md new file mode 100644 index 0000000..ba1e833 --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/sandbox.md @@ -0,0 +1,48 @@ +--- +category: agent +--- + +# Sandbox(插件可用) + +Sandbox 是 Agent 的计算机使用运行时(shell/python/文件上传下载)。 + +## 快速入口 + +```python +ctx = self.context +umo = event.unified_msg_origin +``` +## 底层方法(给 booter/工具实现使用) + +- `get_booter(context, session_id)` +- `get_local_booter()` +- `booter.shell.exec(command, cwd=None, env=None, timeout=30, shell=True, background=False)` +- `booter.python.exec(code, kernel_id=None, timeout=30, silent=False)` +- `booter.upload_file(path, file_name)` +- `booter.download_file(remote_path, local_path)` +- `booter.available()` + +## UMO 与当前 Sandbox 的绑定规则 + +- 当前会话标识使用 `event.unified_msg_origin`。 +- 工具执行时用 `event.unified_msg_origin` 调用 `get_booter(...)` 获取当前会话 booter。 +- `get_booter` 内部按 `session_id` 缓存:`session_booter[session_id]`。 +- 若缓存实例 `available()` 为 false,会先移除再重建。 +- `get_booter` 会读取 `context.get_config(umo=session_id)`,因此会话级配置可生效。 + +## 配置键(常用) + +- `provider_settings.computer_use_runtime`: `none | local | sandbox` +- `provider_settings.sandbox.booter`: `shipyard | boxlite` +- `provider_settings.sandbox.shipyard_endpoint` +- `provider_settings.sandbox.shipyard_access_token` +- `provider_settings.sandbox.shipyard_ttl` +- `provider_settings.sandbox.shipyard_max_sessions` + +## 易翻车点 + +- `shipyard_endpoint` 或 `shipyard_access_token` 缺失时,sandbox 工具不会注入。 +- `astrbot_execute_shell` 要求 `admin` 角色,否则返回 permission denied。 +- `astrbot_download_file(..., also_send_to_user=True)` 会发送后删除本地临时文件。 +- `local` 与 `sandbox` 是两套运行时:`local` 走 `get_local_booter()`,`sandbox` 走 `get_booter(..., umo)`。 + diff --git a/docs/snapshots/v4.24.4/agent/subagents.md b/docs/snapshots/v4.24.4/agent/subagents.md new file mode 100644 index 0000000..2ad5ee3 --- /dev/null +++ b/docs/snapshots/v4.24.4/agent/subagents.md @@ -0,0 +1,70 @@ +--- +category: agent +--- + +# Subagents(子智能体 / Handoff) + +Subagent 是给主 Agent 使用的 handoff 工具。主模型通过 `transfer_to_` 把任务转交给子智能体执行。 +`from astrbot.api import agent`(详见 `docs/agent/agent-registration.md`) + +## 配置式(推荐) + +### 最小配置 + +```json +{ + "subagent_orchestrator": { + "main_enable": true, + "remove_main_duplicate_tools": false, + "router_system_prompt": "You are a task router...", + "agents": [ + { + "enabled": true, + "name": "writer", + "public_description": "负责技术文档整理与重写", + "persona_id": null, + "system_prompt": "你是文档子智能体,输出精简且结构化。", + "provider_id": "openai_gpt4o_mini", + "tools": ["search_docs", "rewrite_text"] + } + ] + } +} +``` + +### `agents[]` 字段(源码对齐) + +- `enabled`: 是否启用 +- `name`: 子智能体名;工具名会生成为 `transfer_to_` +- `public_description`: 暴露给主模型的工具描述(决定主模型是否愿意调用) +- `persona_id`: 可选;存在时优先使用 persona 的 `system_prompt/begin_dialogs/tools` +- `system_prompt`: 未命中 persona 时使用 +- `provider_id`: 可选;子智能体专用 chat provider 覆盖 +- `tools`: 子智能体可用工具名列表(字符串) + +## 运行规则 + +- `main_enable=true` 时,主 Agent 会把所有 handoff 工具加入工具集。 +- `remove_main_duplicate_tools=true` 时,会把“已分配给子智能体”的同名工具从主 Agent 工具集移除。 +- `router_system_prompt` 会拼接到主 Agent 的 `system_prompt`。 +- `provider_id` 不为空时,handoff 执行优先用该 provider;否则回退当前会话 provider。 + +## SDK/代码式(高级) + +```python +from astrbot.api import agent + +@agent(name="writer", instruction="你是写作子智能体。") +async def writer_agent(event): + return None +``` + +> 代码式注册、`run_hooks`、专属工具挂载见:`docs/agent/agent-registration.md` + +## MUST + +- `name` 必须非空,且在同一实例中保持唯一。 +- `public_description` 必须写“适用任务”,不要写空泛人设。 +- `tools` 必须显式写成字符串列表(不要依赖隐式行为)。 + + diff --git a/docs/snapshots/v4.24.4/design_standards/architecture_overview.md b/docs/snapshots/v4.24.4/design_standards/architecture_overview.md new file mode 100644 index 0000000..4c6eec1 --- /dev/null +++ b/docs/snapshots/v4.24.4/design_standards/architecture_overview.md @@ -0,0 +1,21 @@ +--- +category: design_standards +--- + +# 核心架构综述 + +AstrBot 采用基于**插件化 (Plugin-based)** 和 **事件驱动 (Event-driven)** 的架构。其核心(Core)负责协调各个管理器(Manager),并通过 `Context` 对象向插件(Star)暴露能力。 + +### 核心管理器分工 + +- **`PluginManager`**: 负责插件的加载、卸载、重载以及元数据管理。 +- **`PlatformManager`**: 管理所有已接入的消息平台适配器,负责分发事件。 +- **`ProviderManager`**: 管理大语言模型(LLM)、语音识别(STT)、语音合成(TTS)等服务提供商。 +- **`ConversationManager`**: 管理用户会话历史、上下文存储及切换。 +- **`PersonaManager`**: 管理人格设定(Persona),包括系统提示词(System Prompt)和工具配置。 + +### 核心设计原则 + +1. **解耦**: 核心系统与平台适配器、AI 提供商、插件之间高度解耦。 +2. **统一模型**: 所有的平台消息都被转化为统一的 `AstrBotMessage` 模型。 +3. **插件化**: 功能尽可能通过插件实现,核心仅提供基础调度能力。 diff --git a/docs/snapshots/v4.24.4/design_standards/best_practices.md b/docs/snapshots/v4.24.4/design_standards/best_practices.md new file mode 100644 index 0000000..845cc5e --- /dev/null +++ b/docs/snapshots/v4.24.4/design_standards/best_practices.md @@ -0,0 +1,43 @@ +--- +category: design_standards +--- + +# AI 插件开发最佳实践 + +为了确保插件的稳定性、安全性和易用性,建议遵循以下实践方案。 + +### 1. 异常处理 + +务必捕获可能的异常,并给用户明确的反馈。 + +```python +try: + # 逻辑代码 +except TimeoutError: + yield event.plain_result("⌛ 会话已超时,请重新开始。") +except Exception as e: + logger.error(f"插件执行出错: {e}") + yield event.plain_result(f"❌ 发生错误: {e}") +finally: + event.stop_event() # 已经处理过错误,通常建议停止事件继续传播 +``` + +### 2. 平台差异化 + +虽然 AstrBot 提供了统一模型,但在调用底层 SDK 功能(如 `call_action`)时,需进行环境检查: + +```python +if event.get_platform_name() == "aiocqhttp": + # 调用 OneBot 特有 API + pass +``` + +### 3. 工具 (Tools) 开发 + +- 推荐使用 `agent-as-tool` 模式。 +- 完善 Docstring,这直接决定了大模型对工具的理解能力。 +- 尽量保持工具功能的单一性。 + +### 4. 资源清理 + +在插件卸载时,应在 `terminate()` 方法中清理定时器、数据库连接或文件句柄。 diff --git a/docs/snapshots/v4.24.4/design_standards/context_usage.md b/docs/snapshots/v4.24.4/design_standards/context_usage.md new file mode 100644 index 0000000..22dc222 --- /dev/null +++ b/docs/snapshots/v4.24.4/design_standards/context_usage.md @@ -0,0 +1,30 @@ +--- +category: design_standards +--- + +# Context 对象使用规范 + +`Context` 对象是 AstrBot 的能力中枢,在插件初始化时通过 `__init__` 注入。它是插件与系统核心交互的唯一桥梁。 + +### 重要属性 + +通过 `self.context` 可以访问各个管理器: + +- `self.context.conversation_manager`: 会话管理器。 +- `self.context.persona_manager`: 人格管理器。 +- `self.context.platform_manager`: 平台管理器。 +- `self.context.provider_manager`: 提供商管理器。 + +### 核心方法 + +#### 消息与平台相关 +- `send_message(umo: str, message_chain: MessageChain)`: 向指定源主动发送消息。 +- `get_platform(platform_type: PlatformAdapterType)`: 获取指定类型的平台实例。 + +#### AI 与工具相关 +- `add_llm_tools(*tools)`: 动态注册函数工具。 +- `get_using_provider(umo)`: 获取当前使用的 LLM 提供商。 + +#### 配置与插件 +- `get_config(umo=None)`: 获取当前配置。 +- `get_all_stars()`: 获取所有已加载插件的元数据。 diff --git a/docs/snapshots/v4.24.4/design_standards/core_concepts.md b/docs/snapshots/v4.24.4/design_standards/core_concepts.md new file mode 100644 index 0000000..58549b4 --- /dev/null +++ b/docs/snapshots/v4.24.4/design_standards/core_concepts.md @@ -0,0 +1,128 @@ +# AstrBot 核心概念 API 清单 + +本文档仅列出 AstrBot 插件开发的核心功能 API。 + +### 1. 装饰器 (Decorators) + +- `@register(id, author, description, version, repo_url)`: 注册插件。 +- `@filter.command(name, alias, priority)`: 注册指令。支持带参函数。 +- `@filter.command_group(name)`: 注册指令组。 +- `@filter.event_message_type(type)`: 过滤消息类型 (`ALL`, `PRIVATE_MESSAGE`, `GROUP_MESSAGE`)。 +- `@filter.platform_adapter_type(type)`: 过滤平台类型 (如 `AIOCQHTTP`, `TELEGRAM`)。 +- `@filter.permission_type(type)`: 校验权限 (如 `ADMIN`)。 +- `@filter.regex(pattern)`: 正则匹配。 +- `@filter.llm_tool(name)`: 注册为 AI 可调用的工具。 +- `@session_waiter(timeout, record_history_chains)`: 等待下一条用户消息。 + +### 2. 消息组件 (Message Components) + +- `Plain(text)`: 纯文本。 +- `At(user_id)`: 提及用户。 +- `Image.fromFileSystem(path)` / `Image.fromURL(url)`: 图片。 +- `Record.fromFileSystem(path)`: 语音。 +- `Video.fromFileSystem(path)` / `Video.fromURL(url)`: 视频。 +- `File.fromFileSystem(path, name)`: 文件。 +- `Face(id)`: 系统表情。 +- `Reply(message_id)`: 回复特定消息。 +- `Node(uin, name, content)` / `Nodes(nodes)`: 合并转发节点 (部分平台支持)。 + +### 3. 核心对象与方法 + +**AstrMessageEvent (事件对象)** + +- 消息事件对象,包含消息内容、发送者信息、群组信息等。 +- 提供消息发送和结果构建方法。 + +**Context (核心枢纽)** + +- `context.send_message(umo, chain)`: 向指定源主动发送消息。 +- `context.get_platform(type)`: 获取指定类型的平台实例。 +- `context.get_using_provider(umo)`: 获取当前 LLM 提供商。 +- `context.add_llm_tools(*tools)`: 动态注册 AI 工具。 + +**v4.5.7+ 新增 LLM API** + +```python +umo = event.unified_msg_origin +prov_id = await self.context.get_current_chat_provider_id(umo) +``` + +- `await context.get_current_chat_provider_id(umo) -> str`: 获取当前会话使用的 chat provider ID。 +- `await context.llm_generate(chat_provider_id, prompt, contexts=None, system_prompt=None, tools=None) -> LLMResponse`: 简化的 LLM 调用。 +- `await context.tool_loop_agent(event, chat_provider_id, prompt, tools, system_prompt=None, max_steps=30, tool_call_timeout=60) -> LLMResponse`: 工具循环 Agent。 + +**MessageChain (消息链构建器)** + +- `MessageChain().message(text)`: 添加文本。 +- `MessageChain().file_image(path)`: 添加图片文件。 +- `MessageChain().at(user_id)`: 添加 At。 + +### 4. 存储与工具 (Storage & Utils) + +- `await self.get_kv_data(key, default)`: 获取插件隔离的 KV 数据。 +- `await self.put_kv_data(key, value)`: 存储插件隔离的 KV 数据。 +- `await self.delete_kv_data(key)`: 删除 KV 数据。 +- `await self.html_render(html_text=None, url=None, data=None, options=None)`: 将 HTML 字符串或网页渲染为图片。基于 Playwright。 +- `text_to_image(text)`: 将文字转为图片。 + +### 5. 系统钩子 (Hooks) + +Hooks 分为两层,不建议在"概念清单"里重复列举具体 hook 名单(容易过时): + +- 插件事件钩子(`@filter.on_*`):见 `docs/plugin_config/hooks.md` +- Agent 运行钩子(`BaseAgentRunHooks`):见 `docs/agent/agent-related-hooks.md` + +### 6. Agent 智能体 + +- Agent 相关能力(tools / providers / persona / sandbox / cron / subagents):见 `docs/agent/` +- `context.tool_loop_agent(...)`: 调用工具循环 Agent(可结合子智能体 handoff) +- v4.7.0+ Agent Runner 架构:见 `docs/agent/agent-runner.md` + +### 7. Tool 定义 (v4.5.7+ 推荐) + +推荐使用 dataclass 模式定义 Tool: + +```python +from pydantic import Field +from pydantic.dataclasses import dataclass +from astrbot.core.agent.tool import FunctionTool +from astrbot.core.agent.run_context import ContextWrapper +from astrbot.core.astr_agent_context import AstrAgentContext + +@dataclass +class MyTool(FunctionTool[AstrAgentContext]): + name: str = "my_tool" + description: str = "工具描述" + parameters: dict = Field(default_factory=lambda: { + "type": "object", + "properties": {"query": {"type": "string", "description": "参数描述"}}, + "required": ["query"], + }) + + async def call(self, context: ContextWrapper[AstrAgentContext], **kwargs) -> str: + return "结果" +``` + +### 8. 多智能体 (Multi-Agent) v4.5.7+ + +使用 agent-as-tool 模式实现多智能体: + +```python +@dataclass +class SubAgentTool(FunctionTool[AstrAgentContext]): + name: str = "sub_agent" + description: str = "子智能体描述" + parameters: dict = Field(default_factory=lambda: {...}) + + async def call(self, context: ContextWrapper[AstrAgentContext], **kwargs) -> str: + ctx = context.context.context + event = context.context.event + llm_resp = await ctx.tool_loop_agent( + event=event, + chat_provider_id=await ctx.get_current_chat_provider_id(event.unified_msg_origin), + prompt=kwargs["query"], + tools=ToolSet([SomeTool()]), + max_steps=30, + ) + return llm_resp.completion_text +``` diff --git a/docs/snapshots/v4.24.4/design_standards/event_flow.md b/docs/snapshots/v4.24.4/design_standards/event_flow.md new file mode 100644 index 0000000..16389ba --- /dev/null +++ b/docs/snapshots/v4.24.4/design_standards/event_flow.md @@ -0,0 +1,20 @@ +--- +category: design_standards +--- + +# 消息流转模型 + +AstrBot 的消息处理遵循一个清晰的流转过程。 + +### 核心流程图 + +1. **接收**: 平台适配器(Platform)接收原始消息。 +2. **转换**: 调用 `convert_message` 将其封装为 `AstrBotMessage`。 +3. **提交**: 封装为 `AstrMessageEvent` 后通过 `self.commit_event(event)` 提交到事件队列。 +4. **分发**: `PlatformManager` 按优先级将事件分发给所有插件的 Handler。 +5. **处理**: 插件执行业务逻辑。 + - 若调用 `event.stop_event()`,流程在此终止。 +6. **LLM 交互**: 若消息未被拦截,且符合 AI 触发条件,调用配置的 LLM。 +7. **结果装饰**: 发送前调用 `on_decorating_result` 钩子。 +8. **回复**: 调用 `event.send()` 或 `yield`,触发适配器的 `send` 方法。 +9. **发送**: 适配器调用平台 SDK 发送消息。 diff --git a/docs/snapshots/v4.24.4/design_standards/sandbox.md b/docs/snapshots/v4.24.4/design_standards/sandbox.md new file mode 100644 index 0000000..faf01d3 --- /dev/null +++ b/docs/snapshots/v4.24.4/design_standards/sandbox.md @@ -0,0 +1,20 @@ +--- +title: Sandbox 存储挂载与文件共享 (Sandbox Storage Mounting & File Sharing) +type: improvement +status: stable +last_updated: 2025-02-10 +related_base: agent/sandbox.md +--- + +## 概述 +在基于 Shipyard 的 Sandbox 运行时中,系统通过 Docker Volume 建立了宿主机与沙盒环境之间的共享临时目录。这一变更明确了文件在宿主机与沙盒之间流转的物理路径契约,是 `astrbot_upload_file` 等文件操作工具正常运行的基础设施保障。 + +## 存储映射契约 +为了实现宿主机与沙盒环境的高效文件交换,系统建立了以下挂载关系: +- **宿主机源路径**: `${PWD}/data/temp` (即 AstrBot 运行根目录下的临时文件夹) +- **沙盒目标路径**: `/AstrBot/data/temp` (沙盒环境内的绝对路径) + +## 变更影响分析 +1. **文件访问一致性**:AI 开发者在编写涉及沙盒文件操作的工具(Tools)时,应知晓 `/AstrBot/data/temp` 是预设的共享交换区。上传到宿主机临时目录的文件将直接映射至此路径,无需通过网络流重复传输。 +2. **底层实现透明化**:此变更解释了 `ShipyardBooter` 如何在物理层面处理文件可见性。如果开发者在非标准 Docker 环境下部署,需手动配置类似的卷挂载以维持 `astrbot_upload_file` 和 `astrbot_download_file` 的功能兼容性。 +3. **边界情况**:宿主机对 `data/temp` 的清理操作会同步反映在沙盒内。在执行长时间运行的 Agent 任务时,需注意临时文件的生命周期管理,避免因宿主机清理导致沙盒内路径失效。 \ No newline at end of file diff --git a/docs/snapshots/v4.24.4/design_standards/visual_utils.md b/docs/snapshots/v4.24.4/design_standards/visual_utils.md new file mode 100644 index 0000000..1a18162 --- /dev/null +++ b/docs/snapshots/v4.24.4/design_standards/visual_utils.md @@ -0,0 +1,89 @@ +--- +category: design_standards +--- + +# 视觉与渲染工具 (Visual Utils) + +AstrBot 提供了一些工具函数,帮助插件实现更丰富的视觉表现,如 HTML 渲染图片。 + +### 1. HTML 渲染 (html_render) + +AstrBot 内置了基于 **Playwright** 的 HTML 渲染引擎,支持将 HTML 字符串(支持 Jinja2 模板)或远程网页渲染为图片。 + +#### `await self.html_render(html_text: str = None, url: str = None, data: dict = None, options: dict = None) -> str` + +- **参数**: + - `html_text`: Jinja2 格式的 HTML 模板字符串。 + - `url`: 目标网页的 URL。如果提供了 `url`,将优先使用 `url` 而忽略 `html_text`。 + - `data`: 传入模板的变量字典(仅在提供 `html_text` 时有效)。 + - `options`: 渲染选项(映射自 Playwright API)。 + - `viewport`: 视口大小,例如 `{"width": 800, "height": 600}`。 + - `selector`: 等待并截图指定的 CSS 选择器对应的元素。 + - `wait_until`: 等待页面加载的状态。可选值:`"commit"`, `"domcontentloaded"`, `"load"`, `"networkidle"` (默认)。 + - `timeout`: 截图超时时间(毫秒)。 + - `type`: 图片格式,`"jpeg"` 或 `"png"`。 + - `quality`: 仅 JPEG 有效 (0-100)。 + - `omit_background`: 是否透明背景 (仅 PNG)。 + - `full_page`: 是否截取整页 (默认为 True,如果指定了 `selector` 则失效)。 + - `clip`: 裁切区域 `{"x": 0, "y": 0, "width": 100, "height": 100}`。 + - `animations`: `"allow"` 或 `"disabled"`。 + - `scale`: `"css"` 或 `"device"`。 +- **返回值**: 渲染后的图片本地路径。 + +#### 使用示例 + +##### 渲染 HTML 模板 + +```python +TMPL = """ +
+

Hello {{ name }}!

+

This is rendered via AstrBot HTML Render.

+
+""" + +@filter.command("hello_render") +async def hello_render(self, event: AstrMessageEvent): + # 渲染 HTML 字符串并传入数据 + image_path = await self.html_render(html_text=TMPL, data={"name": event.get_sender_id()}) + + # 将结果作为图片发送 + yield event.image_result(image_path) +``` + +##### 渲染远程网页 + +```python +@filter.command("screenshot") +async def screenshot(self, event: AstrMessageEvent, site_url: str): + # 渲染指定 URL,并设置视口大小 + image_path = await self.html_render( + url=site_url, + options={"viewport": {"width": 1280, "height": 720}, "wait_until": "networkidle"} + ) + yield event.image_result(image_path) +``` + +#### 转换为 Image 组件 + +`html_render` 返回的是图片的本地路径。你可以使用 `event.image_result(path)` 快速发送,也可以手动构建 `Image` 组件: + +```python +from astrbot.api.message_components import Image + +image_path = await self.html_render(url="...") +image_comp = Image.fromFileSystem(image_path) + +# 放入消息链发送 +# yield event.chain_result([Plain("这是截图:"), image_comp]) +``` + +### 2. 文字转图片 (text_to_image) + +#### `text_to_image(text: str, return_url: bool = True) -> str` + +- **说明**: 简单的文字转图片工具。 +- **参数**: + - `text`: 要转换的文字内容。 + - `return_url`: 是否返回 URL 格式。 +- **返回值**: 图片的路径或 URL。 diff --git a/docs/snapshots/v4.24.4/index.md b/docs/snapshots/v4.24.4/index.md new file mode 100644 index 0000000..dfa66d2 --- /dev/null +++ b/docs/snapshots/v4.24.4/index.md @@ -0,0 +1,11 @@ +# v4.24.4 文档快照 + +这是 AstrBot `v4.24.4` 的文档快照(仅 docs/ 内容)。 + +## 快速入口 + +- [核心概念](/snapshots/v4.24.4/design_standards/core_concepts) +- [架构总览](/snapshots/v4.24.4/design_standards/architecture_overview) +- [消息模型](/snapshots/v4.24.4/messages/model) +- [插件配置 Schema](/snapshots/v4.24.4/plugin_config/schema) +- [平台适配器接口](/snapshots/v4.24.4/platform_adapters/adapter_interface) diff --git a/docs/snapshots/v4.24.4/messages/components.md b/docs/snapshots/v4.24.4/messages/components.md new file mode 100644 index 0000000..ce7f2dd --- /dev/null +++ b/docs/snapshots/v4.24.4/messages/components.md @@ -0,0 +1,41 @@ +--- +category: messages +--- + +# 消息链组件 (Message Components) + +AstrBot 使用消息链(MessageChain)来描述消息结构,它是一个由多个消息段(MessagePart/Component)组成的有序列表。 + +### 核心组件及其兼容性 + +| 组件类型 | 描述 | 参数示例 | 平台兼容性建议 | +| :--- | :--- | :--- | :--- | +| `Plain` | 纯文本 | `text="Hello"` | 所有平台支持。 | +| `At` | 提及/艾特 | `user_id="xxx"` | 大多数平台支持。 | +| `Image` | 图片 | `fromFileSystem(path)`, `fromURL(url)` | 所有平台支持。URL 必须以 `http` 或 `https` 开头。 | +| `Record` | 语音 | `file="path/to/wav"` | 广泛支持。目前主要支持 `wav` 格式。 | +| `Video` | 视频 | `fromFileSystem(path)`, `fromURL(url)` | 广泛支持。常用格式为 `mp4` | +| `File` | 文件 | `file="path"`, `name="a.txt"` | 部分平台不支持。 | +| `Face` | 表情 | `id="123"` | 主要在 OneBot v11 (QQ) 平台支持。 | +| `Node/Nodes` | 合并转发节点 | `uin`, `name`, `content` | 仅 OneBot v11 支持。 | +| `Poke` | 戳一戳 | - | 主要在 OneBot v11 支持。 | +| `Reply` | 回复特定消息 | `message_id="xxx"` | 广泛支持。 | + +### 消息构建示例 + +```python +import astrbot.api.message_components as Comp + +# 方式 1:手动构建列表 +chain = [ + Comp.At(user_id=event.get_sender_id()), + Comp.Plain(" 来看这张图:"), + Comp.Image.fromURL("https://example.com/image.jpg") +] +yield event.chain_result(chain) + +# 方式 2:使用 MessageChain 流式构建 +from astrbot.api.event import MessageChain +message_chain = MessageChain().message("Hello!").file_image("path/to/image.jpg") +await self.context.send_message(event.unified_msg_origin, message_chain) +``` diff --git a/docs/snapshots/v4.24.4/messages/events.md b/docs/snapshots/v4.24.4/messages/events.md new file mode 100644 index 0000000..c8681f9 --- /dev/null +++ b/docs/snapshots/v4.24.4/messages/events.md @@ -0,0 +1,33 @@ +--- +title: 消息事件 (AstrMessageEvent) +type: improvement +status: stable +last_updated: 2024-05-22 +related_base: messages/events.md +--- + +## 概述 +`AstrMessageEvent` 是插件处理逻辑的核心上下文对象。在最新版本中,该对象的会话标识属性(`session_id` 与 `unified_msg_origin`)已重构为基于 `MessageSession` 对象的动态属性(Property),增强了会话管理的一致性。 + +## 核心属性与 Setter 契约 + +这些属性现在不仅支持读取,还支持通过 Setter 进行动态修改,且修改会自动同步到底层的 `MessageSession` 状态: + +- **`event.unified_msg_origin` (UMO)**: + - **Getter**: 返回格式为 `platform_name:message_type:session_id` 的统一标识符。 + - **Setter**: 允许通过赋值 UMO 字符串来重置事件的会话上下文。内部通过 `MessageSession.from_str(value)` 重新解析并覆盖当前 session 对象。 +- **`event.session_id`**: + - **Getter**: 获取当前会话的唯一 ID。 + - **Setter**: 直接修改当前会话 ID,此变更会立即反映在 `unified_msg_origin` 的输出中。 + +## 内部实现逻辑 + +`AstrMessageEvent` 不再在 `__init__` 中静态存储 `session_id` 和 `unified_msg_origin` 字符串,而是统一维护一个 `self.session` (`MessageSession` 类实例)。 +- **初始化**: 修正了 `MessageSession` 的拼写错误并确保其在事件创建时被正确初始化。 +- **响应式更新**: 通过 Python `@property` 装饰器,确保了 UMO 和 Session ID 始终指向同一个数据源,消除了状态不一致的风险。 + +## 变更影响分析 + +1. **动态会话切换**: 插件开发者现在可以在事件处理过程中,通过修改 `event.unified_msg_origin` 动态地将事件“重定向”到另一个会话上下文。这对于实现跨群指令触发或会话劫持逻辑至关重要。 +2. **副作用警示**: 修改 `unified_msg_origin` 会导致底层的 `platform_name` 和 `message_type` 同时发生变化。如果仅需修改用户 ID,应优先使用 `event.session_id` 的 setter。 +3. **最佳实践**: 在编写需要持久化或比对会话的逻辑时,应始终依赖 `event.unified_msg_origin` 属性,因为它现在是经过 `MessageSession` 校验的权威来源。 \ No newline at end of file diff --git a/docs/snapshots/v4.24.4/messages/model.md b/docs/snapshots/v4.24.4/messages/model.md new file mode 100644 index 0000000..4394c9d --- /dev/null +++ b/docs/snapshots/v4.24.4/messages/model.md @@ -0,0 +1,31 @@ +--- +category: messages +--- + +# 消息模型 (AstrBotMessage) + +`AstrBotMessage` 是适配器层生成的标准化消息对象,它屏蔽了不同平台(QQ、飞书等)的差异,使插件可以“一次编写,到处运行”。 + +### AstrBotMessage 结构 + +在适配器中,必须填充 `AstrBotMessage` 的以下字段: + +```python +class AstrBotMessage: + type: MessageType # 消息类型(GROUP_MESSAGE 或 FRIEND_MESSAGE) + self_id: str # 机器人 ID + session_id: str # 会话 ID,决定了上下文隔离 + message_id: str # 消息 ID + group_id: str # 群组 ID(如果是私聊则为空) + sender: MessageMember # 发送者信息(含 user_id 和 nickname) + message: List[BaseMessageComponent] # 消息链(组件列表) + message_str: str # 纯文本汇总内容 + raw_message: object # 原始平台消息对象(用于 Debug 或特殊处理) + timestamp: int # 时间戳 +``` + +### 属性详解 + +- **`session_id`**: 核心字段,用于决定 LLM 对话的上下文隔离。 +- **`message_str`**: 插件处理逻辑中常用的纯文本内容。 +- **`message`**: 结构化消息内容,由各种消息组件组成。 diff --git a/docs/snapshots/v4.24.4/messages/umo.md b/docs/snapshots/v4.24.4/messages/umo.md new file mode 100644 index 0000000..3c432a9 --- /dev/null +++ b/docs/snapshots/v4.24.4/messages/umo.md @@ -0,0 +1,22 @@ +--- +category: messages +--- + +# 统一消息源 (Unified Message Origin) + +统一消息源(Unified Message Origin,简称 **UMO**)是 AstrBot 识别跨平台会话的核心标识。 + +### 格式 + +UMO 是一个格式如下的字符串: +`platform_id:message_type:session_id` + +- **`platform_id`**: 平台 ID(如 `aiocqhttp`, `qqofficial`)。 +- **`message_type`**: 消息类型(`group` 或 `private`)。 +- **`session_id`**: 会话 ID(群号或用户 ID)。 + +### 用途 + +1. **会话识别**: 唯一标识一个消息来源。 +2. **主动发送**: 通过 `context.send_message(umo, message_chain)` 向指定的源发送消息。 +3. **获取方式**: 在插件中通过 `event.unified_msg_origin` 获取。 diff --git a/docs/snapshots/v4.24.4/platform_adapters/adapter_interface.md b/docs/snapshots/v4.24.4/platform_adapters/adapter_interface.md new file mode 100644 index 0000000..ca0b211 --- /dev/null +++ b/docs/snapshots/v4.24.4/platform_adapters/adapter_interface.md @@ -0,0 +1,374 @@ +# Platform Adapter + +平台适配器将外部消息平台接入 AstrBot。插件可注册自定义适配器。 + +## 注册适配器 + +`@register_platform_adapter(adapter_name="id", desc="描述", default_config_tmpl={"key": "value"}, adapter_display_name="显示名", logo_path="logo.png", support_streaming_message=True)` + +## Platform 基类 + +继承 `Platform` 并实现以下方法: + +### 必须实现 + +- `run() -> Coroutine`: 异步阻塞方法,启动客户端 SDK 并持续监听消息。 +- `meta() -> PlatformMetadata`: 返回适配器元数据。 +- `send_by_session(session: MessageSession, message_chain: MessageChain)`: 通过会话发送消息。 + +### 可选重写 + +- `terminate()`: 终止平台运行。 +- `get_client() -> object`: 获取平台客户端对象。 +- `webhook_callback(request) -> Any`: 统一 Webhook 回调入口。 + +### 辅助方法 + +- `commit_event(event: AstrMessageEvent)`: 提交事件到事件队列。 +- `unified_webhook() -> bool`: 是否使用统一 Webhook 模式。 +- `get_stats() -> dict`: 获取平台统计信息。 +- `record_error(message: str, traceback_str: str | None)`: 记录错误。 +- `clear_errors()`: 清除错误记录。 + +### 属性 + +- `config: dict`: 平台配置(用户填写的 default_config_tmpl)。 +- `status: PlatformStatus`: 运行状态(PENDING/RUNNING/ERROR/STOPPED)。 +- `errors: list[PlatformError]`: 错误列表。 +- `last_error: PlatformError | None`: 最近错误。 + +## PlatformMetadata + +```python +PlatformMetadata( + name="adapter_id", # 平台类型标识 + description="适配器描述", + id="adapter_id", # 唯一标识符 + default_config_tmpl={}, # 默认配置模板 + adapter_display_name="显示名", # WebUI 显示名称 + logo_path="logo.png", # Logo 路径(相对于插件目录) + support_streaming_message=True, # 是否支持流式消息 + support_proactive_message=True, # 是否支持主动消息 +) +``` + +## AstrBotMessage + +适配器必须填充以下字段: + +```python +AstrBotMessage( + type=MessageType.GROUP_MESSAGE, # GROUP_MESSAGE / FRIEND_MESSAGE / OTHER_MESSAGE + self_id="bot_id", # 机器人 ID + session_id="session_id", # 会话 ID(决定上下文隔离) + message_id="msg_id", # 消息 ID + group=Group(group_id="123"), # 群组信息(私聊为 None) + sender=MessageMember(user_id="uid", nickname="昵称"), + message=[Plain(text="内容")], # 消息链 + message_str="纯文本内容", # 纯文本汇总 + raw_message=original_data, # 原始平台消息 + timestamp=1234567890, # 时间戳 +) +``` + +### 属性 + +- `group_id: str`: 群组 ID(私聊返回空字符串)。 + +## MessageType 枚举 + +- `MessageType.GROUP_MESSAGE`: 群组消息 +- `MessageType.FRIEND_MESSAGE`: 私聊消息 +- `MessageType.OTHER_MESSAGE`: 其他消息 + +## MessageMember + +```python +MessageMember(user_id="uid", nickname="昵称") +``` + +## Group + +```python +Group( + group_id="123", + group_name="群名", + group_avatar="头像URL", + group_owner="群主ID", + group_admins=["admin1", "admin2"], + members=[MessageMember(...)], +) +``` + +## MessageSession + +```python +MessageSession( + platform_name="adapter_id", # 平台 ID + message_type=MessageType.GROUP_MESSAGE, + session_id="session_id", +) +# 字符串格式: "platform_id:message_type:session_id" +``` + +### 方法 + +- `MessageSession.from_str(session_str)`: 从字符串解析。 + +## AstrMessageEvent + +事件基类,平台适配器需继承并实现 `send()` 方法。 + +### 核心属性 + +- `message_str: str`: 纯文本消息。 +- `message_obj: AstrBotMessage`: 完整消息对象。 +- `platform_meta: PlatformMetadata`: 平台元数据。 +- `session: MessageSession`: 会话对象。 +- `unified_msg_origin: str`: UMO(格式: `platform_id:message_type:session_id`)。 +- `session_id: str`: 会话 ID。 +- `role: str`: 用户角色("member" / "admin")。 +- `is_wake: bool`: 是否唤醒。 +- `is_at_or_wake_command: bool`: 是否 At 或唤醒词。 +- `call_llm: bool`: 是否调用 LLM。 + +### 获取信息方法 + +- `get_platform_name() -> str`: 获取平台类型。 +- `get_platform_id() -> str`: 获取平台 ID。 +- `get_message_str() -> str`: 获取消息文本。 +- `get_message_outline() -> str`: 获取消息概要(图片转 `[图片]`)。 +- `get_messages() -> list[BaseMessageComponent]`: 获取消息链。 +- `get_message_type() -> MessageType`: 获取消息类型。 +- `get_session_id() -> str`: 获取会话 ID。 +- `get_group_id() -> str`: 获取群组 ID。 +- `get_self_id() -> str`: 获取机器人 ID。 +- `get_sender_id() -> str`: 获取发送者 ID。 +- `get_sender_name() -> str`: 获取发送者昵称。 +- `is_private_chat() -> bool`: 是否私聊。 +- `is_wake_up() -> bool`: 是否唤醒。 +- `is_admin() -> bool`: 是否管理员。 + +### 消息发送方法 + +- `send(message: MessageChain)`: 发送消息到平台。 +- `send_streaming(generator: AsyncGenerator, use_fallback: bool)`: 发送流式消息。 +- `react(emoji: str)`: 添加表情回应。 +- `get_group(group_id: str | None) -> Group | None`: 获取群组数据。 + +### 结果设置方法 + +- `set_result(result: MessageEventResult | str)`: 设置事件结果。 +- `stop_event()`: 终止事件传播。 +- `continue_event()`: 继续事件传播。 +- `is_stopped() -> bool`: 是否已终止。 +- `should_call_llm(call_llm: bool)`: 是否调用 LLM。 +- `get_result() -> MessageEventResult | None`: 获取结果。 +- `clear_result()`: 清除结果。 + +### 快捷构建结果 + +- `make_result() -> MessageEventResult`: 创建空结果。 +- `plain_result(text: str) -> MessageEventResult`: 文本结果。 +- `image_result(url_or_path: str) -> MessageEventResult`: 图片结果。 +- `chain_result(chain: list) -> MessageEventResult`: 消息链结果。 + +### LLM 请求 + +- `request_llm(prompt: str, func_tool_manager=None, tool_set=None, session_id="", image_urls=None, contexts=None, system_prompt="", conversation=None) -> ProviderRequest`: 创建 LLM 请求。 + +### 额外信息 + +- `set_extra(key, value)`: 设置额外信息。 +- `get_extra(key: str | None, default=None) -> Any`: 获取额外信息。 +- `clear_extra()`: 清除额外信息。 + +## MessageChain + +消息链,用于构建和发送消息。 + +### 构建方法 + +- `message(text: str)`: 添加文本。 +- `at(name: str, qq: str | int)`: 添加 At。 +- `at_all()`: 添加 AtAll。 +- `url_image(url: str)`: 添加网络图片。 +- `file_image(path: str)`: 添加本地图片。 +- `base64_image(base64_str: str)`: 添加 base64 图片。 +- `use_t2i(use_t2i: bool)`: 设置是否使用文本转图片。 + +### 工具方法 + +- `get_plain_text(with_other_comps_mark: bool) -> str`: 获取纯文本。 +- `squash_plain()`: 合并所有 Plain 消息段。 + +## MessageEventResult + +继承 MessageChain,增加事件控制。 + +### 方法 + +- `stop_event()`: 终止事件传播。 +- `continue_event()`: 继续事件传播。 +- `is_stopped() -> bool`: 是否终止。 +- `set_async_stream(stream: AsyncGenerator)`: 设置异步流。 +- `set_result_content_type(typ: ResultContentType)`: 设置结果类型。 +- `is_llm_result() -> bool`: 是否 LLM 结果。 + +## 消息组件 + +### Plain + +`Plain(text="文本内容")` + +### Image + +```python +Image.fromURL("https://example.com/img.jpg") +Image.fromFileSystem("/path/to/image.jpg") +Image.fromBase64("base64_data") +Image.fromBytes(bytes_data) +``` + +- `convert_to_file_path() -> str`: 转换为本地路径。 +- `convert_to_base64() -> str`: 转换为 base64。 +- `register_to_file_service() -> str`: 注册到文件服务。 + +### Record + +```python +Record.fromFileSystem("/path/to/audio.wav") +Record.fromURL("https://example.com/audio.wav") +Record.fromBase64("base64_data") +``` + +- `convert_to_file_path() -> str`: 转换为本地路径。 +- `convert_to_base64() -> str`: 转换为 base64。 +- `register_to_file_service() -> str`: 注册到文件服务。 + +### Video + +```python +Video.fromFileSystem("/path/to/video.mp4") +Video.fromURL("https://example.com/video.mp4") +``` + +- `convert_to_file_path() -> str`: 转换为本地路径。 +- `register_to_file_service() -> str`: 注册到文件服务。 + +### File + +`File(name="文件名", file="/path/to/file", url="https://...")` + +- `get_file(allow_return_url: bool) -> str`: 异步获取文件。 +- `register_to_file_service() -> str`: 注册到文件服务。 + +### At / AtAll + +```python +At(qq="user_id", name="昵称") +AtAll() +``` + +### Reply + +`Reply(id="message_id", chain=[...], sender_id="uid", sender_nickname="昵称", time=timestamp, message_str="文本")` + +### Face + +`Face(id=123)` + +### Node / Nodes + +```python +Node(uin="qq号", name="昵称", content=[Plain("内容")]) +Nodes(nodes=[Node(...), Node(...)]) +``` + +### Forward + +`Forward(id="forward_id")` + +### Poke + +`Poke(type="poke_type")` + +### Json + +`Json(data={"key": "value"})` + +### WechatEmoji + +`WechatEmoji(md5="md5值", md5_len=长度, cdnurl="CDN链接")` + +## 完整示例 + +```python +from astrbot.api.platform import ( + Platform, AstrBotMessage, MessageMember, MessageType, + PlatformMetadata, register_platform_adapter +) +from astrbot.api.event import AstrMessageEvent, MessageChain +from astrbot.core.platform.astr_message_event import MessageSesion + +@register_platform_adapter("myplatform", "我的平台适配器", default_config_tmpl={ + "token": "", + "enable": False, +}) +class MyPlatformAdapter(Platform): + def __init__(self, platform_config: dict, platform_settings: dict, event_queue: asyncio.Queue): + super().__init__(platform_config, event_queue) + self.settings = platform_settings + + def meta(self) -> PlatformMetadata: + return PlatformMetadata(name="myplatform", description="我的平台", id=self.config.get("id", "myplatform")) + + async def run(self): + async def on_message(data): + abm = await self.convert_message(data) + await self.handle_msg(abm) + # 启动客户端监听... + + async def convert_message(self, data: dict) -> AstrBotMessage: + abm = AstrBotMessage() + abm.type = MessageType.GROUP_MESSAGE + abm.session_id = data["session_id"] + abm.message_id = data["message_id"] + abm.sender = MessageMember(user_id=data["user_id"], nickname=data["nickname"]) + abm.message_str = data["content"] + abm.message = [Plain(text=data["content"])] + abm.raw_message = data + return abm + + async def handle_msg(self, message: AstrBotMessage): + event = MyPlatformEvent( + message_str=message.message_str, + message_obj=message, + platform_meta=self.meta(), + session_id=message.session_id, + client=self.client, + ) + self.commit_event(event) + + async def send_by_session(self, session: MessageSesion, message_chain: MessageChain): + # 实现发送逻辑... + await super().send_by_session(session, message_chain) + +class MyPlatformEvent(AstrMessageEvent): + def __init__(self, message_str, message_obj, platform_meta, session_id, client): + super().__init__(message_str, message_obj, platform_meta, session_id) + self.client = client + + async def send(self, message: MessageChain): + for comp in message.chain: + if isinstance(comp, Plain): + await self.client.send_text(self.get_sender_id(), comp.text) + await super().send(message) +``` + +## 注意事项 + +- `run()` 必须是阻塞方法,持续监听消息。 +- `convert_message()` 必须正确设置 `session_id`,它决定 LLM 上下文隔离。 +- `commit_event()` 用于提交事件到队列,不可遗漏。 +- 事件类必须实现 `send()` 方法,并在最后调用 `await super().send(message)`。 diff --git a/docs/snapshots/v4.24.4/platform_adapters/message_conversion.md b/docs/snapshots/v4.24.4/platform_adapters/message_conversion.md new file mode 100644 index 0000000..4d56d3c --- /dev/null +++ b/docs/snapshots/v4.24.4/platform_adapters/message_conversion.md @@ -0,0 +1,29 @@ +--- +category: platform_adapters +--- + +# 消息转换逻辑 (Message Conversion) + +`convert_message` 是适配器中最关键的方法,它负责将平台原始的消息格式映射到 AstrBot 的统一模型。 + +### 转换要求 + +在 `convert_message` 中,必须填充 `AstrBotMessage` 的以下核心字段: + +1. **`type`**: 识别是 `GROUP_MESSAGE` 还是 `FRIEND_MESSAGE`。 +2. **`session_id`**: 设置会话隔离。 +3. **`message_str`**: 提取纯文本内容。 +4. **`message`**: 将平台各段消息(如图片、表情)映射为 AstrBot 的 `MessageComponent` 列表。 +5. **`sender`**: 提取发送者的 ID 和昵称。 +6. **`raw_message`**: 保存原始对象。 + +### 提交事件 + +转换完成后,需将其封装为 `AstrMessageEvent` 并提交: + +```python +async def handle_raw_message(self, data): + bot_msg = self.convert_message(data) + event = AstrMessageEvent(bot_msg, self) # 或子类 + self.commit_event(event) +``` diff --git a/docs/snapshots/v4.24.4/platform_adapters/telegram_media_group.md b/docs/snapshots/v4.24.4/platform_adapters/telegram_media_group.md new file mode 100644 index 0000000..823c09e --- /dev/null +++ b/docs/snapshots/v4.24.4/platform_adapters/telegram_media_group.md @@ -0,0 +1,40 @@ +--- +title: Telegram 媒体组处理机制 (Telegram Media Group Handling) +type: feature +status: stable +last_updated: 2025-02-08 +related_base: platform_adapters/adapter_interface.md +--- + +## 概述 + +Telegram 平台在发送包含多张图片或视频的“相册”(Media Group)时,会将其拆分为多个独立的 Update 发送。AstrBot 的 Telegram 适配器实现了缓存与防抖机制,将这些碎片化的消息合并为单个 `AstrMessageEvent`,从而保证插件逻辑的一致性。 + +## 核心逻辑与参数 + +### 1. 收集与防抖机制 +适配器通过 `media_group_id` 识别属于同一相册的消息,并使用 `APScheduler` 进行异步调度处理: +- **`telegram_media_group_timeout` (默认 2.5s)**: 防抖延迟。每收到该组内的一条新消息,计时器都会重置。这是收集所有媒体项的窗口期。 +- **`telegram_media_group_max_wait` (默认 10.0s)**: 硬性超时上限。防止因消息流持续不断导致的无限延迟,达到此时间后将强制触发合并处理。 + +### 2. 消息合并策略 +在 `process_media_group` 方法中,系统执行以下合并逻辑: +- **基础元数据**: 以媒体组的第一条消息作为基准,保留其 `message_str`(通常是相册的 Caption)、回复关系(Reply Chain)和会话上下文。 +- **组件聚合**: 遍历组内所有后续消息,调用 `convert_message` 提取其媒体组件(如 `Image`, `Video`, `File`),并将其 `extend` 到基准消息的 `message` 列表(MessageChain)中。 +- **事件分发**: 合并完成后,仅提交一个封装了完整 `MessageChain` 的 `AstrMessageEvent` 到事件循环。 + +## 关键方法签名 + +- `handle_media_group_message(update, context)`: 拦截带有 `media_group_id` 的消息并管理缓存与调度任务。 +- `process_media_group(media_group_id)`: 核心合并函数,负责从缓存提取数据、重组 `AstrBotMessage` 并触发 `handle_msg`。 + +## 变更影响分析 + +- **插件开发者**: + - **事件密度变化**: 针对 Telegram 平台的相册消息,插件现在只会接收到一个 `AstrMessageEvent`。开发者应预期 `event.message` 列表中可能包含多个 `Image` 或 `Video` 组件。 + - **响应延迟**: 处理 Telegram 相册消息时会有至少 2.5s 的固有延迟,这是为了确保媒体收集完整,属于预期行为。 +- **适配器开发者**: + - 此机制展示了处理“流式/碎片化”平台消息的标准范式:`缓存 -> 防抖调度 -> 组件合并 -> 统一分发`。在接入类似具有媒体组概念的平台(如 Discord)时应参考此实现。 +- **边界情况**: + - 如果相册中的不同图片带有不同的文字说明(虽然 Telegram UI 通常只允许一个 Caption),目前逻辑仅保留第一条消息的文本。 + - 超过 `max_wait` 后到达的消息将被视为独立消息处理。 \ No newline at end of file diff --git a/docs/snapshots/v4.24.4/plugin-development-workflow.md b/docs/snapshots/v4.24.4/plugin-development-workflow.md new file mode 100644 index 0000000..dc33541 --- /dev/null +++ b/docs/snapshots/v4.24.4/plugin-development-workflow.md @@ -0,0 +1,133 @@ +# Plugin Development Workflow + +## 1. Scaffold or Inspect + +Expected plugin layout: + +```text +astrbot_plugin_example/ +├── main.py +├── metadata.yaml +├── _conf_schema.json # optional but recommended for settings/secrets +├── requirements.txt # optional dependencies +├── README.md +├── LICENSE # recommended for publishable plugins +├── .gitignore # ignore __pycache__, venvs, IDE state, logs +└── tools/ # optional LLM FunctionTool classes +``` + +Minimum `metadata.yaml` fields: + +```yaml +name: astrbot_plugin_example +display_name: Example +desc: Short user-facing description. +version: v0.1.0 +author: YourName +repo: https://github.com/owner/astrbot_plugin_example +``` + +Optional metadata: `support_platforms: [...]`, `tags: [...]`, `social_link: ...`, `astrbot_version: ">=4.5.0"`. + +Before scaffolding from memory, skim the structured reference entrypoint `references/offline/xunxiing-AstrBot-Skill/docs/REFERENCE.md` and the core concept map `references/offline/xunxiing-AstrBot-Skill/docs/design_standards/core_concepts.md`. + +## 2. Implement the Plugin Class + +```python +from astrbot.api import logger +from astrbot.api.event import AstrMessageEvent, filter +from astrbot.api.star import Context, Star + +class ExamplePlugin(Star): + def __init__(self, context: Context): + super().__init__(context) + + @filter.command("hello") + async def hello(self, event: AstrMessageEvent): + """Say hello to the sender.""" + logger.info("hello command triggered") + yield event.plain_result(f"Hello, {event.get_sender_name()}!") + + async def terminate(self): + """Clean up background tasks/resources when unloaded.""" +``` + +Rules: +- Handler methods live on the `Star` subclass and include `self` plus `event` unless the hook explicitly documents otherwise. +- Use `async def` for handlers and hooks; avoid blocking network/file calls. +- Include short docstrings for commands/tools because AstrBot surfaces them to users and agents. + +## 3. Listen to Events + +Common filters: +- `@filter.command("name")` for slash-style commands. +- `@filter.command_group("group")` then `@group.command("sub")` for grouped commands. +- `@filter.on_full_match(...)`, `@filter.on_prefix(...)`, `@filter.on_keyword(...)`, `@filter.on_regex(...)` for text triggers. +- `@filter.event_message_type(...)` to restrict private/group/all message types. +- `@filter.permission_type(...)` for permission-gated non-tool handlers. + +Special hooks such as `on_llm_request`, `on_llm_response`, `on_decorating_result`, and `after_message_sent` should send with `await event.send(...)` instead of yielding results. + +Do not mix hook layers: +- Plugin event hooks/decorators: `references/offline/xunxiing-AstrBot-Skill/docs/plugin_config/hooks.md`. +- Agent runner hooks (`BaseAgentRunHooks`): `references/offline/xunxiing-AstrBot-Skill/docs/agent/agent-related-hooks.md`. + +## 4. Work With Messages + +- Plain text input: `event.message_str`. +- Full message chain: `event.message_obj.message`. +- Raw platform payload: `event.message_obj.raw_message` for debugging and adapter-specific details. +- Components: import `astrbot.api.message_components as Comp` and build chains such as `Comp.Plain(...)`, `Comp.At(...)`, `Comp.Image(...)`, `Comp.Record(...)`, `Comp.Video(...)`, `Comp.Reply(...)`. + +Passive replies usually yield a result: + +```python +yield event.plain_result("done") +``` + +For richer output, return/yield message-chain results or call `event.chain_result([...])` when available in the target version. Active sends require a platform/session target; inspect existing plugin patterns or official docs before implementing. + +## 5. Add Configuration + +Use `_conf_schema.json` for editable plugin config. Prefer schema fields for API keys, feature toggles, limits, prompt templates, and provider/tool names. In code, read the config through the plugin/context pattern used by the target AstrBot version; never hard-code secrets or deployment-specific IDs. + +Use `StarTools.get_data_dir()` for persistent plugin files. Treat the returned value as a `Path`. + +## 6. Session and Conversation Control + +- Use `event.unified_msg_origin` to identify the current conversation origin when working with `conversation_manager`. +- Check `platform_settings.unique_session` behavior if the plugin relies on exact session IDs. +- Use the official `SessionController` patterns for custom session grouping; avoid inventing incompatible IDs. +- For conversation history, access `self.context.conversation_manager` and await its async methods. + +## 7. AI Calls and Tools + +Provider calls: +- Prefer provider/context abstractions documented for the target AstrBot version. +- Pass the relevant tools if the call should use plugin/MCP tools; get the LLM tool manager from context when needed. +- Surface provider/model selection as config when users may have multiple providers. + +Function tools: +- Prefer dataclass/class-based tools by subclassing `FunctionTool` and registering via `self.context.add_llm_tools(...)` on supported versions. +- For v4.5.7+ targets, cross-check the dataclass pattern in `references/offline/xunxiing-AstrBot-Skill/docs/design_standards/core_concepts.md`. +- For `@filter.llm_tool`, include a parseable docstring and typed parameters matching the documented JSON parameter schema. +- Do not combine `@filter.permission_type` with `@filter.llm_tool`; it is ineffective. + +## 8. HTML-to-Image + +Use AstrBot's text-to-image/HTML rendering helpers documented in the plugin guide when replies are too long or need layout. Keep templates local to the plugin, sanitize user-provided HTML/text, and provide a plain-text fallback for platforms that cannot send images. + +## 9. MCP and Skill Integration Basics + +- MCP tools are managed by AstrBot and can appear in the LLM tool manager; do not reimplement an MCP server inside a plugin unless the user asks. +- If a plugin depends on MCP tools, document setup commands and required environment variables in `README.md` and config schema. +- AstrBot Skills are uploaded as zipped skill folders and may execute in Local or Sandbox environments; plugins should treat them as agent capabilities, not as trusted local code. + +## 10. Debug and Validate + +- Log through `astrbot.api.logger`. +- During message parsing bugs, inspect both `event.message_obj.message` and `event.message_obj.raw_message`. +- Test command registration, config defaults, permission behavior, reload/unload via `terminate`, and platform-specific component support. +- Run `scripts/check_astrbot_plugin.py ` for static structure checks. + +When writing README/API docs for AI consumption, use `references/offline/xunxiing-AstrBot-Skill/docs4agent/REFERENCE.md`: keep docs minimal, code-first, structured, and focused on exact callable APIs. diff --git a/docs/snapshots/v4.24.4/plugin_config/command.md b/docs/snapshots/v4.24.4/plugin_config/command.md new file mode 100644 index 0000000..14578a5 --- /dev/null +++ b/docs/snapshots/v4.24.4/plugin_config/command.md @@ -0,0 +1,112 @@ +# 指令注册 (Commands) + +AstrBot 基于 `astrbot.api.event.filter` 提供一套装饰器用于注册指令和过滤消息。插件入口为 `self.context`。 + +--- + +## 基础注册 + +### @register +标记插件类,提供基础元数据。 + +> 不推荐使用,建议通过 `metadata.yaml` 配置插件元数据(更灵活且支持更多字段)。 + +```python +from astrbot.api.star import register, Star + +@register("demo", "Author", "示例插件", "1.0.0") +class DemoPlugin(Star): + pass +``` + +### @filter.command +注册指令,支持带参函数和别名。 + +```python +from astrbot.api.event import filter + +@filter.command("hello") +async def hello(self, event: AstrMessageEvent): + yield event.plain_result("你好!") + +# 带参数 +@filter.command("add") +async def add(self, event: AstrMessageEvent, a: int, b: int): + yield event.plain_result(f"结果:{a + b}") + +# 别名和优先级 +@filter.command("hi", alias=["嗨", "hey"], priority=10) +async def hi(self, event: AstrMessageEvent): + yield event.plain_result("Hi!") +``` + +| 参数 | 说明 | +|------|------| +| `name` | 指令名(不含前缀) | +| `alias` | 别名列表 | +| `priority` | 优先级,数值越大越高(默认 0) | + +### @filter.command_group +注册指令组,子指令通过 `@组名.command` 注册。 + +```python +@filter.command_group("manage") +class ManageCommands: + @manage.command("list") + async def list_items(self, event): + yield event.plain_result("列表") + + @manage.command("delete") + async def delete_item(self, event, id: int): + yield event.plain_result(f"删除 {id}") +``` + +--- + +## 消息过滤 + +过滤器遵循 **AND 逻辑**,所有条件满足时才触发。 + +| 装饰器 | 说明 | 参数 | +|--------|------|------| +| `@filter.event_message_type(type)` | 消息类型筛选 | `ALL`, `PRIVATE_MESSAGE`, `GROUP_MESSAGE` | +| `@filter.platform_adapter_type(type)` | 平台适配器筛选 | `AIOCQHTTP`, `TELEGRAM`, `GEWECHAT` 等 | +| `@filter.permission_type(type)` | 权限筛选 | `ADMIN`, `MEMBER` | +| `@filter.regex(pattern)` | 正则匹配内容 | 正则字符串 | + +```python +@filter.command("admin") +@filter.permission_type(filter.PermissionType.ADMIN) +async def admin_cmd(self, event: AstrMessageEvent): + yield event.plain_result("管理员专用") + +@filter.command("group") +@filter.event_message_type(filter.EventMessageType.GROUP_MESSAGE) +async def group_cmd(self, event: AstrMessageEvent): + yield event.plain_result("群聊专用") + +# 多平台组合(按位或 | ) +@filter.command("multi") +@filter.platform_adapter_type( + filter.PlatformAdapterType.AIOCQHTTP | filter.PlatformAdapterType.TELEGRAM +) +async def multi_cmd(self, event: AstrMessageEvent): + yield event.plain_result("多平台") +``` + +--- + +## 运行时管理 + +Dashboard 支持动态修改指令权限和启用状态。装饰器定义的静态配置仅作为初始默认值。 + +| 优先级 | 来源 | +|--------|------| +| 高 | Dashboard 动态配置 `alter_cmd` | +| 低 | 装饰器静态定义 | + +``` +alter_cmd -> {plugin_name} -> {handler_name} -> { "permission": "admin" | "member" } +``` + +> **注意事项**:调试权限问题时优先检查 Dashboard 的动态配置;指令名不应包含空格。 diff --git a/docs/snapshots/v4.24.4/plugin_config/schema.md b/docs/snapshots/v4.24.4/plugin_config/schema.md new file mode 100644 index 0000000..8be8d00 --- /dev/null +++ b/docs/snapshots/v4.24.4/plugin_config/schema.md @@ -0,0 +1,154 @@ +# 配置 Schema (`_conf_schema.json`) + +AstrBot 通过 Schema 实现配置的自动解析与 WebUI 可视化。在插件目录添加 `_conf_schema.json` 文件定义配置结构。 + +--- + +## 基础字段 + +| 字段 | 类型 | 说明 | +|------|------|------| +| `type` | **必填** | `string`, `text`, `int`, `float`, `bool`, `object`, `list`, `dict`, `template_list`, `file` | +| `description` | string | 配置描述 | +| `hint` | string | 悬浮提示 | +| `obvious_hint` | bool | 是否显眼显示 hint | +| `default` | 任意 | 默认值 | +| `options` | list | 下拉选项列表 | +| `invisible` | bool | 是否隐藏(默认 false) | + +--- + +## 特殊类型 + +### text +多行文本输入,可拖拽调整高度。 + +### dict +键值对编辑,支持 `template_schema` 定义子项: + +```json +{ + "custom_params": { + "type": "dict", + "description": "自定义参数", + "template_schema": { + "temperature": { + "type": "float", + "default": 0.6, + "slider": {"min": 0, "max": 2, "step": 0.1} + } + } + } +} +``` + +### template_list +多组重复配置(v4.10.4+): + +```json +{ + "providers": { + "type": "template_list", + "description": "API 供应商列表", + "templates": { + "openai": { + "name": "OpenAI", + "items": { + "api_key": {"type": "string", "default": "sk-xxxx"}, + "model": {"type": "string", "default": "gpt-4"} + } + } + } + } +} +``` + +存储格式(带 `__template_key` 标识): + +```json +{ + "providers": [ + {"__template_key": "openai", "api_key": "sk-xxx", "model": "gpt-4"} + ] +} +``` + +### file +文件上传(v4.13.0+): + +```json +{ + "uploads": { + "type": "file", + "description": "上传文件", + "file_types": [".pdf", ".docx"], + "default": [] + } +} +``` + +文件存储位置:`data/plugins//files//` + +--- + +## 内置选择器 + +通过 `_special` 字段调用 AstrBot 内置的数据选择(v4.0.0+): + +| 值 | 返回类型 | 说明 | +|-----|---------|------| +| `select_provider` | string | 选择模型提供商 | +| `select_provider_tts` | string | 选择 TTS 提供商 | +| `select_provider_stt` | string | 选择 STT 提供商 | +| `select_persona` | string | 选择人格 | +| `select_knowledgebase` | list | 选择知识库(多选) | + +示例: + +```json +{ + "model": { + "type": "string", + "description": "默认模型", + "_special": "select_provider" + }, + "persona": { + "type": "string", + "description": "使用的人格", + "_special": "select_persona" + }, + "kb_list": { + "type": "list", + "description": "知识库列表", + "_special": "select_knowledgebase", + "default": [] + } +} +``` + +--- + +## 在插件中使用 + +```python +from astrbot.api import AstrBotConfig + +class MyPlugin(Star): + def __init__(self, context: Context, config: AstrBotConfig): + super().__init__(context) + self.config = config + + # 读取配置 + api_key = self.config.get("api_key") + + # 保存配置(修改后调用) + # self.config.save_config() +``` + +--- + +## 配置更新机制 + +- 自动添加缺失的默认值 +- 自动移除 Schema 中不存在的配置项 +- 更新 `_conf_schema.json` 后重载插件生效 diff --git a/docs/snapshots/v4.24.4/plugin_config/session_control.md b/docs/snapshots/v4.24.4/plugin_config/session_control.md new file mode 100644 index 0000000..16fcbcc --- /dev/null +++ b/docs/snapshots/v4.24.4/plugin_config/session_control.md @@ -0,0 +1,106 @@ +# 会话控制 (Session Control) + +AstrBot 提供开箱即用的会话控制功能,适用于多轮对话场景(如成语接龙、问答式交互)。 + +--- + +## 快速入口 + +```python +from astrbot.core.utils.session_waiter import session_waiter, SessionController +``` + +--- + +## @session_waiter + +用于定义一个等待用户输入的异步函数,超时会抛出 `TimeoutError`。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| `timeout` | float | 必填,超时时间(秒) | +| `record_history_chains` | bool | 是否记录消息历史(默认 False) | + +```python +@filter.command("成语接龙") +async def idiom_game(self, event: AstrMessageEvent): + yield event.plain_result("请发送一个成语~") + + @session_waiter(timeout=60) + async def waiter(controller: SessionController, event: AstrMessageEvent): + text = event.message_str + + if text == "退出": + await event.send(event.plain_result("已退出游戏~")) + controller.stop() # 立即结束会话 + return + + if len(text) != 4: + await event.send(event.plain_result("必须是四字成语!")) + return # 返回等待下一次输入 + + # ...处理逻辑 + controller.keep(timeout=60, reset_timeout=True) # 重置超时 + + try: + await waiter(event) + except TimeoutError: + yield event.plain_result("超时了!") +``` + +--- + +## SessionController + +用于控制会话状态和获取历史消息。 + +### keep() +保持会话,可选择重置超时时间。 + +```python +controller.keep(timeout=60, reset_timeout=True) +``` + +- `reset_timeout=True`: 重置为新的 timeout 值(必须 > 0) +- `reset_timeout=False`: 在剩余时间基础上增加(可 < 0) + +### stop() +立即终止会话。 + +```python +controller.stop() +``` + +### get_history_chains() +获取已记录的消息历史(需先设置 `record_history_chains=True`)。 + +```python +history = controller.get_history_chains() # List[List[Comp.BaseMessageComponent]] +``` + +--- + +## 自定义会话隔离(SessionFilter) + +默认基于 `sender_id` 识别不同会话。通过继承 `SessionFilter` 可自定义隔离范围(如按群组拦截): + +```python +from astrbot.core.utils.session_waiter import SessionFilter + +class GroupFilter(SessionFilter): + def filter(self, event: AstrMessageEvent) -> str: + # 按群组 ID 隔离,整个群共用一个会话 + return event.get_group_id() or event.unified_msg_origin + +# 使用 +await waiter(event, session_filter=GroupFilter()) +``` + +--- + +## 注意事项 + +1. 会话内必须使用 `await event.send()` 发消息,不能用 `yield` +2. 超时后会抛出 `TimeoutError`,需用 try/except 捕获 +3. 不执行 `stop()` 或 `keep()` 时,函数返回后会话继续保持 +4. 可用来实现群内组队功能(群级会话) diff --git a/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/.github/workflows/release.yml b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/.github/workflows/release.yml new file mode 100644 index 0000000..d9991dd --- /dev/null +++ b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/.github/workflows/release.yml @@ -0,0 +1,107 @@ +name: Auto Release + +on: + push: + branches: [main] + paths: + - 'metadata.yaml' + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Extract version from metadata.yaml + id: get_version + run: | + # 提取版本号(去除 # 后面的注释) + VERSION=$(grep -E '^version:' metadata.yaml | sed 's/version: *//' | sed 's/ *#.*//' | tr -d ' ') + echo "version=$VERSION" >> $GITHUB_OUTPUT + echo "Extracted version: $VERSION" + + - name: Check if release exists + id: check_release + run: | + if gh release view ${{ steps.get_version.outputs.version }} &>/dev/null; then + echo "exists=true" >> $GITHUB_OUTPUT + echo "Release ${{ steps.get_version.outputs.version }} already exists" + else + echo "exists=false" >> $GITHUB_OUTPUT + echo "Release ${{ steps.get_version.outputs.version }} does not exist" + fi + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract changelog for version + if: steps.check_release.outputs.exists == 'false' + id: get_changelog + run: | + VERSION="${{ steps.get_version.outputs.version }}" + echo "Looking for version: $VERSION" + + # 创建 Python 脚本文件来提取 changelog + cat > extract_changelog.py << 'PYTHON_SCRIPT' + import re + import sys + + version = sys.argv[1] + + try: + with open('CHANGELOG.md', 'r', encoding='utf-8') as f: + content = f.read() + except FileNotFoundError: + print('修复了一些已知问题') + sys.exit(0) + + # 匹配指定版本的内容 (匹配 ## [vX.Y.Z] 到下一个 ## [ 或文件结尾) + pattern = rf'## \[{re.escape(version)}\]\s*-\s*\d{{4}}-\d{{2}}-\d{{2}}\s*\n(.*?)(?=\n## \[|\Z)' + match = re.search(pattern, content, re.DOTALL) + + if match: + changelog = match.group(1).strip() + if changelog: + print(changelog) + else: + print('修复了一些已知问题') + else: + print('修复了一些已知问题') + PYTHON_SCRIPT + + # 执行 Python 脚本并将输出写入文件 + python3 extract_changelog.py "$VERSION" > changelog_output.txt + + # 读取文件内容到变量 + CHANGELOG=$(cat changelog_output.txt) + + # 如果 changelog 为空,使用默认提示 + if [ -z "$CHANGELOG" ]; then + CHANGELOG="修复了一些已知问题" + fi + + echo "Extracted changelog:" + echo "$CHANGELOG" + + # 写入 GitHub Actions 输出 + { + echo "changelog<> $GITHUB_OUTPUT + + # 清理临时文件 + rm -f extract_changelog.py changelog_output.txt + + - name: Create Release + if: steps.check_release.outputs.exists == 'false' + uses: softprops/action-gh-release@v1 + with: + tag_name: ${{ steps.get_version.outputs.version }} + name: ${{ steps.get_version.outputs.version }} + body: ${{ steps.get_changelog.outputs.changelog }} + generate_release_notes: false + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/.gitignore b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/.gitignore new file mode 100644 index 0000000..b7faf40 --- /dev/null +++ b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/.gitignore @@ -0,0 +1,207 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock +#poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +#pdm.lock +#pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +#pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Cursor +# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to +# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data +# refer to https://docs.cursor.com/context/ignore-files +.cursorignore +.cursorindexingignore + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ diff --git a/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/CHANGELOG.md b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/CHANGELOG.md new file mode 100644 index 0000000..2fcf716 --- /dev/null +++ b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [1.0.0] - 2025-01-01 + +### Added + +- Initial release of the plugin +- Basic greeting command `hello` +- Echo command with parameter support diff --git a/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/LICENSE b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/LICENSE new file mode 100644 index 0000000..3423cec --- /dev/null +++ b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) 2022-2099 AstrBot Plugin Authors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/README.md b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/README.md new file mode 100644 index 0000000..5e0463f --- /dev/null +++ b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/README.md @@ -0,0 +1,14 @@ +# astrbot-plugin-helloworld + +AstrBot 插件模板 / A template plugin for AstrBot plugin feature + +> [!NOTE] +> This repo is just a template of [AstrBot](https://github.com/AstrBotDevs/AstrBot) Plugin. +> +> [AstrBot](https://github.com/AstrBotDevs/AstrBot) is an agentic assistant for both personal and group conversations. It can be deployed across dozens of mainstream instant messaging platforms, including QQ, Telegram, Feishu, DingTalk, Slack, LINE, Discord, Matrix, etc. In addition, it provides a reliable and extensible conversational AI infrastructure for individuals, developers, and teams. Whether you need a personal AI companion, an intelligent customer support agent, an automation assistant, or an enterprise knowledge base, AstrBot enables you to quickly build AI applications directly within your existing messaging workflows. + +# Supports + +- [AstrBot Repo](https://github.com/AstrBotDevs/AstrBot) +- [AstrBot Plugin Development Docs (Chinese)](https://docs.astrbot.app/dev/star/plugin-new.html) +- [AstrBot Plugin Development Docs (English)](https://docs.astrbot.app/en/dev/star/plugin-new.html) diff --git a/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/_conf_schema.json b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/_conf_schema.json new file mode 100644 index 0000000..ce7bb4d --- /dev/null +++ b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/_conf_schema.json @@ -0,0 +1,20 @@ +{ + "enable_greeting": { + "type": "bool", + "default": true, + "hint": "启用打招呼功能" + }, + "greeting_message": { + "type": "string", + "default": "你好!我是示例插件~", + "hint": "打招呼时发送的消息" + }, + "admin_users": { + "type": "list", + "items": { + "type": "string" + }, + "default": [], + "hint": "管理员用户 ID 列表" + } +} diff --git a/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/main.py b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/main.py new file mode 100644 index 0000000..91b0953 --- /dev/null +++ b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/main.py @@ -0,0 +1,23 @@ +from astrbot.api.event import filter, AstrMessageEvent +from astrbot.api.star import Context, Star +from astrbot.api import logger + +class MyPlugin(Star): + def __init__(self, context: Context): + super().__init__(context) + + async def initialize(self): + """可选择实现异步的插件初始化方法,当实例化该插件类之后会自动调用该方法。""" + + # 注册指令的装饰器。指令名为 helloworld。注册成功后,发送 `/helloworld` 就会触发这个指令,并回复 `你好, {user_name}!` + @filter.command("helloworld") + async def helloworld(self, event: AstrMessageEvent): + """这是一个 hello world 指令""" # 这是 handler 的描述,将会被解析方便用户了解插件内容。建议填写。 + user_name = event.get_sender_name() + message_str = event.message_str # 用户发的纯文本消息字符串 + message_chain = event.get_messages() # 用户所发的消息的消息链 # from astrbot.api.message_components import * + logger.info(message_chain) + yield event.plain_result(f"Hello, {user_name}, 你发了 {message_str}!") # 发送一条纯文本消息 + + async def terminate(self): + """可选择实现异步的插件销毁方法,当插件被卸载/停用时会调用。""" diff --git a/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/metadata.yaml b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/metadata.yaml new file mode 100644 index 0000000..985a56f --- /dev/null +++ b/docs/snapshots/v4.24.4/script/astrbot-plugin-demo/metadata.yaml @@ -0,0 +1,7 @@ +name: astrbot_plugin_helloworld # 插件唯一识别名,以 astrbot_plugin_ 前缀开头 +display_name: helloworld # 用于展示的名字,可以是方便人类阅读的名字(需要版本 >= v4.5.0,低版本不会报错,请放心填写) +desc: AstrBot 插件示例。 # 插件简短描述 +short_desc: AstrBot 插件示例。 +version: v1.3.0 # 插件版本号。格式:v1.1.1 或者 v1.1 +author: Soulter # 作者 +repo: https://github.com/Soulter/helloworld # 插件的仓库地址 diff --git a/docs/snapshots/v4.24.4/webui/plugin-pages.md b/docs/snapshots/v4.24.4/webui/plugin-pages.md new file mode 100644 index 0000000..1c0e472 --- /dev/null +++ b/docs/snapshots/v4.24.4/webui/plugin-pages.md @@ -0,0 +1,131 @@ +# 插件 Pages + +AstrBot 支持插件通过 `pages/` 目录暴露 Dashboard 页面。`pages/` 下的每个一级子目录都是一个独立 Page: + +```text +astrbot_plugin_page_demo/ +├─ main.py +└─ pages/ + ├─ bridge-demo/ + │ ├─ index.html + │ ├─ app.js + │ ├─ style.css + │ └─ assets/ + │ └─ logo.svg + └─ settings/ + └─ index.html +``` + +AstrBot 会扫描 `pages//index.html`;没有 `index.html` 的目录会被忽略。 + +如果只是让用户填写几个配置项,优先使用 [`_conf_schema.json`](./plugin-config.md)。插件 Pages 更适合复杂表单、Dashboard、日志、文件上传下载、SSE 和自定义交互流程。 + +## 最小前端示例 + +`pages/bridge-demo/index.html` + +```html + + + + + Plugin Page Demo + + + + +

+    
+  
+
+```
+
+`pages/bridge-demo/app.js`
+
+```js
+const bridge = window.AstrBotPluginPage;
+const output = document.getElementById("output");
+
+const context = await bridge.ready();
+output.textContent = JSON.stringify(context, null, 2);
+
+document.getElementById("ping").addEventListener("click", async () => {
+  const result = await bridge.apiGet("ping");
+  output.textContent = JSON.stringify(result, null, 2);
+});
+```
+
+这里不需要手动引入 bridge SDK。AstrBot 会在返回的 HTML 里自动插入 `/api/plugin/page/bridge-sdk.js`。
+
+## 注册后端 API
+
+前端调用 `bridge.apiGet("ping")` 时,Dashboard 会转发到:
+
+```text
+/api/plug//ping
+```
+
+因此注册 Web API 时,路由必须带上插件名作为前缀:
+
+```python
+from quart import jsonify
+from astrbot.api.star import Context, Star
+
+PLUGIN_NAME = "astrbot_plugin_page_demo"
+
+
+class MyPlugin(Star):
+    def __init__(self, context: Context):
+        super().__init__(context)
+        context.register_web_api(
+            f"/{PLUGIN_NAME}/ping",
+            self.page_ping,
+            ["GET"],
+            "Page ping",
+        )
+
+    async def page_ping(self):
+        return jsonify({"message": "pong"})
+```
+
+## Bridge API
+
+插件 Page 中可直接使用 `window.AstrBotPluginPage`:
+
+- `ready()`: 等待 bridge 就绪并返回上下文
+- `getContext()`: 读取当前上下文
+- `apiGet(endpoint, params)`: 发送 GET 请求
+- `apiPost(endpoint, body)`: 发送 POST 请求
+- `upload(endpoint, file)`: 以 `multipart/form-data` 上传单个文件
+- `download(endpoint, params, filename)`: 下载后端响应
+- `subscribeSSE(endpoint, handlers, params)`: 订阅 SSE
+- `unsubscribeSSE(subscriptionId)`: 取消 SSE 订阅
+
+当前 `ready()` 上下文类似:
+
+```json
+{
+  "pluginName": "astrbot_plugin_page_demo",
+  "displayName": "Plugin Page Demo"
+}
+```
+
+`endpoint` 必须是插件内相对路径,不能为空,不能包含 `\`、URL scheme、query、hash,也不能包含 `.` 或 `..` 路径片段。
+
+## 静态资源路径规则
+
+AstrBot 会重写相对资源路径,并自动补上短期 `asset_token`。你只需要正常写相对路径,不要自己拼接 `/api/plugin/page/content/...`。
+
+AstrBot 会重写:
+
+- HTML `src` 和 `href`
+- CSS `url(...)`
+- JavaScript `import`
+- JavaScript `export ... from`
+- JavaScript 动态 `import()`
+
+建议把静态资源写成 `./style.css`、`./assets/logo.svg` 这类相对路径。不要手动追加 `asset_token`,也不要依赖 `..` 逃逸 Page 根目录。
+
+如果你构建 SPA,建议使用 hash routing。静态资源服务按真实文件路径解析;history routing 刷新页面时需要对应路径上真的存在文件。
+
+
diff --git a/scripts/state.json b/scripts/state.json
index 5a19011..2bb03c8 100644
--- a/scripts/state.json
+++ b/scripts/state.json
@@ -1,4 +1,4 @@
 {
-    "last_commit_sha": "06fd2d2428dd1333eca30447f6c5329fa7686144",
-    "last_tag": "v4.20.0"
+    "last_commit_sha": "e05dd650ab4bc37df1edcf4884326a46baec5362",
+    "last_tag": "v4.24.4"
 }
\ No newline at end of file