Dev (#40)
* 滚木 * 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): 统一代码风格和常量命名 --------- Co-authored-by: baby20162016 <2185823427@qq.com>
This commit is contained in:
259
docs/api/media.md
Normal file
259
docs/api/media.md
Normal file
@@ -0,0 +1,259 @@
|
||||
# 媒体 API
|
||||
|
||||
这一页讲的是怎么处理图片、语音等媒体文件。虽然方法不多,但都很实用。
|
||||
|
||||
## 能力检查
|
||||
|
||||
### `can_send_image` - 检查是否可以发送图片
|
||||
|
||||
```python
|
||||
async def can_send_image(self) -> Dict[str, Any]
|
||||
```
|
||||
|
||||
检查当前上下文是否允许发送图片。
|
||||
|
||||
**返回值:**
|
||||
- 包含检查结果的字典,通常有 `yes` 或 `no` 字段
|
||||
|
||||
**示例:**
|
||||
```python
|
||||
@matcher.command("sendpic")
|
||||
async def handle_sendpic(event: MessageEvent, args: str):
|
||||
# 先检查能不能发图片
|
||||
result = await event.bot.can_send_image()
|
||||
|
||||
if result.get("yes"):
|
||||
# 可以发图片
|
||||
await event.reply(MessageSegment.image("https://example.com/image.jpg"))
|
||||
else:
|
||||
# 不能发图片
|
||||
await event.reply("当前环境不支持发送图片")
|
||||
```
|
||||
|
||||
### `can_send_record` - 检查是否可以发送语音
|
||||
|
||||
```python
|
||||
async def can_send_record(self) -> Dict[str, Any]
|
||||
```
|
||||
|
||||
检查当前上下文是否允许发送语音消息。
|
||||
|
||||
**示例:**
|
||||
```python
|
||||
result = await bot.can_send_record()
|
||||
if result.get("yes"):
|
||||
print("可以发语音")
|
||||
else:
|
||||
print("不能发语音")
|
||||
```
|
||||
|
||||
## 图片信息
|
||||
|
||||
### `get_image` - 获取图片信息
|
||||
|
||||
```python
|
||||
async def get_image(self, file: str) -> Dict[str, Any]
|
||||
```
|
||||
|
||||
获取图片的详细信息,比如大小、尺寸、MD5 等。
|
||||
|
||||
**参数:**
|
||||
- `file`: 图片文件名、路径或 URL
|
||||
|
||||
**返回值:**
|
||||
- 包含图片信息的字典
|
||||
|
||||
**示例:**
|
||||
```python
|
||||
@matcher.command("imageinfo")
|
||||
async def handle_imageinfo(event: MessageEvent):
|
||||
# 检查消息中是否有图片
|
||||
for segment in event.message:
|
||||
if segment.type == "image":
|
||||
file = segment.data.get("file", "")
|
||||
if file:
|
||||
# 获取图片信息
|
||||
info = await event.bot.get_image(file)
|
||||
await event.reply(
|
||||
f"图片信息:\n"
|
||||
f"大小: {info.get('size', '未知')} 字节\n"
|
||||
f"尺寸: {info.get('width', '?')}x{info.get('height', '?')}\n"
|
||||
f"MD5: {info.get('md5', '未知')}"
|
||||
)
|
||||
return
|
||||
|
||||
await event.reply("消息中没有图片")
|
||||
```
|
||||
|
||||
## 实际应用示例
|
||||
|
||||
### 图片转发器
|
||||
|
||||
```python
|
||||
@matcher.command("forwardimage")
|
||||
async def handle_forwardimage(event: MessageEvent, args: str):
|
||||
"""
|
||||
将收到的图片转发到指定群
|
||||
用法: /forwardimage 群号
|
||||
"""
|
||||
if not args.isdigit():
|
||||
await event.reply("参数错误,需要群号")
|
||||
return
|
||||
|
||||
target_group = int(args)
|
||||
|
||||
# 查找消息中的图片
|
||||
images = []
|
||||
for segment in event.message:
|
||||
if segment.type == "image":
|
||||
images.append(segment)
|
||||
|
||||
if not images:
|
||||
await event.reply("消息中没有图片")
|
||||
return
|
||||
|
||||
# 检查是否能发图片到目标群
|
||||
can_send = await event.bot.can_send_image()
|
||||
if not can_send.get("yes"):
|
||||
await event.reply("当前环境不支持发送图片")
|
||||
return
|
||||
|
||||
# 转发所有图片
|
||||
for image in images:
|
||||
await event.bot.send_group_msg(target_group, image)
|
||||
await asyncio.sleep(0.5) # 避免发送太快
|
||||
|
||||
await event.reply(f"已转发 {lenimages()} 张图片到群 {target_group}")
|
||||
```
|
||||
|
||||
### 图片信息查询插件
|
||||
|
||||
```python
|
||||
@matcher.on_event(GroupMessageEvent)
|
||||
async def handle_image_autoinfo(event: GroupMessageEvent):
|
||||
"""
|
||||
自动回复图片信息(当有人发图片时)
|
||||
"""
|
||||
# 只处理包含图片的消息
|
||||
images = [seg for seg in event.message if seg.type == "image"]
|
||||
if not images:
|
||||
return
|
||||
|
||||
# 只处理第一张图片(避免消息太长)
|
||||
image_seg = images[0]
|
||||
file = image_seg.data.get("file", "")
|
||||
|
||||
if not file:
|
||||
return
|
||||
|
||||
try:
|
||||
# 获取图片信息
|
||||
info = await event.bot.get_image(file)
|
||||
|
||||
# 构建回复消息
|
||||
msg = "📷 图片信息:n\"
|
||||
if "size" in info:
|
||||
size_kb = info["size"] / 1024
|
||||
msg += f"大小: {size_kb:.1f} KB\n"
|
||||
if "width" in info and "height" in info:
|
||||
msg += f"尺寸: {info['width']}×{info['height']}\n"
|
||||
if "md5" in info:
|
||||
msg += f"MD5: {info['md5'][:8]}...\n"
|
||||
|
||||
await event.reply(msg)
|
||||
except Exception as e:
|
||||
# 获取图片信息失败,静默处理
|
||||
pass
|
||||
```
|
||||
|
||||
### 图片发送安全检查
|
||||
|
||||
```python
|
||||
async def safe_send_image(bot, target_id, image_url, is_group=True):
|
||||
"""
|
||||
安全发送图片:先检查是否能发,再发送
|
||||
"""
|
||||
# 检查发送能力
|
||||
can_send = await bot.can_send_image()
|
||||
if not can_send.get("yes"):
|
||||
return False, "当前环境不支持发送图片"
|
||||
|
||||
# 检查图片是否存在(简单检查)
|
||||
if not image_url:
|
||||
return False, "图片URL为空"
|
||||
|
||||
try:
|
||||
# 发送图片
|
||||
if is_group:
|
||||
await bot.send_group_msg(target_id, MessageSegment.image(image_url))
|
||||
else:
|
||||
await bot.send_private_msg(target_id, MessageSegment.image(image_url))
|
||||
return True, "图片发送成功"
|
||||
except Exception as e:
|
||||
return False, f"发送失败: {e}"
|
||||
|
||||
@matcher.command("safepic")
|
||||
async def handle_safepic(event: MessageEvent, args: str):
|
||||
"""
|
||||
安全发送图片示例
|
||||
"""
|
||||
if not args:
|
||||
await event.reply("需要图片URL")
|
||||
return
|
||||
|
||||
# 是判断群聊还是私聊
|
||||
is_group = hasattr(event, "group_id") and event.group_id
|
||||
|
||||
if is_group:
|
||||
target_id = event.group_id
|
||||
else:
|
||||
target_id = event.user_id
|
||||
|
||||
# 安全发送
|
||||
success, message = await safe_send_image(
|
||||
event.bot, target_id, args, is_group
|
||||
)
|
||||
|
||||
if not success:
|
||||
await event.reply(message)
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **客户端支持**: 不是所有 OneBot 客户端都完全支持媒体 API。
|
||||
2. **网络限制**: 发送图片和语音可能受网络环境限制。
|
||||
3. **文件大小**: 图片和语音文件有大小限制,太大的文件可能发送失败。
|
||||
4. **缓存**: 图片默认会缓存,重复发送同一图片会更快。
|
||||
5. **安全性**: 不要发送可疑或非法内容。
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 为什么 `can_send_image` 总是返回可以?
|
||||
A: 这取决于 OneBot 客户端的实现。有些客户端可能不检查实际能力,总是返回可以。
|
||||
|
||||
### Q: 怎么发送本地图片?
|
||||
A: 使用 `file://` 协议或直接使用本地路径:
|
||||
```python
|
||||
# 本地文件路径
|
||||
image = MessageSegment.image("file:///path/to/image.jpg")
|
||||
# 或者(取决于客户端)
|
||||
image = MessageSegment.image("/path/to/image.jpg")
|
||||
```
|
||||
|
||||
### Q: 怎么发送语音消息?
|
||||
A: NEO Bot 目前没有封装发送语音的 API,但你可以通过 `call_api` 直接调用:
|
||||
```python
|
||||
await bot.call_api("send_group_msg", {
|
||||
"group_id": 123456,
|
||||
"message": [{
|
||||
"type": "record",
|
||||
"data": {"file": "http://example.com/voice.amr"}
|
||||
}]
|
||||
})
|
||||
```
|
||||
|
||||
## 下一步
|
||||
|
||||
- [消息 API](./message.md): 怎么发消息、撤回消息,包含消息段的使用
|
||||
- [群组 API](./group.md): 管理群聊相关功能
|
||||
- [好友 API](./friend.md): 管理好友相关功能
|
||||
Reference in New Issue
Block a user