koishi-plugin-group-analysis-mx 1.7.9 → 1.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/plugins/command.js +249 -247
- package/lib/service/analysis.js +12 -10
- package/lib/service/llm.js +25 -7
- package/lib/service/message.js +45 -31
- package/lib/service/renderer.js +47 -5
- package/lib/utils.js +1 -1
- package/package.json +3 -1
package/lib/plugins/command.js
CHANGED
|
@@ -1,248 +1,250 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.inject = void 0;
|
|
4
|
-
exports.apply = apply;
|
|
5
|
-
const utils_1 = require("../utils");
|
|
6
|
-
exports.inject = {
|
|
7
|
-
group_analysis: {
|
|
8
|
-
required: true
|
|
9
|
-
}
|
|
10
|
-
};
|
|
11
|
-
function apply(ctx, config) {
|
|
12
|
-
const checkGroup = (session, target) => {
|
|
13
|
-
if (config.enableAllGroupsByDefault)
|
|
14
|
-
return true;
|
|
15
|
-
if (!config.listenerGroups)
|
|
16
|
-
return false;
|
|
17
|
-
return (0, utils_1.shouldListenToMessage)({
|
|
18
|
-
guildId: target?.guildId ?? session.guildId ?? undefined,
|
|
19
|
-
channelId: target?.channelId ?? session.channelId ?? undefined,
|
|
20
|
-
platform: session.platform,
|
|
21
|
-
selfId: session.selfId
|
|
22
|
-
}, config.listenerGroups);
|
|
23
|
-
};
|
|
24
|
-
const settings = ctx
|
|
25
|
-
.command('群分析 [query:text]', '分析本群的近期聊天记录')
|
|
26
|
-
.usage('本功能会分析本群的近期聊天记录,并生成一份报告。\n' +
|
|
27
|
-
'默认情况下,本功能会分析最近 1 天的聊天记录。\n' +
|
|
28
|
-
'也可以直接输入自然语言进行查询和对话。\n' +
|
|
29
|
-
'例如:/群分析 告诉我最近三小时都聊了什么')
|
|
30
|
-
.alias('group-analysis')
|
|
31
|
-
.option('force', '-f 是否强制刷新群分析')
|
|
32
|
-
.option('group', '-g <guildId:string> 指定群号', {
|
|
33
|
-
authority: 3
|
|
34
|
-
})
|
|
35
|
-
.option('channel', '-c <channelId:string> 指定频道号', {
|
|
36
|
-
authority: 3
|
|
37
|
-
})
|
|
38
|
-
.action(async ({ session, options }, query) => {
|
|
39
|
-
if (config.personaBlacklist.includes(session.userId)) {
|
|
40
|
-
return '您无权使用本插件。';
|
|
41
|
-
}
|
|
42
|
-
if (session.isDirect && !options.group && !options.channel) {
|
|
43
|
-
return '私聊中请使用 -g 或 -c 指定目标群或频道。';
|
|
44
|
-
}
|
|
45
|
-
const targetGuildId = options.group ?? session.guildId ?? undefined;
|
|
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
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
.
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
.
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
.
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
.
|
|
136
|
-
.
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
.
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
.
|
|
152
|
-
.
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
.
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
.alias('
|
|
171
|
-
.
|
|
172
|
-
.
|
|
173
|
-
.
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
.alias('
|
|
214
|
-
.
|
|
215
|
-
.
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
}
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.inject = void 0;
|
|
4
|
+
exports.apply = apply;
|
|
5
|
+
const utils_1 = require("../utils");
|
|
6
|
+
exports.inject = {
|
|
7
|
+
group_analysis: {
|
|
8
|
+
required: true
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
function apply(ctx, config) {
|
|
12
|
+
const checkGroup = (session, target) => {
|
|
13
|
+
if (config.enableAllGroupsByDefault)
|
|
14
|
+
return true;
|
|
15
|
+
if (!config.listenerGroups)
|
|
16
|
+
return false;
|
|
17
|
+
return (0, utils_1.shouldListenToMessage)({
|
|
18
|
+
guildId: target?.guildId ?? session.guildId ?? undefined,
|
|
19
|
+
channelId: target?.channelId ?? session.channelId ?? undefined,
|
|
20
|
+
platform: session.platform,
|
|
21
|
+
selfId: session.selfId
|
|
22
|
+
}, config.listenerGroups);
|
|
23
|
+
};
|
|
24
|
+
const settings = ctx
|
|
25
|
+
.command('群分析 [query:text]', '分析本群的近期聊天记录')
|
|
26
|
+
.usage('本功能会分析本群的近期聊天记录,并生成一份报告。\n' +
|
|
27
|
+
'默认情况下,本功能会分析最近 1 天的聊天记录。\n' +
|
|
28
|
+
'也可以直接输入自然语言进行查询和对话。\n' +
|
|
29
|
+
'例如:/群分析 告诉我最近三小时都聊了什么')
|
|
30
|
+
.alias('group-analysis')
|
|
31
|
+
.option('force', '-f 是否强制刷新群分析')
|
|
32
|
+
.option('group', '-g <guildId:string> 指定群号', {
|
|
33
|
+
authority: 3
|
|
34
|
+
})
|
|
35
|
+
.option('channel', '-c <channelId:string> 指定频道号', {
|
|
36
|
+
authority: 3
|
|
37
|
+
})
|
|
38
|
+
.action(async ({ session, options }, query) => {
|
|
39
|
+
if (config.personaBlacklist.includes(session.userId)) {
|
|
40
|
+
return '您无权使用本插件。';
|
|
41
|
+
}
|
|
42
|
+
if (session.isDirect && !options.group && !options.channel) {
|
|
43
|
+
return '私聊中请使用 -g 或 -c 指定目标群或频道。';
|
|
44
|
+
}
|
|
45
|
+
const targetGuildId = options.group ?? session.guildId ?? undefined;
|
|
46
|
+
// 显式指定 -g 时不再带当前会话 channelId,否则会分析当前频道而不是目标群
|
|
47
|
+
const targetChannelId = options.channel ?? (options.group ? undefined : session.channelId ?? undefined);
|
|
48
|
+
if (!targetGuildId && !targetChannelId) {
|
|
49
|
+
return '请使用 -g 或 -c 指定目标群或频道。';
|
|
50
|
+
}
|
|
51
|
+
if (!checkGroup(session, {
|
|
52
|
+
guildId: targetGuildId,
|
|
53
|
+
channelId: targetChannelId
|
|
54
|
+
}))
|
|
55
|
+
return '目标群未启用分析功能,请使用 群分析.启用 来启用目标群的分析功能。';
|
|
56
|
+
const queryText = typeof query === 'string' ? query.trim() : undefined;
|
|
57
|
+
try {
|
|
58
|
+
if (queryText) {
|
|
59
|
+
await ctx.group_analysis.executeGroupQuery(session, {
|
|
60
|
+
guildId: targetGuildId || undefined,
|
|
61
|
+
channelId: targetChannelId || undefined
|
|
62
|
+
}, queryText);
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
const analysisDays = ctx.config?.cronAnalysisDays || 1;
|
|
66
|
+
if (analysisDays > 7)
|
|
67
|
+
return '出于性能考虑,最多只能分析 7 天的数据。';
|
|
68
|
+
await ctx.group_analysis.executeGroupAnalysis(session.selfId, {
|
|
69
|
+
guildId: targetGuildId || undefined,
|
|
70
|
+
channelId: targetChannelId || undefined
|
|
71
|
+
}, analysisDays, undefined, options.force ?? false);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
ctx.logger.error('执行分析时发生未捕获的错误:', err);
|
|
76
|
+
return '群分析执行失败,请检查日志。';
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
settings
|
|
80
|
+
.subcommand('.enable', '启用本群的分析功能', {
|
|
81
|
+
authority: 3
|
|
82
|
+
})
|
|
83
|
+
.alias('.启用')
|
|
84
|
+
.action(async ({ session }) => {
|
|
85
|
+
if (session.isDirect)
|
|
86
|
+
return '请在群聊中使用此命令。';
|
|
87
|
+
const config = ctx.config;
|
|
88
|
+
const originalGroupSetting = config.listenerGroups.find((settings) => (settings.channelId === session.channelId &&
|
|
89
|
+
session.channelId != null) ||
|
|
90
|
+
(settings.guildId !== null &&
|
|
91
|
+
settings.guildId === session.guildId));
|
|
92
|
+
if (originalGroupSetting) {
|
|
93
|
+
originalGroupSetting.enabled = true;
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
config.listenerGroups.push({
|
|
97
|
+
guildId: session.guildId,
|
|
98
|
+
channelId: session.channelId,
|
|
99
|
+
selfId: session.selfId,
|
|
100
|
+
enabled: true,
|
|
101
|
+
platform: session.platform
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
ctx.scope.parent.scope.parent.scope.update(config, true);
|
|
105
|
+
const guildId = session.event.guild.id;
|
|
106
|
+
const guildName = (await session.bot
|
|
107
|
+
.getGuild(guildId)
|
|
108
|
+
.then((guild) => guild.name)) || session.event.guild.name;
|
|
109
|
+
return `已为当前群 ${guildName} (${guildId}) 启用日常分析功能。`;
|
|
110
|
+
});
|
|
111
|
+
settings
|
|
112
|
+
.subcommand('.disable', '禁用本群的分析功能', {
|
|
113
|
+
authority: 3
|
|
114
|
+
})
|
|
115
|
+
.alias('.禁用')
|
|
116
|
+
.action(async ({ session }) => {
|
|
117
|
+
if (session.isDirect)
|
|
118
|
+
return '请在群聊中使用此命令。';
|
|
119
|
+
const config = ctx.config;
|
|
120
|
+
const originalGroupSetting = config.listenerGroups.findIndex((settings) => (settings.channelId === session.channelId &&
|
|
121
|
+
session.channelId != null) ||
|
|
122
|
+
(settings.guildId !== null &&
|
|
123
|
+
settings.guildId === session.guildId));
|
|
124
|
+
if (originalGroupSetting !== -1) {
|
|
125
|
+
config.listenerGroups.splice(originalGroupSetting, 1);
|
|
126
|
+
}
|
|
127
|
+
ctx.scope.parent.scope.parent.scope.update(config, true);
|
|
128
|
+
const guildId = session.event.guild.id;
|
|
129
|
+
const guildName = (await session.bot
|
|
130
|
+
.getGuild(guildId)
|
|
131
|
+
.then((guild) => guild.name)) || session.event.guild.name;
|
|
132
|
+
return `已为当前群 ${guildName} (${guildId}) 禁用日常分析功能。`;
|
|
133
|
+
});
|
|
134
|
+
settings
|
|
135
|
+
.subcommand('clear', '清理当前群分析的某些缓存')
|
|
136
|
+
.alias('.清理')
|
|
137
|
+
.action(async ({ session }) => {
|
|
138
|
+
if (session.isDirect)
|
|
139
|
+
return '请在群聊中使用此命令。';
|
|
140
|
+
const guildId = session.event.guild.id;
|
|
141
|
+
const guildName = (await session.bot
|
|
142
|
+
.getGuild(guildId)
|
|
143
|
+
.then((guild) => guild.name)) || session.event.guild.name;
|
|
144
|
+
ctx.database.remove('group_analysis_messages', {
|
|
145
|
+
guildId: session.guildId,
|
|
146
|
+
channelId: session.channelId || session.guildId
|
|
147
|
+
});
|
|
148
|
+
return `已清理当前群 ${guildName} (${guildId}) 的分析缓存。`;
|
|
149
|
+
});
|
|
150
|
+
settings
|
|
151
|
+
.subcommand('.status', '查看当前分析设置')
|
|
152
|
+
.alias('.状态')
|
|
153
|
+
.action(async ({ session }) => {
|
|
154
|
+
if (session.isDirect)
|
|
155
|
+
return '请在群聊中使用此命令。';
|
|
156
|
+
const config = ctx.config;
|
|
157
|
+
const originalGroupSetting = config.listenerGroups.find((settings) => (settings.channelId === session.channelId &&
|
|
158
|
+
session.channelId != null) ||
|
|
159
|
+
(settings.guildId !== null &&
|
|
160
|
+
settings.guildId === session.guildId));
|
|
161
|
+
ctx.scope.parent.scope.parent.scope.update(config, true);
|
|
162
|
+
const guildId = session.event.guild.id;
|
|
163
|
+
const guildName = (await session.bot
|
|
164
|
+
.getGuild(guildId)
|
|
165
|
+
.then((guild) => guild.name)) || session.event.guild.name;
|
|
166
|
+
const enabled = originalGroupSetting?.enabled ? '已启用' : '未启用';
|
|
167
|
+
return `当前群 ${guildName} (${guildId}) 分析功能状态: ${enabled}`;
|
|
168
|
+
});
|
|
169
|
+
ctx.command('用户画像 [user:user]', '查看指定用户的画像')
|
|
170
|
+
.alias('group-analysis.persona')
|
|
171
|
+
.alias('群分析.用户画像')
|
|
172
|
+
.usage('使用方法:/群分析.用户画像 @用户 或 /群分析.用户画像 <用户ID> 或 /群分析.用户画像。不带参数时查看当前用户。查看其他用户需要为 bot 管理员。')
|
|
173
|
+
.option('force', '-f 是否强制更新用户画像')
|
|
174
|
+
.action(async ({ session, options }, user) => {
|
|
175
|
+
if (session.isDirect)
|
|
176
|
+
return '请在群聊中使用此命令。';
|
|
177
|
+
// 黑名单检查
|
|
178
|
+
if (config.personaBlacklist.includes(session.userId)) {
|
|
179
|
+
return '您无权使用本插件。';
|
|
180
|
+
}
|
|
181
|
+
if (!checkGroup(session))
|
|
182
|
+
return '本群未启用群分析功能,请使用 群分析.启用 来启用本群的群分析功能。';
|
|
183
|
+
let userId = user?.split(':')?.[1] ?? session.userId;
|
|
184
|
+
const isSelf = userId === session.userId;
|
|
185
|
+
const isWhitelist = config.personaWhitelist.includes(session.userId);
|
|
186
|
+
// 白名单用户可查看他人,不受权限限制
|
|
187
|
+
if (!isSelf && !isWhitelist) {
|
|
188
|
+
// 不能查看白名单用户
|
|
189
|
+
if (config.personaWhitelist.includes(userId)) {
|
|
190
|
+
return '您的权限不足,无法查看特权用户。';
|
|
191
|
+
}
|
|
192
|
+
// 权限检查
|
|
193
|
+
if ((session.user?.authority ?? 0) < (config.personaViewAuthority ?? 3)) {
|
|
194
|
+
await session.send(`你没有权限查看其他用户的画像。需要权限 ${config.personaViewAuthority ?? 3} 级。将转为查看自己的画像。`);
|
|
195
|
+
userId = session.userId;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (!userId) {
|
|
199
|
+
return '无法获取目标用户信息。';
|
|
200
|
+
}
|
|
201
|
+
if (config.personaUserFilter.includes(userId)) {
|
|
202
|
+
return '该用户已被设置为禁止分析用户画像。';
|
|
203
|
+
}
|
|
204
|
+
try {
|
|
205
|
+
await ctx.group_analysis.executeUserPersonaAnalysis(session, userId, options.force ?? false);
|
|
206
|
+
}
|
|
207
|
+
catch (err) {
|
|
208
|
+
ctx.logger.error(`执行用户画像分析时发生未捕获的错误 (用户: ${userId}):`, err);
|
|
209
|
+
return '用户画像分析执行失败,请检查日志。';
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
ctx.command('每日漫画 [days:number]', '生成今日群聊漫画')
|
|
213
|
+
.alias('daily-comic')
|
|
214
|
+
.alias('群分析.每日漫画')
|
|
215
|
+
.usage('使用方法:/每日漫画 或 /每日漫画 3(回溯 3 天)。需要已配置生图 API。')
|
|
216
|
+
.option('group', '-g <guildId:string> 指定群号', {
|
|
217
|
+
authority: 3
|
|
218
|
+
})
|
|
219
|
+
.option('channel', '-c <channelId:string> 指定频道号', {
|
|
220
|
+
authority: 3
|
|
221
|
+
})
|
|
222
|
+
.action(async ({ session, options }, days) => {
|
|
223
|
+
if (config.personaBlacklist.includes(session.userId)) {
|
|
224
|
+
return '您无权使用本插件。';
|
|
225
|
+
}
|
|
226
|
+
if (session.isDirect && !options.group && !options.channel) {
|
|
227
|
+
return '私聊中请使用 -g 或 -c 指定目标群或频道。';
|
|
228
|
+
}
|
|
229
|
+
const targetGuildId = options.group ?? session.guildId ?? undefined;
|
|
230
|
+
// 显式指定 -g 时不再带当前会话 channelId,否则会分析当前频道而不是目标群
|
|
231
|
+
const targetChannelId = options.channel ?? (options.group ? undefined : session.channelId ?? undefined);
|
|
232
|
+
if (!targetGuildId && !targetChannelId) {
|
|
233
|
+
return '请使用 -g 或 -c 指定目标群或频道。';
|
|
234
|
+
}
|
|
235
|
+
if (!checkGroup(session, {
|
|
236
|
+
guildId: targetGuildId,
|
|
237
|
+
channelId: targetChannelId
|
|
238
|
+
})) {
|
|
239
|
+
return '目标群未启用分析功能,请使用 群分析.启用 来启用目标群的分析功能。';
|
|
240
|
+
}
|
|
241
|
+
const targetDays = typeof days === 'number' && days >= 1
|
|
242
|
+
? Math.min(days, 7)
|
|
243
|
+
: undefined;
|
|
244
|
+
await ctx.group_analysis.executeDailyComic(session.selfId, {
|
|
245
|
+
guildId: targetGuildId || undefined,
|
|
246
|
+
channelId: targetChannelId || undefined
|
|
247
|
+
}, targetDays);
|
|
248
|
+
});
|
|
249
|
+
}
|
|
248
250
|
//# sourceMappingURL=command.js.map
|
package/lib/service/analysis.js
CHANGED
|
@@ -847,21 +847,23 @@ class AnalysisService extends koishi_1.Service {
|
|
|
847
847
|
.join('\n');
|
|
848
848
|
// LLM analyses in parallel
|
|
849
849
|
const users = Object.values(userStats);
|
|
850
|
-
const [
|
|
850
|
+
const [topicsResult, titlesResult, quotesResult] = await Promise.allSettled([
|
|
851
851
|
this.ctx.group_analysis_llm.summarizeTopics(idBasedMessagesText || messagesText, context),
|
|
852
852
|
this.config.userTitleAnalysis
|
|
853
853
|
? this.ctx.group_analysis_llm.analyzeUserTitles(users, context)
|
|
854
854
|
: Promise.resolve([]),
|
|
855
855
|
this.ctx.group_analysis_llm.analyzeGoldenQuotes(idBasedMessagesText || messagesText, this.config.maxGoldenQuotes, context)
|
|
856
|
-
])
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
856
|
+
]);
|
|
857
|
+
// 单项失败只丢该项,避免一项 YAML 异常把话题/称号/金句全部清空。
|
|
858
|
+
const topics = topicsResult.status === 'fulfilled' ? (topicsResult.value ?? []) : [];
|
|
859
|
+
const userTitles = titlesResult.status === 'fulfilled' ? (titlesResult.value ?? []) : [];
|
|
860
|
+
const goldenQuotes = quotesResult.status === 'fulfilled' ? (quotesResult.value ?? []) : [];
|
|
861
|
+
if (topicsResult.status === 'rejected')
|
|
862
|
+
this.ctx.logger.error('话题分析失败:', topicsResult.reason);
|
|
863
|
+
if (titlesResult.status === 'rejected')
|
|
864
|
+
this.ctx.logger.error('用户称号分析失败:', titlesResult.reason);
|
|
865
|
+
if (quotesResult.status === 'rejected')
|
|
866
|
+
this.ctx.logger.error('金句分析失败:', quotesResult.reason);
|
|
865
867
|
// Final statistics
|
|
866
868
|
const sortedUsers = users.sort((a, b) => b.messageCount - a.messageCount);
|
|
867
869
|
// 群名片解析:官方 QQ bot 消息作者名是"个人昵称",群名片需通过 getGuildMember 获取。
|
package/lib/service/llm.js
CHANGED
|
@@ -15,6 +15,25 @@ function repairUnclosedQuotedFields(source) {
|
|
|
15
15
|
}).join('\n');
|
|
16
16
|
return changed ? repaired : null;
|
|
17
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* 从模型回复中取出 YAML 正文。
|
|
20
|
+
* 兼容三类常见输出:完整代码围栏、缺少结尾围栏、完全没有围栏但正文是 YAML 列表。
|
|
21
|
+
*/
|
|
22
|
+
function extractYamlSource(rawContent) {
|
|
23
|
+
const text = String(rawContent ?? '');
|
|
24
|
+
const fenced = text.match(/```ya?ml[ \t]*\r?\n([\s\S]*?)\r?\n?[ \t]*```/i);
|
|
25
|
+
if (fenced)
|
|
26
|
+
return fenced[1];
|
|
27
|
+
// 只有开头围栏,结尾被模型截断/漏写
|
|
28
|
+
const openOnly = text.match(/```ya?ml[ \t]*\r?\n([\s\S]*)$/i);
|
|
29
|
+
if (openOnly)
|
|
30
|
+
return openOnly[1].replace(/[ \t]*```\s*$/, '').trim();
|
|
31
|
+
// 没有任何围栏,但正文以 YAML 列表项开头
|
|
32
|
+
const listStart = text.search(/^[ \t]*-[ \t]+\S/m);
|
|
33
|
+
if (listStart >= 0)
|
|
34
|
+
return text.slice(listStart).trim();
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
18
37
|
class LLMService extends koishi_1.Service {
|
|
19
38
|
config;
|
|
20
39
|
constructor(ctx, config) {
|
|
@@ -48,20 +67,19 @@ class LLMService extends koishi_1.Service {
|
|
|
48
67
|
}
|
|
49
68
|
async _callLLM(prompt, taskName) {
|
|
50
69
|
const rawContent = await this._callOpenAI(prompt, taskName);
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
this.ctx.logger.warn(`未找到 YAML 代码块,无法解析。`);
|
|
70
|
+
const yamlSource = extractYamlSource(rawContent);
|
|
71
|
+
if (!yamlSource) {
|
|
72
|
+
this.ctx.logger.warn(`未找到 YAML 内容,无法解析。`);
|
|
55
73
|
throw new Error('未找到 YAML 响应。');
|
|
56
74
|
}
|
|
57
75
|
try {
|
|
58
76
|
// json: true 容忍重复 key(LLM 偶尔会重复输出 sender 等字段),后者覆盖前者
|
|
59
77
|
let data;
|
|
60
78
|
try {
|
|
61
|
-
data = (0, js_yaml_1.load)(
|
|
79
|
+
data = (0, js_yaml_1.load)(yamlSource, { json: true });
|
|
62
80
|
}
|
|
63
81
|
catch (parseError) {
|
|
64
|
-
const repairedYaml = repairUnclosedQuotedFields(
|
|
82
|
+
const repairedYaml = repairUnclosedQuotedFields(yamlSource);
|
|
65
83
|
if (!repairedYaml)
|
|
66
84
|
throw parseError;
|
|
67
85
|
data = (0, js_yaml_1.load)(repairedYaml, { json: true });
|
|
@@ -74,7 +92,7 @@ class LLMService extends koishi_1.Service {
|
|
|
74
92
|
}
|
|
75
93
|
catch (err) {
|
|
76
94
|
this.ctx.logger.error('解析 YAML 失败:', err);
|
|
77
|
-
this.ctx.logger.error('待解析的 YAML 字符串:',
|
|
95
|
+
this.ctx.logger.error('待解析的 YAML 字符串:', yamlSource || '[空字符串]');
|
|
78
96
|
throw err;
|
|
79
97
|
}
|
|
80
98
|
}
|
package/lib/service/message.js
CHANGED
|
@@ -137,7 +137,7 @@ class MessageService extends koishi_1.Service {
|
|
|
137
137
|
await this.flushIdleBuffers();
|
|
138
138
|
}, this.bufferSweepIntervalMs);
|
|
139
139
|
this.ctx.on('dispose', async () => {
|
|
140
|
-
this.flushAllBuffers();
|
|
140
|
+
await this.flushAllBuffers();
|
|
141
141
|
});
|
|
142
142
|
const retentionDays = this.config.retentionDays;
|
|
143
143
|
if (retentionDays === 0) {
|
|
@@ -251,6 +251,11 @@ class MessageService extends koishi_1.Service {
|
|
|
251
251
|
const platform = inferred.platform || botFromSelfId?.platform;
|
|
252
252
|
const selfId = inferred.selfId || filter.selfId;
|
|
253
253
|
const bot = this.ctx.bots.find((b) => b.platform === platform && b.selfId === selfId);
|
|
254
|
+
// 把推断出的平台/机器人补进过滤条件,DB 路径据此隔离不同 bot/平台的相同群 ID
|
|
255
|
+
if (platform && !filter.platform)
|
|
256
|
+
filter = { ...filter, platform };
|
|
257
|
+
if (selfId && !filter.selfId)
|
|
258
|
+
filter = { ...filter, selfId };
|
|
254
259
|
if (this.config.alwaysPersistMessages) {
|
|
255
260
|
this.ctx.logger.info('使用数据库历史消息获取功能。');
|
|
256
261
|
return this.getDatabaseHistoricalMessages(filter).then((messages) => {
|
|
@@ -394,10 +399,11 @@ class MessageService extends koishi_1.Service {
|
|
|
394
399
|
query.guildId = filter.guildId;
|
|
395
400
|
if (filter.channelId)
|
|
396
401
|
query.channelId = filter.channelId;
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
402
|
+
// 限定平台/机器人,避免不同 bot 或平台的相同群 ID 串数据
|
|
403
|
+
if (filter.platform)
|
|
404
|
+
query.platform = filter.platform;
|
|
405
|
+
if (filter.selfId)
|
|
406
|
+
query.selfId = filter.selfId;
|
|
401
407
|
if (filter.startTime || filter.endTime) {
|
|
402
408
|
query.timestamp = {};
|
|
403
409
|
if (filter.startTime)
|
|
@@ -405,31 +411,22 @@ class MessageService extends koishi_1.Service {
|
|
|
405
411
|
if (filter.endTime)
|
|
406
412
|
query.timestamp.$lte = filter.endTime;
|
|
407
413
|
}
|
|
408
|
-
//
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
? {
|
|
414
|
-
$in: filter.userId.filter((userId) => !this.config.userFilter.includes(userId))
|
|
415
|
-
}
|
|
416
|
-
: { $nin: this.config.userFilter };
|
|
414
|
+
// 用户条件:显式指定的用户 ∩ 排除名单。所有排除项合并,而不是互相覆盖。
|
|
415
|
+
const excluded = new Set((this.config.personaBlacklist || []).map(String));
|
|
416
|
+
if (filter.purpose === 'group-analysis') {
|
|
417
|
+
for (const id of (this.config.userFilter || []))
|
|
418
|
+
excluded.add(String(id));
|
|
417
419
|
}
|
|
418
|
-
else if (filter.purpose === 'user-persona'
|
|
419
|
-
this.config.personaUserFilter
|
|
420
|
-
|
|
421
|
-
query.userId = query.userId
|
|
422
|
-
? {
|
|
423
|
-
$in: filter.userId.filter((userId) => !this.config.userFilter.includes(userId))
|
|
424
|
-
}
|
|
425
|
-
: { $nin: this.config.personaUserFilter };
|
|
420
|
+
else if (filter.purpose === 'user-persona') {
|
|
421
|
+
for (const id of (this.config.personaUserFilter || []))
|
|
422
|
+
excluded.add(String(id));
|
|
426
423
|
}
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
424
|
+
if (filter.userId && filter.userId.length > 0) {
|
|
425
|
+
const included = filter.userId.map(String).filter((id) => !excluded.has(id));
|
|
426
|
+
query.userId = { $in: included };
|
|
427
|
+
}
|
|
428
|
+
else if (excluded.size > 0) {
|
|
429
|
+
query.userId = { $nin: [...excluded] };
|
|
433
430
|
}
|
|
434
431
|
const messages = await this.ctx.database
|
|
435
432
|
.select('group_analysis_messages')
|
|
@@ -438,7 +435,16 @@ class MessageService extends koishi_1.Service {
|
|
|
438
435
|
.limit(filter.limit ?? 100)
|
|
439
436
|
.orderBy(($) => $.timestamp, 'desc')
|
|
440
437
|
.execute();
|
|
441
|
-
|
|
438
|
+
// 与 OneBot/Bot API 路径保持一致:应用 wordsFilter,并跳过转发卡片等非聊天内容
|
|
439
|
+
const wordsFilter = this.config.wordsFilter || [];
|
|
440
|
+
return messages
|
|
441
|
+
.filter((message) => {
|
|
442
|
+
const content = String(message.content ?? '');
|
|
443
|
+
if ((0, utils_1.isJunkMessage)(content))
|
|
444
|
+
return false;
|
|
445
|
+
return !wordsFilter.some((word) => word && content.includes(word));
|
|
446
|
+
})
|
|
447
|
+
.map((message) => ({
|
|
442
448
|
...message,
|
|
443
449
|
elements: koishi_1.h.parse(message.content)
|
|
444
450
|
}));
|
|
@@ -493,7 +499,13 @@ class MessageService extends koishi_1.Service {
|
|
|
493
499
|
return;
|
|
494
500
|
const payload = buffer.messages.splice(0, buffer.messages.length);
|
|
495
501
|
this.persistenceBuffers.delete(key);
|
|
496
|
-
await this.persistMessages(payload);
|
|
502
|
+
const ok = await this.persistMessages(payload);
|
|
503
|
+
if (!ok) {
|
|
504
|
+
// 写库失败:放回缓冲,下一轮再试,避免瞬时故障导致消息丢失
|
|
505
|
+
const existing = this.persistenceBuffers.get(key) || { messages: [], lastMessageAt: Date.now() };
|
|
506
|
+
existing.messages.unshift(...payload);
|
|
507
|
+
this.persistenceBuffers.set(key, existing);
|
|
508
|
+
}
|
|
497
509
|
}
|
|
498
510
|
async flushIdleBuffers() {
|
|
499
511
|
const now = Date.now();
|
|
@@ -520,12 +532,14 @@ class MessageService extends koishi_1.Service {
|
|
|
520
532
|
}
|
|
521
533
|
async persistMessages(messages) {
|
|
522
534
|
if (!messages.length)
|
|
523
|
-
return;
|
|
535
|
+
return true;
|
|
524
536
|
try {
|
|
525
537
|
await this.ctx.database.upsert('group_analysis_messages', messages);
|
|
538
|
+
return true;
|
|
526
539
|
}
|
|
527
540
|
catch (error) {
|
|
528
541
|
this.ctx.logger.warn('Failed to store message in database:', error);
|
|
542
|
+
return false;
|
|
529
543
|
}
|
|
530
544
|
}
|
|
531
545
|
getRecentMessages(guildId, channelId, limit = 100) {
|
package/lib/service/renderer.js
CHANGED
|
@@ -42,9 +42,15 @@ class RendererService extends koishi_1.Service {
|
|
|
42
42
|
await this.init();
|
|
43
43
|
});
|
|
44
44
|
}
|
|
45
|
-
|
|
45
|
+
/** 当前皮肤目录:原项目皮肤放在 original/<skin>,自制皮肤直接放在 <skin>。 */
|
|
46
|
+
getSkinDir() {
|
|
46
47
|
const skin = this.config.skin || 'md3';
|
|
47
|
-
return
|
|
48
|
+
return ORIGINAL_SKINS.includes(skin)
|
|
49
|
+
? path_1.default.resolve(this.templateDir, 'original', skin)
|
|
50
|
+
: path_1.default.resolve(this.templateDir, skin);
|
|
51
|
+
}
|
|
52
|
+
getSkinPath(filename) {
|
|
53
|
+
return path_1.default.resolve(this.getSkinDir(), filename);
|
|
48
54
|
}
|
|
49
55
|
async imageToBase64(url) {
|
|
50
56
|
// 已内联的 data URI 直接返回,无需再下载
|
|
@@ -153,7 +159,11 @@ class RendererService extends koishi_1.Service {
|
|
|
153
159
|
const hour = new Date().getHours();
|
|
154
160
|
theme = hour >= 19 || hour < 6 ? 'dark' : 'light';
|
|
155
161
|
}
|
|
156
|
-
const
|
|
162
|
+
const skin = this.config.skin || 'md3';
|
|
163
|
+
// 原项目皮肤必须走 nunjucks 模板,否则会去找不存在的 template_group.html
|
|
164
|
+
const page = ORIGINAL_SKINS.includes(skin)
|
|
165
|
+
? await this._renderOriginalSkinGroup(data, theme)
|
|
166
|
+
: await this._renderGroupAnalysis(data, theme);
|
|
157
167
|
const pdfBuffer = await page.pdf({ format: 'A4' });
|
|
158
168
|
await page.close();
|
|
159
169
|
return pdfBuffer;
|
|
@@ -287,6 +297,32 @@ class RendererService extends koishi_1.Service {
|
|
|
287
297
|
return { ...topic, detail };
|
|
288
298
|
})
|
|
289
299
|
};
|
|
300
|
+
// 皮肤模板直接把字段拼进 HTML:对纯文本字段统一转义,避免昵称/内容中的 < & 破坏结构。
|
|
301
|
+
// topic.detail 已在上面转换过(含胶囊 HTML),不能再转义。
|
|
302
|
+
const escapeField = (value) => escapeTopicHtml(value).replace(/\r?\n/g, '<br>');
|
|
303
|
+
data = {
|
|
304
|
+
...data,
|
|
305
|
+
groupName: escapeField(data.groupName),
|
|
306
|
+
userStats: (data.userStats || []).map((u) => u ? { ...u, nickname: escapeField(u.nickname), rawName: escapeField(u.rawName) } : u),
|
|
307
|
+
userTitles: (data.userTitles || []).map((t) => t ? {
|
|
308
|
+
...t,
|
|
309
|
+
name: escapeField(t.name),
|
|
310
|
+
title: escapeField(t.title),
|
|
311
|
+
mbti: escapeField(t.mbti),
|
|
312
|
+
reason: escapeField(t.reason)
|
|
313
|
+
} : t),
|
|
314
|
+
goldenQuotes: (data.goldenQuotes || []).map((q) => q ? {
|
|
315
|
+
...q,
|
|
316
|
+
sender: escapeField(q.sender),
|
|
317
|
+
content: escapeField(q.content),
|
|
318
|
+
reason: escapeField(q.reason)
|
|
319
|
+
} : q),
|
|
320
|
+
topics: (data.topics || []).map((t) => t ? {
|
|
321
|
+
...t,
|
|
322
|
+
topic: escapeField(t.topic),
|
|
323
|
+
contributors: (t.contributors || []).map(escapeField)
|
|
324
|
+
} : t)
|
|
325
|
+
};
|
|
290
326
|
const templatePath = this.getSkinPath('template_group.html');
|
|
291
327
|
const randomId = Math.random().toString(36).substring(2, 15);
|
|
292
328
|
const skin = this.config.skin || 'md3';
|
|
@@ -550,7 +586,13 @@ class RendererService extends koishi_1.Service {
|
|
|
550
586
|
const templatePath = this.getSkinPath('template_user.html');
|
|
551
587
|
const randomId = Math.random().toString(36).substring(2, 15);
|
|
552
588
|
const skin = this.config.skin || 'md3';
|
|
553
|
-
|
|
589
|
+
// 原项目皮肤没有 template_user.html,画像统一回退到自带皮肤,避免直接报模板不存在
|
|
590
|
+
const personaTemplateExists = fs_1.existsSync(templatePath);
|
|
591
|
+
const personaSkin = personaTemplateExists ? skin : 'md3';
|
|
592
|
+
const personaTemplatePath = personaTemplateExists
|
|
593
|
+
? templatePath
|
|
594
|
+
: path_1.default.resolve(this.templateDir, 'md3', 'template_user.html');
|
|
595
|
+
const outTemplateHtmlPath = path_1.default.resolve(this.templateDir, personaSkin, `${randomId}.html`);
|
|
554
596
|
const renderer = skins_1.skinRegistry.getSafe(skin);
|
|
555
597
|
const formatTags = (tags) => {
|
|
556
598
|
if (renderer.formatTags) {
|
|
@@ -590,7 +632,7 @@ class RendererService extends koishi_1.Service {
|
|
|
590
632
|
'https://cravatar.cn/avatar/00000000000000000000000000000000?d=mp';
|
|
591
633
|
// 将头像转换为 Base64
|
|
592
634
|
const dynamicAvatarBase64 = await this.imageToBase64(dynamicAvatarUrl);
|
|
593
|
-
const templateHtml = await fs_1.promises.readFile(
|
|
635
|
+
const templateHtml = await fs_1.promises.readFile(personaTemplatePath, 'utf-8');
|
|
594
636
|
const filledHtml = (0, utils_1.renderTemplate)(templateHtml, {
|
|
595
637
|
avatar: dynamicAvatarBase64,
|
|
596
638
|
username,
|
package/lib/utils.js
CHANGED
|
@@ -99,7 +99,7 @@ function calculateBasicStats(messages) {
|
|
|
99
99
|
? parseFloat((stat.replyCount / stat.messageCount).toFixed(2))
|
|
100
100
|
: 0;
|
|
101
101
|
stat.emojiRatio = stat.messageCount
|
|
102
|
-
? parseFloat((
|
|
102
|
+
? parseFloat((((stat.emojiStats?.face || 0) + (stat.emojiStats?.sticker || 0)) / stat.messageCount).toFixed(2))
|
|
103
103
|
: 0;
|
|
104
104
|
}
|
|
105
105
|
return { userStats, totalChars, totalEmojiCount, allMessagesText };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "koishi-plugin-group-analysis-mx",
|
|
3
3
|
"description": "群聊分析插件 - 生成精美群聊统计报告,支持 AI 话题总结(独立版,不依赖 ChatLuna)",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.8.1",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"module": "lib/index.mjs",
|
|
7
7
|
"typings": "lib/index.d.ts",
|
|
@@ -64,3 +64,5 @@
|
|
|
64
64
|
|
|
65
65
|
|
|
66
66
|
|
|
67
|
+
|
|
68
|
+
|