插件模式最小示例
约 440 字大约 1 分钟
2025-02-08
文件结构
文件结构(工作目录为 main.py 所在目录):
main.py
plugins/
hello_plugin/
hello_plugin.py
__init__.py
hello_plugin/hello_plugin.py
from ncatbot.plugin_system import NcatBotPlugin
from ncatbot.plugin_system import command_registry
from ncatbot.plugin_system import filter_registry
from ncatbot.core.event import BaseMessageEvent, PrivateMessageEvent
class HelloPlugin(NcatBotPlugin):
name = "HelloPlugin"
version = "1.0.0"
async def on_load(self):
# 可留空,保持轻量
pass
@command_registry.command("hello")
async def hello_cmd(self, event: BaseMessageEvent):
await event.reply("你好!我是插件 HelloPlugin。")
@filter_registry.private_filter
async def on_private_msg(self, event: PrivateMessageEvent):
await event.reply("你发送了一条私聊消息!")
插件类
插件类可以利用 NcatBot 插件系统的强大功能,来定义一组功能的集合。一个插件作为一个整体能够非常灵活的迁移,参见。
command_registry
用于以命令的形式识别和处理消息,参见。
filter_registry
用于以非命令的形式识别和处理消息,参见。
ncatbot.core.event
事件数据结构,用于描述收到的消息、加群请求等,参见。
hello_plugin/__init__.py
from .hello_plugin import HelloPlugin
__all__ = ["HelloPlugin"]
用于导出和整理插件,以便插件系统识别和加载插件。
main.py
from ncatbot.core import BotClient
bot = BotClient()
bot.run_frontend()
BotClient
用于启动和终止 Bot,安装、配置、连接 NapCat;引导插件系统的加载;提供回调函数注册接口,参见。
运行
工作目录下执行 python main.py
。
可以通过配置项指定 QQ 号等信息,以便无需每次输入 QQ 号。
版权所有
版权归属:huan-yp