qingci-plugin-sdk 1.15.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,196 @@
1
+ """Qingci-Bot 插件 SDK — 独立可安装的插件开发工具包
2
+
3
+ 使用方式:
4
+ from qingci_plugin_sdk import PluginBase, on_command, MatcherContext
5
+
6
+ 安装:
7
+ uv pip install -e . # 从 Plugins-SDK 目录
8
+ """
9
+
10
+ __version__ = "1.15.2"
11
+
12
+ from .base import PluginBase, PluginStatus
13
+ from .context import MessageContext
14
+ from .events import (
15
+ FriendAddNotice,
16
+ FriendPokeNotice,
17
+ FriendRecallNotice,
18
+ FriendRequestEvent,
19
+ GroupAdminNotice,
20
+ GroupBanNotice,
21
+ GroupCardNotice,
22
+ GroupDecreaseNotice,
23
+ GroupEssenceNotice,
24
+ GroupHonorChangeNotice,
25
+ GroupIncreaseNotice,
26
+ GroupLuckyKingNotice,
27
+ GroupRecallNotice,
28
+ GroupRequestEvent,
29
+ GroupSignInNotice,
30
+ GroupUploadNotice,
31
+ MessageEditedEvent,
32
+ NoticeEvent,
33
+ PokeNotice,
34
+ RequestEvent,
35
+ detail_type_to_notice_type,
36
+ notice_type_to_detail_type,
37
+ parse_event,
38
+ parse_notice_event,
39
+ parse_request_event,
40
+ parse_v12_event,
41
+ translate_v11_event,
42
+ )
43
+ from .i18n import I18n
44
+ from .llm_tool import LlmToolSpec, begin_tool_collection, end_tool_collection, llm_tool
45
+ from .matcher import (
46
+ Matcher,
47
+ MatcherContext,
48
+ begin_module_collection,
49
+ end_module_collection,
50
+ on_command,
51
+ on_keyword,
52
+ on_message,
53
+ on_notice,
54
+ on_request,
55
+ on_startswith,
56
+ )
57
+ from .media import DEFAULT_MAX_BYTES, resolve_image, resolve_images
58
+ from .permission import (
59
+ ADMIN,
60
+ EVERYONE,
61
+ GROUP,
62
+ GROUP_MEMBER,
63
+ MEMBER,
64
+ PRIVATE,
65
+ SUPERUSER,
66
+ USER,
67
+ Permission,
68
+ describe_permission,
69
+ )
70
+ from .ratelimit import RateLimiter
71
+ from .rule import (
72
+ Rule,
73
+ command,
74
+ contains,
75
+ endswith,
76
+ fullmatch,
77
+ is_group,
78
+ is_private,
79
+ keyword,
80
+ rate_limit,
81
+ regex,
82
+ startswith,
83
+ subcommand,
84
+ to_me,
85
+ )
86
+ from .segments import (
87
+ Message,
88
+ MessageSegment,
89
+ SegmentType,
90
+ normalize_v11_segment,
91
+ parse_cq_string,
92
+ segments_to_v11,
93
+ segments_to_v12,
94
+ to_v11_segment,
95
+ )
96
+ from .session import FinishException, PauseException, RejectException, Session
97
+
98
+ __all__ = [
99
+ # 版本
100
+ "__version__",
101
+ # 基础
102
+ "PluginBase",
103
+ "PluginStatus",
104
+ "MessageContext",
105
+ # i18n
106
+ "I18n",
107
+ # 类型化事件
108
+ "NoticeEvent",
109
+ "GroupIncreaseNotice",
110
+ "GroupDecreaseNotice",
111
+ "GroupBanNotice",
112
+ "GroupAdminNotice",
113
+ "GroupRecallNotice",
114
+ "FriendRecallNotice",
115
+ "FriendAddNotice",
116
+ "GroupUploadNotice",
117
+ "PokeNotice",
118
+ "FriendPokeNotice",
119
+ "GroupLuckyKingNotice",
120
+ "GroupHonorChangeNotice",
121
+ "GroupCardNotice",
122
+ "GroupEssenceNotice",
123
+ "GroupSignInNotice",
124
+ "MessageEditedEvent",
125
+ "RequestEvent",
126
+ "FriendRequestEvent",
127
+ "GroupRequestEvent",
128
+ "parse_event",
129
+ "parse_notice_event",
130
+ "parse_request_event",
131
+ "parse_v12_event",
132
+ "translate_v11_event",
133
+ "detail_type_to_notice_type",
134
+ "notice_type_to_detail_type",
135
+ # 消息段
136
+ "SegmentType",
137
+ "MessageSegment",
138
+ "Message",
139
+ "parse_cq_string",
140
+ "normalize_v11_segment",
141
+ "to_v11_segment",
142
+ "segments_to_v11",
143
+ "segments_to_v12",
144
+ # LLM 工具
145
+ "LlmToolSpec",
146
+ "llm_tool",
147
+ "begin_tool_collection",
148
+ "end_tool_collection",
149
+ # Matcher
150
+ "Matcher",
151
+ "MatcherContext",
152
+ "on_message",
153
+ "on_command",
154
+ "on_startswith",
155
+ "on_keyword",
156
+ "on_notice",
157
+ "on_request",
158
+ "begin_module_collection",
159
+ "end_module_collection",
160
+ # Permission
161
+ "Permission",
162
+ "EVERYONE",
163
+ "SUPERUSER",
164
+ "ADMIN",
165
+ "PRIVATE",
166
+ "GROUP",
167
+ "MEMBER",
168
+ "USER",
169
+ "GROUP_MEMBER",
170
+ "describe_permission",
171
+ # Rule
172
+ "Rule",
173
+ "startswith",
174
+ "endswith",
175
+ "fullmatch",
176
+ "contains",
177
+ "regex",
178
+ "command",
179
+ "subcommand",
180
+ "to_me",
181
+ "is_private",
182
+ "is_group",
183
+ "keyword",
184
+ "rate_limit",
185
+ # RateLimit
186
+ "RateLimiter",
187
+ # 会话阶梯
188
+ "Session",
189
+ "PauseException",
190
+ "FinishException",
191
+ "RejectException",
192
+ # 媒体解析
193
+ "resolve_image",
194
+ "resolve_images",
195
+ "DEFAULT_MAX_BYTES",
196
+ ]
@@ -0,0 +1,393 @@
1
+ """插件基类 — 插件 SDK 独立版本"""
2
+
3
+ import enum
4
+ from abc import ABC, abstractmethod
5
+ from collections.abc import Sequence
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Any, cast
8
+
9
+ from .context import MessageContext
10
+
11
+ if TYPE_CHECKING:
12
+ from .matcher import Matcher
13
+
14
+
15
+ # 已弃用的旧式事件钩子 → 推荐替代方式。
16
+ # 键必须与 PluginBase 上的方法名一致;覆写时在类创建阶段告警(见 __init_subclass__)。
17
+ _DEPRECATED_HOOKS: dict[str, str] = {
18
+ "on_message": "Matcher 工厂 on_message()/on_command() 等",
19
+ "on_notice": "Matcher 工厂 on_notice()(matcher.py)",
20
+ "on_request": "Matcher 工厂 on_request()(matcher.py)",
21
+ }
22
+
23
+
24
+ class PluginStatus(str, enum.Enum):
25
+ """插件状态枚举"""
26
+
27
+ LOADING = "loading" # 正在加载(on_load 执行中)
28
+ LOADED = "loaded" # 已加载,正常运行
29
+ DISABLED = "disabled" # 已禁用,跳过事件分发
30
+ ERROR = "error" # 加载/运行出错
31
+ UNLOADING = "unloading" # 正在卸载(on_unload 执行中)
32
+
33
+
34
+ class PluginBase(ABC):
35
+ """插件基类
36
+
37
+ 支持两种消息处理方式:
38
+ 1. 旧式:重写 on_message(ctx) -> str | None
39
+ 2. 新式:在 on_load 中注册 Matcher(self.matchers.append(on_command(...)(handler)))
40
+ 或用模块级装饰器 @on_command(...)(PluginManager 自动收集)
41
+
42
+ 新旧方式可共存,Dispatcher 按优先级统一调度。
43
+
44
+ 插件级配置:
45
+ - 定义 Config 内嵌类(pydantic BaseModel 风格)声明配置项
46
+ - 框架自动从 config.yaml 的 plugins.<name> 节加载到 self.plugin_config
47
+
48
+ 插件导出:
49
+ - on_load 中调用 self.export("key", value) 暴露接口
50
+ - 依赖方通过 self.get_exports("plugin_name") 获取导出字典
51
+
52
+ 状态/生命周期:
53
+ - LOADING → LOADED → DISABLED ↔ LOADED → UNLOADING
54
+ - LOADING → ERROR(加载失败)
55
+ - 禁用/启用不触发 on_load/on_unload
56
+ """
57
+
58
+ # 插件元信息
59
+ name: str = ""
60
+ version: str = "1.0.0"
61
+ author: str = ""
62
+ description: str = ""
63
+ category: str = "" # 插件分类:chat / admin / tool / fun / 自定义
64
+ # 依赖的插件 name 列表:支持 PEP 440 版本约束,如 "chat>=1.0,<2.0"
65
+ # 依赖缺失或形成循环依赖时插件加载失败(借鉴 NoneBot2 require 机制)
66
+ require: list[str] = []
67
+
68
+ # 插件状态(由 PluginManager 管理)
69
+ _status: PluginStatus = PluginStatus.LOADING
70
+
71
+ # 依赖引用(由框架注入)
72
+ # 标注为 Any | None:这些对象由宿主实现,SDK 不依赖其类型(避免反向依赖),
73
+ # 但用 object 会让下游插件的 self.bot.xxx / self.llm.chat() 在 mypy 下
74
+ # 全部报「object 无该属性」。与下方 scheduler / tool_registry 等保持一致。
75
+ bot: Any | None = None
76
+ db: Any | None = None
77
+ config: Any | None = None
78
+ connection: Any | None = None
79
+ llm: Any | None = None
80
+ scheduler: Any | None = None
81
+ tool_registry: Any | None = None
82
+ knowledge_store: Any | None = None
83
+ session_state: Any | None = None # TTL 会话状态存储
84
+ event_bus: Any | None = None # 跨插件事件总线(发布-订阅)
85
+
86
+ # Matcher 列表
87
+ matchers: list["Matcher"] | None = None
88
+
89
+ # 插件级配置(由 PluginManager 从 config.yaml 加载)
90
+ plugin_config: Any | None = None
91
+
92
+ # 导出注册表(插件间服务接口)
93
+ _exports: dict[str, Any]
94
+
95
+ # Web 管理页面注册
96
+ _pages: list[dict[str, str]]
97
+
98
+ # Web API 注册(插件级 HTTP 接口,由主项目挂载到 /api/plugin-web/<name>/)
99
+ _apis: list[dict[str, Any]]
100
+
101
+ # 中间件链(per-handler 钩子)
102
+ # before_handler: async (matcher, ctx) -> str | None
103
+ # - 返回非 None 时拦截,跳过 handler 并将返回值作为回复
104
+ # after_handler: async (matcher, ctx, result) -> str | None
105
+ # - 可修改/替换 handler 返回值
106
+ _before_handlers: list[Any]
107
+ _after_handlers: list[Any]
108
+
109
+ # data_dir 解析缓存:(数据根, 插件名) -> 已创建目录(避免每次访问都 mkdir)
110
+ _data_dir_cache: tuple[tuple[str, str], Path] | None = None
111
+
112
+ def __init_subclass__(cls, **kwargs: Any) -> None:
113
+ """为每个插件类隔离 require 列表,并对弃用钩子的覆写发出告警
114
+
115
+ `require` 默认值是类级可变对象(list)。若子类未重新声明,多个插件
116
+ 会共享同一个列表,任一插件执行 `self.require.append(...)` 都会污染
117
+ 同进程其他插件。此处为未显式声明 require 的子类复制一份独立列表。
118
+
119
+ 弃用钩子(`on_message` / `on_notice` / `on_request`)仍保留默认空实现
120
+ 以兼容旧插件,但子类覆写时会在加载阶段记录 WARNING——否则插件作者
121
+ 得不到任何运行时信号,弃用状态会无限期延续下去。
122
+ """
123
+ super().__init_subclass__(**kwargs)
124
+ if "require" not in cls.__dict__:
125
+ cls.require = list(getattr(cls, "require", ()))
126
+
127
+ for hook, replacement in _DEPRECATED_HOOKS.items():
128
+ if hook in cls.__dict__:
129
+ import logging
130
+
131
+ logging.getLogger("qingci-bot.sdk").warning(
132
+ "插件 %s 覆写了已弃用的钩子 %s(),请改用 %s;"
133
+ "该钩子计划在下一个主版本(2.0)移除",
134
+ cls.__name__,
135
+ hook,
136
+ replacement,
137
+ )
138
+
139
+ def __init__(self):
140
+ self._exports = {}
141
+ self._pages = []
142
+ self._apis = []
143
+ self._before_handlers = []
144
+ self._after_handlers = []
145
+ self._status = PluginStatus.LOADING
146
+ self._data_dir_cache = None
147
+ # 国际化:插件可声明 i18n/<locale>.json 翻译资源,self._ = self.i18n.t。
148
+ # 翻译文件放在**插件模块同级**的 i18n/ 目录(如 plugins/<name>/i18n/zh-CN.json),
149
+ # 宿主加载插件时自动 load_dir 并应用全局语言(Qingci-Bot-CE 的
150
+ # PluginManager._load_i18n → load_plugin_i18n),插件无需手动调用。
151
+ # 独立开发(无宿主)时才需要自己 self.i18n.load_dir(<插件目录>)。
152
+ from .i18n import I18n
153
+
154
+ self.i18n = I18n("zh-CN")
155
+ self._ = self.i18n.t
156
+
157
+ # ---- 数据目录 ----
158
+
159
+ @property
160
+ def data_dir(self) -> Path:
161
+ """插件专属数据目录(自动创建,建议用于持久化文件数据)
162
+
163
+ 路径约定:data_root()/plugins/<name>/;宿主卸载插件默认保留该目录,
164
+ 仅宿主「彻底删除(purge)」时删除,供插件存储运行时数据(缓存、导出文件等)。
165
+
166
+ 结果按 (数据根, 插件名) 缓存:mkdir 是系统调用,早期实现每次访问都执行
167
+ 一次(实测约 110µs),handler 内多次读取会显著拖慢消息处理。宿主通过
168
+ set_data_root() 切换数据根或插件名变更时自动失效。
169
+ """
170
+ from .paths import data_root
171
+
172
+ root = data_root()
173
+ cache_key = (str(root), self.name)
174
+ cached = self._data_dir_cache
175
+ if cached is not None and cached[0] == cache_key:
176
+ return cached[1]
177
+
178
+ d = root / "plugins" / self.name
179
+ d.mkdir(parents=True, exist_ok=True)
180
+ self._data_dir_cache = (cache_key, d)
181
+ return d
182
+
183
+ # ---- 状态 ----
184
+
185
+ @property
186
+ def status(self) -> PluginStatus:
187
+ """插件当前状态"""
188
+ return self._status
189
+
190
+ @property
191
+ def enabled(self) -> bool:
192
+ """向后兼容:LOADED 视为启用(含 LOADING 过渡态)"""
193
+ return self._status in (PluginStatus.LOADING, PluginStatus.LOADED)
194
+
195
+ @enabled.setter
196
+ def enabled(self, value: bool) -> None:
197
+ """向后兼容:setter 由 PluginManager.disable/enable 使用"""
198
+ if value:
199
+ if self._status == PluginStatus.DISABLED:
200
+ self._status = PluginStatus.LOADED
201
+ else:
202
+ if self._status == PluginStatus.LOADED:
203
+ self._status = PluginStatus.DISABLED
204
+
205
+ # ---- 导出机制 ----
206
+
207
+ def export(self, key: str, value: Any) -> None:
208
+ """导出接口供依赖方调用(在 on_load 中使用)"""
209
+ self._exports[key] = value
210
+
211
+ def get_exports(self, plugin_name: str) -> dict[str, Any]:
212
+ """获取依赖插件的导出字典(需在 on_load 中声明 require)
213
+
214
+ 注意:方法名为 get_exports,避免与 require 依赖声明属性重名。
215
+ """
216
+ if self.bot is None:
217
+ raise RuntimeError("插件未初始化,无法获取依赖")
218
+ bot: Any = self.bot # bot 由框架注入(类型为 object | None),运行时具备 plugin_manager
219
+ dep = bot.plugin_manager.get(plugin_name)
220
+ if dep is None:
221
+ raise RuntimeError(f"依赖插件 {plugin_name} 未加载")
222
+ return cast(dict[str, Any], dep._exports)
223
+
224
+ # ---- 中间件 ----
225
+
226
+ def register_before(self, fn) -> None:
227
+ """注册 handler 前置钩子:async (matcher, ctx) -> str | None"""
228
+ if fn not in self._before_handlers:
229
+ self._before_handlers.append(fn)
230
+
231
+ def register_after(self, fn) -> None:
232
+ """注册 handler 后置钩子:async (matcher, ctx, result) -> str | None"""
233
+ if fn not in self._after_handlers:
234
+ self._after_handlers.append(fn)
235
+
236
+ def register_page(self, title: str, icon: str = "◇", static_dir: str = "") -> None:
237
+ """注册插件 Web 管理页面
238
+
239
+ 在 on_load 中调用,入口自动显示在插件管理页的插件卡片上。
240
+
241
+ Args:
242
+ title: 页面标题,显示在按钮上
243
+ icon: 图标字符,默认 ◇
244
+ static_dir: 静态文件目录的绝对路径。可省略,框架自动探测
245
+ 插件 __init__.py 同级的 web/ 目录。
246
+ """
247
+ import os
248
+
249
+ if not static_dir:
250
+ # 自动探测:插件类所在模块同级的 web/ 目录
251
+ module_file = getattr(type(self), "__module__", None)
252
+ if module_file:
253
+ import importlib
254
+ import logging
255
+
256
+ try:
257
+ mod = importlib.import_module(module_file)
258
+ mod_path = getattr(mod, "__file__", None)
259
+ if mod_path:
260
+ candidate = os.path.join(os.path.dirname(mod_path), "web")
261
+ if os.path.isdir(candidate):
262
+ static_dir = candidate
263
+ except Exception as e:
264
+ # 探测失败记录日志,避免静默吞异常导致页面注册无 web/ 目录
265
+ logging.getLogger("qingci-bot.sdk").debug(
266
+ f"插件 web/ 目录探测失败: {module_file}: {e}"
267
+ )
268
+ self._pages.append(
269
+ {
270
+ "title": title,
271
+ "icon": icon,
272
+ "static_dir": static_dir,
273
+ }
274
+ )
275
+
276
+ def register_api(
277
+ self,
278
+ path: str,
279
+ handler,
280
+ *,
281
+ methods: Sequence[str] | None = None,
282
+ description: str = "",
283
+ ) -> None:
284
+ """注册插件 Web API(在 on_load 中调用)
285
+
286
+ 由主项目挂载到 `/api/plugin-web/<插件名>/<path>`,鉴权对齐主项目
287
+ API 体系。插件可借此提供 WebUI 管理接口(配合 register_page 的
288
+ 前端页面使用)。
289
+
290
+ handler 契约(任意平台实现均按此签名适配):
291
+ async def handler(request) -> Response | (data, status) | data
292
+ - request:框架 HTTP 请求对象(主项目为 FastAPI Request,可读取
293
+ `request.query_params` / `request.headers`、`await request.json()`
294
+ 取 JSON body、`await request.form()` 取上传文件等)
295
+ - 返回 Response 对象(如 `JSONResponse` / `FileResponse`)时原样返回;
296
+ 返回 `(data, status_code)` 二元组时按 JSON 序列化并指定状态码;
297
+ 返回 dict / list / str 时自动 JSON 序列化
298
+
299
+ Args:
300
+ path: 相对路径(固定字面路径,不含 {id} 动态段;动态取值经
301
+ query 参数传递),如 "checkin-ranking"、"content-safety/terms/add"
302
+ handler: 处理函数(见上方契约)
303
+ methods: HTTP 方法列表,默认 ["GET"]
304
+ description: 接口描述(调试/文档用)
305
+ """
306
+ self._apis.append(
307
+ cast(
308
+ dict,
309
+ {
310
+ "path": str(path or "").strip("/"),
311
+ "handler": handler,
312
+ "methods": [str(m).upper() for m in (methods or ["GET"])],
313
+ "description": str(description or ""),
314
+ },
315
+ )
316
+ )
317
+
318
+ # ---- 生命周期 ----
319
+
320
+ @abstractmethod
321
+ async def on_load(self):
322
+ """插件加载时调用"""
323
+ ...
324
+
325
+ @abstractmethod
326
+ async def on_unload(self):
327
+ """插件卸载时调用"""
328
+ ...
329
+
330
+ async def on_message(self, ctx: MessageContext) -> str | None:
331
+ """处理消息事件,返回回复文本或 None(已弃用)
332
+
333
+ Deprecated: 请改用 Matcher(on_message / on_command 等)注册消息处理。
334
+ 本回调保留仅为兼容旧插件,新插件请勿使用。
335
+ """
336
+ return None
337
+
338
+ async def on_notice(self, event: dict) -> None:
339
+ """处理通知事件(已弃用)
340
+
341
+ Deprecated: 请改用 Matcher 工厂 on_notice()(matcher.py)注册事件处理。
342
+ """
343
+ return None
344
+
345
+ async def on_request(self, event: dict) -> bool | None:
346
+ """处理请求事件(加群/加好友),返回 True 同意 / False 拒绝 / None 忽略(已弃用)
347
+
348
+ Deprecated: 请改用 Matcher 工厂 on_request()(matcher.py)注册事件处理。
349
+ """
350
+ return None
351
+
352
+ async def on_disable(self):
353
+ """插件被禁用时调用(可选覆写,用于停用定时任务等轻量清理)"""
354
+ return None
355
+
356
+ async def on_enable(self):
357
+ """插件被启用时调用(可选覆写,用于恢复定时任务等)"""
358
+ return None
359
+
360
+ # ---- 全局生命周期钩子(可选覆写,默认空实现) ----
361
+
362
+ async def on_startup(self):
363
+ """Bot 启动完成后调用(所有插件加载完毕、连接就绪后)
364
+
365
+ 用于连接数据库、注册后台任务等耗时初始化。异常隔离,不影响启动。
366
+ """
367
+ return None
368
+
369
+ async def on_shutdown(self):
370
+ """Bot 停止时调用(在插件 on_unload 之前)
371
+
372
+ 用于释放 on_startup 中申请的资源。异常隔离。
373
+ """
374
+ return None
375
+
376
+ async def on_bot_connect(self):
377
+ """有 QQ 会话(LLBot)连接到反向 WebSocket 时调用
378
+
379
+ 初始连接与重连均触发,用于初始化会话相关资源。
380
+ """
381
+ return None
382
+
383
+ async def on_metaevent(self, event: dict) -> bool | None:
384
+ """处理元事件(生命周期,如 heartbeat / connect / enable)
385
+
386
+ 旁路通知:宿主向每个覆写了本钩子的插件各调一次,**忽略返回值**——没有
387
+ 「消费掉、后续插件不再收到」的语义。返回 ``True`` 不会阻止其他插件收到,
388
+ 也不会影响事件分发。
389
+
390
+ 需要拦截事件用 Matcher 的 ``block``;需要审批加好友/加群用
391
+ ``on_request`` 返回 ``bool``(那个返回值是真被消费的)。
392
+ """
393
+ return None