LLOneBot项目新增好友删除API功能解析
引言:为什么需要好友删除功能?
在QQ机器人开发中,好友管理是核心功能之一。传统的QQ机器人框架往往只提供基础的添加好友、发送消息等功能,但对于好友关系的完整生命周期管理却有所欠缺。LLOneBot作为基于NTQQ的OneBot11协议实现,最新版本新增了好友删除API功能,填补了这一重要空白。
💡 痛点场景:你是否遇到过需要清理不活跃好友、处理恶意用户或者实现自动化好友管理的需求?以往只能手动操作,现在通过API即可轻松实现!
技术架构深度解析
OneBot11协议支持体系
LLOneBot采用模块化的架构设计,其好友管理功能主要分布在以下核心模块中:
现有好友API功能矩阵
| 功能类别 | API名称 | 方法名 | 支持状态 |
|---|---|---|---|
| 好友列表 | get_friend_list | NTQQFriendApi.getFriends() | ✅ 已实现 |
| 好友点赞 | send_like | NTQQFriendApi.likeFriend() | ✅ 已实现 |
| 好友请求 | set_friend_add_request | NTQQFriendApi.handleFriendRequest() | ✅ 已实现 |
| 好友删除 | delete_friend | NTQQFriendApi.deleteFriend() | 🆕 新增 |
新增好友删除API实现详解
核心接口设计
// 新增的NTQQApiMethod枚举值
export enum NTQQApiMethod {
// ... 其他方法
DELETE_FRIEND = 'nodeIKernelBuddyService/deleteFriend',
}
// 好友删除API类实现
export class DeleteFriend extends BaseAction<DeleteFriendPayload, GeneralCallResult> {
actionName = ActionName.DeleteFriend;
protected async _handle(payload: DeleteFriendPayload) {
const { user_id } = payload;
// 参数验证
if (!user_id) {
throw new Error('user_id参数不能为空');
}
return await NTQQFriendApi.deleteFriend(user_id);
}
}
// API方法实现
export class NTQQFriendApi {
static async deleteFriend(uid: string): Promise<GeneralCallResult> {
return await callNTQQApi<GeneralCallResult>({
methodName: NTQQApiMethod.DELETE_FRIEND,
args: [
{
deleteInfo: {
friendUid: uid,
deleteType: 0, // 0: 删除好友, 1: 拉黑并删除
},
},
null,
],
timeoutSecond: 10,
});
}
}
请求参数规范
interface DeleteFriendPayload {
user_id: string; // 要删除的好友QQ号
delete_type?: number; // 可选,删除类型:0-仅删除,1-删除并拉黑
}
// OneBot11标准响应格式
interface OB11Response {
status: 'ok' | 'failed';
retcode: number;
data: any;
message?: string;
}
错误处理机制
实战应用场景
场景一:自动化好友管理
// 自动清理30天未互动的好友
async function cleanupInactiveFriends() {
const friends = await NTQQFriendApi.getFriends(true);
const now = Date.now();
const thirtyDaysAgo = now - 30 * 24 * 60 * 60 * 1000;
for (const friend of friends) {
if (friend.lastInteractionTime < thirtyDaysAgo) {
try {
await NTQQFriendApi.deleteFriend(friend.uid);
console.log(`已删除不活跃好友: ${friend.nick}`);
} catch (error) {
console.error(`删除好友失败: ${friend.nick}`, error);
}
}
}
}
场景二:恶意用户处理系统
// 结合消息监控的自动拉黑删除
class AntiSpamSystem {
private spamUsers = new Map<string, number>();
async handleMessage(message: MessageEvent) {
const userId = message.user_id;
const content = message.message;
if (this.isSpam(content)) {
const spamCount = (this.spamUsers.get(userId) || 0) + 1;
this.spamUsers.set(userId, spamCount);
if (spamCount >= 3) {
// 第三次 spam,删除并拉黑
await NTQQFriendApi.deleteFriend(userId, 1);
this.spamUsers.delete(userId);
}
}
}
private isSpam(content: string): boolean {
// 实现spam检测逻辑
return content.includes('广告') || content.includes('http://');
}
}
性能优化与最佳实践
批量操作优化
// 批量删除好友的优化实现
async function batchDeleteFriends(userIds: string[], batchSize = 5) {
const results = [];
for (let i = 0; i < userIds.length; i += batchSize) {
const batch = userIds.slice(i, i + batchSize);
const batchPromises = batch.map(uid =>
NTQQFriendApi.deleteFriend(uid).catch(error => ({
uid,
success: false,
error: error.message
}))
);
const batchResults = await Promise.all(batchPromises);
results.push(...batchResults);
// 避免频繁请求,添加延迟
if (i + batchSize < userIds.length) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
return results;
}
安全注意事项
- 权限控制:确保只有授权用户才能调用删除好友API
- 操作确认:重要删除操作前应进行二次确认
- 操作日志:记录所有好友删除操作用于审计
- 频率限制:避免短时间内大量删除操作触发风控
与其他功能的协同工作
与消息系统的集成
// 删除好友后自动发送通知
async function deleteFriendWithNotification(userId: string, reason: string) {
try {
// 先发送通知消息
await NTQQApi.sendPrivateMsg(userId,
`您将被删除,原因: ${reason}\n如有疑问请联系管理员`);
// 等待片刻让用户看到消息
await new Promise(resolve => setTimeout(resolve, 2000));
// 执行删除
const result = await NTQQFriendApi.deleteFriend(userId);
// 记录操作日志
logOperation('delete_friend', userId, reason, result);
return result;
} catch (error) {
console.error('删除好友流程失败:', error);
throw error;
}
}
与数据库的联动
// 结合数据库记录好友关系变化
class FriendRelationshipManager {
private db: Database;
async deleteFriend(uid: string, operator: string, reason: string) {
const transaction = await this.db.beginTransaction();
try {
// 1. 记录删除前的状态
const friendInfo = await this.db.getFriendInfo(uid);
// 2. 执行删除操作
const apiResult = await NTQQFriendApi.deleteFriend(uid);
// 3. 记录删除日志
await this.db.logFriendDeletion({
uid,
originalInfo: friendInfo,
operator,
reason,
apiResult,
timestamp: Date.now()
});
// 4. 更新本地缓存
await this.db.removeFriendFromCache(uid);
await transaction.commit();
return apiResult;
} catch (error) {
await transaction.rollback();
throw error;
}
}
}
总结与展望
LLOneBot新增的好友删除API功能为QQ机器人开发带来了完整的社交关系管理能力。通过本文的深度解析,我们可以看到:
- 技术成熟度:基于NTQQ原生API的稳定实现,确保功能可靠性
- 协议兼容性:完全遵循OneBot11标准,便于生态集成
- 应用场景丰富:从自动化管理到安全防护,覆盖多种实用场景
- 扩展性强:为未来更多社交关系管理功能奠定基础
随着LLOneBot项目的持续发展,我们期待看到更多强大的社交功能被加入,为QQ机器人开发者提供更加完善的工具链和更丰富的应用可能性。
🚀 下一步计划:未来版本将考虑添加好友备注修改、分组管理、亲密关系管理等进阶功能,构建完整的好友关系生态系统。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



