From 0bb339c5be76373e09db2bbbea21e4ae6194729c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=95=80=E9=93=AC=E9=85=B8=E9=92=BE?= <148796996+K2cr2O1@users.noreply.github.com> Date: Tue, 13 Jan 2026 09:33:56 +0800 Subject: [PATCH] Dev (#38) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 滚木 * feat: 重构核心架构,增强类型安全与插件管理 本次提交对核心模块进行了深度重构,引入 Pydantic 增强配置管理的类型安全性,并全面优化了插件管理系统。 主要变更详情: 1. 核心架构与配置 - 重构配置加载模块:引入 Pydantic 模型 (`core/config_models.py`),提供严格的配置项类型检查、验证及默认值管理。 - 统一模块结构:规范化模块导入路径,移除冗余的 `__init__.py` 文件,提升项目结构的清晰度。 - 性能优化:集成 Redis 缓存支持 (`RedisManager`),有效降低高频 API 调用开销,提升响应速度。 2. 插件系统升级 - 实现热重载机制:新增插件文件变更监听功能,支持开发过程中自动重载插件,提升开发效率。 - 优化生命周期管理:改进插件加载与卸载逻辑,支持精确卸载指定插件及其关联的命令、事件处理器和定时任务。 3. 功能特性增强 - 新增媒体 API:引入 `MediaAPI` 模块,封装图片、语音等富媒体资源的获取与处理接口。 - 完善权限体系:重构权限管理系统,实现管理员与操作员的分级控制,支持更细粒度的命令权限校验。 4. 代码质量与稳定性 - 全面类型修复:解决 `mypy` 静态类型检查发现的大量类型错误(包括 `CommandManager`、`EventFactory` 及 `Bot` API 签名不匹配问题)。 - 增强错误处理:优化消息处理管道的异常捕获机制,完善关键路径的日志记录,提升系统运行稳定性。 * feat: 添加测试用例并优化代码结构 refactor(permission_manager): 调整初始化顺序和逻辑 fix(admin_manager): 修复初始化逻辑和目录创建问题 feat(ws): 优化Bot实例初始化条件 feat(message): 增强MessageSegment功能并添加测试 feat(events): 支持字符串格式的消息解析 test: 添加核心功能测试用例 refactor(plugin_manager): 改进插件路径处理 style: 清理无用导入和代码 chore: 更新依赖项 * refactor(handler): 移除TYPE_CHECKING并直接导入Bot类 简化类型注解,直接导入Bot类而非使用TYPE_CHECKING条件导入,提高代码可读性和维护性 * fix(command_manager): 修复插件卸载时元信息移除不精确的问题 修复 CommandManager 中 unload_plugin 方法移除插件元信息时使用 startswith 导致可能误删其他插件的问题,改为精确匹配 同时调整相关测试用例验证精确匹配行为 * refactor: 清理未使用的导入和更新文档结构 docs: 添加config_models.py到项目结构文档 docs: 调整数据目录位置到core/data下 docs: 更新权限管理器文档描述 * 文档更新 * 更新thpic插件 支持一次返回多张图 * feat: 添加测试覆盖率并修复相关问题 refactor(redis_manager): 移除冗余的ConnectionError处理 refactor(event_handler): 优化Bot类型注解 refactor(factory): 移除未使用的GroupCardNoticeEvent test: 添加全面的单元测试覆盖 - 添加test_import.py测试模块导入 - 添加test_debug.py测试插件加载调试 - 添加test_plugin_error.py测试错误处理 - 添加test_config_loader.py测试配置加载 - 添加test_redis_manager.py测试Redis管理 - 添加test_bot.py测试Bot功能 - 扩展test_models.py测试消息模型 - 添加test_plugin_manager_coverage.py测试插件管理 - 添加test_executor.py测试代码执行器 - 添加test_ws.py测试WebSocket - 添加test_api.py测试API接口 - 添加test_core_managers.py测试核心管理模块 fix(plugin_manager): 修复插件加载日志变量问题 覆盖率已到达86%(忽略插件) * 更新/help指令,现在会发送图片 * feat(help): 重构帮助系统为图片渲染模式 添加浏览器管理器和图片管理器,用于通过 Playwright 渲染帮助菜单为图片 重构命令管理器以支持图片缓存和同步功能 添加 HTML 模板用于帮助菜单渲染 * build: 更新依赖文件 requirements.txt * build: 更新依赖文件 * feat: 添加性能优化和架构文档,更新依赖和核心模块 refactor(browser_manager): 实现页面池机制以提升性能 refactor(image_manager): 添加模板缓存并集成页面池 refactor(bili_parser): 迁移到异步HTTP请求并实现会话复用 docs: 新增性能优化、架构设计和最佳实践文档 chore: 更新requirements.txt添加新依赖 * docs: 更新文档内容并优化语言风格 重构所有文档内容,使用更简洁直接的语言风格 更新架构、插件开发、部署等核心文档 优化代码示例和图表说明 统一术语和格式规范 * docs: 更新文档内容,简化语言并修正格式 - 简化插件开发指南中的描述,移除冗余内容 - 调整部署文档中的Python版本说明 - 优化最佳实践文档的措辞和格式 - 更新性能优化文档,删除不准确的数据 - 重构核心概念文档,使用更简洁的语言 - 修正README中的项目描述和技术栈说明 - 更新快速上手文档,简化安装步骤 - 调整事件流转文档的描述方式 - 简化架构文档内容 - 更新指令处理文档,添加参数注入示例 - 优化单例管理器文档的表述 * refactor(core): 优化权限管理和事件模型 - 重构 AdminManager 和 PermissionManager 以 Redis 为主要数据源 - 为所有事件模型添加 slots=True 提升性能 - 更新文档说明 Mypyc 编译注意事项 - 清理测试和调试文件 - 移动静态资源到 web_static 目录 * feat: 添加模块编译脚本和导出依赖功能 refactor(events): 移除数据类的slots参数以提升兼容性 build: 更新requirements.txt依赖列表 --------- Co-authored-by: baby20162016 <2185823427@qq.com> --- compile_machine_code.py | 294 +++++++++++++++++++++++++++++++++++++++ export_requirements.py | 8 ++ models/events/base.py | 2 +- models/events/message.py | 2 +- models/events/meta.py | 2 +- models/events/notice.py | 2 +- models/events/request.py | 2 +- requirements.txt | 72 ++++++++++ 8 files changed, 379 insertions(+), 5 deletions(-) create mode 100644 compile_machine_code.py create mode 100644 export_requirements.py diff --git a/compile_machine_code.py b/compile_machine_code.py new file mode 100644 index 0000000..cce551d --- /dev/null +++ b/compile_machine_code.py @@ -0,0 +1,294 @@ +#!/usr/bin/env python3 +""" +跨平台 Python 模块编译脚本 + +将核心 Python 模块编译为机器码(.pyd 或 .so)以提升性能。 + +支持的平台: +- Windows: 生成 .pyd 文件 +- Linux: 生成 .so 文件 + +使用方法: + python compile_machine_code.py [options] + +选项: + --compile, -c 编译指定的模块(默认) + --list, -l 列出已编译的模块 + --clean, -k 清理编译生成的文件 + --help, -h 显示帮助信息 + +注意: + 1. 需要安装 C 编译器 (Windows 上需要 Visual Studio Build Tools, Linux 上需要 GCC) + 2. 需要安装 mypyc: pip install mypyc + 3. 编译后的文件是平台相关的,不能跨平台复制 + 4. 建议在部署的目标环境上运行此脚本 +""" +import os +import sys +import glob +import subprocess +import shutil +import argparse + +# 检测当前平台 +PLATFORM = sys.platform +if PLATFORM.startswith('win'): + EXTENSION = '.pyd' + BUILD_PREFIX = 'cp314-win_amd64' + BUILD_PATH = os.path.join('build', f'lib.win-amd64-cpython-314') +elif PLATFORM.startswith('linux'): + EXTENSION = '.so' + BUILD_PREFIX = 'cp314-x86_64-linux-gnu' + BUILD_PATH = os.path.join('build', f'lib.linux-x86_64-cpython-314') +else: + print(f"不支持的平台: {PLATFORM}") + sys.exit(1) + +# 要编译的模块列表 +# 注意:Mypyc 对动态特性支持有限,只选择计算密集或类型明确的模块 +MODULES = [ + # 工具模块 + 'core/utils/json_utils.py', # JSON 处理 + 'core/utils/executor.py', # 代码执行引擎 + 'core/utils/singleton.py', # 单例模式基类 + 'core/utils/exceptions.py', # 自定义异常 + 'core/utils/logger.py', # 日志模块 + + # 核心管理模块 + 'core/managers/command_manager.py', # 指令匹配和分发 + 'core/managers/admin_manager.py', # 管理员管理 + 'core/managers/permission_manager.py', # 权限管理 + 'core/managers/plugin_manager.py', # 插件管理器 + 'core/managers/redis_manager.py', # Redis 管理器 + 'core/managers/image_manager.py', # 图片管理器 + + # 核心基础模块 + 'core/ws.py', # WebSocket 核心 + 'core/bot.py', # Bot 核心抽象 + 'core/config_loader.py', # 配置加载 + 'core/config_models.py', # 配置模型 + 'core/permission.py', # 权限枚举 + + # API 模块 - 注意:这些类会被 Bot 类多继承使用 + # 因此不适合编译,否则会导致 "multiple bases have instance lay-out conflict" 错误 + # 'core/api/base.py', # API 基础类 + # 'core/api/account.py', # 账号相关 API + # 'core/api/friend.py', # 好友相关 API + # 'core/api/group.py', # 群组相关 API + # 'core/api/media.py', # 媒体相关 API + # 'core/api/message.py', # 消息相关 API + + # 数据模型(适合编译的高频使用数据类) + 'models/message.py', # 消息段模型 + 'models/sender.py', # 发送者模型 + 'models/objects.py', # API 响应数据模型 + + # 事件处理相关 + 'core/handlers/event_handler.py', # 事件处理器 + + # 注意:以下文件不适合编译 + # - 主程序文件(main.py) + # - 测试文件(tests/目录) + # - 插件文件(plugins/目录) + # - 编译脚本(compile_machine_code.py等) + # - 临时文件(scratch_files/目录) + # - 抽象基类(models/events/base.py) + # - 事件工厂(models/events/factory.py) + # - 包含复杂动态特性的文件 +] + +def list_compiled_modules(): + """列出已编译的模块""" + print(f"\n已编译的 {PLATFORM} 模块:") + print("=" * 50) + + # 查找所有编译后的文件 + compiled_files = [] + for ext in [EXTENSION, f'__mypyc{EXTENSION}']: + compiled_files.extend(glob.glob(f'**/*{ext}', recursive=True)) + + # 过滤掉虚拟环境中的文件 + compiled_files = [f for f in compiled_files if 'venv' not in f] + + if compiled_files: + for f in sorted(compiled_files): + size = os.path.getsize(f) // 1024 # KB + print(f"{f} ({size} KB)") + else: + print(f"未找到已编译的 {EXTENSION} 文件") + + print(f"\n总计: {len(compiled_files)} 个文件") + +def clean_compiled_files(): + """清理编译生成的文件""" + print(f"\n清理编译生成的 {EXTENSION} 文件...") + + # 查找所有编译后的文件 + compiled_files = [] + for ext in [EXTENSION, f'__mypyc{EXTENSION}']: + compiled_files.extend(glob.glob(f'**/*{ext}', recursive=True)) + + # 过滤掉虚拟环境中的文件 + compiled_files = [f for f in compiled_files if 'venv' not in f] + + if compiled_files: + for f in sorted(compiled_files): + try: + os.remove(f) + print(f"已删除: {f}") + except Exception as e: + print(f"删除失败 {f}: {e}") + + # 清理 build 目录 + if os.path.exists('build'): + try: + shutil.rmtree('build') + print("已删除 build 目录") + except Exception as e: + print(f"删除 build 目录失败: {e}") + else: + print(f"没有可清理的 {EXTENSION} 文件") + +def get_platform_specific_module_name(module_path): + """获取平台特定的模块文件名""" + module_name = module_path.replace('.py', '') + return f"{module_name}.{BUILD_PREFIX}{EXTENSION}" + +def compile_module(module_path): + """编译单个模块""" + print(f"\n编译: {module_path}") + + try: + # 直接调用 mypyc 命令行工具 + result = subprocess.run( + [sys.executable, '-m', 'mypyc', module_path], + capture_output=True, + text=True, + check=True + ) + + # 获取平台特定的模块名 + platform_module = get_platform_specific_module_name(module_path) + mypyc_platform_module = platform_module.replace(EXTENSION, f'__mypyc{EXTENSION}') + + # 检查编译产物是否在当前目录 + if os.path.exists(platform_module): + print(f" ✓ 编译成功: {platform_module}") + return True + else: + # 检查 build 目录中是否有编译产物 + build_module_path = os.path.join(BUILD_PATH, platform_module) + build_mypyc_path = os.path.join(BUILD_PATH, mypyc_platform_module) + + if os.path.exists(build_module_path): + # 如果在 build 目录中,复制到正确位置 + os.makedirs(os.path.dirname(platform_module), exist_ok=True) + shutil.copy2(build_module_path, platform_module) + shutil.copy2(build_mypyc_path, mypyc_platform_module) + print(f" ✓ 编译成功(已从 build 目录复制): {platform_module}") + return True + else: + print(f" ✗ 编译失败:找不到编译产物") + if result.stdout: + print(f" 编译输出:{result.stdout[:500]}...") + if result.stderr: + print(f" 错误信息:{result.stderr[:500]}...") + return False + + except subprocess.CalledProcessError as e: + print(f" ✗ 编译失败,退出码: {e.returncode}") + if e.stdout: + print(f" 编译输出:{e.stdout[:500]}...") + if e.stderr: + print(f" 错误信息:{e.stderr[:500]}...") + return False + except Exception as e: + print(f" ✗ 编译失败,意外错误: {e}") + return False + +def should_skip_module(module_path): + """检查模块是否应该被跳过编译""" + try: + with open(module_path, 'r', encoding='utf-8') as f: + content = f.read() + + # 检查是否包含抽象基类相关代码 + if 'from abc import ABC' in content or 'from abc import abstractmethod' in content: + return True, "包含抽象基类,不适合编译" + + # 检查是否包含动态特性 + if 'eval(' in content or 'exec(' in content or 'getattr(' in content or 'setattr(' in content: + return True, "包含动态特性,不适合编译" + + return False, "" + except Exception as e: + return True, f"读取文件时出错: {e}" + +def compile_all_modules(): + """编译所有指定的模块""" + print(f"\n开始编译 {len(MODULES)} 个模块 (平台: {PLATFORM})") + print("=" * 60) + + # 验证模块文件是否存在并检查是否适合编译 + valid_modules = [] + for module_path in MODULES: + if os.path.exists(module_path): + should_skip, reason = should_skip_module(module_path) + if should_skip: + print(f"跳过: {module_path} ({reason})") + else: + valid_modules.append(module_path) + else: + print(f"警告: 模块 {module_path} 不存在,将被跳过") + + if not valid_modules: + print("错误: 没有有效的模块可编译") + return False + + # 编译模块 + success_count = 0 + for module_path in valid_modules: + if compile_module(module_path): + success_count += 1 + + print(f"\n" + "=" * 60) + print(f"编译完成: {success_count}/{len(valid_modules)} 个模块成功") + + if success_count == len(valid_modules): + print("✓ 所有模块编译成功") + return True + else: + print("✗ 部分模块编译失败") + return False + +def main(): + """主函数""" + parser = argparse.ArgumentParser(description='跨平台 Python 模块编译脚本') + + group = parser.add_mutually_exclusive_group() + group.add_argument('--compile', '-c', action='store_true', default=True, + help='编译指定的模块 (默认)') + group.add_argument('--list', '-l', action='store_true', + help='列出已编译的模块') + group.add_argument('--clean', '-k', action='store_true', + help='清理编译生成的文件') + + args = parser.parse_args() + + # 检查是否安装了 mypyc + try: + import mypyc + except ImportError: + print("错误: 未安装 mypyc,请先安装: pip install mypyc") + sys.exit(1) + + if args.list: + list_compiled_modules() + elif args.clean: + clean_compiled_files() + else: + compile_all_modules() + print("\n使用 --list 选项查看已编译的模块") + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/export_requirements.py b/export_requirements.py new file mode 100644 index 0000000..a3bb109 --- /dev/null +++ b/export_requirements.py @@ -0,0 +1,8 @@ +import subprocess + +# 运行pip freeze命令获取所有依赖 +result = subprocess.run(['pip', 'freeze'], capture_output=True, text=True) + +# 将输出写入requirements.txt文件 +with open('requirements.txt', 'w', encoding='utf-8') as f: + f.write(result.stdout) \ No newline at end of file diff --git a/models/events/base.py b/models/events/base.py index ba90aeb..8d0ff83 100644 --- a/models/events/base.py +++ b/models/events/base.py @@ -30,7 +30,7 @@ class EventType: """消息发送事件 (message_sent): 机器人自己发送消息的上报。""" -@dataclass(slots=True) +@dataclass class OneBotEvent(ABC): """ OneBot v11 事件的抽象基类。 diff --git a/models/events/message.py b/models/events/message.py index f20ed24..421c843 100644 --- a/models/events/message.py +++ b/models/events/message.py @@ -12,7 +12,7 @@ from models.sender import Sender from .base import OneBotEvent, EventType -@dataclass(slots=True) +@dataclass class Anonymous: """ 匿名信息 diff --git a/models/events/meta.py b/models/events/meta.py index 345c3f5..e3593ce 100644 --- a/models/events/meta.py +++ b/models/events/meta.py @@ -8,7 +8,7 @@ from typing import Optional, Final from .base import OneBotEvent, EventType -@dataclass(slots=True) +@dataclass class HeartbeatStatus: """ 心跳状态接口 diff --git a/models/events/notice.py b/models/events/notice.py index c917426..9376b2d 100644 --- a/models/events/notice.py +++ b/models/events/notice.py @@ -7,7 +7,7 @@ from dataclasses import dataclass, field from .base import OneBotEvent, EventType -@dataclass(slots=True) +@dataclass class NoticeEvent(OneBotEvent): """ 通知事件基类 diff --git a/models/events/request.py b/models/events/request.py index 34658d2..41ea580 100644 --- a/models/events/request.py +++ b/models/events/request.py @@ -7,7 +7,7 @@ from dataclasses import dataclass from .base import OneBotEvent, EventType -@dataclass(slots=True) +@dataclass class RequestEvent(OneBotEvent): """ 请求事件基类 diff --git a/requirements.txt b/requirements.txt index e69de29..fce77f4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -0,0 +1,72 @@ +aiohappyeyeballs==2.6.1 +aiohttp==3.13.3 +aiosignal==1.4.0 +annotated-types==0.7.0 +anyio==4.12.1 +astroid==4.0.3 +attrs==25.4.0 +beautifulsoup4==4.14.3 +bs4==0.0.2 +cachetools==6.2.4 +certifi==2026.1.4 +cffi==2.0.0 +charset-normalizer==3.4.4 +colorama==0.4.6 +coverage==7.13.1 +cryptography==46.0.3 +dill==0.4.0 +docker==7.1.0 +docopt==0.6.2 +frozenlist==1.8.0 +greenlet==3.3.0 +h11==0.16.0 +httpcore==1.0.9 +httpx==0.27.0 +idna==3.11 +iniconfig==2.3.0 +isort==7.0.0 +Jinja2==3.1.6 +librt==0.7.7 +loguru==0.7.3 +MarkupSafe==3.0.3 +mccabe==0.7.0 +multidict==6.7.0 +mypy==1.19.1 +mypy_extensions==1.1.0 +orjson==3.11.5 +packaging==25.0 +pathspec==1.0.3 +pillow==12.1.0 +pipreqs==0.4.13 +platformdirs==4.5.1 +playwright==1.57.0 +pluggy==1.6.0 +propcache==0.4.1 +pycparser==2.23 +pydantic==2.12.5 +pydantic_core==2.41.5 +pyee==13.0.0 +Pygments==2.19.2 +pylint==4.0.4 +pytest==9.0.2 +pytest-asyncio==1.3.0 +pytest-cov==7.0.0 +pytest-mock==3.15.1 +redis==7.1.0 +requests==2.32.5 +setuptools==80.9.0 +sniffio==1.3.1 +soupsieve==2.8.1 +toml==0.10.2 +tomlkit==0.13.3 +types-cachetools==6.2.0.20251022 +types-docker==7.1.0.20251202 +types-paramiko==4.0.0.20250822 +types-requests==2.32.4.20260107 +typing-inspection==0.4.2 +typing_extensions==4.15.0 +urllib3==2.6.3 +watchdog==6.0.0 +websockets==16.0 +yarg==0.1.10 +yarl==1.22.0