wechat-tools.js
4.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* wechat-tools.js — 微信数据导入 MCP 工具
*
* 提供两个 Master Agent 工具:
* import_wechat_contacts — 批量导入微信联系人到图谱
* import_wechat_chat — 导入指定联系人聊天记录
*/
const { WechatImporter } = require('../../../services/wechat/wechat-importer');
const { WechatReader } = require('../../../services/wechat/wechat-reader');
const { getGraphStore } = require('../../../db/GraphStore');
// 懒加载单例
let _importer = null;
function importer() {
if (!_importer) _importer = new WechatImporter();
return _importer;
}
function createWechatTools() {
return [
{
name: 'import_wechat_contacts',
description: '从本地微信数据库导入联系人到知识图谱。limit 参数控制导入数量,默认 200。',
parameters: {
type: 'object',
required: [],
properties: {
limit: {
type: 'number',
description: '导入数量上限,默认 200,最大 5000',
},
},
},
async execute(params) {
const limit = Math.min(params.limit || 200, 5000);
try {
const result = importer().importContacts(limit);
return `✅ 微信联系人导入完成\n总计:${result.total} 条\n成功导入:${result.imported} 人\n跳过(无效数据):${result.skipped} 条`;
} catch (e) {
return `❌ 导入联系人失败:${e.message}`;
}
},
},
{
name: 'import_wechat_chat',
description: '导入指定微信联系人的聊天记录(最近 N 条),创建 Event 节点关联到该联系人。',
parameters: {
type: 'object',
required: ['username_or_name'],
properties: {
username_or_name: {
type: 'string',
description: '微信 ID (wxid_xxx) 或联系人姓名',
},
limit: {
type: 'number',
description: '导入消息条数上限,默认 50',
},
},
},
async execute(params) {
const limit = params.limit || 50;
let username = params.username_or_name;
// 如果不是 wxid_ 格式,尝试从图谱查找对应 wechatId
if (!username.startsWith('wxid_') && !username.match(/^\d+@chatroom$/)) {
const g = getGraphStore();
const results = g.findByName(username, 'Person');
const person = results.find(n => n.wechatId);
if (person?.wechatId) {
username = person.wechatId;
} else {
// 尝试直接用输入值作为 username(可能是非标准微信 ID)
const reader = new WechatReader();
const contacts = reader.getContacts(5000);
const found = contacts.find(
c => c.remark === params.username_or_name ||
c.nickName === params.username_or_name ||
c.alias === params.username_or_name
);
if (found) {
username = found.username;
} else {
return `❌ 未找到联系人:${params.username_or_name},请使用微信 ID(wxid_xxx)或已导入联系人的姓名。`;
}
}
}
try {
const result = importer().importChatHistory(username, limit);
if (!result.eventId) {
return `⚠️ 未找到 ${username} 的聊天记录(可能消息为空或无文本消息)。`;
}
return `✅ 聊天记录导入完成\n联系人:${username}\n消息条数:${result.messages}\nEvent ID:${result.eventId}`;
} catch (e) {
return `❌ 导入聊天记录失败:${e.message}`;
}
},
},
];
}
module.exports = { createWechatTools };