koishi-plugin-group-analysis-mx 1.8.0 → 1.8.2

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/config.js CHANGED
@@ -214,7 +214,7 @@ exports.Config = koishi_1.Schema.intersect([
214
214
  .default([]),
215
215
  personaBlacklist: koishi_1.Schema.array(String)
216
216
  .role('table')
217
- .description('黑名单用户 ID。黑名单用户无法使用用户画像和群分析命令。')
217
+ .description('用户画像黑名单。只影响用户画像(不采集、不分析、不可查询),不影响群分析的统计与报告。')
218
218
  .default([])
219
219
  }).description('用户画像设置'),
220
220
  koishi_1.Schema.object({
@@ -1,248 +1,244 @@
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
- const targetChannelId = options.channel ?? session.channelId ?? undefined;
47
- if (!targetGuildId && !targetChannelId) {
48
- return '请使用 -g 或 -c 指定目标群或频道。';
49
- }
50
- if (!checkGroup(session, {
51
- guildId: targetGuildId,
52
- channelId: targetChannelId
53
- }))
54
- return '目标群未启用分析功能,请使用 群分析.启用 来启用目标群的分析功能。';
55
- const queryText = typeof query === 'string' ? query.trim() : undefined;
56
- try {
57
- if (queryText) {
58
- await ctx.group_analysis.executeGroupQuery(session, {
59
- guildId: targetGuildId || undefined,
60
- channelId: targetChannelId || undefined
61
- }, queryText);
62
- }
63
- else {
64
- const analysisDays = ctx.config?.cronAnalysisDays || 1;
65
- if (analysisDays > 7)
66
- return '出于性能考虑,最多只能分析 7 天的数据。';
67
- await ctx.group_analysis.executeGroupAnalysis(session.selfId, {
68
- guildId: targetGuildId || undefined,
69
- channelId: targetChannelId || undefined
70
- }, analysisDays, undefined, options.force ?? false);
71
- }
72
- }
73
- catch (err) {
74
- ctx.logger.error('执行分析时发生未捕获的错误:', err);
75
- return '群分析执行失败,请检查日志。';
76
- }
77
- });
78
- settings
79
- .subcommand('.enable', '启用本群的分析功能', {
80
- authority: 3
81
- })
82
- .alias('.启用')
83
- .action(async ({ session }) => {
84
- if (session.isDirect)
85
- return '请在群聊中使用此命令。';
86
- const config = ctx.config;
87
- const originalGroupSetting = config.listenerGroups.find((settings) => (settings.channelId === session.channelId &&
88
- session.channelId != null) ||
89
- (settings.guildId !== null &&
90
- settings.guildId === session.guildId));
91
- if (originalGroupSetting) {
92
- originalGroupSetting.enabled = true;
93
- }
94
- else {
95
- config.listenerGroups.push({
96
- guildId: session.guildId,
97
- channelId: session.channelId,
98
- selfId: session.selfId,
99
- enabled: true,
100
- platform: session.platform
101
- });
102
- }
103
- ctx.scope.parent.scope.parent.scope.update(config, true);
104
- const guildId = session.event.guild.id;
105
- const guildName = (await session.bot
106
- .getGuild(guildId)
107
- .then((guild) => guild.name)) || session.event.guild.name;
108
- return `已为当前群 ${guildName} (${guildId}) 启用日常分析功能。`;
109
- });
110
- settings
111
- .subcommand('.disable', '禁用本群的分析功能', {
112
- authority: 3
113
- })
114
- .alias('.禁用')
115
- .action(async ({ session }) => {
116
- if (session.isDirect)
117
- return '请在群聊中使用此命令。';
118
- const config = ctx.config;
119
- const originalGroupSetting = config.listenerGroups.findIndex((settings) => (settings.channelId === session.channelId &&
120
- session.channelId != null) ||
121
- (settings.guildId !== null &&
122
- settings.guildId === session.guildId));
123
- if (originalGroupSetting !== -1) {
124
- config.listenerGroups.splice(originalGroupSetting, 1);
125
- }
126
- ctx.scope.parent.scope.parent.scope.update(config, true);
127
- const guildId = session.event.guild.id;
128
- const guildName = (await session.bot
129
- .getGuild(guildId)
130
- .then((guild) => guild.name)) || session.event.guild.name;
131
- return `已为当前群 ${guildName} (${guildId}) 禁用日常分析功能。`;
132
- });
133
- settings
134
- .subcommand('clear', '清理当前群分析的某些缓存')
135
- .alias('.清理')
136
- .action(async ({ session }) => {
137
- if (session.isDirect)
138
- return '请在群聊中使用此命令。';
139
- const guildId = session.event.guild.id;
140
- const guildName = (await session.bot
141
- .getGuild(guildId)
142
- .then((guild) => guild.name)) || session.event.guild.name;
143
- ctx.database.remove('group_analysis_messages', {
144
- guildId: session.guildId,
145
- channelId: session.channelId || session.guildId
146
- });
147
- return `已清理当前群 ${guildName} (${guildId}) 的分析缓存。`;
148
- });
149
- settings
150
- .subcommand('.status', '查看当前分析设置')
151
- .alias('.状态')
152
- .action(async ({ session }) => {
153
- if (session.isDirect)
154
- return '请在群聊中使用此命令。';
155
- const config = ctx.config;
156
- const originalGroupSetting = config.listenerGroups.find((settings) => (settings.channelId === session.channelId &&
157
- session.channelId != null) ||
158
- (settings.guildId !== null &&
159
- settings.guildId === session.guildId));
160
- ctx.scope.parent.scope.parent.scope.update(config, true);
161
- const guildId = session.event.guild.id;
162
- const guildName = (await session.bot
163
- .getGuild(guildId)
164
- .then((guild) => guild.name)) || session.event.guild.name;
165
- const enabled = originalGroupSetting?.enabled ? '已启用' : '未启用';
166
- return `当前群 ${guildName} (${guildId}) 分析功能状态: ${enabled}`;
167
- });
168
- ctx.command('用户画像 [user:user]', '查看指定用户的画像')
169
- .alias('group-analysis.persona')
170
- .alias('群分析.用户画像')
171
- .usage('使用方法:/群分析.用户画像 @用户 或 /群分析.用户画像 <用户ID> 或 /群分析.用户画像。不带参数时查看当前用户。查看其他用户需要为 bot 管理员。')
172
- .option('force', '-f 是否强制更新用户画像')
173
- .action(async ({ session, options }, user) => {
174
- if (session.isDirect)
175
- return '请在群聊中使用此命令。';
176
- // 黑名单检查
177
- if (config.personaBlacklist.includes(session.userId)) {
178
- return '您无权使用本插件。';
179
- }
180
- if (!checkGroup(session))
181
- return '本群未启用群分析功能,请使用 群分析.启用 来启用本群的群分析功能。';
182
- let userId = user?.split(':')?.[1] ?? session.userId;
183
- const isSelf = userId === session.userId;
184
- const isWhitelist = config.personaWhitelist.includes(session.userId);
185
- // 白名单用户可查看他人,不受权限限制
186
- if (!isSelf && !isWhitelist) {
187
- // 不能查看白名单用户
188
- if (config.personaWhitelist.includes(userId)) {
189
- return '您的权限不足,无法查看特权用户。';
190
- }
191
- // 权限检查
192
- if ((session.user?.authority ?? 0) < (config.personaViewAuthority ?? 3)) {
193
- await session.send(`你没有权限查看其他用户的画像。需要权限 ${config.personaViewAuthority ?? 3} 级。将转为查看自己的画像。`);
194
- userId = session.userId;
195
- }
196
- }
197
- if (!userId) {
198
- return '无法获取目标用户信息。';
199
- }
200
- if (config.personaUserFilter.includes(userId)) {
201
- return '该用户已被设置为禁止分析用户画像。';
202
- }
203
- try {
204
- await ctx.group_analysis.executeUserPersonaAnalysis(session, userId, options.force ?? false);
205
- }
206
- catch (err) {
207
- ctx.logger.error(`执行用户画像分析时发生未捕获的错误 (用户: ${userId}):`, err);
208
- return '用户画像分析执行失败,请检查日志。';
209
- }
210
- });
211
- ctx.command('每日漫画 [days:number]', '生成今日群聊漫画')
212
- .alias('daily-comic')
213
- .alias('群分析.每日漫画')
214
- .usage('使用方法:/每日漫画 或 /每日漫画 3(回溯 3 天)。需要已配置生图 API。')
215
- .option('group', '-g <guildId:string> 指定群号', {
216
- authority: 3
217
- })
218
- .option('channel', '-c <channelId:string> 指定频道号', {
219
- authority: 3
220
- })
221
- .action(async ({ session, options }, days) => {
222
- if (config.personaBlacklist.includes(session.userId)) {
223
- return '您无权使用本插件。';
224
- }
225
- if (session.isDirect && !options.group && !options.channel) {
226
- return '私聊中请使用 -g 或 -c 指定目标群或频道。';
227
- }
228
- const targetGuildId = options.group ?? session.guildId ?? undefined;
229
- const targetChannelId = options.channel ?? session.channelId ?? undefined;
230
- if (!targetGuildId && !targetChannelId) {
231
- return '请使用 -g 或 -c 指定目标群或频道。';
232
- }
233
- if (!checkGroup(session, {
234
- guildId: targetGuildId,
235
- channelId: targetChannelId
236
- })) {
237
- return '目标群未启用分析功能,请使用 群分析.启用 来启用目标群的分析功能。';
238
- }
239
- const targetDays = typeof days === 'number' && days >= 1
240
- ? Math.min(days, 7)
241
- : undefined;
242
- await ctx.group_analysis.executeDailyComic(session.selfId, {
243
- guildId: targetGuildId || undefined,
244
- channelId: targetChannelId || undefined
245
- }, targetDays);
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 (session.isDirect && !options.group && !options.channel) {
40
+ return '私聊中请使用 -g 或 -c 指定目标群或频道。';
41
+ }
42
+ const targetGuildId = options.group ?? session.guildId ?? undefined;
43
+ // 显式指定 -g 时不再带当前会话 channelId,否则会分析当前频道而不是目标群
44
+ const targetChannelId = options.channel ?? (options.group ? undefined : session.channelId ?? undefined);
45
+ if (!targetGuildId && !targetChannelId) {
46
+ return '请使用 -g 或 -c 指定目标群或频道。';
47
+ }
48
+ if (!checkGroup(session, {
49
+ guildId: targetGuildId,
50
+ channelId: targetChannelId
51
+ }))
52
+ return '目标群未启用分析功能,请使用 群分析.启用 来启用目标群的分析功能。';
53
+ const queryText = typeof query === 'string' ? query.trim() : undefined;
54
+ try {
55
+ if (queryText) {
56
+ await ctx.group_analysis.executeGroupQuery(session, {
57
+ guildId: targetGuildId || undefined,
58
+ channelId: targetChannelId || undefined
59
+ }, queryText);
60
+ }
61
+ else {
62
+ const analysisDays = ctx.config?.cronAnalysisDays || 1;
63
+ if (analysisDays > 7)
64
+ return '出于性能考虑,最多只能分析 7 天的数据。';
65
+ await ctx.group_analysis.executeGroupAnalysis(session.selfId, {
66
+ guildId: targetGuildId || undefined,
67
+ channelId: targetChannelId || undefined
68
+ }, analysisDays, undefined, options.force ?? false);
69
+ }
70
+ }
71
+ catch (err) {
72
+ ctx.logger.error('执行分析时发生未捕获的错误:', err);
73
+ return '群分析执行失败,请检查日志。';
74
+ }
75
+ });
76
+ settings
77
+ .subcommand('.enable', '启用本群的分析功能', {
78
+ authority: 3
79
+ })
80
+ .alias('.启用')
81
+ .action(async ({ session }) => {
82
+ if (session.isDirect)
83
+ return '请在群聊中使用此命令。';
84
+ const config = ctx.config;
85
+ const originalGroupSetting = config.listenerGroups.find((settings) => (settings.channelId === session.channelId &&
86
+ session.channelId != null) ||
87
+ (settings.guildId !== null &&
88
+ settings.guildId === session.guildId));
89
+ if (originalGroupSetting) {
90
+ originalGroupSetting.enabled = true;
91
+ }
92
+ else {
93
+ config.listenerGroups.push({
94
+ guildId: session.guildId,
95
+ channelId: session.channelId,
96
+ selfId: session.selfId,
97
+ enabled: true,
98
+ platform: session.platform
99
+ });
100
+ }
101
+ ctx.scope.parent.scope.parent.scope.update(config, true);
102
+ const guildId = session.event.guild.id;
103
+ const guildName = (await session.bot
104
+ .getGuild(guildId)
105
+ .then((guild) => guild.name)) || session.event.guild.name;
106
+ return `已为当前群 ${guildName} (${guildId}) 启用日常分析功能。`;
107
+ });
108
+ settings
109
+ .subcommand('.disable', '禁用本群的分析功能', {
110
+ authority: 3
111
+ })
112
+ .alias('.禁用')
113
+ .action(async ({ session }) => {
114
+ if (session.isDirect)
115
+ return '请在群聊中使用此命令。';
116
+ const config = ctx.config;
117
+ const originalGroupSetting = config.listenerGroups.findIndex((settings) => (settings.channelId === session.channelId &&
118
+ session.channelId != null) ||
119
+ (settings.guildId !== null &&
120
+ settings.guildId === session.guildId));
121
+ if (originalGroupSetting !== -1) {
122
+ config.listenerGroups.splice(originalGroupSetting, 1);
123
+ }
124
+ ctx.scope.parent.scope.parent.scope.update(config, true);
125
+ const guildId = session.event.guild.id;
126
+ const guildName = (await session.bot
127
+ .getGuild(guildId)
128
+ .then((guild) => guild.name)) || session.event.guild.name;
129
+ return `已为当前群 ${guildName} (${guildId}) 禁用日常分析功能。`;
130
+ });
131
+ settings
132
+ .subcommand('clear', '清理当前群分析的某些缓存')
133
+ .alias('.清理')
134
+ .action(async ({ session }) => {
135
+ if (session.isDirect)
136
+ return '请在群聊中使用此命令。';
137
+ const guildId = session.event.guild.id;
138
+ const guildName = (await session.bot
139
+ .getGuild(guildId)
140
+ .then((guild) => guild.name)) || session.event.guild.name;
141
+ ctx.database.remove('group_analysis_messages', {
142
+ guildId: session.guildId,
143
+ channelId: session.channelId || session.guildId
144
+ });
145
+ return `已清理当前群 ${guildName} (${guildId}) 的分析缓存。`;
146
+ });
147
+ settings
148
+ .subcommand('.status', '查看当前分析设置')
149
+ .alias('.状态')
150
+ .action(async ({ session }) => {
151
+ if (session.isDirect)
152
+ return '请在群聊中使用此命令。';
153
+ const config = ctx.config;
154
+ const originalGroupSetting = config.listenerGroups.find((settings) => (settings.channelId === session.channelId &&
155
+ session.channelId != null) ||
156
+ (settings.guildId !== null &&
157
+ settings.guildId === session.guildId));
158
+ ctx.scope.parent.scope.parent.scope.update(config, true);
159
+ const guildId = session.event.guild.id;
160
+ const guildName = (await session.bot
161
+ .getGuild(guildId)
162
+ .then((guild) => guild.name)) || session.event.guild.name;
163
+ const enabled = originalGroupSetting?.enabled ? '已启用' : '未启用';
164
+ return `当前群 ${guildName} (${guildId}) 分析功能状态: ${enabled}`;
165
+ });
166
+ ctx.command('用户画像 [user:user]', '查看指定用户的画像')
167
+ .alias('group-analysis.persona')
168
+ .alias('群分析.用户画像')
169
+ .usage('使用方法:/群分析.用户画像 @用户 或 /群分析.用户画像 <用户ID> 或 /群分析.用户画像。不带参数时查看当前用户。查看其他用户需要为 bot 管理员。')
170
+ .option('force', '-f 是否强制更新用户画像')
171
+ .action(async ({ session, options }, user) => {
172
+ if (session.isDirect)
173
+ return '请在群聊中使用此命令。';
174
+ // 黑名单检查
175
+ if (config.personaBlacklist.includes(session.userId)) {
176
+ return '您无权使用本插件。';
177
+ }
178
+ if (!checkGroup(session))
179
+ return '本群未启用群分析功能,请使用 群分析.启用 来启用本群的群分析功能。';
180
+ let userId = user?.split(':')?.[1] ?? session.userId;
181
+ const isSelf = userId === session.userId;
182
+ const isWhitelist = config.personaWhitelist.includes(session.userId);
183
+ // 白名单用户可查看他人,不受权限限制
184
+ if (!isSelf && !isWhitelist) {
185
+ // 不能查看白名单用户
186
+ if (config.personaWhitelist.includes(userId)) {
187
+ return '您的权限不足,无法查看特权用户。';
188
+ }
189
+ // 权限检查
190
+ if ((session.user?.authority ?? 0) < (config.personaViewAuthority ?? 3)) {
191
+ await session.send(`你没有权限查看其他用户的画像。需要权限 ${config.personaViewAuthority ?? 3} 级。将转为查看自己的画像。`);
192
+ userId = session.userId;
193
+ }
194
+ }
195
+ if (!userId) {
196
+ return '无法获取目标用户信息。';
197
+ }
198
+ if (config.personaUserFilter.includes(userId)) {
199
+ return '该用户已被设置为禁止分析用户画像。';
200
+ }
201
+ try {
202
+ await ctx.group_analysis.executeUserPersonaAnalysis(session, userId, options.force ?? false);
203
+ }
204
+ catch (err) {
205
+ ctx.logger.error(`执行用户画像分析时发生未捕获的错误 (用户: ${userId}):`, err);
206
+ return '用户画像分析执行失败,请检查日志。';
207
+ }
208
+ });
209
+ ctx.command('每日漫画 [days:number]', '生成今日群聊漫画')
210
+ .alias('daily-comic')
211
+ .alias('群分析.每日漫画')
212
+ .usage('使用方法:/每日漫画 或 /每日漫画 3(回溯 3 天)。需要已配置生图 API。')
213
+ .option('group', '-g <guildId:string> 指定群号', {
214
+ authority: 3
215
+ })
216
+ .option('channel', '-c <channelId:string> 指定频道号', {
217
+ authority: 3
218
+ })
219
+ .action(async ({ session, options }, days) => {
220
+ if (session.isDirect && !options.group && !options.channel) {
221
+ return '私聊中请使用 -g 或 -c 指定目标群或频道。';
222
+ }
223
+ const targetGuildId = options.group ?? session.guildId ?? undefined;
224
+ // 显式指定 -g 时不再带当前会话 channelId,否则会分析当前频道而不是目标群
225
+ const targetChannelId = options.channel ?? (options.group ? undefined : session.channelId ?? undefined);
226
+ if (!targetGuildId && !targetChannelId) {
227
+ return '请使用 -g 或 -c 指定目标群或频道。';
228
+ }
229
+ if (!checkGroup(session, {
230
+ guildId: targetGuildId,
231
+ channelId: targetChannelId
232
+ })) {
233
+ return '目标群未启用分析功能,请使用 群分析.启用 来启用目标群的分析功能。';
234
+ }
235
+ const targetDays = typeof days === 'number' && days >= 1
236
+ ? Math.min(days, 7)
237
+ : undefined;
238
+ await ctx.group_analysis.executeDailyComic(session.selfId, {
239
+ guildId: targetGuildId || undefined,
240
+ channelId: targetChannelId || undefined
241
+ }, targetDays);
242
+ });
243
+ }
248
244
  //# sourceMappingURL=command.js.map
@@ -65,10 +65,7 @@ class MessageService extends koishi_1.Service {
65
65
  return result;
66
66
  }
67
67
  async handleMessage(session) {
68
- // 黑名单用户的消息完全不记录、不参与统计
69
- if (this.config.personaBlacklist?.includes(session.userId)) {
70
- return;
71
- }
68
+ // 黑名单只限制用户画像(见 handleIncomingMessageForPersona),消息本身仍需入库供群分析统计
72
69
  // 清洗掉官方 bot 的原始表情/协议标签,只保留正常文字
73
70
  const cleanContent = (0, utils_1.cleanContent)(session.content);
74
71
  // 腾讯官方 bot 的签名等非聊天垃圾内容,不记录
@@ -137,7 +134,7 @@ class MessageService extends koishi_1.Service {
137
134
  await this.flushIdleBuffers();
138
135
  }, this.bufferSweepIntervalMs);
139
136
  this.ctx.on('dispose', async () => {
140
- this.flushAllBuffers();
137
+ await this.flushAllBuffers();
141
138
  });
142
139
  const retentionDays = this.config.retentionDays;
143
140
  if (retentionDays === 0) {
@@ -211,8 +208,8 @@ class MessageService extends koishi_1.Service {
211
208
  // Filter out users in personaUserFilter for user persona
212
209
  purposeFilter = !this.config.personaUserFilter.includes(msg.userId);
213
210
  }
214
- // 黑名单用户的消息一律排除
215
- if (this.config.personaBlacklist?.includes(msg.userId)) {
211
+ // 黑名单仅作用于用户画像,不影响群分析统计
212
+ if (filter.purpose === 'user-persona' && this.config.personaBlacklist?.includes(msg.userId)) {
216
213
  purposeFilter = false;
217
214
  }
218
215
  return (withinTimeRange &&
@@ -251,6 +248,11 @@ class MessageService extends koishi_1.Service {
251
248
  const platform = inferred.platform || botFromSelfId?.platform;
252
249
  const selfId = inferred.selfId || filter.selfId;
253
250
  const bot = this.ctx.bots.find((b) => b.platform === platform && b.selfId === selfId);
251
+ // 把推断出的平台/机器人补进过滤条件,DB 路径据此隔离不同 bot/平台的相同群 ID
252
+ if (platform && !filter.platform)
253
+ filter = { ...filter, platform };
254
+ if (selfId && !filter.selfId)
255
+ filter = { ...filter, selfId };
254
256
  if (this.config.alwaysPersistMessages) {
255
257
  this.ctx.logger.info('使用数据库历史消息获取功能。');
256
258
  return this.getDatabaseHistoricalMessages(filter).then((messages) => {
@@ -341,8 +343,8 @@ class MessageService extends koishi_1.Service {
341
343
  purposeFilter =
342
344
  !this.config.personaUserFilter.includes(userId);
343
345
  }
344
- // 黑名单用户的消息一律排除
345
- if (this.config.personaBlacklist?.includes(userId)) {
346
+ // 黑名单仅作用于用户画像,不影响群分析统计
347
+ if (filter.purpose === 'user-persona' && this.config.personaBlacklist?.includes(userId)) {
346
348
  purposeFilter = false;
347
349
  }
348
350
  return (withinTimeRange &&
@@ -394,10 +396,11 @@ class MessageService extends koishi_1.Service {
394
396
  query.guildId = filter.guildId;
395
397
  if (filter.channelId)
396
398
  query.channelId = filter.channelId;
397
- if (filter.userId && filter.userId.length > 0)
398
- query.userId = {
399
- $in: filter.userId
400
- };
399
+ // 限定平台/机器人,避免不同 bot 或平台的相同群 ID 串数据
400
+ if (filter.platform)
401
+ query.platform = filter.platform;
402
+ if (filter.selfId)
403
+ query.selfId = filter.selfId;
401
404
  if (filter.startTime || filter.endTime) {
402
405
  query.timestamp = {};
403
406
  if (filter.startTime)
@@ -405,31 +408,27 @@ class MessageService extends koishi_1.Service {
405
408
  if (filter.endTime)
406
409
  query.timestamp.$lte = filter.endTime;
407
410
  }
408
- // Apply purpose-based filtering
409
- if (filter.purpose === 'group-analysis' &&
410
- this.config.userFilter.length > 0) {
411
- // Exclude users in userFilter for group analysis
412
- query.userId = query.userId
413
- ? {
414
- $in: filter.userId.filter((userId) => !this.config.userFilter.includes(userId))
415
- }
416
- : { $nin: this.config.userFilter };
411
+ // 用户条件:显式指定的用户 ∩ 排除名单。所有排除项合并,而不是互相覆盖。
412
+ // 黑名单只影响用户画像,群分析不排除这些用户
413
+ const excluded = new Set();
414
+ if (filter.purpose === 'user-persona') {
415
+ for (const id of (this.config.personaBlacklist || []))
416
+ excluded.add(String(id));
417
417
  }
418
- else if (filter.purpose === 'user-persona' &&
419
- this.config.personaUserFilter.length > 0) {
420
- // Exclude users in personaUserFilter for user persona
421
- query.userId = query.userId
422
- ? {
423
- $in: filter.userId.filter((userId) => !this.config.userFilter.includes(userId))
424
- }
425
- : { $nin: this.config.personaUserFilter };
418
+ if (filter.purpose === 'group-analysis') {
419
+ for (const id of (this.config.userFilter || []))
420
+ excluded.add(String(id));
426
421
  }
427
- // 黑名单用户的消息一律排除
428
- if (this.config.personaBlacklist?.length > 0) {
429
- const blacklist = this.config.personaBlacklist;
430
- query.userId = query.userId
431
- ? { $in: filter.userId.filter((userId) => !blacklist.includes(userId)) }
432
- : { $nin: blacklist };
422
+ else if (filter.purpose === 'user-persona') {
423
+ for (const id of (this.config.personaUserFilter || []))
424
+ excluded.add(String(id));
425
+ }
426
+ if (filter.userId && filter.userId.length > 0) {
427
+ const included = filter.userId.map(String).filter((id) => !excluded.has(id));
428
+ query.userId = { $in: included };
429
+ }
430
+ else if (excluded.size > 0) {
431
+ query.userId = { $nin: [...excluded] };
433
432
  }
434
433
  const messages = await this.ctx.database
435
434
  .select('group_analysis_messages')
@@ -438,7 +437,16 @@ class MessageService extends koishi_1.Service {
438
437
  .limit(filter.limit ?? 100)
439
438
  .orderBy(($) => $.timestamp, 'desc')
440
439
  .execute();
441
- return messages.map((message) => ({
440
+ // 与 OneBot/Bot API 路径保持一致:应用 wordsFilter,并跳过转发卡片等非聊天内容
441
+ const wordsFilter = this.config.wordsFilter || [];
442
+ return messages
443
+ .filter((message) => {
444
+ const content = String(message.content ?? '');
445
+ if ((0, utils_1.isJunkMessage)(content))
446
+ return false;
447
+ return !wordsFilter.some((word) => word && content.includes(word));
448
+ })
449
+ .map((message) => ({
442
450
  ...message,
443
451
  elements: koishi_1.h.parse(message.content)
444
452
  }));
@@ -493,7 +501,13 @@ class MessageService extends koishi_1.Service {
493
501
  return;
494
502
  const payload = buffer.messages.splice(0, buffer.messages.length);
495
503
  this.persistenceBuffers.delete(key);
496
- await this.persistMessages(payload);
504
+ const ok = await this.persistMessages(payload);
505
+ if (!ok) {
506
+ // 写库失败:放回缓冲,下一轮再试,避免瞬时故障导致消息丢失
507
+ const existing = this.persistenceBuffers.get(key) || { messages: [], lastMessageAt: Date.now() };
508
+ existing.messages.unshift(...payload);
509
+ this.persistenceBuffers.set(key, existing);
510
+ }
497
511
  }
498
512
  async flushIdleBuffers() {
499
513
  const now = Date.now();
@@ -520,12 +534,14 @@ class MessageService extends koishi_1.Service {
520
534
  }
521
535
  async persistMessages(messages) {
522
536
  if (!messages.length)
523
- return;
537
+ return true;
524
538
  try {
525
539
  await this.ctx.database.upsert('group_analysis_messages', messages);
540
+ return true;
526
541
  }
527
542
  catch (error) {
528
543
  this.ctx.logger.warn('Failed to store message in database:', error);
544
+ return false;
529
545
  }
530
546
  }
531
547
  getRecentMessages(guildId, channelId, limit = 100) {
@@ -42,9 +42,15 @@ class RendererService extends koishi_1.Service {
42
42
  await this.init();
43
43
  });
44
44
  }
45
- getSkinPath(filename) {
45
+ /** 当前皮肤目录:原项目皮肤放在 original/<skin>,自制皮肤直接放在 <skin>。 */
46
+ getSkinDir() {
46
47
  const skin = this.config.skin || 'md3';
47
- return path_1.default.resolve(this.templateDir, skin, filename);
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 page = await this._renderGroupAnalysis(data, theme);
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
- const outTemplateHtmlPath = path_1.default.resolve(this.templateDir, skin, `${randomId}.html`);
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(templatePath, 'utf-8');
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((totalEmojiCount / stat.messageCount).toFixed(2))
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.8.0",
4
+ "version": "1.8.2",
5
5
  "main": "lib/index.js",
6
6
  "module": "lib/index.mjs",
7
7
  "typings": "lib/index.d.ts",
@@ -65,3 +65,5 @@
65
65
 
66
66
 
67
67
 
68
+
69
+