koishi-plugin-group-analysis-mx 1.8.0 → 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.
@@ -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
- 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 (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
@@ -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
- if (filter.userId && filter.userId.length > 0)
398
- query.userId = {
399
- $in: filter.userId
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
- // 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 };
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.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 };
420
+ else if (filter.purpose === 'user-persona') {
421
+ for (const id of (this.config.personaUserFilter || []))
422
+ excluded.add(String(id));
426
423
  }
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 };
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
- return messages.map((message) => ({
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) {
@@ -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.1",
5
5
  "main": "lib/index.js",
6
6
  "module": "lib/index.mjs",
7
7
  "typings": "lib/index.d.ts",
@@ -65,3 +65,4 @@
65
65
 
66
66
 
67
67
 
68
+