Files
NeoBot/docs/api/friend.md
镀铬酸钾 ad8f7e761f 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>
2026-01-18 21:07:01 +08:00

273 lines
7.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 好友 API
这一页讲的是怎么管理好友:获取好友列表、给好友点赞、处理加好友请求,还有获取陌生人信息。
## 好友列表
### `get_friend_list` - 获取好友列表
```python
async def get_friend_list(self, no_cache: bool = False) -> List[FriendInfo]
```
获取机器人账号的所有好友列表。默认会缓存 1 小时。
**参数:**
- `no_cache`: 是否跳过缓存,直接从服务器获取最新列表
**返回值:**
- `List[FriendInfo]`: 好友信息对象列表
**示例:**
```python
friends = await bot.get_friend_list()
print(f"我有 {len(friends)} 个好友")
for friend in friends:
print(f"{friend.user_id}: {friend.nickname} (备注: {friend.remark})")
```
`FriendInfo` 对象包含以下字段:
- `user_id`: QQ 号
- `nickname`: 昵称
- `remark`: 备注(你给好友设置的备注名)
- 其他可能的信息字段
## 陌生人信息
### `get_stranger_info` - 获取陌生人信息
```python
async def get_stranger_info(
self,
user_id: int,
no_cache: bool = False
) -> StrangerInfo
```
获取非好友的 QQ 用户信息。默认会缓存 1 小时。
**参数:**
- `user_id`: 目标用户的 QQ 号
- `no_cache`: 是否跳过缓存
**返回值:**
- `StrangerInfo`: 陌生人信息对象
**示例:**
```python
@matcher.command("who")
async def handle_who(event: MessageEvent, args: str):
if not args.isdigit():
await event.reply("参数错误,需要 QQ 号")
return
target_id = int(args)
info = await event.bot.get_stranger_info(target_id)
msg = f"用户 {target_id} 的信息:\n"
msg += f"昵称: {info.nickname}\n"
msg += f"性别: {info.sex}\n"
msg += f"年龄: {info.age}\n"
msg += f"等级: {info.level}"
await event.reply(msg)
```
`StrangerInfo` 对象包含以下字段:
- `user_id`: QQ 号
- `nickname`: 昵称
- `sex`: 性别(`male`/`female`/`unknown`
- `age`: 年龄
- `level`: QQ 等级
- 其他可能的信息字段
## 互动功能
### `send_like` - 发送点赞(戳一戳)
```python
async def send_like(
self,
user_id: int,
times: int = 1
) -> Dict[str, Any]
```
给指定用户发送"戳一戳"(点赞)。每天有次数限制,建议不要超过 10 次。
**参数:**
- `user_id`: 目标用户的 QQ 号
- `times`: 点赞次数,建议 1-10 次
**示例:**
```python
@matcher.command("like")
async def handle_like(event: MessageEvent, args: str):
# 给发送者点赞
await event.bot.send_like(event.user_id, times=1)
await event.reply("给你点了个赞!")
# 如果提供了参数,给指定用户点赞
if args.isdigit():
target_id = int(args)
await event.bot.send_like(target_id, times=1)
await event.reply(f"{target_id} 点了个赞!")
```
**注意:**
- 不是所有 OneBot 实现都支持这个 API
- 有每日次数限制,不要滥用
- 对方可能关闭了"戳一戳"功能,这时会失败
## 加好友请求处理
### `set_friend_add_request` - 处理加好友请求
```python
async def set_friend_add_request(
self,
flag: str,
approve: bool = True,
remark: str = ""
) -> Dict[str, Any]
```
处理收到的加好友请求。需要在 `request` 事件中调用。
**参数:**
- `flag`: 请求标识,从 `request` 事件的 `flag` 字段获取
- `approve`: 是否同意,`True` 同意,`False` 拒绝
- `remark`: 同意请求时,为该好友设置的备注(可选)
**示例:**
```python
from models.events.request import RequestEvent
from core.managers.command_manager import matcher
# 处理所有加好友请求
@matcher.on_event(RequestEvent)
async def handle_friend_request(event: RequestEvent):
if event.request_type == "friend":
# 自动同意并设置备注
await event.bot.set_friend_add_request(
flag=event.flag,
approve=True,
remark=f"自动添加-{event.user_id}"
)
# 给新好友发个欢迎消息
await event.bot.send_private_msg(
event.user_id,
"你好!我是机器人,已自动通过你的好友请求。"
)
```
## 实用示例
### 好友信息查询插件
```python
@matcher.command("friendinfo")
async def handle_friendinfo(event: MessageEvent):
# 获取好友列表
friends = await event.bot.get_friend_list()
# 按备注名排序
sorted_friends = sorted(friends, key=lambda f: f.remark or f.nickname)
# 生成好友列表消息
if len(sorted_friends) > 50:
msg = f"好友太多啦只显示前50个{len(sorted_friends)}个)\n"
sorted_friends = sorted_friends[:50]
else:
msg = f"我的好友列表(共{len(sorted_friends)}个):\n"
for i, friend in enumerate(sorted_friends, 1):
remark_display = friend.remark if friend.remark else "(无备注)"
msg += f"{i}. {friend.nickname} ({friend.user_id}) - 备注: {remark_display}\n"
await event.reply(msg)
```
### 自动通过特定用户的好友请求
```python
@matcher.on_event(RequestEvent)
async def handle_specific_friend_request(event: RequestEvent):
if event.request_type != "friend":
return
# 允许列表
allowed_users = [123456, 789012, 345678]
if event.user_id in allowed_users:
# 自动同意
await event.bot.set_friend_add_request(
flag=event.flag,
approve=True,
remark="重要联系人"
)
# 发送欢迎消息
await event.bot.send_private_msg(
event.user_id,
"你好!已通过你的好友请求。\n"
"发送 /help 查看可用指令。"
)
else:
# 拒绝其他人
await event.bot.set_friend_add_request(
flag=event.flag,
approve=False,
reason="仅限授权用户添加"
)
```
### 批量给好友发送消息(谨慎使用!)
```python
@matcher.command("broadcast", permission="admin")
async def handle_broadcast(event: MessageEvent, args: str):
if not args:
await event.reply("需要广播内容")
return
# 获取好友列表
friends = await event.bot.get_friend_list()
success_count = 0
fail_count = 0
await event.reply(f"开始向 {len(friends)} 个好友发送广播...")
for friend in friends:
try:
await event.bot.send_private_msg(friend.user_id, args)
success_count += 1
# 避免发送太快被限制
await asyncio.sleep(0.5)
except Exception as e:
print(f"发送给 {friend.user_id} 失败: {e}")
fail_count += 1
await event.reply(
f"广播完成!\n"
f"成功: {success_count}\n"
f"失败: {fail_count}"
)
```
**注意**:批量发送消息容易被腾讯限制,谨慎使用!
## 注意事项
1. **频率限制**: 获取好友列表、查询陌生人信息等操作有频率限制。
2. **缓存**: 好友列表和陌生人信息默认缓存 1 小时,如果需要实时数据,设 `no_cache=True`
3. **权限**: 有些 API 需要特定的权限或客户端支持。
4. **隐私**: 处理好友请求时,注意保护用户隐私。
## 下一步
- [账号 API](./account.md): 管理机器人自己的信息
- [群组 API](./group.md): 管理群聊相关功能
- [消息 API](./message.md): 怎么发消息、撤回消息