### Quick Start Example Source: https://docs.ncatbot.xyz/guide/kd1r9jkg An example of how to use the GitHub API within a NcatBot plugin to manage issues and comments. ```APIDOC ## Quick Start ```python from ncatbot.core import registrar from ncatbot.event.github import GitHubIssueEvent from ncatbot.plugin import NcatBotPlugin class MyPlugin(NcatBotPlugin): name = "github_ops" version = "1.0.0" @registrar.github.on_issue() async def on_issue(self, event: GitHubIssueEvent): if event.action == "opened": # Auto add labels await self.api.github.add_labels(event.repo, event.issue_number, ["triage"]) # Comment await self.api.github.create_issue_comment( event.repo, event.issue_number, "已标记为 triage,等待处理。" ) ``` ``` -------------------------------- ### Docker build example for NapCat installation Source: https://docs.ncatbot.xyz/reference/h713brec Example command for installing NapCat non-interactively within a Docker build process. ```dockerfile RUN ncatbot napcat install --yes ``` -------------------------------- ### Install NapCat + QQ Source: https://docs.ncatbot.xyz/reference/h713brec Installs NapCat and QQ. Skips if already installed. Use --yes for non-interactive installation. ```bash ncatbot napcat install [OPTIONS] ``` -------------------------------- ### napcat install Source: https://docs.ncatbot.xyz/reference/h713brec Installs NapCat and QQ. Skips if already installed. ```APIDOC ## napcat install ``` ncatbot napcat install [OPTIONS] ``` Installs NapCat + QQ. Skips if already installed. Options: `--yes` / `-y` (flag, default: False): Skip interactive confirmation and install directly (for Docker/CI scenarios). Docker build example: ``` RUN ncatbot napcat install --yes ``` ``` -------------------------------- ### Quick Example: Bilibili Plugin Source: https://docs.ncatbot.xyz/guide/9jzb0z71 A practical example demonstrating how to create a Bilibili plugin and use the API to add a live room listener. ```APIDOC ## Quick Example: Bilibili Plugin ### Description This example shows a basic NcatBot plugin that utilizes the Bilibili API to listen for live room events. ### Code Example ```python from ncatbot.plugin import NcatBotPlugin from ncatbot.core import registrar class BiliPlugin(NcatBotPlugin): name = "bili_demo" version = "1.0.0" async def on_enable(self): # Add live room listener await self.api.bilibili.add_live_room(12345) @registrar.on_message(platform="bilibili") async def on_msg(self, event): await event.reply(text="Received danmaku!") ``` ``` -------------------------------- ### Typical Workflow Example Source: https://docs.ncatbot.xyz/guide/ofkjsvyt An example demonstrating the typical workflow for setting up and using RBAC permissions in a plugin. ```APIDOC ## Typical Workflow Example ### Description An example demonstrating the typical workflow for setting up and using RBAC permissions in a plugin. ### Code Example ```python async def on_load(self): self.add_permission("my_plugin.admin") self.add_role("my_plugin_admin") self.rbac.grant("role", "my_plugin_admin", "my_plugin.admin") @registrar.on_group_command("管理命令") async def on_admin_cmd(self, event: GroupMessageEvent): if self.check_permission(str(event.user_id), "my_plugin.admin"): await event.reply(text="执行成功") ``` ``` -------------------------------- ### NapCatLauncher Setup Mode Flow Source: https://docs.ncatbot.xyz/reference/klad65iz Details the process flow for NapCatLauncher when operating in Setup Mode. ```APIDOC ## Setup Mode Flow **Two-Stage Account Verification**: The new login process verifies the actual logged-in account via HTTP *before* `wait_for_service()`. If `bot_uin` is default and does not match, the actual account is written back immediately, and WS configuration is pushed via HTTP. Otherwise, the WebSocket will never be ready due to missing WS configuration for that account. **Setup Mode** (Default): 1. Detect if the NapCat service is already online. 2. If online, verify the account via WS and complete. 3. If offline, proceed with installation/update -> configuration (file writing) -> process startup -> login. * For new logins: After logging in, first check the account via **HTTP** (handling default `bot_uin`), then wait for WS readiness, and finally perform final WS verification. **Connect Mode** (`skip_setup: true`): * Attempt to connect to the existing NapCat service directly. * Completion occurs upon successful connection. * `NcatBotError` is raised on connection failure (no automatic installation or startup of NapCat). ``` -------------------------------- ### Full Multi-Step Dialog Example Source: https://docs.ncatbot.xyz/guide/uwanjc8v A complete example demonstrating a multi-step registration process using `_wait_user_reply` for user input, handling timeouts, cancellations, and input validation before saving data. ```python @registrar.on_group_command("注册") async def on_register(self, event: GroupMessageEvent): gid, uid = event.group_id, event.user_id # 步骤 1: 询问名字 await event.reply(f"📝 请输入你的名字({TIMEOUT}秒内回复,输入「取消」退出):") try: name = await self._wait_user_reply(gid, uid) except asyncio.TimeoutError: await self.api.qq.post_group_msg(gid, text="⏰ 注册超时,已取消") return if name == "取消": await self.api.qq.post_group_msg(gid, text="❌ 注册已取消") return # 步骤 2: 询问年龄 await self.api.qq.post_group_msg(gid, text=f"好的,{name}!请输入你的年龄:") try: age_str = await self._wait_user_reply(gid, uid) except asyncio.TimeoutError: await self.api.qq.post_group_msg(gid, text="⏰ 注册超时,已取消") return if age_str == "取消": await self.api.qq.post_group_msg(gid, text="❌ 注册已取消") return if not age_str.isdigit(): await self.api.qq.post_group_msg(gid, text="❌ 年龄必须是数字,注册已取消") return age = int(age_str) # 步骤 3: 确认 await self.api.qq.post_group_msg( gid, text=f"请确认你的信息:\n 名字: {name}\n 年龄: {age}\n回复「确认」完成注册:", ) try: confirm = await self._wait_user_reply(gid, uid) except asyncio.TimeoutError: await self.api.qq.post_group_msg(gid, text="⏰ 确认超时,已取消") return if confirm != "确认": await self.api.qq.post_group_msg(gid, text="❌ 注册已取消") return # 保存数据 self.data.setdefault("users", {})[str(uid)] = {"name": name, "age": age} await self.api.qq.post_group_msg(gid, text=f"✅ 注册成功!欢迎你,{name}({age}岁)") ``` -------------------------------- ### Minimal config.yaml Example Source: https://docs.ncatbot.xyz/guide/44hxka0i This is a basic example of a config.yaml file for NcatBot, specifying bot and root UINs, and adapter configuration. ```yaml bot_uin: '1234567890' root: '9876543210' adapters: - type: napcat platform: qq enabled: true config: ws_uri: ws://localhost:3001 ``` -------------------------------- ### QQAPIClient Configuration Example Source: https://docs.ncatbot.xyz/guide/uxoxz0nf Example of configuring the QQAPIClient using the recommended new format with an 'adapters' list. This format is preferred for defining bot adapters and their specific configurations. ```yaml # 新格式(推荐) bot_uin: "999999" adapters: - type: napcat platform: qq enabled: true config: ws_uri: ws://localhost:3001 ws_token: napcat_ws ``` -------------------------------- ### Handle Live Stream Start and End Events Source: https://docs.ncatbot.xyz/reference/z3hgpwbq This example shows how to use registrar decorators to specifically handle live stream start and end events. It accesses event data to print stream information like title and anchor name upon starting. ```python from ncatbot.event.bilibili import LiveNoticeEvent @registrar.bilibili.on_live_start() async def on_start(self, event: LiveNoticeEvent): data = event._data # LiveStatusEventData print(f"本场直播开播时间戳: {data.live_time}") if data.room_info: title = data.room_info.room_info.title anchor = data.room_info.anchor_info.name print(f"[开播] {anchor}: {title}") @registrar.bilibili.on_live_end() async def on_end(self, event: LiveNoticeEvent): print("[下播]") ``` -------------------------------- ### Plugin Entry Module Example Source: https://docs.ncatbot.xyz/guide/uxoxz0nf An example of a plugin's main entry module, demonstrating how to inherit from NcatBotPlugin, implement lifecycle methods like on_load and on_close, and register commands using the registrar. ```python from ncatbot.core import registrar from ncatbot.event.qq import GroupMessageEvent from ncatbot.plugin import NcatBotPlugin class MyPlugin(NcatBotPlugin): name = "my_plugin" version = "1.0.0" async def on_load(self): pass async def on_close(self): pass @registrar.on_group_command("hello") async def on_hello(self, event: GroupMessageEvent): # self.api 是 BotAPIClient,通过 .qq 访问 QQ 平台 API await self.api.qq.post_group_msg(event.group_id, text="Hello! 👋") ``` -------------------------------- ### Install pre-commit Hooks Source: https://docs.ncatbot.xyz/contributing/afd9taf5 Install the pre-commit Git hooks to automate checks before each commit. ```bash uv run pre-commit install ``` -------------------------------- ### YAML Configuration Example Source: https://docs.ncatbot.xyz/reference/m3pmk1ut An example of how the NcatBot configuration can be structured in a YAML file, demonstrating settings for bot UIN, root UIN, debug mode, adapters, and plugins. ```yaml bot_uin: "1234567890" root: "9876543210" debug: false websocket_timeout: 15 adapters: - type: napcat platform: qq enabled: true config: ws_uri: "ws://localhost:3001" ws_token: "your_token" plugin: plugins_dir: "plugins" load_plugin: true ``` -------------------------------- ### APICallAssertion - Chained Usage Example Source: https://docs.ncatbot.xyz/reference/pu58sr79 An example demonstrating the chained usage of APICallAssertion methods. ```APIDOC ## APICallAssertion ### Chained Usage ```python h.assert_api("send_group_msg").called().with_params(group_id="100").with_text("hello") ``` ``` -------------------------------- ### Cross-Platform Plugin Example Source: https://docs.ncatbot.xyz/guide/mg63xeur An example demonstrating how to use various mixins to handle messages in a cross-platform manner. ```APIDOC ```python from ncatbot.event import Replyable, GroupScoped, Bannable @registrar.on_message() async def cross_platform_handler(self, event): """Handles messages from all platforms""" if isinstance(event, Replyable): await event.reply(text=f"Message received from {event.platform}") if isinstance(event, GroupScoped): print(f"Group/Channel: {event.group_id}") if isinstance(event, Bannable): # Events that can ban users pass ``` ``` -------------------------------- ### Install uv Package Manager Source: https://docs.ncatbot.xyz/contributing/afd9taf5 Install the uv package manager using PowerShell on Windows or curl on Linux/macOS. ```bash # 安装 uv — Windows (PowerShell) powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` ```bash # 安装 uv — Linux / macOS curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Bilibili Live Event Example Source: https://docs.ncatbot.xyz/guide/5kxxkqvy A practical example demonstrating how to use Bilibili platform decorators to monitor live stream events. ```APIDOC ## Bilibili Live Event Monitoring Example This example shows how to use `on_live_start` and `on_live_end` decorators to monitor Bilibili live stream status and post messages to a QQ group. ```python from ncatbot.core import registrar from ncatbot.event.bilibili import LiveNoticeEvent # Assuming NcatBotPlugin and GROUP_ID are defined elsewhere # class NcatBotPlugin: # async def api(self): # pass # GROUP_ID = 12345 class LiveMonitor(NcatBotPlugin): name = "live_monitor" version = "1.0.0" @registrar.bilibili.on_live_start() async def on_start(self, event: LiveNoticeEvent): data = event._data # LiveStatusEventData print(f"live_time={data.live_time}") if data.room_info: title = data.room_info.room_info.title anchor = data.room_info.anchor_info.name area = data.room_info.room_info.area_name await self.api.qq.post_group_msg( GROUP_ID, text=f"【开播】{anchor} 正在直播: {title}({area})", ) else: await self.api.qq.post_group_msg(GROUP_ID, text="直播间已开播!") @registrar.bilibili.on_live_end() async def on_end(self, event: LiveNoticeEvent): await self.api.qq.post_group_msg(GROUP_ID, text="直播已结束。") ``` **Note:** The `room_info` field is populated only during `on_live_start`. It is `None` for `on_live_end` events. `live_time` defaults to `0` if missing. ``` -------------------------------- ### NapCatWebSocket Connection Flow Example Source: https://docs.ncatbot.xyz/reference/klad65iz An example demonstrating the typical usage of NapCatWebSocket within the NapCatAdapter's connect method. ```APIDOC ## Connection Flow Example Typical invocation within `NapCatAdapter.connect()`: ```python async def connect(self) -> None: uri = ncatbot_config.get_uri_with_token() self._ws = NapCatWebSocket(uri) await self._ws.connect() self._protocol = OB11Protocol(self._ws) self._api = NapCatBotAPI(self._protocol) self._protocol.set_event_handler(self._on_event) ``` **Process Description**: 1. Retrieve WebSocket URI (including Token) from configuration. 2. Create a `NapCatWebSocket` instance and establish the connection. 3. Instantiate `OB11Protocol` for request-response matching. 4. Create `NapCatBotAPI` implementing `IQQAPIClient`. 5. Register the internal event handler with the protocol layer. ``` -------------------------------- ### CommandGroupHook Example Source: https://docs.ncatbot.xyz/reference/knwm7kyw Demonstrates setting up a command group with subcommands using CommandGroupHook. ```python hook = CommandGroupHook("admin", "/admin", "a") @hook.subcommand("ban", "禁言") async def admin_ban(event, user_id: int, minutes: int = 60): ... @hook.subcommand("kick") async def admin_kick(event, user_id: int): ... @registrar.on_group_message() @hook async def handle_admin(self, event, subcommand: str = ""): ... ``` -------------------------------- ### NcatBot Configuration YAML Example Source: https://docs.ncatbot.xyz/reference/c1734blh A comprehensive example of the `config.yaml` file, illustrating settings for bot identification, debugging, proxy configurations (GitHub and general HTTP/SOCKS5), NapCat connection details, and plugin management. ```yaml # 基础配置 bot_uin: "1234567890" root: "9876543210" debug: false websocket_timeout: 15 enable_webui_interaction: true check_ncatbot_update: true skip_ncatbot_install_check: false # GitHub 代理(留空或删除此行使用自动探测) github_proxy: "https://proxy.example.com" # 标准 HTTP/SOCKS5 代理(用于 Attachment 下载、MiscAPI 请求等) http_proxy: "http://127.0.0.1:7890" # NapCat 连接配置 napcat: ws_uri: "ws://localhost:3001" ws_token: "your_strong_token_here" ws_listen_ip: "localhost" webui_uri: "http://localhost:6099" webui_token: "your_webui_token_here" enable_webui: true enable_update_check: false stop_napcat: false # Linux 下关闭 Bot 时才会停止本机 NapCat skip_setup: false # 插件配置 plugin: plugins_dir: "plugins" load_plugin: true plugin_whitelist: [] # 空=不过滤 plugin_blacklist: [] auto_install_pip_deps: true plugin_configs: my_plugin: key: value ``` -------------------------------- ### List installed plugins Source: https://docs.ncatbot.xyz/reference/h713brec Lists all installed plugins, displaying their name, version, author, and status. Reads metadata from manifest.toml. ```bash ncatbot plugin list ``` -------------------------------- ### Bilibili Monitor Plugin Example Source: https://docs.ncatbot.xyz/guide/jjmcihg7 A practical example demonstrating how to use Bilibili API methods within a NcatBot plugin. It shows adding listeners on plugin enable and cleaning them up on disable. ```python class BiliMonitor(NcatBotPlugin): name = "bili_monitor" version = "1.0.0" async def on_enable(self): # Add listeners on startup await self.api.bilibili.add_live_room(12345) await self.api.bilibili.add_comment_watch("BV1xx411c7mD") await self.api.bilibili.add_dynamic_watch(uid=12345678) # Check current data sources sources = await self.api.bilibili.list_sources() print(f"已监听 {len(sources)} 个数据源") async def on_disable(self): # Clean up on disable await self.api.bilibili.remove_live_room(12345) await self.api.bilibili.remove_comment_watch("BV1xx411c7mD") await self.api.bilibili.remove_dynamic_watch(uid=12345678) ``` -------------------------------- ### Install Dependencies with uv Source: https://docs.ncatbot.xyz/contributing/afd9taf5 Use the `uv sync --extra dev` command to automatically create a virtual environment, install runtime dependencies, and development tools like pytest, ruff, mypy, tox, and pre-commit. ```bash uv sync --extra dev ``` -------------------------------- ### RBACMixin - Basic Usage Example Source: https://docs.ncatbot.xyz/guide/sbal250z Example demonstrating how to use RBACMixin to add permissions, create roles, grant permissions, and protect commands. ```APIDOC ```python class MyPlugin(NcatBotPlugin): name = "rbac_demo" version = "1.0.0" async def on_load(self): # Register permission paths self.add_permission("rbac.admin") self.add_permission("rbac.user") # Create roles self.add_role("rbac_admin", exist_ok=True) self.add_role("rbac_user", exist_ok=True) # Assign permissions to roles (via underlying RBAC service) if self.rbac: self.rbac.grant("role", "rbac_admin", "rbac.admin") self.rbac.grant("role", "rbac_admin", "rbac.user") self.rbac.grant("role", "rbac_user", "rbac.user") @registrar.on_group_command("授权") async def on_grant(self, event: GroupMessageEvent, target: At = None): """Grant admin role to a user""" if target is None: await event.reply("Please @ a user") return target_uid = str(target.user_id) if self.rbac: self.rbac.assign_role("user", target_uid, "rbac_admin") await event.reply(f"Granted admin privileges to {target_uid} ✅") @registrar.on_group_command("管理命令") async def on_admin_cmd(self, event: GroupMessageEvent): """Command protected by permission""" uid = str(event.user_id) if self.check_permission(uid, "rbac.admin"): await event.reply("🔑 Admin command executed successfully!") else: await event.reply("🚫 You do not have permission to execute this command") @registrar.on_group_command("查权限") async def on_check_perm(self, event: GroupMessageEvent): """Check own permissions""" uid = str(event.user_id) has_admin = self.check_permission(uid, "rbac.admin") is_admin_role = self.user_has_role(uid, "rbac_admin") await event.reply( f"👤 Permission Status:\n" f" Role rbac_admin: {'✅' if is_admin_role else '❌'}\n" f" Permission rbac.admin: {'✅' if has_admin else '❌'}" ) ``` ``` -------------------------------- ### Bilibili Live Room Management Plugin Example Source: https://docs.ncatbot.xyz/guide/tokfrklt An example plugin demonstrating how to manage live room operations, including adding rooms, automatically replying to danmaku, and banning users for specific content. This snippet requires `NcatBotPlugin` and `registrar` imports. ```python from ncatbot.core import registrar class LiveManager(NcatBotPlugin): name = "live_manager" version = "1.0.0" async def on_enable(self): await self.api.bilibili.add_live_room(12345) @registrar.on_message(platform="bilibili") async def on_danmu(self, event): # 自动回复弹幕 if "你好" in event.content: await self.api.bilibili.send_danmu(event.room_id, "欢迎!") # 违规弹幕自动禁言 if "广告" in event.content: await self.api.bilibili.ban_user(event.room_id, event.user_id, hour=1) ``` -------------------------------- ### run Source: https://docs.ncatbot.xyz/reference/h713brec Starts NcatBot, connecting to NapCat, loading plugins, and listening for events. ```APIDOC ## run ``` ncatbot run [OPTIONS] ``` Starts NcatBot (connects to NapCat + loads plugins + listens for events). Options: `--debug` (flag, default: False): Enable debug mode. `--no-hot-reload` (flag, default: False): Disable plugin hot-reloading. `--plugins-dir` (str, default: uses config default): Plugin directory path. `--non-interactive` (flag, default: False): Run in non-interactive mode (all confirmations use default values). `--bot-uin` (str, default: uses config/environment variable): Bot QQ number (overrides config and environment variables). `--root` (str, default: uses config/environment variable): Administrator QQ number (overrides config and environment variables). If `bot_uin` is not configured (defaults to `123456`), it automatically enters the `ncatbot init` process. Providing a valid value via `--bot-uin` or the `NCATBOT_BOT_UIN` environment variable skips this. ``` -------------------------------- ### RBACMixin - Practical Example: Group Management Permissions Source: https://docs.ncatbot.xyz/guide/sbal250z Example showing how to implement group management permissions using RBACMixin, protecting commands like kicking users. ```APIDOC ```python class GroupManagerPlugin(NcatBotPlugin): name = "group_manager" version = "1.0.0" async def on_load(self): self.add_permission("group_manager.admin") self.add_role("gm_admin", exist_ok=True) if self.rbac: self.rbac.grant("role", "gm_admin", "group_manager.admin") def _is_admin(self, user_id) -> bool: return self.check_permission(str(user_id), "group_manager.admin") @registrar.on_group_command("踢") async def on_kick(self, event: GroupMessageEvent, target: At = None): if not self._is_admin(event.user_id): await event.reply("🚫 You do not have administrative privileges") return if target is None: await event.reply("Please @ a user") return await self.api.qq.manage.set_group_kick(event.group_id, target.user_id) await event.reply(f"Kicked user {target.user_id}") ``` ``` -------------------------------- ### Handling Request Events Example Source: https://docs.ncatbot.xyz/reference/glw0469e Example of how to handle incoming request events using the `on_request` decorator and event object methods. ```APIDOC ```python @bot.on_request() async def handle_request(event: RequestEvent): if event.request_type == RequestType.FRIEND: await event.approve(remark="Auto-approved friend request") elif event.request_type == RequestType.GROUP: await event.reject(reason="Not accepting group requests at this time") ``` ``` -------------------------------- ### Cross-Platform Handler Example Source: https://docs.ncatbot.xyz/guide/mg63xeur A comprehensive example demonstrating how to handle messages across different platforms using `Replyable`, `GroupScoped`, and `Bannable` mixins. It shows conditional logic based on event capabilities. ```python from ncatbot.event import Replyable, GroupScoped, Bannable @registrar.on_message() async def cross_platform_handler(self, event): """处理所有平台的消息""" if isinstance(event, Replyable): await event.reply(text=f"来自 {event.platform} 的消息已收到") if isinstance(event, GroupScoped): print(f"群/频道: {event.group_id}") if isinstance(event, Bannable): # 可以禁言的事件 pass ``` -------------------------------- ### setup_logging Source: https://docs.ncatbot.xyz/reference/4g9ojhm3 全局日志初始化函数,应在应用启动时调用一次。支持控制台和文件日志级别、日志目录、备份数量和路由规则配置。 ```APIDOC ## setup_logging ### Description 全局日志初始化,应在应用启动时调用一次。内部做幂等保护(重复调用无效)。 ### Method ```python def setup_logging( *, console_level: str | None = None, file_level: str | None = None, log_dir: str | None = None, backup_count: int | None = None, routing_rules: Sequence[tuple[str, str]] | None = None, ) -> None ``` ### Parameters #### Keyword Parameters - **console_level** (str | None) - Optional - 控制台日志级别,默认为环境变量 `LOG_LEVEL`,兜底为 "DEBUG"。 - **file_level** (str | None) - Optional - 文件日志级别,默认为环境变量 `FILE_LOG_LEVEL`,兜底为 "DEBUG"。 - **log_dir** (str | None) - Optional - 日志目录,默认为环境变量 `LOG_FILE_PATH`,兜底为 "./logs"。 - **backup_count** (int | None) - Optional - 日志保留天数,默认为环境变量 `BACKUP_COUNT`,兜底为 7。 - **routing_rules** (Sequence[tuple[str, str]] | None) - Optional - 日志路由规则,默认为 `DEFAULT_ROUTING_RULES`。 ### Request Example ```python from ncatbot.utils.logger.setup import setup_logging setup_logging( console_level="INFO", file_level="DEBUG", log_dir="./logs", backup_count=7, ) ``` ``` -------------------------------- ### Install ncatbot via pyproject.toml Source: https://docs.ncatbot.xyz/reference/h713brec Defines the ncatbot entry point in your project's pyproject.toml file. ```toml [project.scripts] ncatbot = "ncatbot.cli:main" ``` -------------------------------- ### Run ncatbot Source: https://docs.ncatbot.xyz/reference/h713brec Starts the NcatBot service, connecting to NapCat, loading plugins, and listening for events. ```bash ncatbot run [OPTIONS] ``` -------------------------------- ### Get plugin information Source: https://docs.ncatbot.xyz/reference/h713brec Displays the metadata from a plugin's manifest.toml file. ```bash ncatbot plugin info NAME ``` -------------------------------- ### 全局日志初始化 Source: https://docs.ncatbot.xyz/reference/4g9ojhm3 调用 setup_logging 在应用启动时进行全局日志初始化。可配置控制台和文件日志级别、日志目录及备份数量。 ```python from ncatbot.utils.logger.setup import setup_logging setup_logging( console_level="INFO", file_level="DEBUG", log_dir="./logs", backup_count=7, ) ``` -------------------------------- ### Verify NcatBot Installation Source: https://docs.ncatbot.xyz/contributing/afd9taf5 Confirm that NcatBot is installed and available by running a Python command. Also, verify the pytest installation. ```bash python -c "import ncatbot; print('ncatbot 可用')" uv run pytest --version ``` -------------------------------- ### BotClient Initialization and Event Handling Source: https://docs.ncatbot.xyz/guide/uxoxz0nf Demonstrates the basic usage of BotClient as the entry point for the bot. It shows how to initialize the client, register message event handlers using decorators, and start the bot's execution. ```python from ncatbot.app import BotClient bot = BotClient() @bot.on("message.group") async def on_group_msg(event): await event.reply("hello") bot.run() ``` -------------------------------- ### Verify NcatBot Installation Source: https://docs.ncatbot.xyz/guide/0y9ejqdf Run this command to confirm that NcatBot has been installed correctly and is accessible in your Python environment. ```python python -c "import ncatbot; print('NcatBot 可用')" ``` -------------------------------- ### init Source: https://docs.ncatbot.xyz/reference/h713brec Initializes a new project by creating a config.yaml, plugins/ directory, and a template plugin. ```APIDOC ## init ``` ncatbot init [OPTIONS] ``` Initializes the project, creating `config.yaml`, a `plugins/` directory, and a template plugin named after the current computer username. Options: `--dir` (str, default: '.') : Target directory Interactive Prompts: - Please enter the bot QQ number: Writes to `bot_uin` - Please enter the administrator QQ number: Writes to `root` - Select enabled adapters: Checkbox multi-select, calls `cli_configure()` hook for each adapter. Adapter `cli_configure()` hooks have smart skipping logic: - NapCat (auto-install): Skips WS/WebUI address input, uses defaults. - NapCat (not auto-install): Interactively inputs WS address, Token, WebUI address, Token. - Bilibili (scan QR code): Skips manual input of sessdata, etc. (auto-obtained via scan). - Bilibili (no scan): Interactively inputs sessdata, bili_jct, buvid3, etc. Cookie fields. - GitHub: Inputs PAT, repository, Webhook/Polling mode. If `config.yaml` exists, prompts for overwrite. The generated template plugin is in `plugins/{username}/` with `manifest.toml` and `plugin.py`, implementing a 'hello'/'hi' response for group/private chats. Skips if the template plugin directory already exists. ``` -------------------------------- ### Bilibili Plugin Example Source: https://docs.ncatbot.xyz/guide/9jzb0z71 Demonstrates how to create a Bilibili plugin, add live room listeners, and reply to messages. Requires importing NcatBotPlugin and registrar. ```python from ncatbot.plugin import NcatBotPlugin from ncatbot.core import registrar class BiliPlugin(NcatBotPlugin): name = "bili_demo" version = "1.0.0" async def on_enable(self): # 添加直播间监听 await self.api.bilibili.add_live_room(12345) @registrar.on_message(platform="bilibili") async def on_msg(self, event): await event.reply(text="收到弹幕!") ``` -------------------------------- ### Platform Filtering Example Source: https://docs.ncatbot.xyz/guide/5kxxkqvy Example demonstrating how to filter events for a specific platform using the `platform` parameter. ```APIDOC ## Platform Filtering All decorators support the `platform` parameter to restrict event handling to specific platforms. ### Example: Handling only QQ platform group messages ```python from ncatbot.core import registrar from ncatbot.event.qq import GroupMessageEvent @registrar.on_group_message(platform="qq") async def qq_only(self, event: GroupMessageEvent): await event.reply(text="QQ 平台的消息") ``` ### Example: Handling messages from all platforms (default) ```python @registrar.on_message() async def all_platforms(self, event): print(f"来自 {event.platform} 的消息") ``` ``` -------------------------------- ### Install NcatBot using pip Source: https://docs.ncatbot.xyz/guide/0y9ejqdf Use pip to install the NcatBot package. Ensure you have Python 3.12 or higher. ```bash pip install ncatbot5 ``` -------------------------------- ### Plugin Mode Example Source: https://docs.ncatbot.xyz/guide/reuhhz5p Shows how to create a plugin using NcatBotPlugin, registering a command handler with @registrar.on_group_command, and interacting with platform APIs within the plugin. ```python from ncatbot.plugin import NcatBotPlugin from ncatbot.core import registrar from ncatbot.event.qq import GroupMessageEvent class DemoPlugin(NcatBotPlugin): name = "demo" version = "1.0.0" @registrar.on_group_command("ping") async def on_ping(self, event: GroupMessageEvent): await event.reply(text="pong!", image="photo.jpg") await self.api.qq.post_group_msg(event.group_id, text="Hello!", at=event.user_id) ``` -------------------------------- ### Platform API Interface Example Source: https://docs.ncatbot.xyz/contributing/ut5fzafu Example of a platform-specific API interface that combines trait protocols with platform-exclusive methods. ```python # Platform API interface (`api/platforms/`) IQQAPI(ABC) ``` -------------------------------- ### Configure Adapters in config.yaml Source: https://docs.ncatbot.xyz/guide/vagz7643 Directly edit the `config.yaml` file to manage adapter settings. This example shows configuration for QQ, Bilibili, GitHub, and AI adapters. ```yaml adapters: - type: napcat # Adapter name platform: qq # Platform identifier enabled: true config: # Adapter-specific configuration ws_uri: ws://localhost:3001 ws_token: napcat_ws ``` ```yaml adapters: - type: napcat platform: qq enabled: true config: ws_uri: ws://localhost:3001 - type: bilibili platform: bilibili enabled: true config: live_rooms: [12345] - type: github platform: github enabled: true config: token: "ghp_xxxx" repos: ["owner/repo"] - type: ai platform: ai enabled: true config: completion_model: "gpt-4" ``` -------------------------------- ### Accessing Multi-Platform APIs Source: https://docs.ncatbot.xyz/guide/reuhhz5p Demonstrates how to use universal reply methods and platform-specific API calls for QQ, Bilibili, and GitHub. Ensure the relevant platform client is initialized. ```python await event.reply(text="收到") ``` ```python await self.api.qq.post_group_msg(group_id, text="Hello!") ``` ```python await self.api.qq.messaging.send_group_msg(group_id, message) ``` ```python await self.api.qq.manage.set_group_ban(group_id, user_id, 600) ``` ```python await self.api.bilibili.send_danmu(room_id, "弹幕内容") ``` ```python await self.api.bilibili.send_private_msg(user_id, "私信内容") ``` ```python await self.api.github.create_issue_comment("owner/repo", 42, "已处理") ``` ```python await self.api.github.merge_pr("owner/repo", 10, merge_method="squash") ``` -------------------------------- ### 发送 JSON GET 请求 Source: https://docs.ncatbot.xyz/reference/4g9ojhm3 get_json 函数用于发送 JSON GET 请求。超时抛出 TimeoutError,HTTP 非 200 抛出 urllib.error.HTTPError。 ```python def get_json( url: str, headers: Optional[dict] = None, timeout: float = 5.0, ) -> dict ``` -------------------------------- ### Initialize ncatbot project Source: https://docs.ncatbot.xyz/reference/h713brec Initializes a new ncatbot project by creating configuration files and a template plugin. ```bash ncatbot init [OPTIONS] ``` -------------------------------- ### Minimal Runnable Plugin Source: https://docs.ncatbot.xyz/guide/r3952n4t A basic example of a plugin that responds to a 'hello' command. It demonstrates the core structure required for a plugin, including inheritance from NcatBotPlugin and command registration using the registrar decorator. ```python from ncatbot.plugin import NcatBotPlugin from ncatbot.core import registrar from ncatbot.event.qq import GroupMessageEvent class HelloPlugin(NcatBotPlugin): name = "hello" version = "1.0.0" @registrar.on_group_command("hello") async def on_hello(self, event: GroupMessageEvent): await event.reply(text="Hello!") ``` -------------------------------- ### Misc API HTTP GET Request Source: https://docs.ncatbot.xyz/reference/8tjs0s36 Perform an HTTP GET request to a specified URL. This is a general-purpose network utility in the MiscAPI. ```python http_get() ``` -------------------------------- ### RBACMixin Basic Usage Example Source: https://docs.ncatbot.xyz/guide/sbal250z Demonstrates how to register permissions, create roles, assign permissions to roles, and protect commands with RBAC. Ensure the RBACService is available via `self.rbac`. ```python class MyPlugin(NcatBotPlugin): name = "rbac_demo" version = "1.0.0" async def on_load(self): # 注册权限路径 self.add_permission("rbac.admin") self.add_permission("rbac.user") # 创建角色 self.add_role("rbac_admin", exist_ok=True) self.add_role("rbac_user", exist_ok=True) # 给角色分配权限(通过底层 RBAC 服务) if self.rbac: self.rbac.grant("role", "rbac_admin", "rbac.admin") self.rbac.grant("role", "rbac_admin", "rbac.user") self.rbac.grant("role", "rbac_user", "rbac.user") @registrar.on_group_command("授权") async def on_grant(self, event: GroupMessageEvent, target: At = None): """授予用户 admin 角色""" if target is None: await event.reply("请 @一个用户") return target_uid = str(target.user_id) if self.rbac: self.rbac.assign_role("user", target_uid, "rbac_admin") await event.reply(f"已授予 {target_uid} 管理员权限 ✅") @registrar.on_group_command("管理命令") async def on_admin_cmd(self, event: GroupMessageEvent): """受权限保护的命令""" uid = str(event.user_id) if self.check_permission(uid, "rbac.admin"): await event.reply("🔑 管理命令执行成功!") else: await event.reply("🚫 你没有执行此命令的权限") @registrar.on_group_command("查权限") async def on_check_perm(self, event: GroupMessageEvent): """查看自己的权限""" uid = str(event.user_id) has_admin = self.check_permission(uid, "rbac.admin") is_admin_role = self.user_has_role(uid, "rbac_admin") await event.reply( f"👤 权限状态:\n" f" 角色 rbac_admin: {'✅' if is_admin_role else '❌'}\n" f" 权限 rbac.admin: {'✅' if has_admin else '❌'}" ) ``` -------------------------------- ### Bilibili Comment Bot Example Source: https://docs.ncatbot.xyz/guide/d6derub8 An example of a NcatBot plugin that listens for new comments on a video and automatically replies. Requires `add_comment_watch` and a notice handler. ```python class CommentBot(NcatBotPlugin): name = "comment_bot" version = "1.0.0" async def on_enable(self): # 监听视频评论 await self.api.bilibili.add_comment_watch("BV1xx411c7mD", "video") @registrar.on_notice(platform="bilibili") async def on_new_comment(self, event): # 自动回复新评论 if hasattr(event, "comment_id"): await self.api.bilibili.reply_comment( resource_id=event.resource_id, resource_type=event.resource_type, root_id=event.comment_id, parent_id=event.comment_id, text="感谢评论!", ) ``` -------------------------------- ### Start Background Task in on_load() Source: https://docs.ncatbot.xyz/guide/8a7lrplq Use `asyncio.create_task()` in `on_load()` to start a persistent background task. Ensure the task is cancellable in `on_close()` to prevent resource leaks. ```python class MyPlugin(NcatBotPlugin): name = "my_plugin" version = "1.0.0" async def on_load(self): self._task = asyncio.create_task(self._background_worker()) async def on_close(self): if hasattr(self, "_task"): self._task.cancel() async def _background_worker(self): try: async with self.events("message") as stream: async for event in stream: LOG.info("收到消息: %s", event.data.raw_message) except asyncio.CancelledError: pass ``` -------------------------------- ### Generate config.yaml using CLI Source: https://docs.ncatbot.xyz/guide/0y9ejqdf Use the NcatBot CLI to interactively generate the config.yaml file. This is the recommended method for initial setup. ```bash ncatbot init ``` -------------------------------- ### Non-blocking Bot Startup with Event-Driven Main Loop Source: https://docs.ncatbot.xyz/guide/fzk8vub0 Demonstrates how to run a bot in a non-plugin mode using `run_async()` and consume events directly from `bot.dispatcher`. Includes a background keyword monitor task. ```python import asyncio from ncatbot.app import BotClient from ncatbot.core import same_group, has_keyword bot = BotClient() async def keyword_monitor(): """后台监控:检测到关键词时自动提醒""" async with bot.dispatcher.events("message.group") as stream: async for event in stream: if "紧急" in event.data.raw_message: await bot.api.qq.post_group_msg( event.data.group_id, text=f"⚠️ 检测到紧急消息 (来自 {event.data.user_id})", ) async def main(): await bot.run_async() # Bot 就绪,后台监听 # 启动后台监控任务 monitor_task = asyncio.create_task(keyword_monitor()) try: await asyncio.Event().wait() except asyncio.CancelledError: pass finally: monitor_task.cancel() await bot.shutdown() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Show current configuration Source: https://docs.ncatbot.xyz/reference/h713brec Displays the entire current configuration in YAML format. ```bash ncatbot config show ``` -------------------------------- ### View Help Information Source: https://docs.ncatbot.xyz/reference/h713brec Use these commands to view general help or specific command help. ```bash ncatbot --help # 查看所有命令 ncatbot --help # 查看单个命令帮助 ``` -------------------------------- ### List Loaded and Indexed Plugins Source: https://docs.ncatbot.xyz/examples/common/09_plugin_management This command lists all currently loaded plugins and all plugins that have been indexed by the framework. It uses loader.list_plugins() to get loaded plugins and loader.list_indexed() to get all indexed plugins. ```python @registrar.on_command("插件列表") async def on_list_plugins(self, event): """List all loaded and indexed plugins""" loader = self._plugin_loader loaded = loader.list_plugins() indexed = loader.list_indexed() lines = ["📦 Plugin List:"] lines.append(f" Loaded: {len(loaded)} plugins") lines.append(f" Indexed: {len(indexed)} plugins") lines.append("") for name in sorted(indexed.keys()): manifest = indexed[name] status = "✅ Loaded" if name in loaded else "⬚ Not Loaded" lines.append(f" {status} {name} v{manifest.version}") if isinstance(event, Replyable): await event.reply(text="\n".join(lines)) ``` -------------------------------- ### Download File with Progress - Python Source: https://docs.ncatbot.xyz/reference/c1734blh Demonstrates downloading a file using `download_file`, which internally utilizes the custom `tqdm` wrapper to display download progress with NcatBot's styling. ```python from ncatbot import download_file download_file("https://example.com/large.zip", "large.zip") # 处理中: 45%|████████████ | 45/100 [00:03<00:04, 12.50it/s] ``` -------------------------------- ### Asynchronous HTTP GET Request - Python Source: https://docs.ncatbot.xyz/reference/c1734blh Performs an asynchronous HTTP GET request to a specified URL. Allows custom headers, proxy configuration, and a timeout. Returns the response body as bytes. ```python from ncatbot.utils import async_http_get async def http_get_example(): response_data = await async_http_get( "https://api.example.com/data", headers={"Authorization": "Bearer token"}, proxy="http://localhost:8080", timeout=5.0 ) ``` -------------------------------- ### Initialize NcatBot Project via CLI Source: https://docs.ncatbot.xyz/guide/695ruqzj Create a new NcatBot project directory and initialize it using the ncatbot CLI. This command prompts for essential bot details and generates a basic project structure. ```bash mkdir my-bot && cd my-bot ncatbot init ``` -------------------------------- ### ConfigManager Initialization Source: https://docs.ncatbot.xyz/reference/m3pmk1ut Demonstrates how to get the ConfigManager instance, either with default path or a specified configuration file path. ```APIDOC ## ConfigManager Initialization ### Description Get the global singleton ConfigManager instance. If a path is provided, a new instance will be created. ### Method `get_config_manager(path: Optional[str] = None) -> ConfigManager` ### Parameters #### Path Parameters - **path** (`Optional[str]`) - Optional - The path to the configuration file. If `None`, it uses the environment variable `NCATBOT_CONFIG_PATH` or `./config.yaml`. ### Usage Example ```python from ncatbot.utils.config.manager import ConfigManager, get_config_manager # Get ConfigManager with default path cm = get_config_manager() # Get ConfigManager with a specified path cm = get_config_manager("dev/config.yaml") ``` ```