* 滚木 * 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依赖列表 * docs: 更新性能优化文档并修复命令管理器帮助输出 更新性能优化相关文档,详细说明 Python 3.14 JIT 编译器的使用方法和原理,补充与 Mypyc 的互补策略。同时修复命令管理器中帮助信息的输出方式,移除图片发送仅保留文本输出。 调整部署文档结构,明确两种性能优化方案(AOT 和 JIT)的配置方法和适用场景。完善架构文档中关于 JIT 的原理和启用方式说明。 * feat(help): 重构帮助菜单界面并优化样式 refactor(bili_parser): 修复 API 响应 content-type 问题 fix(command_manager): 添加帮助图片获取的错误处理 docs(deployment): 简化部署文档并移除 JIT 相关内容 * feat: 新增自动同意请求插件和API文档 docs: 更新文档结构和内容 * refactor(scripts): 重构并优化脚本文件结构 feat(scripts): 添加Python环境检查脚本 feat(scripts): 增强依赖导出脚本功能 perf(plugins/bili_parser): 优化B站解析器性能和代码结构 style(plugins/bili_parser): 统一代码风格和常量命名 * fix(scripts): 修复编码问题并添加错误追踪 在compile_machine_code.py中添加utf-8编码设置以避免潜在编码问题 添加traceback.print_exc()以在编译失败时打印完整错误堆栈 更新.gitignore以忽略config.toml文件 * feat(性能分析): 实现性能分析工具模块并添加相关测试 添加性能分析工具模块,包括时间测量、内存分析和性能统计功能 添加测试文件和示例配置,完善性能分析工具的使用场景 在工具模块中实现单例装饰器并导出到__init__.py * feat(douyin_parser): 新增抖音视频解析插件 refactor(performance): 移除未使用的asyncio导入并优化性能测试 style(compile_modules): 修正字符串引号格式 chore: 删除废弃的编译脚本和临时文件 fix(bili_parser): 增强B站链接解析的健壮性 refactor(singleton): 重构单例模式实现 docs: 更新配置文件和事件模型注释 * feat: 添加抖音视频解析插件并优化代码结构 添加抖音视频解析插件,支持自动解析抖音分享链接并提取视频信息。优化现有代码结构,包括: - 重构单例模式实现 - 移除未使用的导入和文件 - 修复性能测试脚本中的异步调用 - 优化消息事件模型中的权限常量定义 - 改进编译脚本的错误处理 - 增强B站解析插件的稳定性 同时清理了多个废弃脚本和临时文件,提升代码可维护性。 * 1 * Delete core/data/temp/help_menu.png * fix(权限管理): 增强权限检查的类型安全并修复权限引用 修复权限检查中可能传入非Permission类型导致的错误,将echo插件的权限引用从MessageEvent.ADMIN迁移到Permission.ADMIN * redis取消tls * feat(github_parser): 添加GitHub仓库信息查询功能 - 新增github_parser插件,支持通过命令或自动解析链接查询GitHub仓库信息 - 添加github_repo.html模板用于渲染仓库信息图片 - 优化图片管理器支持高质量截图和CSS缩放 - 重构消息事件类权限常量定义方式 - 更新帮助页面样式为三列布局并优化响应式设计 * feat(web_parser): 新增通用web链接解析插件框架 refactor: 重构B站、抖音、GitHub解析器为模块化结构 fix(executor): 增强docker容器错误处理和回调稳定性 style(templates): 优化帮助页面和代码执行结果的样式 perf(web_parser): 添加API缓存和消息去重机制 docs: 更新插件元信息和注释 chore: 移除旧的独立解析器插件文件 * refactor(managers): 重构单例管理器实现并优化代码结构 feat(ws_pool): 新增 WebSocket 连接池实现 perf(json): 使用 orjson 替代标准 json 库提升性能 style: 清理未使用的导入和冗余代码 docs: 更新架构文档和开发规范 test: 添加 WebSocket 连接池测试用例 fix(plugins): 修复自动审批插件 API 调用参数格式 --------- Co-authored-by: baby20162016 <2185823427@qq.com> Co-authored-by: web vscode <youremail@example.com>
285 lines
12 KiB
Python
285 lines
12 KiB
Python
"""
|
||
群组相关 API 模块
|
||
|
||
该模块定义了 `GroupAPI` Mixin 类,提供了所有与群组管理、成员操作
|
||
等相关的 OneBot v11 API 封装。
|
||
"""
|
||
from typing import List, Dict, Any, Optional
|
||
import orjson
|
||
from ..managers.redis_manager import redis_manager
|
||
from .base import BaseAPI
|
||
from models.objects import GroupInfo, GroupMemberInfo, GroupHonorInfo
|
||
from ..utils.logger import logger
|
||
|
||
|
||
class GroupAPI(BaseAPI):
|
||
"""
|
||
`GroupAPI` Mixin 类,提供了所有与群组操作相关的 API 方法。
|
||
"""
|
||
|
||
async def set_group_kick(self, group_id: int, user_id: int, reject_add_request: bool = False) -> Dict[str, Any]:
|
||
"""
|
||
将指定成员踢出群组。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
user_id (int): 要踢出的成员的 QQ 号。
|
||
reject_add_request (bool, optional): 是否拒绝该用户此后的加群请求。Defaults to False.
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
return await self.call_api("set_group_kick", {"group_id": group_id, "user_id": user_id, "reject_add_request": reject_add_request})
|
||
|
||
async def set_group_ban(self, group_id: int, user_id: int, duration: int = 1800) -> Dict[str, Any]:
|
||
"""
|
||
禁言群组中的指定成员。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
user_id (int): 要禁言的成员的 QQ 号。
|
||
duration (int, optional): 禁言时长,单位为秒。设置为 0 表示解除禁言。
|
||
Defaults to 1800 (30 分钟).
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
return await self.call_api("set_group_ban", {"group_id": group_id, "user_id": user_id, "duration": duration})
|
||
|
||
async def set_group_anonymous_ban(self, group_id: int, anonymous: Optional[Dict[str, Any]] = None, duration: int = 1800, flag: Optional[str] = None) -> Dict[str, Any]:
|
||
"""
|
||
禁言群组中的匿名用户。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
anonymous (Dict[str, Any], optional): 要禁言的匿名用户对象,
|
||
可从群消息事件的 `anonymous` 字段中获取。Defaults to None.
|
||
duration (int, optional): 禁言时长,单位为秒。Defaults to 1800.
|
||
flag (str, optional): 要禁言的匿名用户的 flag 标识,
|
||
可从群消息事件的 `anonymous` 字段中获取。Defaults to None.
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
params: Dict[str, Any] = {"group_id": group_id, "duration": duration}
|
||
if anonymous:
|
||
params["anonymous"] = anonymous
|
||
if flag:
|
||
params["flag"] = flag
|
||
return await self.call_api("set_group_anonymous_ban", params)
|
||
|
||
async def set_group_whole_ban(self, group_id: int, enable: bool = True) -> Dict[str, Any]:
|
||
"""
|
||
开启或关闭群组全员禁言。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
enable (bool, optional): True 表示开启全员禁言,False 表示关闭。Defaults to True.
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
return await self.call_api("set_group_whole_ban", {"group_id": group_id, "enable": enable})
|
||
|
||
async def set_group_admin(self, group_id: int, user_id: int, enable: bool = True) -> Dict[str, Any]:
|
||
"""
|
||
设置或取消群组成员的管理员权限。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
user_id (int): 目标成员的 QQ 号。
|
||
enable (bool, optional): True 表示设为管理员,False 表示取消管理员。Defaults to True.
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
return await self.call_api("set_group_admin", {"group_id": group_id, "user_id": user_id, "enable": enable})
|
||
|
||
async def set_group_anonymous(self, group_id: int, enable: bool = True) -> Dict[str, Any]:
|
||
"""
|
||
开启或关闭群组的匿名聊天功能。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
enable (bool, optional): True 表示开启匿名,False 表示关闭。Defaults to True.
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
return await self.call_api("set_group_anonymous", {"group_id": group_id, "enable": enable})
|
||
|
||
async def set_group_card(self, group_id: int, user_id: int, card: str = "") -> Dict[str, Any]:
|
||
"""
|
||
设置群组成员的群名片。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
user_id (int): 目标成员的 QQ 号。
|
||
card (str, optional): 要设置的群名片内容。
|
||
传入空字符串 `""` 或 `None` 表示删除该成员的群名片。Defaults to "".
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
return await self.call_api("set_group_card", {"group_id": group_id, "user_id": user_id, "card": card})
|
||
|
||
async def set_group_name(self, group_id: int, group_name: str) -> Dict[str, Any]:
|
||
"""
|
||
设置群组的名称。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
group_name (str): 新的群组名称。
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
return await self.call_api("set_group_name", {"group_id": group_id, "group_name": group_name})
|
||
|
||
async def set_group_leave(self, group_id: int, is_dismiss: bool = False) -> Dict[str, Any]:
|
||
"""
|
||
退出或解散一个群组。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
is_dismiss (bool, optional): 是否解散群组。
|
||
仅当机器人是群主时,此项设为 True 才能解散群。Defaults to False.
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
return await self.call_api("set_group_leave", {"group_id": group_id, "is_dismiss": is_dismiss})
|
||
|
||
async def set_group_special_title(self, group_id: int, user_id: int, special_title: str = "", duration: int = -1) -> Dict[str, Any]:
|
||
"""
|
||
为群组成员设置专属头衔。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
user_id (int): 目标成员的 QQ 号。
|
||
special_title (str, optional): 专属头衔内容。
|
||
传入空字符串 `""` 或 `None` 表示删除头衔。Defaults to "".
|
||
duration (int, optional): 头衔有效期,单位为秒。-1 表示永久。Defaults to -1.
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
return await self.call_api("set_group_special_title", {"group_id": group_id, "user_id": user_id, "special_title": special_title, "duration": duration})
|
||
|
||
async def get_group_info(self, group_id: int, no_cache: bool = False) -> GroupInfo:
|
||
"""
|
||
获取群组的详细信息。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
no_cache (bool, optional): 是否不使用缓存,直接从服务器获取最新信息。Defaults to False.
|
||
|
||
Returns:
|
||
GroupInfo: 包含群组信息的 `GroupInfo` 数据对象。
|
||
"""
|
||
cache_key = f"neobot:cache:get_group_info:{group_id}"
|
||
if not no_cache:
|
||
cached_data = await redis_manager.redis.get(cache_key)
|
||
if cached_data:
|
||
return GroupInfo(**orjson.loads(cached_data))
|
||
|
||
res = await self.call_api("get_group_info", {"group_id": group_id})
|
||
await redis_manager.redis.set(cache_key, orjson.dumps(res), ex=3600) # 缓存 1 小时
|
||
return GroupInfo(**res)
|
||
|
||
async def get_group_list(self) -> Any:
|
||
"""
|
||
获取机器人加入的所有群组的列表。
|
||
|
||
Returns:
|
||
Any: 包含所有群组信息的列表(可能是字典列表或对象列表)。
|
||
"""
|
||
res = await self.call_api("get_group_list")
|
||
|
||
# 增加日志记录 API 原始返回
|
||
logger.debug(f"OneBot API 'get_group_list' raw response: {res}")
|
||
return res
|
||
|
||
# 健壮性处理:处理标准的 OneBot v11 响应格式
|
||
if isinstance(res, dict) and res.get("status") == "ok":
|
||
group_data = res.get("data", [])
|
||
if isinstance(group_data, list):
|
||
return [GroupInfo(**item) for item in group_data]
|
||
else:
|
||
logger.error(f"The 'data' field in 'get_group_list' response is not a list: {group_data}")
|
||
return []
|
||
|
||
# 兼容处理:如果返回的是列表(非标准但可能存在)
|
||
if isinstance(res, list):
|
||
return [GroupInfo(**item) for item in res]
|
||
|
||
logger.error(f"Unexpected response format from 'get_group_list': {res}")
|
||
return []
|
||
|
||
async def get_group_member_info(self, group_id: int, user_id: int, no_cache: bool = False) -> GroupMemberInfo:
|
||
"""
|
||
获取指定群组成员的详细信息。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
user_id (int): 目标成员的 QQ 号。
|
||
no_cache (bool, optional): 是否不使用缓存。Defaults to False.
|
||
|
||
Returns:
|
||
GroupMemberInfo: 包含群成员信息的 `GroupMemberInfo` 数据对象。
|
||
"""
|
||
cache_key = f"neobot:cache:get_group_member_info:{group_id}:{user_id}"
|
||
if not no_cache:
|
||
cached_data = await redis_manager.redis.get(cache_key)
|
||
if cached_data:
|
||
return GroupMemberInfo(**orjson.loads(cached_data))
|
||
|
||
res = await self.call_api("get_group_member_info", {"group_id": group_id, "user_id": user_id})
|
||
await redis_manager.redis.set(cache_key, orjson.dumps(res), ex=3600) # 缓存 1 小时
|
||
return GroupMemberInfo(**res)
|
||
|
||
async def get_group_member_list(self, group_id: int) -> List[GroupMemberInfo]:
|
||
"""
|
||
获取一个群组的所有成员列表。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
|
||
Returns:
|
||
List[GroupMemberInfo]: 包含所有群成员信息的 `GroupMemberInfo` 对象列表。
|
||
"""
|
||
res = await self.call_api("get_group_member_list", {"group_id": group_id})
|
||
return [GroupMemberInfo(**item) for item in res]
|
||
|
||
async def get_group_honor_info(self, group_id: int, type: str) -> GroupHonorInfo:
|
||
"""
|
||
获取群组的荣誉信息(如龙王、群聊之火等)。
|
||
|
||
Args:
|
||
group_id (int): 目标群组的群号。
|
||
type (str): 要获取的荣誉类型。
|
||
可选值: "talkative", "performer", "legend", "strong_newbie", "emotion" 等。
|
||
|
||
Returns:
|
||
GroupHonorInfo: 包含群荣誉信息的 `GroupHonorInfo` 数据对象。
|
||
"""
|
||
res = await self.call_api("get_group_honor_info", {"group_id": group_id, "type": type})
|
||
return GroupHonorInfo(**res)
|
||
|
||
async def set_group_add_request(self, flag: str, sub_type: str, approve: bool = True, reason: str = "") -> Dict[str, Any]:
|
||
"""
|
||
处理加群请求或邀请。
|
||
|
||
Args:
|
||
flag (str): 请求的标识,需要从 `request` 事件中获取。
|
||
sub_type (str): 请求的子类型,`add` 或 `invite`,
|
||
需要与 `request` 事件中的 `sub_type` 字段相符。
|
||
approve (bool, optional): 是否同意请求或邀请。Defaults to True.
|
||
reason (str, optional): 拒绝加群的理由(仅在 `approve` 为 False 时有效)。Defaults to "".
|
||
|
||
Returns:
|
||
Dict[str, Any]: OneBot API 的响应数据。
|
||
"""
|
||
return await self.call_api("set_group_add_request", {"flag": flag, "sub_type": sub_type, "approve": approve, "reason": reason})
|
||
|