非插件模式启动
约 672 字大约 2 分钟
2026-03-19
在 main.py 中直接用 registrar 装饰器注册回调 — 最快的启动方式,适合快速原型和简单 Bot。
前提条件
- 已完成 安装与配置
完整示例
创建 main.py:
from ncatbot.app import BotClient
from ncatbot.core import registrar
from ncatbot.event.qq import GroupMessageEvent, PrivateMessageEvent
bot = BotClient()
@registrar.on_group_command("hello", ignore_case=True)
async def on_hello(event: GroupMessageEvent):
await event.reply(text="Hello, NcatBot!")
@registrar.on_private_command("ping")
async def on_ping(event: PrivateMessageEvent):
await event.reply(text="pong!")
if __name__ == "__main__":
bot.run()启动:
python main.py在群聊发送 hello,Bot 回复 "Hello, NcatBot!" 即成功。
项目结构
my-bot/
├── config.yaml # 配置文件
└── main.py # 入口文件,所有逻辑写在这里异步非阻塞启动
上面的 bot.run() 是同步阻塞调用——它会占据主线程直到 Bot 关闭。如果你需要在启动后继续执行自定义的异步逻辑(例如事件驱动主循环、定时推送、与其他异步服务集成),可以使用 run_async():
import asyncio
from ncatbot.app import BotClient
from ncatbot.core import registrar, from_event, msg_equals
from ncatbot.event.qq import GroupMessageEvent
bot = BotClient()
# 装饰器注册依然可用
@registrar.on_group_command("hello")
async def on_hello(event: GroupMessageEvent):
await event.reply(text="Hello!")
async def main():
await bot.run_async()
# 此处 bot.api / bot.dispatcher 已可用,Bot 在后台监听事件
# 示例:用 dispatcher 直接等待特定事件
print("Bot 已就绪,等待第一条群消息...")
first_msg = await bot.dispatcher.wait_event(
predicate=lambda e: e.type.startswith("message.group"),
timeout=60.0,
)
print(f"收到: {first_msg.data.raw_message}")
# 保持运行,直到 Ctrl+C
try:
await asyncio.Event().wait()
except asyncio.CancelledError:
pass
finally:
await bot.shutdown()
if __name__ == "__main__":
asyncio.run(main())run() vs run_async() 对比
| 维度 | run() | run_async() |
|---|---|---|
| 阻塞性 | 同步阻塞,占据主线程 | 异步返回,Bot 在后台监听 |
| 调用方式 | bot.run() | await bot.run_async() |
| 适用场景 | 简单 Bot,无需启动后自定义逻辑 | 需要启动后执行异步编排、与其他服务集成 |
bot.api | 阻塞期间可用(在 handler 内) | 返回后立即可用 |
bot.dispatcher | 阻塞期间可用(在 handler 内) | 返回后立即可用 |
run_async() 完成 startup 后立即返回——适配器连接、分发器、API 客户端、插件全部就绪,后台 task 负责持续监听事件。
适用场景与限制
适合:快速验证想法、简单的单文件 Bot、学习框架基础。
不支持:Mixin 能力(配置持久化 / 数据存储 / RBAC / 定时任务)、热重载、插件依赖管理。
需要这些能力时 → 插件模式。
延伸阅读
版权所有
版权归属:huan-yp
