### Dashboard (WebUI) Setup: pnpm install and dev Source: https://github.com/astrbotdevs/astrbot/blob/master/AGENTS.md Installs dashboard dependencies (first time only) and starts the development server on http://localhost:3000 by default. Requires pnpm; install globally with npm if missing. ```bash cd dashboard pnpm install # First time only. Use npm install -g pnpm if pnpm is not installed. pnpm dev ``` -------------------------------- ### Install dependencies and run with uv Source: https://github.com/astrbotdevs/astrbot/blob/master/docs/en/deploy/astrbot/cli.md Recommended method using uv to sync dependencies and start AstrBot. Run in the AstrBot directory. For subsequent startups after installing plugins, use the --no-sync parameter to avoid reinstalling plugin dependencies. ```bash uv sync uv run main.py ``` ```bash uv run --no-sync main.py ``` -------------------------------- ### Core Setup: uv sync and run main.py Source: https://github.com/astrbotdevs/astrbot/blob/master/AGENTS.md Initializes the Python environment and starts the AstrBot core server, which exposes an API on http://localhost:6185 by default. ```bash uv sync uv run main.py ``` -------------------------------- ### Install and Run AstrBot with uv Source: https://github.com/astrbotdevs/astrbot/blob/master/README.md One-click deployment using uv. Requires uv to be installed. On macOS, the first run of the astrbot command may take 10-20 seconds due to security checks. Run 'astrbot init' only on first initialization. ```bash uv tool install astrbot --python 3.12 astrbot init # Only execute this command for the first time to initialize the environment astrbot run ``` -------------------------------- ### Check bubblewrap on Linux Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-astrbot-agent-sandbox Check whether bubblewrap is installed and can start. If it prints 'AstrBot is good to go!', bubblewrap is installed and passes the basic startup check. ```bash command -v bwrap bwrap --unshare-all --ro-bind / / --proc /proc --dev /dev /bin/sh -c 'echo "AstrBot is good to go!"' ``` -------------------------------- ### Set up development environment with git clone, pre-commit, and ruff Source: https://github.com/astrbotdevs/astrbot/blob/master/README.md Clone the AstrBot repository and install pre-commit hooks. AstrBot uses ruff for code formatting and linting, so pre-commit is required before contributing. ```bash git clone https://github.com/AstrBotDevs/AstrBot pip install pre-commit pre-commit install ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/astrbotdevs/astrbot/blob/master/AGENTS.md Installs the pre-commit package and activates the hooks so they run automatically on git commit. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Update astrbot with uv Source: https://github.com/astrbotdevs/astrbot/blob/master/README.md Upgrades the astrbot installation to the latest version using uv. ```bash uv tool upgrade astrbot --python 3.12 ``` -------------------------------- ### Start AstrBot with common options Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-cli Shows examples of starting AstrBot with the --port, --reload, and --reset-password options. ```bash astrbot run --port 6185 astrbot run --reload astrbot run --reset-password ``` -------------------------------- ### Activate venv, install dependencies, and run on Mac/Linux/WSL Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-cli Activates the virtual environment, installs dependencies from requirements.txt using the Tsinghua mirror, and starts AstrBot. For Mac/Linux/WSL systems. ```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 ``` -------------------------------- ### Activate venv, install dependencies, and run on Windows Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-cli Activates the virtual environment, installs dependencies from requirements.txt using the Tsinghua mirror, and starts AstrBot. For Windows systems. ```bash venv\Scripts\activate python -m pip install -r requirements.txt -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple python main.py ``` -------------------------------- ### Google-Style Docstring Example for calculate_metrics Source: https://github.com/astrbotdevs/astrbot/blob/master/AGENTS.md Mandatory Google format for all docstrings, including Args, Returns, and Raises sections. Use for any non-obvious function or method. ```python def calculate_metrics(user_id: int, force_refresh: bool = False) -> dict: """Brief description of the function. Args: user_id: Description of the ID. force_refresh: Description of the flag. Returns: Description of the returned dict. Raises: ValueError: Description of when this occurs. """ # Inline implementation here... ``` -------------------------------- ### Install bubblewrap on Fedora Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-astrbot-agent-sandbox Install bubblewrap using dnf on Fedora. ```bash sudo dnf install bubblewrap ``` -------------------------------- ### Install ffmpeg on Linux Source: https://github.com/astrbotdevs/astrbot/wiki/en-platform-wecom Install ffmpeg for voice input support on Linux systems. ```bash apt install ffmpeg ``` -------------------------------- ### Start astrbot.service with systemctl Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-sys-pm Starts the AstrBot user service using systemctl. Recommended over direct commands because it provides automatic restart and log rotation. ```bash systemctl --user start astrbot.service ``` -------------------------------- ### Start AstrBot and Ollama with astrbot_booter.sh Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-compshare Run this in a JupyterLab terminal after creating an instance from the AstrBot image. It starts both AstrBot and Ollama services in the background. The expected output shows the services starting successfully. ```bash cd ./astrbot_booter.sh ``` ```txt (py312) root@f8396035c96d:/workspace# cd ./astrbot_booter.sh Starting AstrBot... Starting ollama... Both services started in the background. ``` -------------------------------- ### Install bubblewrap on Debian/Ubuntu Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-astrbot-agent-sandbox Install bubblewrap using apt on Debian or Ubuntu. ```bash sudo apt update sudo apt install bubblewrap ``` -------------------------------- ### Enable astrbot.service for auto-start on boot Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-sys-pm Enables the AstrBot user service to start automatically on boot. Add --now to start it immediately. Runs as a user for security reasons. ```bash # For security reasons, it is designed to run as a user. systemctl --user enable astrbot.service # If you need to start it immediately, add --now # systemctl --user enable --now astrbot.service ``` -------------------------------- ### Minimal plugin instance in main.py Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-simple Defines a minimal AstrBot plugin class inheriting from Star. Registers a 'helloworld' command that replies with the sender's name. The plugin file must be named main.py. ```python from astrbot.api.event import filter, AstrMessageEvent, MessageEventResult from astrbot.api.star import Context, Star from astrbot.api import logger # Use the logger interface provided by AstrBot class MyPlugin(Star): def __init__(self, context: Context): super().__init__(context) # Decorator to register a command. The command name is "helloworld". Once registered, sending `/helloworld` will trigger this command and respond with `Hello, {user_name}!` @filter.command("helloworld") async def helloworld(self, event: AstrMessageEvent): """This is a hello world command""" # This is the handler's description, which will be parsed to help users understand the plugin's functionality. Highly recommended to provide. user_name = event.get_sender_name() message_str = event.message_str # Get the plain text content of the message logger.info("Hello world command triggered!") yield event.plain_result(f"Hello, {user_name}!") # Send a plain text message async def terminate(self): """Optionally implement the terminate function, which will be called when the plugin is uninstalled/disabled.""" ``` -------------------------------- ### Download and Run a Model with lms get Source: https://github.com/astrbotdevs/astrbot/wiki/en-providers-provider-lmstudio Use the LM Studio CLI to download and run a model locally, such as deepseek-r1-qwen-7b. Requires LM Studio installed and hardware requirements met. ```bash lms get deepseek-r1-qwen-7b ``` -------------------------------- ### Install CUA via uv in AstrBot project directory Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-astrbot-agent-sandbox Alternative installation for AstrBot environments managed with `uv`. Run this command in the project directory. ```bash uv pip install cua ``` -------------------------------- ### Example plugin view directory Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-plugin-i18n Shows the directory structure for a plugin view named 'settings'. ```text views/ settings/ index.html ``` -------------------------------- ### Install bubblewrap on Arch Linux Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-astrbot-agent-sandbox Install bubblewrap using pacman on Arch Linux. ```bash sudo pacman -S bubblewrap ``` -------------------------------- ### Start Mattermost with bundled NGINX Source: https://github.com/astrbotdevs/astrbot/wiki/en-platform-mattermost Starts Mattermost using the docker-compose.yml and docker-compose.nginx.yml files. Access the server at https://your-domain. ```bash docker compose -f docker-compose.yml -f docker-compose.nginx.yml up -d ``` -------------------------------- ### Install ffmpeg on macOS Source: https://github.com/astrbotdevs/astrbot/wiki/en-platform-wecom Install ffmpeg for voice input support on macOS using Homebrew. ```bash brew install ffmpeg ``` -------------------------------- ### POST /api/v1/plugins/install/url Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Installs a plugin from a URL. ```APIDOC ## POST /api/v1/plugins/install/url ### Description Installs a plugin from a URL. ### Method POST ### Endpoint /api/v1/plugins/install/url ``` -------------------------------- ### Clone AstrBot repository and run Docker Compose Source: https://github.com/astrbotdevs/astrbot/blob/master/docs/en/deploy/astrbot/docker.md Clones the AstrBot repository and starts the container with Docker Compose. Run from a terminal with Docker installed. For mainland China networks, modify compose.yml to replace the image with m.daocloud.io/docker.io/soulter/astrbot:latest. ```bash git clone https://github.com/AstrBotDevs/AstrBot cd AstrBot ``` ```bash sudo docker compose up -d ``` -------------------------------- ### Install CasaOS Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-casaos Run this command in a terminal to install CasaOS. Requires sudo privileges. ```bash curl -fsSL https://get.casaos.io | sudo bash ``` -------------------------------- ### Unattended installation on Linux/macOS/WSL Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-package Downloads the installer and runs it non-interactively. --download-source accepts china, official, or custom; default language is English. If source is omitted, Chinese uses mainland China mirrors, English and Japanese use official sources. ```bash curl -fsSL https://docs.astrbot.app/install.sh -o install.sh bash install.sh --language en-US --download-source official --non-interactive ``` -------------------------------- ### Interactive installation on Linux/macOS/WSL Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-package Runs the AstrBot installer interactively using curl. Installs uv, AstrBot, and Python 3.12. ```bash curl -fsSL https://docs.astrbot.app/install.sh | bash ``` -------------------------------- ### Install CUA via pip for source or virtual-environment deployments Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-astrbot-agent-sandbox Install the optional `cua` package in AstrBot's Python environment. CUA is not installed by default; without it, sandbox startup reports a missing dependency. ```bash pip install cua ``` -------------------------------- ### Install astrbot-git with paru Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-sys-pm Installs the AUR package astrbot-git using paru. During the review step, press 'q' to exit and continue installation. After installation, the data directory is fixed at ~/.local/share/astrbot. ```bash paru -S astrbot-git # Note: # The review step will begin; press 'q' to exit review and continue installation. # After installation, the data directory is fixed at: ~/.local/share/astrbot ``` -------------------------------- ### POST /api/v1/plugins/install/upload Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Installs a plugin by uploading a file. ```APIDOC ## POST /api/v1/plugins/install/upload ### Description Installs a plugin by uploading a file. ### Method POST ### Endpoint /api/v1/plugins/install/upload ``` -------------------------------- ### POST /api/v1/plugins/install/github Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Installs a plugin from GitHub. ```APIDOC ## POST /api/v1/plugins/install/github ### Description Installs a plugin from GitHub. ### Method POST ### Endpoint /api/v1/plugins/install/github ``` -------------------------------- ### Install plugin with GitHub proxy Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-cli Installs a plugin using a GitHub proxy, and updates all updatable plugins using the same proxy. ```bash astrbot plug install example-plugin --proxy https://gh-proxy.example.com/ astrbot plug update --proxy https://gh-proxy.example.com/ ``` -------------------------------- ### POST /api/v1/plugins/install/git Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Installs a plugin from a Git repository. ```APIDOC ## POST /api/v1/plugins/install/git ### Description Installs a plugin from a Git repository. ### Method POST ### Endpoint /api/v1/plugins/install/git ``` -------------------------------- ### Install uv in Docker container via pip Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-mcp If uv is missing in the Docker container, install it using Python's pip. This is an alternative to using the 'Install pip Package' feature in the WebUI. Packages installed this way may be lost when the container is recreated. ```bash docker exec astrbot python -m pip install uv ``` -------------------------------- ### Start Mattermost without bundled NGINX Source: https://github.com/astrbotdevs/astrbot/wiki/en-platform-mattermost Starts Mattermost using the docker-compose.yml and docker-compose.without-nginx.yml files. Access the server at http://your-domain:8065. ```bash docker compose -f docker-compose.yml -f docker-compose.without-nginx.yml up -d ``` -------------------------------- ### Read query parameters from request.query Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-plugin-pages Shows how to read query parameters with `get()` and `getlist()`. `get()` supports a type argument and default value. ```python limit = request.query.get("limit", 20, type=int) tags = request.query.getlist("tag") ``` -------------------------------- ### Initialize and run AstrBot Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-package Run these commands manually after installation. AstrBot installed by script does not support upgrades through the WebUI; use uv tool upgrade astrbot --python 3.12 to update. ```bash astrbot init astrbot run ``` -------------------------------- ### Video component examples Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-send-message Send a video using Comp.Video.fromFileSystem or Comp.Video.fromURL. ```python path = "path/to/video.mp4" Comp.Video.fromFileSystem(path=path) Comp.Video.fromURL(url="https://example.com/video.mp4") ``` -------------------------------- ### Optional flags for prepare_release.py Source: https://github.com/astrbotdevs/astrbot/blob/master/AGENTS.md Use --generate-api-client to regenerate the API client, --dashboard-build to build the dashboard, and --commit --push to commit and push changes. ```bash uv run python scripts/prepare_release.py 4.25.0 --generate-api-client ``` ```bash uv run python scripts/prepare_release.py 4.25.0 --dashboard-build ``` ```bash uv run python scripts/prepare_release.py 4.25.0 --commit --push ``` -------------------------------- ### Clone Mattermost Docker repository and copy env.example Source: https://github.com/astrbotdevs/astrbot/wiki/en-platform-mattermost Quick-start flow recommended by Mattermost. Clone the official docker repository, enter the directory, and copy env.example to .env before editing required values. ```bash git clone https://github.com/mattermost/docker cd docker cp env.example .env ``` -------------------------------- ### Prepare a release with uv run python scripts/prepare_release.py Source: https://github.com/astrbotdevs/astrbot/blob/master/AGENTS.md Run from a clean worktree to prepare a release. Updates pyproject.toml and astrbot/__init__.py, creates changelogs/v4.25.0.md, runs required Python checks, and prints remaining steps. ```bash uv run python scripts/prepare_release.py 4.25.0 ``` -------------------------------- ### on_agent_begin Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-listen-message-event Hook triggered when the Agent starts running. Requires AstrBot version > v4.23.1. ```APIDOC ## on_agent_begin ### Description Hook triggered when the Agent starts running. Requires AstrBot version > v4.23.1. ### Method Hook (decorator: @filter.on_agent_begin()) ### Parameters - **event** (AstrMessageEvent) - Required - The message event. - **run_context** (ContextWrapper[AstrAgentContext]) - Required - The agent run context. ### Usage Example ```python from astrbot.api.event import filter, AstrMessageEvent from astrbot.core.agent.run_context import ContextWrapper from astrbot.core.astr_agent_context import AstrAgentContext @filter.on_agent_begin() async def on_agent_begin(self, event: AstrMessageEvent, run_context: ContextWrapper[AstrAgentContext]): print("Agent started") ``` ### Notes - Cannot use yield to send messages; use event.send() instead. ``` -------------------------------- ### Get Current Chat Provider ID Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-ai Retrieves the chat model ID for the current session using the unified message origin. Added in v4.5.7. ```python umo = event.unified_msg_origin provider_id = await self.context.get_current_chat_provider_id(umo=umo) ``` -------------------------------- ### Use astrbot.api.web helpers for new plugins Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-plugin-pages New plugins and new documentation should use `astrbot.api.web` helpers instead of Quart's. Do not mix the two `request` proxies in the same handler. ```python from astrbot.api.web import json_response, request ``` -------------------------------- ### Initialize a new Skill with init_skill.py Source: https://github.com/astrbotdevs/astrbot/blob/master/astrbot/builtin_stars/astrbot/skills/skill-creator/SKILL.md Bundled initializer for creating a new Skill when Python and shell execution are available. Add `--resources scripts,references,assets` with only needed directories; it refuses to overwrite an existing Skill. ```text python /scripts/init_skill.py --path --description ``` -------------------------------- ### get_default_persona_v3 Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-ai Gets the default persona (v3 format) to use based on the current session configuration. Falls back to DEFAULT_PERSONALITY if configuration doesn't specify one or the specified persona doesn't exist. ```APIDOC ## get_default_persona_v3 ### Description Get the default persona (v3 format) to use based on the current session configuration. Falls back to `DEFAULT_PERSONALITY` if configuration doesn't specify one or the specified persona doesn't exist. ### Method `get_default_persona_v3` ### Arguments - **umo** (str | MessageSession | None) - Required - Session identifier, used to read user-level configuration ### Returns `Personality` - Default persona object in v3 format ``` -------------------------------- ### Get Current LLM Conversation History for a Session Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-ai Retrieves the current conversation ID and the Conversation object for a given session using the conversation manager. Requires an event with unified_msg_origin and access to self.context. ```python from astrbot.core.conversation_mgr import Conversation uid = event.unified_msg_origin conv_mgr = self.context.conversation_manager curr_cid = await conv_mgr.get_curr_conversation_id(uid) conversation = await conv_mgr.get_conversation(uid, curr_cid) # Conversation ``` -------------------------------- ### Plugin metadata.yaml example Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-plugin-publish Complete metadata.yaml example parsed by the AstrBot plugin marketplace system. Includes required fields (name, display_name, desc, version, author, repo) and optional fields (short_desc, astrbot_version, support_platforms, social_link, tags). The plugin zip package must not exceed 16MB; the CI/CD pipeline rejects larger submissions. ```yaml name: astrbot_plugin_example # Plugin identifier, English, unique display_name: Plugin Display Name # Plugin display name # short_desc: A one-line summary of your plugin # (Optional) Short description for compact UI desc: Detailed description of your plugin's features, usage, etc. # Detailed plugin description Supports multi-line text with Markdown formatting. version: 1.0.0 # Plugin version (follow semantic versioning) author: Author Name # Author name repo: https://github.com/your-name/repo # Plugin repository URL # astrbot_version: ">=4.17.0" # (Optional) AstrBot version range # support_platforms: # (Optional) Supported platform adapter list # - aiocqhttp # - qq_official # social_link: https://github.com/your-web # (Optional) Your personal website, GitHub profile, etc. # tags: # (Optional) Tag list for marketplace categorization and search # - example ``` -------------------------------- ### Full config.yaml Example with Notes Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-astrbot-agent-sandbox Production configuration for Bay in Docker Compose container_network mode. Requires updating security.api_key with a strong random secret. Includes server, database, driver, cargo, security, proxy, warm pool, and profiles settings. ```yaml # Bay Production Config - Docker Compose (container_network mode) # # Bay runs inside Docker and communicates with Ship/Gull containers # through a shared Docker network. # In this mode, sandbox containers do not need to expose ports to the host. # # At minimum, update: # 1. security.api_key — set a strong random secret server: # Bay API listen address host: "0.0.0.0" # Bay API listen port port: 8114 database: # SQLite is the default for single-node deployment. # For multi-instance / HA deployments, you can switch to PostgreSQL, for example: # url: "postgresql+asyncpg://user:pass@db-host:5432/bay" url: "sqlite+aiosqlite:///./data/bay.db" echo: false driver: # Docker is the default driver type: docker # Whether to pull images when creating new sandboxes. # In production, always is usually recommended so you get the latest images. image_pull_policy: always docker: # Docker Socket endpoint socket: "unix:///var/run/docker.sock" # When Bay, Ship, and Gull all run in containers, # container_network is recommended for direct container-network communication. connect_mode: container_network # Shared network name; must match the network in docker-compose.yaml network: "bay-network" # Whether to expose sandbox container ports to the host. # Disabling this is generally recommended in production. publish_ports: false host_port: null cargo: # Cargo storage root path on the Bay side root_path: "/var/lib/bay/cargos" # Default workspace size limit (MB) default_size_limit_mb: 1024 # Path mounted inside the sandbox. This is AstrBot/Neo's workspace root. mount_path: "/workspace" security: # Required: set a strong random secret, for example openssl rand -hex 32 api_key: "CHANGE-ME" # Whether anonymous access is allowed. false is recommended for production. allow_anonymous: false # Proxy environment variable injection for containers. # When enabled, Bay injects HTTP(S)_PROXY and NO_PROXY into sandbox containers. proxy: enabled: false # http_proxy: "http://proxy.example.com:7890" # https_proxy: "http://proxy.example.com:7890" # no_proxy: "my-internal.service" # Warm Pool: keep standby sandboxes pre-warmed to reduce cold-start latency. # When a user creates a sandbox, Bay will first try to claim a pre-warmed instance. warm_pool: enabled: true # Number of warmup queue workers warmup_queue_workers: 2 # Maximum warmup queue size warmup_queue_max_size: 256 # Policy when the queue is full warmup_queue_drop_policy: "drop_newest" # Useful threshold for operational alerts warmup_queue_drop_alert_threshold: 50 # Warm pool maintenance interval (seconds) interval_seconds: 30 # Whether to start warm-pool maintenance when Bay starts run_on_startup: true profiles: # ── Standard Python sandbox ──────────────────────── - id: python-default description: "Standard Python sandbox with filesystem and shell access" image: "ghcr.io/astrbotdevs/shipyard-neo-ship:latest" runtime_type: ship runtime_port: 8123 resources: cpus: 1.0 memory: "1g" capabilities: - filesystem # includes upload/download - shell - python # Idle timeout (seconds) idle_timeout: 1800 # Keep 1 warm instance ready warm_pool_size: 1 env: {} # Optional profile-level proxy override # proxy: # enabled: false # ── Data-science sandbox (more resources) ────────── - id: python-data description: "Data science sandbox with extra CPU and memory" image: "ghcr.io/astrbotdevs/shipyard-neo-ship:latest" runtime_type: ship runtime_port: 8123 resources: cpus: 2.0 memory: "4g" capabilities: - filesystem # includes upload/download - shell - python idle_timeout: 1800 warm_pool_size: 1 env: {} # ── Browser + Python multi-container sandbox ─────── - id: browser-python description: "Browser automation with Python backend" containers: - name: ship image: "ghcr.io/astrbotdevs/shipyard-neo-ship:latest" runtime_type: ship runtime_port: 8123 resources: cpus: 1.0 memory: "1g" capabilities: - python - shell - filesystem # includes upload/download # These capabilities are primarily handled by the ship container primary_for: - filesystem - python - shell env: {} - name: browser image: "ghcr.io/astrbotdevs/shipyard-neo-gull:latest" runtime_type: gull runtime_port: 8115 resources: cpus: 1.0 memory: "2g" capabilities: - browser env: {} idle_timeout: 1800 warm_pool_size: 1 ``` -------------------------------- ### Start AstrBot Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-cli Starts AstrBot in the foreground. ```bash astrbot run ``` -------------------------------- ### Interactive installation on Windows PowerShell Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-package Runs the AstrBot installer interactively in PowerShell 5.1 or PowerShell 7+. Installs uv, AstrBot, and Python 3.12. ```powershell irm https://docs.astrbot.app/install.ps1 | iex ``` -------------------------------- ### Deploy Shipyard Neo with Docker Compose Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-astrbot-agent-sandbox Basic deployment flow for Shipyard Neo. Clone the repository, navigate to the deploy/docker directory, modify key settings in config.yaml (such as security.api_key), then start the service with docker compose up -d. ```bash git clone https://github.com/AstrBotDevs/shipyard-neo cd shipyard-neo/deploy/docker # Modify the key settings in config.yaml, such as security.api_key docker compose up -d ``` -------------------------------- ### Create a new plugin Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-cli Creates a new plugin from the template, prompting for author, description, version, and repository URL. ```bash astrbot plug new my-plugin ``` -------------------------------- ### ready() Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-plugin-pages Waits until the bridge is ready and returns the initial context. Use this during page initialization. ```APIDOC ## ready() ### Description Waits until the bridge is ready and returns the initial context. ### Method ready ### Returns `Promise` - The initial context object. ### Example ```js const context = await bridge.ready(); ``` ``` -------------------------------- ### Start from source with password reset Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-cli Starts AstrBot directly from source with the --reset-password option. ```bash python main.py --reset-password ``` -------------------------------- ### Define Multi-Agent Tools with FunctionTool (AssignAgentTool, WeatherTool, SubAgent1, SubAgent2) Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-ai Defines four FunctionTool subclasses for a multi-agent setup: AssignAgentTool lets the main agent delegate tasks, WeatherTool fetches weather (dummy response), and SubAgent1/SubAgent2 are sub-agents exposed as tools. SubAgent1 calls tool_loop_agent with WeatherTool and max_steps=30; SubAgent2 returns a dummy failure message. Requires imports from astrbot.api, astrbot.core.agent, astrbot.core.astr_agent_context, and pydantic. ```python from astrbot.api import logger from astrbot.core.agent.run_context import ContextWrapper from astrbot.core.agent.tool import FunctionTool, ToolExecResult, ToolSet from astrbot.core.astr_agent_context import AstrAgentContext from pydantic import Field from pydantic.dataclasses import dataclass @dataclass class AssignAgentTool(FunctionTool[AstrAgentContext]): """Main agent uses this tool to decide which sub-agent to delegate a task to.""" name: str = "assign_agent" description: str = "Assign an agent to a task based on the given query" parameters: dict = Field( default_factory=lambda: { "type": "object", "properties": { "query": { "type": "string", "description": "The query to call the sub-agent with.", }, }, "required": ["query"], } ) async def call( self, context: ContextWrapper[AstrAgentContext], **kwargs ) -> ToolExecResult: # Here you would implement the actual agent assignment logic. # For demonstration purposes, we'll return a dummy response. return "Based on the query, you should assign agent 1." @dataclass class WeatherTool(FunctionTool[AstrAgentContext]): """In this example, sub agent 1 uses this tool to get weather information.""" name: str = "weather" description: str = "Get weather information for a location" parameters: dict = Field( default_factory=lambda: { "type": "object", "properties": { "city": { "type": "string", "description": "The city to get weather information for.", }, }, "required": ["city"], } ) async def call( self, context: ContextWrapper[AstrAgentContext], **kwargs ) -> ToolExecResult: city = kwargs["city"] # Here you would implement the actual weather fetching logic. # For demonstration purposes, we'll return a dummy response. return f"The current weather in {city} is sunny with a temperature of 25°C." @dataclass class SubAgent1(FunctionTool[AstrAgentContext]): """Define a sub-agent as a function tool.""" name: str = "subagent1_name" description: str = "subagent1_description" parameters: dict = Field( default_factory=lambda: { "type": "object", "properties": { "query": { "type": "string", "description": "The query to call the sub-agent with.", }, }, "required": ["query"], } ) async def call( self, context: ContextWrapper[AstrAgentContext], **kwargs ) -> ToolExecResult: ctx = context.context.context event = context.context.event logger.info(f"the llm context messages: {context.messages}") 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([WeatherTool()]), max_steps=30, ) return llm_resp.completion_text @dataclass class SubAgent2(FunctionTool[AstrAgentContext]): """Define a sub-agent as a function tool.""" name: str = "subagent2_name" description: str = "subagent2_description" parameters: dict = Field( default_factory=lambda: { "type": "object", "properties": { "query": { "type": "string", "description": "The query to call the sub-agent with.", }, }, "required": ["query"], } ) async def call( self, context: ContextWrapper[AstrAgentContext], **kwargs ) -> ToolExecResult: return "I am useless :(, you shouldn't call me :(" ``` -------------------------------- ### Simple KV Storage Example Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-storage Requires AstrBot version >= 4.9.2. Demonstrates using the plugin-scoped key-value store to persist configuration or temporary data. The storage is isolated per plugin. ```python class Main(star.Star): @filter.command("hello") async def hello(self, event: AstrMessageEvent): """Aloha!""" await self.put_kv_data("greeted", True) greeted = await self.get_kv_data("greeted", False) await self.delete_kv_data("greeted") ``` -------------------------------- ### Importing FakePlatformAdapter in main.py Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-plugin-platform-adapter Shows how to import the fake_platform_adapter module during initialization in main.py. The decorator handles registration automatically. ```python from astrbot.api.star import Context, Star class MyPlugin(Star): def __init__(self, context: Context): from .fake_platform_adapter import FakePlatformAdapter # noqa ``` -------------------------------- ### Install AstrBot with uv Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-cli Installs AstrBot using uv with Python 3.12. Creates the astrbot executable and adds it to PATH. ```bash uv tool install astrbot --python 3.12 ``` -------------------------------- ### Deploy Shipyard Separately with Docker Compose (docker-compose.yml) Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-astrbot-agent-sandbox Use this command sequence to deploy Shipyard separately when AstrBot is already deployed but the sandbox environment is not. It downloads the Shipyard docker-compose.yml from the shipyard repository and starts the stack. Modify the environment variables in docker-compose.yml, such as the Shipyard access token, before running. After successful deployment, Shipyard listens on http://:8156 by default. ```bash mkdir astrbot-shipyard cd astrbot-shipyard wget https://raw.githubusercontent.com/AstrBotDevs/shipyard/refs/heads/main/pkgs/bay/docker-compose.yml -O docker-compose.yml # Modify the environment variables in docker-compose.yml, such as the Shipyard access token docker compose -f docker-compose.yml up -d docker pull soulter/shipyard-ship:latest ``` -------------------------------- ### Reload shell environment after installation Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-package The installer runs uv tool update-shell; reload the environment for your shell. Includes commands for Bash, Zsh, Fish, and PowerShell. ```bash # Bash source ~/.bashrc # Zsh source ~/.zshrc # Fish source ~/.config/fish/config.fish # PowerShell . $PROFILE ``` -------------------------------- ### Example context object Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-plugin-pages The context usually contains these fields, including pluginName, displayName, pageName, pageTitle, locale, i18n, and isDark. ```json { "pluginName": "astrbot_plugin_view_demo", "displayName": "Plugin View Demo", "pageName": "bridge-demo", "pageTitle": "Bridge Demo", "locale": "en-US", "i18n": {}, "isDark": false } ``` -------------------------------- ### on_agent_begin hook: agent start notification Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-listen-message-event Triggered when the Agent starts running. Requires AstrBot version > v4.23.1. Cannot use yield; use event.send() instead. ```python from astrbot.api.event import filter, AstrMessageEvent from astrbot.core.agent.run_context import ContextWrapper from astrbot.core.astr_agent_context import AstrAgentContext @filter.on_agent_begin() async def on_agent_begin( self, event: AstrMessageEvent, run_context: ContextWrapper[AstrAgentContext] ): # Note there are three parameters print("Agent started") ``` -------------------------------- ### Linux One-Click Deployment Script using wget Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-community-deployment Alternative to the curl command for systems without curl. Downloads and pipes the Antlia script to bash via wget. ```bash wget -qO- https://raw.githubusercontent.com/zhende1113/Antlia/refs/heads/main/Script/AstrBot/Antlia.sh | bash ``` -------------------------------- ### Sending media using convert_to_file_path Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-plugin-platform-adapter Illustrates the recommended way to send media when the platform SDK requires a local file path. It calls convert_to_file_path() on Image, Record, and Video components instead of manually checking for file:// prefixes. ```python if isinstance(i, Image): image_path = await i.convert_to_file_path() await self.client.send_image(to=self.get_sender_id(), image_path=image_path) elif isinstance(i, Record): audio_path = await i.convert_to_file_path() await self.client.send_audio(to=self.get_sender_id(), audio_path=audio_path) elif isinstance(i, Video): video_path = await i.convert_to_file_path() await self.client.send_video(to=self.get_sender_id(), video_path=video_path) ``` -------------------------------- ### GET /api/v1/skills Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi Lists skills. ```APIDOC ## GET /api/v1/skills ### Description Lists skills. ### Method GET ### Endpoint /api/v1/skills ### Response #### Success Response (200) List of skills. ``` -------------------------------- ### GET /api/v1/plugins Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi Lists plugins. ```APIDOC ## GET /api/v1/plugins ### Description Lists plugins. ### Method GET ### Endpoint /api/v1/plugins ### Response #### Success Response (200) List of plugins. ``` -------------------------------- ### Run ruff format and check manually Source: https://github.com/astrbotdevs/astrbot/blob/master/AGENTS.md Manually runs the ruff formatter and linter, which are also executed automatically by pre-commit hooks on each commit. ```bash ruff format . ruff check . ``` -------------------------------- ### GET /api/v1/personas Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi Lists personas. ```APIDOC ## GET /api/v1/personas ### Description Lists personas. ### Method GET ### Endpoint /api/v1/personas ### Response #### Success Response (200) List of personas. ``` -------------------------------- ### Import response helpers from astrbot.api.web Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-plugin-pages Recommended response helpers for new plugins. ```python from astrbot.api.web import ( error_response, file_response, json_response, stream_response, ) ``` -------------------------------- ### Create Mattermost data directories and set ownership Source: https://github.com/astrbotdevs/astrbot/wiki/en-platform-mattermost Creates the required volume directories for Mattermost and sets ownership to UID/GID 2000. Run after updating .env and before starting the containers. ```bash mkdir -p ./volumes/app/mattermost/{config,data,logs,plugins,client/plugins,bleve-indexes} sudo chown -R 2000:2000 ./volumes/app/mattermost ``` -------------------------------- ### Tag the release from master Source: https://github.com/astrbotdevs/astrbot/blob/master/AGENTS.md After the release PR is merged, create and push the tag from the updated master branch so the tag points to the exact merged code. ```bash git checkout master git pull --ff-only origin master git tag v4.25.0 git push origin v4.25.0 ``` -------------------------------- ### GET /api/v1/plugins/view Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Retrieves a plugin view. ```APIDOC ## GET /api/v1/plugins/view ### Description Retrieves a plugin view. ### Method GET ### Endpoint /api/v1/plugins/view ``` -------------------------------- ### GET /api/v1/plugins/readme Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Retrieves the readme for plugins. ```APIDOC ## GET /api/v1/plugins/readme ### Description Retrieves the readme for plugins. ### Method GET ### Endpoint /api/v1/plugins/readme ``` -------------------------------- ### Deploy AstrBot and Shipyard with Docker Compose (compose-with-shipyard.yml) Source: https://github.com/astrbotdevs/astrbot/wiki/en-use-astrbot-agent-sandbox Use this command sequence to deploy AstrBot together with the legacy Shipyard sandbox driver via Docker Compose. Before running, modify the environment variables in compose-with-shipyard.yml, such as the Shipyard access token. The stack starts the AstrBot main program and the sandbox environment. ```bash git clone https://github.com/AstrBotDevs/AstrBot cd AstrBot # Modify the environment variables in compose-with-shipyard.yml, such as the Shipyard access token docker compose -f compose-with-shipyard.yml up -d docker pull soulter/shipyard-ship:latest ``` -------------------------------- ### GET /api/v1/plugins/page Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Retrieves a plugin page. ```APIDOC ## GET /api/v1/plugins/page ### Description Retrieves a plugin page. ### Method GET ### Endpoint /api/v1/plugins/page ``` -------------------------------- ### GET /api/v1/plugins/config Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Retrieves the plugin configuration. ```APIDOC ## GET /api/v1/plugins/config ### Description Retrieves the plugin configuration. ### Method GET ### Endpoint /api/v1/plugins/config ``` -------------------------------- ### FakePlatform client SDK simulation (FakeClient) Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-plugin-platform-adapter Simulates a messaging platform that sends a message every 5 seconds. Provides methods for sending text and images. Used as the example SDK for the FakePlatform adapter. ```python import asyncio class FakeClient: """Simulates a messaging platform that sends a message every 5 seconds""" 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": "new message", "username": "zhangsan", "userid": "123", "message_id": "asdhoashd", "group_id": "group123", } ) async def send_text(self, to: str, message: str): print("Message sent:", to, message) async def send_image(self, to: str, image_path: str): print("Image sent:", to, image_path) ``` -------------------------------- ### Appending media components from file system Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-plugin-platform-adapter Shows how to append Image, Record, and Video components to a message using factory methods that generate standard file: URIs from local file paths. ```python from astrbot.api.message_components import Image, Record, Video abm.message.append(Image.fromFileSystem("/tmp/image.png")) abm.message.append(Record.fromFileSystem("/tmp/audio.wav")) abm.message.append(Video.fromFileSystem("/tmp/video.mp4")) ``` -------------------------------- ### GET /api/v1/plugins/changelog Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Retrieves the changelog for plugins. ```APIDOC ## GET /api/v1/plugins/changelog ### Description Retrieves the changelog for plugins. ### Method GET ### Endpoint /api/v1/plugins/changelog ``` -------------------------------- ### Run AstrBot with uv --no-sync Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-cli Recommended for subsequent startups after installing plugins, to avoid reinstalling plugin dependencies. Uses the --no-sync flag. ```bash uv run --no-sync main.py ``` -------------------------------- ### GET /api/v1/plugins/by-id Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Retrieves a plugin by its ID. ```APIDOC ## GET /api/v1/plugins/by-id ### Description Retrieves a plugin by its ID. ### Method GET ### Endpoint /api/v1/plugins/by-id ``` -------------------------------- ### GET /api/v1/plugins Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Retrieves the list of plugins. ```APIDOC ## GET /api/v1/plugins ### Description Retrieves the list of plugins. ### Method GET ### Endpoint /api/v1/plugins ``` -------------------------------- ### GET /api/v1/chat/sessions Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Lists all chat sessions. ```APIDOC ## GET /api/v1/chat/sessions ### Description Lists all chat sessions. ### Method GET ### Endpoint /api/v1/chat/sessions ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None documented #### Response Example None documented ``` -------------------------------- ### Frontend JavaScript using window.AstrBotPluginView (views/bridge-demo/app.js) Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-star-guides-plugin-pages Uses the injected bridge SDK to get context and call the ping API. The bridge is available as window.AstrBotPluginView; no manual SDK import is required. ```javascript const bridge = window.AstrBotPluginView; 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", { limit: 20 }); output.textContent = JSON.stringify(result, null, 2); }); ``` -------------------------------- ### GET /api/v1/chat/projects Source: https://github.com/astrbotdevs/astrbot/wiki/en-dev-openapi-scopes Lists all chat projects. ```APIDOC ## GET /api/v1/chat/projects ### Description Lists all chat projects. ### Method GET ### Endpoint /api/v1/chat/projects ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None documented #### Response Example None documented ``` -------------------------------- ### SKILL.md YAML frontmatter with name and description Source: https://github.com/astrbotdevs/astrbot/blob/master/astrbot/builtin_stars/astrbot/skills/skill-creator/SKILL.md Required frontmatter for every Skill. Only `name` and `description` are allowed; the description must be specific enough for discovery because AstrBot loads the body only after the Skill is selected. ```yaml --- name: example-skill description: Describe what the Skill does and the concrete requests or situations that should trigger it. --- ``` -------------------------------- ### Docker-based Deployment Script using wget Source: https://github.com/astrbotdevs/astrbot/wiki/en-deploy-astrbot-community-deployment Downloads the AstrbotScript.sh script with wget, makes it executable, and runs it with sudo. Supports AstrBot and NapCat. Use sudo if you lack permissions. ```bash wget -qO AstrbotScript.sh https://raw.githubusercontent.com/railgun19457/AstrbotScript/main/AstrbotScript.sh chmod +x AstrbotScript.sh sudo ./AstrbotScript.sh ```