### Install and Start AstrBot with uv Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/package.md Use `uv tool install` to get AstrBot. Run `astrbot init` once for initial setup, then `astrbot` to start the application. ```bash uv tool install astrbot astrbot init # 只需要在第一次部署时执行,后续启动不需要执行 astrbot ``` -------------------------------- ### Install Arxiv MCP Server Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/use/mcp.md Example command to install and run the Arxiv MCP server using uv. The --storage-path argument specifies where the server will store its data. ```json { "command": "uv", "args": [ "tool", "run", "arxiv-mcp-server", "--storage-path", "data/arxiv" ] } ``` -------------------------------- ### Send Video Message Example Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/guides/send-message.md Example demonstrating sending video messages using `Video.fromFileSystem` and `Video.fromURL`. ```python from astrbot.api.event import filter, AstrMessageEvent @filter.command("test") async def test(self, event: AstrMessageEvent): from astrbot.api.message_components import Video # fromFileSystem 需要用户的协议端和机器人端处于一个系统中。 music = Video.fromFileSystem( path="test.mp4" ) # 更通用 music = Video.fromURL( url="https://example.com/video.mp4" ) yield event.chain_result([music]) ``` -------------------------------- ### Install CasaOS Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/casaos.md Run this command to install CasaOS on your system. ```bash curl -fsSL https://get.casaos.io | sudo bash ``` -------------------------------- ### Install Dependencies and Run with uv Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/cli.md Recommended method using `uv` to synchronize dependencies and run the main script. Use `--no-sync` for subsequent runs if plugins are installed. ```bash uv sync uv run main.py ``` ```bash uv run --no-sync main.py ``` -------------------------------- ### Install Dependencies and Run with venv (Mac/Linux/WSL) Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/cli.md Activates the virtual environment and installs dependencies from `requirements.txt` using a specified mirror, then runs the main script. ```bash source venv/bin/activate python -m pip install -r requirements.txt -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple python main.py ``` -------------------------------- ### Install Dependencies and Run with venv (Windows) Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/cli.md Activates the virtual environment and installs dependencies from `requirements.txt` using a specified mirror, then runs the main script. ```bash venv\Scripts\activate python -m pip install -r requirements.txt -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple python main.py ``` -------------------------------- ### Install Astrbot from AUR Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/sys-pm.md Use an AUR helper like paru or yay to install the git version of Astrbot. During the process, you will be prompted to review the build steps; press 'q' to quit the review and continue with the installation. The data directory will be fixed at ~/.local/share/astrbot. ```bash paru -S astrbot-git # 提示: # 开始审阅步骤,按q可退出审阅,继续安装 # 安装后数据目录固定在:~/.local/share/astrbot ``` -------------------------------- ### Configuration Management Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/plugin.md Demonstrates how to get the default configuration and session-specific configurations. ```APIDOC ## Configuration Management ### Default Configuration ```py config = self.context.get_config() ``` It is not recommended to modify the default configuration; it is recommended to only read it. ### Session Configuration After v4.0.0, AstrBot supports session-level multi-configuration files. ```py umo = event.unified_msg_origin config = self.context.get_config(umo=umo) ``` ``` -------------------------------- ### Enable Astrbot to Start on Boot Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/sys-pm.md Enable the Astrbot service to start automatically on system boot. It is designed to run as a user service for security reasons. You can also enable and start it immediately using the --now flag. ```bash systemctl --user enable astrbot.service # 如果需要立即启动,加上--now # systemctl --user enable --now astrbot.service ``` -------------------------------- ### Install uv with Docker Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/use/mcp.md Use this command to install the uv tool within a Docker container running AstrBot. ```bash docker exec astrbot python -m pip install uv ``` -------------------------------- ### Start AstrBot and Ollama Services Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/compshare.md Execute this command in the JupyterLab terminal after deploying the AstrBot image to start the services. Ensure you are in the root directory. ```bash cd ./astrbot_booter.sh ``` -------------------------------- ### Start Astrbot Service Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/sys-pm.md Start the Astrbot service using systemctl. This is recommended for features like automatic restarts and log rotation. ```bash systemctl --user start astrbot.service ``` -------------------------------- ### Successful Service Startup Confirmation Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/compshare.md This output indicates that both AstrBot and Ollama services have started successfully in the background after running the boot script. ```txt (py312) root@f8396035c96d:/workspace# cd ./astrbot_booter.sh Starting AstrBot... Starting ollama... Both services started in the background. ``` -------------------------------- ### Simple "Hello World" Command Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/en/dev/star/guides/listen-message-event.md Implement a basic command that responds with a greeting. This example shows how to access sender information and message content within a command handler. ```python from astrbot.api.event import filter, AstrMessageEvent from astrbot.api.star import Context, Star class MyPlugin(Star): def __init__(self, context: Context): super().__init__(context) @filter.command("helloworld") # from astrbot.api.event.filter import command async def helloworld(self, event: AstrMessageEvent): '''This is a hello world command''' user_name = event.get_sender_name() message_str = event.message_str # Get the plain text content of the message yield event.plain_result(f"Hello, {user_name}!") ``` -------------------------------- ### Linux One-Click Deployment Script (curl) Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/community-deployment.md Use this command to download and execute the AstrBot installation script directly on Linux systems. Ensure curl is installed. ```bash bash <(curl -sSL https://raw.githubusercontent.com/zhende1113/Antlia/refs/heads/main/Script/AstrBot/Antlia.sh) ``` -------------------------------- ### Call Agent with tool_loop_agent Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/guides/ai.md Demonstrates how to invoke an agent using the `tool_loop_agent` method. This example sets up a system prompt for the main agent and initiates a task related to weather information. ```python @filter.command("test") async def test(self, event: AstrMessageEvent): umo = event.unified_msg_origin prov_id = await self.context.get_current_chat_provider_id(umo) llm_resp = await self.context.tool_loop_agent( event=event, chat_provider_id=prov_id, prompt="Test calling sub-agent for Beijing's weather information.", system_prompt=( "You are the main agent. Your task is to delegate tasks to sub-agents based on user queries." ``` -------------------------------- ### Running an Ollama Model Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/providers/provider-ollama.md Execute this command to start an interactive session with a downloaded Ollama model. Replace `` with the model you wish to run. ```bash ollama run ``` -------------------------------- ### Delegate Task with AssignAgentTool Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/guides/ai.md Before delegating, use the 'assign_agent' tool to determine which sub-agent is best suited for the task. This example shows how to set up a toolset including sub-agents and the AssignAgentTool. ```python from astrbot.agents.agent import Agent from astrbot.agents.agent_tool import AgentTool from astrbot.agents.tool_set import ToolSet class SubAgent1(Agent): pass class SubAgent2(Agent): pass class AssignAgentTool(AgentTool): pass llm_resp = Agent( """Before delegating, use the 'assign_agent' tool to determine which sub-agent is best suited for the task." ), tools=ToolSet([SubAgent1(), SubAgent2(), AssignAgentTool()]), max_steps=30, ) yield event.plain_result(llm_resp.completion_text) ``` -------------------------------- ### Deploy AstrBot Standalone Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/kubernetes.md Apply the Kubernetes manifests for namespace, persistent volume claim, and deployment for the standalone AstrBot setup. ```bash # 1. 创建命名空间 kubectl apply -f k8s/astrbot/00-namespace.yaml ``` ```bash # 2. 创建持久化存储卷 kubectl apply -f k8s/astrbot/01-pvc.yaml ``` ```bash # 3. 部署应用 kubectl apply -f k8s/astrbot/02-deployment.yaml ``` -------------------------------- ### Define HelloWorldTool Class Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/plugin.md Example of defining a function tool as a class, inheriting from `FunctionTool`. It includes name, description, parameters, and a `run` method. ```python from astrbot.api import FunctionTool from astrbot.api.event import AstrMessageEvent from dataclasses import dataclass, field @dataclass class HelloWorldTool(FunctionTool): name: str = "hello_world" # 工具名称 description: str = "Say hello to the world." # 工具描述 parameters: dict = field( default_factory=lambda: { "type": "object", "properties": { "greeting": { "type": "string", "description": "The greeting message.", }, }, "required": ["greeting"], } ) # 工具参数定义,见 OpenAI 官网或 https://json-schema.org/understanding-json-schema/ async def run( self, event: AstrMessageEvent, # 必须包含此 event 参数在前面,用于获取上下文 greeting: str, # 工具参数,必须与 parameters 中定义的参数名一致 ): return f"{greeting}, World!" # 也支持 mcp.types.CallToolResult 类型 ``` -------------------------------- ### Install Node.js and NVM in Docker Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/use/mcp.md Commands to install Node.js version 22 and its package manager npm within a Docker container. Ensure AstrBot is restarted after installation to apply new environment variables. ```bash sudo docker exec -it astrbot /bin/bash apt update && apt install curl -y export NVM_NODEJS_ORG_MIRROR=http://nodejs.org/dist # Download and install nvm: curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.2/install.sh | bash \. "$HOME/.nvm/nvm.sh" nvm install 22 # Verify version: node -v nvm current npm -v npx -v ``` -------------------------------- ### Initialize Plugin with Configuration Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/guides/plugin-config.md This snippet shows how to initialize a plugin class, receiving the `AstrBotConfig` object which inherits dictionary methods. The configuration can be accessed and optionally saved. ```python from astrbot.api import AstrBotConfig class ConfigPlugin(Star): def __init__(self, context: Context, config: AstrBotConfig): # AstrBotConfig 继承自 Dict,拥有字典的所有方法 super().__init__(context) self.config = config print(self.config) # 支持直接保存配置 # self.config.save_config() # 保存配置 ``` -------------------------------- ### 模拟消息平台客户端 SDK Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/en/dev/plugin-platform-adapter.md 此代码模拟了一个消息平台客户端,包含接收消息和发送消息的方法。`start_polling` 方法用于模拟接收消息的逻辑。 ```python import asyncio class FakeClient(): '''模拟一个消息平台,这里 5 秒钟下发一个消息''' def __init__(self, token: str, username: str): self.token = token self.username = username # ... async def start_polling(self): while True: await asyncio.sleep(5) await getattr(self, 'on_message_received')({ 'bot_id': '123', 'content': '新消息', 'username': 'zhangsan', 'userid': '123', 'message_id': 'asdhoashd', 'group_id': 'group123', }) async def send_text(self, to: str, message: str): print('发了消息:', to, message) async def send_image(self, to: str, image_path: str): print('发了消息:', to, image_path) ``` -------------------------------- ### 最小插件实例 Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/plugin.md 一个继承自 Star 基类的最小插件实例,包含一个 'helloworld' 指令。 ```python from astrbot.api.event import filter, AstrMessageEvent, MessageEventResult from astrbot.api.star import Context, Star from astrbot.api import logger # 使用 astrbot 提供的 logger 接口 class MyPlugin(Star): def __init__(self, context: Context): super().__init__(context) # 注册指令的装饰器。指令名为 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 # 获取消息的纯文本内容 logger.info("触发hello world指令!") yield event.plain_result(f"Hello, {user_name}!") # 发送一条纯文本消息 async def terminate(self): '''可选择实现 terminate 函数,当插件被卸载/停用时会调用。''' ``` -------------------------------- ### Configure Python Command in Legacy Windows Installer Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/en/deploy/astrbot/launcher.md Edit the legacy Windows installer script to specify a custom Python interpreter path or command. This is useful if the default 'python' command is not found or if you need to use a specific Python version. ```batch set PYTHON_CMD=python ``` -------------------------------- ### 创建简单的 'helloworld' 指令 Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/guides/listen-message-event.md 演示如何创建一个简单的指令,当用户输入 'helloworld' 时,机器人会回复 'Hello, [用户名]!'。 ```python from astrbot.api.event import filter, AstrMessageEvent from astrbot.api.star import Context, Star class MyPlugin(Star): def __init__(self, context: Context): super().__init__(context) @filter.command("helloworld") # from astrbot.api.event.filter import command async def helloworld(self, event: AstrMessageEvent): '''这是 hello world 指令''' user_name = event.get_sender_name() message_str = event.message_str # 获取消息的纯文本内容 yield event.plain_result(f"Hello, {user_name}!") ``` -------------------------------- ### Get All Loaded Plugins Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/plugin.md Retrieves metadata for all loaded plugins. ```APIDOC ## Get All Loaded Plugins ```py plugins = self.context.get_all_stars() # Returns StarMetadata containing plugin instances, configurations, etc. ``` ``` -------------------------------- ### Plugin Configuration and Dynamic Saving (Python) Source: https://context7.com/astrbotdevs/astrbot-docs/llms.txt Example of a plugin reading configuration values like API key, mode, and timeout from AstrBotConfig. It also demonstrates dynamically changing a configuration value ('mode') and saving it. ```python from astrbot.api import AstrBotConfig from astrbot.api.event import filter, AstrMessageEvent from astrbot.api.star import Context, Star class MyPlugin(Star): def __init__(self, context: Context, config: AstrBotConfig): super().__init__(context) self.config = config api_key = self.config.get("api_key", "") mode = self.config.get("mode", "chat") timeout = self.config.get("advanced", {}).get("timeout", 30) @filter.command("status") async def status(self, event: AstrMessageEvent): mode = self.config.get("mode", "chat") yield event.plain_result(f"当前模式: {mode}") # 动态修改并保存配置 self.config["mode"] = "agent" self.config.save_config() ``` -------------------------------- ### Get All Loaded Platforms Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/plugin.md Retrieves a list of all loaded platform instances. ```APIDOC ## Get All Loaded Platforms ```py from astrbot.api.platform import Platform platforms = self.context.platform_manager.get_insts() # List[Platform] ``` ``` -------------------------------- ### Get Message Platform Instance Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/plugin.md Shows how to obtain a message platform instance, specifically for aiocqhttp, after v3.4.34. ```APIDOC ## Get Message Platform Instance > After v3.4.34 ```py from astrbot.api.event import filter, AstrMessageEvent @filter.command("test") async def test_(self, event: AstrMessageEvent): from astrbot.api.platform import AiocqhttpAdapter # Other platforms are similar platform = self.context.get_platform(filter.PlatformAdapterType.AIOCQHTTP) assert isinstance(platform, AiocqhttpAdapter) # platform.get_client().api.call_action() ``` ``` -------------------------------- ### Linux Docker-based Deployment Script (wget) Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/community-deployment.md An alternative method for Docker-based AstrBot and NapCat deployment using wget. Download the script, make it executable, and run with sudo. The --no-color option can be used to disable colored output. ```bash wget -qO AstrbotScript.sh https://raw.githubusercontent.com/railgun19457/AstrbotScript/main/AstrbotScript.sh ``` ```bash chmod +x AstrbotScript.sh ``` ```bash sudo ./AstrbotScript.sh ``` ```bash sudo ./AstrbotScript.sh --no-color ``` -------------------------------- ### 克隆 AstrBot 和插件仓库 Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/en/dev/star/guides/env.md 克隆 AstrBot 项目本体和您的插件仓库到本地。确保将插件克隆到 AstrBot 项目的 `data/plugins` 目录下。 ```bash git clone https://github.com/AstrBotDevs/AstrBot mkdir -p AstrBot/data/plugins cd AstrBot/data/plugins git clone 插件仓库地址 ``` -------------------------------- ### GET /api/v1/chat/sessions Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/openapi.md Retrieves a paginated list of chat sessions for a specified username. Requires `username` as a query parameter. ```APIDOC ## GET /api/v1/chat/sessions ### Description Retrieves a paginated list of chat sessions for a specified username. Requires `username` as a query parameter. ### Method GET ### Endpoint /api/v1/chat/sessions ### Parameters #### Query Parameters - **username** (string) - Required - The username whose sessions are to be retrieved. - **page** (integer) - Optional - The page number for pagination. Defaults to 1. - **page_size** (integer) - Optional - The number of sessions per page. Defaults to 20. ### Response #### Success Response (200) - **sessions** (array) - A list of chat session objects. - **total** (integer) - The total number of sessions. #### Response Example ```json { "sessions": [ { "session_id": "my_session_001", "last_message_time": 1678886400, "title": "Session Title" } ], "total": 10 } ``` ``` -------------------------------- ### 获取加载的所有平台 Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/guides/other.md 使用 `context.platform_manager.get_insts()` 方法可以获取当前加载的所有平台实例列表。 ```python from astrbot.api.platform import Platform platforms = self.context.platform_manager.get_insts() # List[Platform] ``` -------------------------------- ### Call QQ Protocol API Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/plugin.md Example of calling the QQ protocol end API, specifically `delete_msg`, for the aiocqhttp platform. ```APIDOC ## Call QQ Protocol End API ```py @filter.command("helloworld") async def helloworld(self, event: AstrMessageEvent): if event.get_platform_name() == "aiocqhttp": # qq from astrbot.core.platform.sources.aiocqhttp.aiocqhttp_message_event import AiocqhttpMessageEvent assert isinstance(event, AiocqhttpMessageEvent) client = event.bot # Get the client payloads = { "message_id": event.message_obj.message_id, } ret = await client.api.call_action('delete_msg', **payloads) # Call the protocol end API logger.info(f"delete_msg: {ret}") ``` For CQHTTP API, please refer to the following documentation: Napcat API Documentation: Lagrange API Documentation: ``` -------------------------------- ### Get Session Configuration Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/plugin.md Retrieves configuration specific to a user session. This is recommended for multi-configuration support in AstrBot v4.0.0 and later. ```python umo = event.unified_msg_origin config = self.context.get_config(umo=umo) ``` -------------------------------- ### Get Current Chat Model ID Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/star/guides/ai.md Retrieve the ID of the chat model currently used in a session. Requires `event.unified_msg_origin`. ```python umo = event.unified_msg_origin provider_id = await self.context.get_current_chat_provider_id(umo=umo) ``` -------------------------------- ### 设置镜像源 Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/use/code-interpreter.md 在中国大陆地区,由于无法直接访问 Docker Hub,您可以使用 `/pi mirror` 命令来设置镜像源。例如,设置为 `cjie.eu.org`。 ```bash /pi mirror cjie.eu.org ``` -------------------------------- ### GET /api/v1/configs Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/dev/openapi.md Retrieves a list of available configuration files. This endpoint is useful for understanding the available settings and options within AstrBot. ```APIDOC ## GET /api/v1/configs ### Description Retrieves a list of available configuration files. This endpoint is useful for understanding the available settings and options within AstrBot. ### Method GET ### Endpoint /api/v1/configs ### Parameters None ### Response #### Success Response (200) - **configs** (array) - A list of available configuration file names. #### Response Example ```json { "configs": [ "config1.yaml", "config2.json" ] } ``` ``` -------------------------------- ### Download Model with LM Studio Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/providers/provider-lmstudio.md Use this command to download a specific model through LM Studio. Ensure LM Studio is installed and running. ```bash lms get deepseek-r1-qwen-7b ``` -------------------------------- ### Linux One-Click Deployment Script (wget) Source: https://github.com/astrbotdevs/astrbot-docs/blob/v4/zh/deploy/astrbot/community-deployment.md Alternative method for Linux deployment if curl is not available. This command downloads the script using wget and pipes it to bash for execution. ```bash wget -qO- https://raw.githubusercontent.com/zhende1113/Antlia/refs/heads/main/Script/AstrBot/Antlia.sh | bash ```