添加注释,增加redis支持,添加了聊天记录构建支持

This commit is contained in:
2026-01-02 17:10:42 +08:00
parent 3163bbf8c1
commit 01b83803c1
24 changed files with 965 additions and 313 deletions

View File

@@ -1,7 +1,17 @@
"""
命令管理器模块
命令与事件管理器模块
提供装饰器用于注册消息指令、通知处理器和请求处理器,并负责事件的分发
该模块定义了 `CommandManager` 类,它是整个机器人框架事件处理的核心
它通过装饰器模式,为插件提供了注册消息指令、通知事件处理器和
请求事件处理器的能力。
主要职责:
- 提供 `@matcher.command()` 装饰器来注册命令。
- 提供 `@matcher.on_notice()` 装饰器来注册通知处理器。
- 提供 `@matcher.on_request()` 装饰器来注册请求处理器。
- 负责解析收到的消息,匹配命令前缀并分发给对应的处理器。
- 统一处理所有类型的事件,并将其分发给所有已注册的处理器。
- 内置一个 `/help` 命令,用于展示所有已加载插件的帮助信息。
"""
import inspect
from typing import Any, Callable, Dict, List, Tuple
@@ -14,22 +24,25 @@ comm_prefixes = global_config.bot.get("command", ("/",))
class CommandManager:
"""
命令管理器,负责注册和分发指令、通知和请求事件
命令管理器,负责注册和分发所有类型的事件
这是一个单例对象(`matcher`),在整个应用中共享。
"""
def __init__(self, prefixes: Tuple[str, ...] = ("/",)):
def __init__(self, prefixes: Tuple[str, ...]):
"""
初始化命令管理器
初始化命令管理器
:param prefixes: 命令前缀元组
Args:
prefixes (Tuple[str, ...]): 一个包含所有合法命令前缀的元组。
"""
self.prefixes = prefixes
self.commands: Dict[str, Callable] = {} # 存储消息指令
self.notice_handlers: List[Dict] = [] # 存储通知处理器
self.request_handlers: List[Dict] = [] # 存储请求处理器
self.plugins: Dict[str, Dict[str, Any]] = {} # 存储插件元数据
self.commands: Dict[str, Callable] = {} # 存储消息指令处理器
self.notice_handlers: List[Dict] = [] # 存储通知事件处理器
self.request_handlers: List[Dict] = [] # 存储请求事件处理器
self.plugins: Dict[str, Dict[str, Any]] = {} # 存储已加载插件元数据
# --- 内置 help 指令 ---
# --- 注册内置 help 指令 ---
self.commands["help"] = self._help_command
self.plugins["core.help"] = {
"name": "帮助",
@@ -39,10 +52,13 @@ class CommandManager:
async def _help_command(self, bot, event):
"""
内置的 /help 指令处理器
内置的 `/help` 命令的实现。
:param bot: Bot 实例
:param event: 消息事件对象
该命令会遍历所有已加载插件的元数据,并生成一段格式化的帮助文本。
Args:
bot: Bot 实例。
event: 消息事件对象。
"""
help_text = "--- 可用指令列表 ---\n"
@@ -57,58 +73,78 @@ class CommandManager:
await bot.send(event, help_text.strip())
# --- 1. 消息指令装饰器 ---
def command(self, name: str):
def command(self, name: str) -> Callable:
"""
装饰器:注册消息指令
装饰器:用于注册一个消息指令处理器。
:param name: 指令名称(不含前缀)
:return: 装饰器函数
Example:
@matcher.command("echo")
async def handle_echo(bot, event, args):
await bot.send(event, " ".join(args))
Args:
name (str): 指令的名称(不包含命令前缀)。
Returns:
Callable: 原函数,使其可以继续被调用。
"""
def decorator(func):
def decorator(func: Callable) -> Callable:
self.commands[name] = func
return func
return decorator
# --- 2. 通知事件装饰器 ---
def on_notice(self, notice_type: str = None):
def on_notice(self, notice_type: str = None) -> Callable:
"""
装饰器:注册通知处理器
装饰器:用于注册一个通知事件处理器
:param notice_type: 通知类型,如果为 None 则处理所有通知
:return: 装饰器函数
如果 `notice_type` 未指定,则该处理器会接收所有类型的通知事件。
Args:
notice_type (str, optional): 要处理的通知类型 (e.g., "group_increase")。
Defaults to None.
Returns:
Callable: 原函数。
"""
def decorator(func):
def decorator(func: Callable) -> Callable:
self.notice_handlers.append({"type": notice_type, "func": func})
return func
return decorator
# --- 3. 请求事件装饰器 ---
def on_request(self, request_type: str = None):
def on_request(self, request_type: str = None) -> Callable:
"""
装饰器:注册请求处理器
装饰器:用于注册一个请求事件处理器
:param request_type: 请求类型,如果为 None 则处理所有请求
:return: 装饰器函数
如果 `request_type` 未指定,则该处理器会接收所有类型的请求事件。
Args:
request_type (str, optional): 要处理的请求类型 (e.g., "friend", "group")。
Defaults to None.
Returns:
Callable: 原函数。
"""
def decorator(func):
def decorator(func: Callable) -> Callable:
self.request_handlers.append({"type": request_type, "func": func})
return func
return decorator
# --- 统一事件分发入口 ---
async def handle_event(self, bot, event):
"""
统一事件分发入口
统一事件分发入口
:param bot: Bot 实例
:param event: 事件对象
由 `WS` 客户端在接收到事件后调用。该方法会根据事件的 `post_type`
将其分发给对应的具体处理方法。
Args:
bot: Bot 实例。
event: 已解析的事件对象。
"""
post_type = event.post_type
@@ -119,13 +155,16 @@ class CommandManager:
elif post_type == 'request':
await self.handle_request(bot, event)
# --- 消息分发逻辑 ---
async def handle_message(self, bot, event):
"""
解析并分发消息指令
处理消息事件,解析并分发指令
:param bot: Bot 实例
:param event: 消息事件对象
该方法会检查消息是否以已配置的命令前缀开头,如果是,则解析出
指令名称和参数,并调用对应的处理器。
Args:
bot: Bot 实例。
event: 消息事件对象。
"""
if not event.raw_message:
return
@@ -155,39 +194,43 @@ class CommandManager:
func = self.commands[cmd_name]
await self._run_handler(func, bot, event, args)
# --- 通知分发逻辑 ---
async def handle_notice(self, bot, event):
"""
分发通知事件
分发通知事件给所有匹配的处理器。
:param bot: Bot 实例
:param event: 通知事件对象
Args:
bot: Bot 实例。
event: 通知事件对象。
"""
for handler in self.notice_handlers:
if handler["type"] is None or handler["type"] == event.notice_type:
await self._run_handler(handler["func"], bot, event)
# --- 请求分发逻辑 ---
async def handle_request(self, bot, event):
"""
分发请求事件
分发请求事件给所有匹配的处理器。
:param bot: Bot 实例
:param event: 请求事件对象
Args:
bot: Bot 实例。
event: 请求事件对象。
"""
for handler in self.request_handlers:
if handler["type"] is None or handler["type"] == event.request_type:
await self._run_handler(handler["func"], bot, event)
# --- 通用执行器:自动注入参数 ---
async def _run_handler(self, func, bot, event, args=None):
async def _run_handler(self, func: Callable, bot, event, args: List[str] = None):
"""
根据函数签名自动注入 bot, event 或 args
智能执行事件处理器。
:param func: 目标处理函
:param bot: Bot 实例
:param event: 事件对象
:param args: 指令参数(仅消息指令有效)
该方法会检查目标处理器的函数签名,并根据签名动态地传入所需的参
(如 `bot`, `event`, `args`),实现了依赖注入。
Args:
func (Callable): 目标处理器函数。
bot: Bot 实例。
event: 事件对象。
args (List[str], optional): 指令参数列表(仅对消息事件有效)。
Defaults to None.
"""
sig = inspect.signature(func)
params = sig.parameters
@@ -204,11 +247,14 @@ class CommandManager:
await func(**kwargs)
# 确保前缀是元组格式
# --- 全局单例 ---
# 确保前缀配置是元组格式
if isinstance(comm_prefixes, list):
comm_prefixes = tuple[Any, ...](comm_prefixes)
comm_prefixes = tuple(comm_prefixes)
elif isinstance(comm_prefixes, str):
comm_prefixes = (comm_prefixes,)
# 实例化全局管理器
# 实例化全局唯一的命令管理器
matcher = CommandManager(prefixes=comm_prefixes)