koishi-plugin-chat-analyse 0.4.2 → 0.4.4
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/Collector.d.ts +1 -1
- package/lib/Manager.d.ts +56 -0
- package/lib/Stat.d.ts +8 -0
- package/lib/WhoAt.d.ts +1 -1
- package/lib/index.d.ts +2 -1
- package/lib/index.js +64 -35
- package/package.json +1 -1
package/lib/Collector.d.ts
CHANGED
package/lib/Manager.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Context, Command } from 'koishi';
|
|
2
|
+
import { Config } from './index';
|
|
3
|
+
/**
|
|
4
|
+
* @class Manager
|
|
5
|
+
* @description
|
|
6
|
+
* 提供数据管理功能,包括导入、导出和清除插件产生的所有数据。
|
|
7
|
+
* 这些命令通常需要较高的权限才能执行。
|
|
8
|
+
*/
|
|
9
|
+
export declare class Manager {
|
|
10
|
+
private ctx;
|
|
11
|
+
private config;
|
|
12
|
+
private readonly tableNames;
|
|
13
|
+
private readonly userRelatableTables;
|
|
14
|
+
/**
|
|
15
|
+
* Manager 类的构造函数。
|
|
16
|
+
* @param {Context} ctx - Koishi 的插件上下文。
|
|
17
|
+
* @param {Config} config - 插件的配置对象。
|
|
18
|
+
*/
|
|
19
|
+
constructor(ctx: Context, config: Config);
|
|
20
|
+
/**
|
|
21
|
+
* @public
|
|
22
|
+
* @method registerCommands
|
|
23
|
+
* @description 在主 `analyse` 命令下注册 `.import`, `.export`, 和 `.clear` 子命令。
|
|
24
|
+
* @param {Command} analyse - 主 `analyse` 命令实例。
|
|
25
|
+
*/
|
|
26
|
+
registerCommands(analyse: Command): void;
|
|
27
|
+
/**
|
|
28
|
+
* @private
|
|
29
|
+
* @async
|
|
30
|
+
* @method handleClearAll
|
|
31
|
+
* @description 处理清空所有数据的逻辑,包括用户确认。
|
|
32
|
+
*/
|
|
33
|
+
private handleClearAll;
|
|
34
|
+
/**
|
|
35
|
+
* @private
|
|
36
|
+
* @async
|
|
37
|
+
* @method clearSingleTable
|
|
38
|
+
* @description 清空单个指定表的数据。
|
|
39
|
+
*/
|
|
40
|
+
private clearSingleTable;
|
|
41
|
+
/**
|
|
42
|
+
* @private
|
|
43
|
+
* @async
|
|
44
|
+
* @method clearScopedData
|
|
45
|
+
* @description 清除指定范围(用户/群组)的数据。
|
|
46
|
+
*/
|
|
47
|
+
private clearScopedData;
|
|
48
|
+
/**
|
|
49
|
+
* @private
|
|
50
|
+
* @async
|
|
51
|
+
* @method clearAllData
|
|
52
|
+
* @description 清空所有由本插件创建的表中的数据。
|
|
53
|
+
* @returns {Promise<Record<string, number>>} 返回一个对象,键为表名,值为被删除的行数。
|
|
54
|
+
*/
|
|
55
|
+
private clearAllData;
|
|
56
|
+
}
|
package/lib/Stat.d.ts
CHANGED
|
@@ -15,6 +15,13 @@ export declare class Stat {
|
|
|
15
15
|
* @param {Config} config - 插件的配置对象。
|
|
16
16
|
*/
|
|
17
17
|
constructor(ctx: Context, config: Config);
|
|
18
|
+
/**
|
|
19
|
+
* @private
|
|
20
|
+
* @method setupCleanupTask
|
|
21
|
+
* @description 设置一个定时清理任务。
|
|
22
|
+
* 此任务会根据配置中的 `rankRetentionDays` 定期删除过期的发言排行数据,以防止数据库膨胀。
|
|
23
|
+
*/
|
|
24
|
+
private setupCleanupTask;
|
|
18
25
|
/**
|
|
19
26
|
* @public
|
|
20
27
|
* @method registerCommands
|
|
@@ -93,6 +100,7 @@ export declare class Stat {
|
|
|
93
100
|
* @description 从数据库中获取并聚合指定时间范围内的活跃用户排行数据。
|
|
94
101
|
* @param {number} hours - 查询过去的小时数。
|
|
95
102
|
* @param {string} [guildId] - (可选) 要查询的群组 ID。若不提供,则进行全局排行。
|
|
103
|
+
* @param {string} [type] - (可选) 要筛选的消息类型。
|
|
96
104
|
* @returns {Promise<{ list: RenderListItem[], total: number } | string>} 返回一个包含列表和总数的对象,或在无数据时返回提示字符串。
|
|
97
105
|
*/
|
|
98
106
|
private getActiveUserStats;
|
package/lib/WhoAt.d.ts
CHANGED
package/lib/index.d.ts
CHANGED
package/lib/index.js
CHANGED
|
@@ -92,10 +92,10 @@ var Collector = class _Collector {
|
|
|
92
92
|
}, { primary: ["uid", "type"] });
|
|
93
93
|
this.ctx.model.extend("analyse_rank", {
|
|
94
94
|
uid: "unsigned",
|
|
95
|
-
|
|
95
|
+
type: "string",
|
|
96
96
|
count: "unsigned",
|
|
97
97
|
timestamp: "timestamp"
|
|
98
|
-
}, { primary: ["uid", "
|
|
98
|
+
}, { primary: ["uid", "timestamp", "type"] });
|
|
99
99
|
if (this.config.enableOriRecord) {
|
|
100
100
|
this.ctx.model.extend("analyse_cache", {
|
|
101
101
|
id: "unsigned",
|
|
@@ -141,29 +141,29 @@ var Collector = class _Collector {
|
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
143
|
const hourStart = new Date(messageTime.getFullYear(), messageTime.getMonth(), messageTime.getDate(), messageTime.getHours());
|
|
144
|
-
const rankKey = `${uid}:${hourStart.toISOString()}`;
|
|
145
|
-
const existingRank = this.rankStatBuffer.get(rankKey);
|
|
146
|
-
if (existingRank) {
|
|
147
|
-
existingRank.count++;
|
|
148
|
-
existingRank.timestamp = messageTime;
|
|
149
|
-
} else {
|
|
150
|
-
this.rankStatBuffer.set(rankKey, { uid, hour: hourStart, count: 1, timestamp: messageTime });
|
|
151
|
-
}
|
|
152
144
|
const uniqueElementTypes = new Set(elements.map((e) => e.type));
|
|
153
145
|
for (const type of uniqueElementTypes) {
|
|
154
|
-
const
|
|
155
|
-
const
|
|
156
|
-
if (
|
|
157
|
-
|
|
158
|
-
|
|
146
|
+
const msgKey = `${uid}:${type}`;
|
|
147
|
+
const existingMsg = this.msgStatBuffer.get(msgKey);
|
|
148
|
+
if (existingMsg) {
|
|
149
|
+
existingMsg.count++;
|
|
150
|
+
existingMsg.timestamp = messageTime;
|
|
151
|
+
} else {
|
|
152
|
+
this.msgStatBuffer.set(msgKey, { uid, type, count: 1, timestamp: messageTime });
|
|
153
|
+
}
|
|
154
|
+
const rankKey = `${uid}:${hourStart.toISOString()}:${type}`;
|
|
155
|
+
const existingRank = this.rankStatBuffer.get(rankKey);
|
|
156
|
+
if (existingRank) {
|
|
157
|
+
existingRank.count++;
|
|
159
158
|
} else {
|
|
160
|
-
this.
|
|
159
|
+
this.rankStatBuffer.set(rankKey, { uid, timestamp: hourStart, type, count: 1 });
|
|
161
160
|
}
|
|
162
161
|
}
|
|
163
162
|
if (this.config.enableWhoAt) {
|
|
164
163
|
const atElements = elements.filter((e) => e.type === "at");
|
|
165
164
|
if (atElements.length > 0) {
|
|
166
|
-
const
|
|
165
|
+
const contentElements = elements.filter((e) => e.type !== "at");
|
|
166
|
+
const sanitizedContent = this.sanitizeContent(contentElements);
|
|
167
167
|
for (const atElement of atElements) {
|
|
168
168
|
const targetId = atElement.attrs.id;
|
|
169
169
|
if (targetId && targetId !== userId) this.whoAtBuffer.push({ uid, target: targetId, content: sanitizedContent, timestamp: messageTime });
|
|
@@ -295,9 +295,9 @@ var Collector = class _Collector {
|
|
|
295
295
|
"analyse_rank",
|
|
296
296
|
(row) => rankBufferToFlush.map((item) => ({
|
|
297
297
|
uid: item.uid,
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
298
|
+
timestamp: item.timestamp,
|
|
299
|
+
type: item.type,
|
|
300
|
+
count: import_koishi.$.add(import_koishi.$.ifNull(row.count, 0), item.count)
|
|
301
301
|
}))
|
|
302
302
|
);
|
|
303
303
|
}
|
|
@@ -546,11 +546,30 @@ var Stat = class {
|
|
|
546
546
|
this.ctx = ctx;
|
|
547
547
|
this.config = config;
|
|
548
548
|
this.renderer = new Renderer(ctx);
|
|
549
|
+
this.setupCleanupTask();
|
|
549
550
|
}
|
|
550
551
|
static {
|
|
551
552
|
__name(this, "Stat");
|
|
552
553
|
}
|
|
553
554
|
renderer;
|
|
555
|
+
/**
|
|
556
|
+
* @private
|
|
557
|
+
* @method setupCleanupTask
|
|
558
|
+
* @description 设置一个定时清理任务。
|
|
559
|
+
* 此任务会根据配置中的 `rankRetentionDays` 定期删除过期的发言排行数据,以防止数据库膨胀。
|
|
560
|
+
*/
|
|
561
|
+
setupCleanupTask() {
|
|
562
|
+
if (this.config.rankRetentionDays > 0) {
|
|
563
|
+
this.ctx.cron("0 0 * * *", async () => {
|
|
564
|
+
try {
|
|
565
|
+
const cutoffDate = new Date(Date.now() - this.config.rankRetentionDays * import_koishi3.Time.day);
|
|
566
|
+
await this.ctx.database.remove("analyse_rank", { timestamp: { $lt: cutoffDate } });
|
|
567
|
+
} catch (error) {
|
|
568
|
+
this.ctx.logger.error("清理发言排行历史记录出错:", error);
|
|
569
|
+
}
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
}
|
|
554
573
|
/**
|
|
555
574
|
* @public
|
|
556
575
|
* @method registerCommands
|
|
@@ -602,17 +621,17 @@ var Stat = class {
|
|
|
602
621
|
});
|
|
603
622
|
}
|
|
604
623
|
if (this.config.enableRankStat) {
|
|
605
|
-
analyse.subcommand(".rank", "用户发言排行").option("guild", "-g <guildId:string> 指定群组").option("
|
|
624
|
+
analyse.subcommand(".rank", "用户发言排行").option("guild", "-g <guildId:string> 指定群组").option("type", "-t <type:string> 指定类型").option("hours", "-h <hours:number> 指定时长", { fallback: 24 }).option("all", "-a 展示全局统计").action(async ({ session, options }) => {
|
|
606
625
|
const guildId = options.all ? void 0 : options.guild || session.guildId;
|
|
607
626
|
if (!guildId && !options.all) return "请提供查询范围";
|
|
608
627
|
try {
|
|
609
|
-
const stats = await this.getActiveUserStats(options.hours, guildId);
|
|
628
|
+
const stats = await this.getActiveUserStats(options.hours, guildId, options.type);
|
|
610
629
|
if (typeof stats === "string") return stats;
|
|
611
630
|
const listWithPercentage = stats.list.map((row) => [
|
|
612
631
|
...row,
|
|
613
632
|
stats.total > 0 ? `${(row[1] / stats.total * 100).toFixed(2)}%` : "0.00%"
|
|
614
633
|
]);
|
|
615
|
-
const title = await this.generateTitle(guildId, void 0, { main: "排行", timeRange: options.hours });
|
|
634
|
+
const title = await this.generateTitle(guildId, void 0, { main: "排行", timeRange: options.hours, subtype: options.type });
|
|
616
635
|
const renderData = { title, time: /* @__PURE__ */ new Date(), total: stats.total, list: listWithPercentage };
|
|
617
636
|
const result = await this.renderer.renderList(renderData, ["用户", "总计发言", "占比"]);
|
|
618
637
|
return Buffer.isBuffer(result) ? import_koishi3.Element.image(result, "image/png") : result;
|
|
@@ -692,8 +711,11 @@ var Stat = class {
|
|
|
692
711
|
const guild = await this.ctx.database.get("analyse_user", { channelId: guildId }, ["channelName"]);
|
|
693
712
|
scopeText = guild[0]?.channelName || guildId;
|
|
694
713
|
}
|
|
695
|
-
if (options.main === "排行")
|
|
696
|
-
|
|
714
|
+
if (options.main === "排行") {
|
|
715
|
+
const typeText = options.subtype ? `“${options.subtype}”` : "";
|
|
716
|
+
return `${scopeText}${options.timeRange}小时${typeText}消息排行`;
|
|
717
|
+
}
|
|
718
|
+
if (options.main === "消息" && options.subtype) return `${scopeText}“${options.subtype}”消息统计`;
|
|
697
719
|
return `${scopeText}${options.main}统计`;
|
|
698
720
|
}
|
|
699
721
|
/**
|
|
@@ -771,22 +793,26 @@ var Stat = class {
|
|
|
771
793
|
* @description 从数据库中获取并聚合指定时间范围内的活跃用户排行数据。
|
|
772
794
|
* @param {number} hours - 查询过去的小时数。
|
|
773
795
|
* @param {string} [guildId] - (可选) 要查询的群组 ID。若不提供,则进行全局排行。
|
|
796
|
+
* @param {string} [type] - (可选) 要筛选的消息类型。
|
|
774
797
|
* @returns {Promise<{ list: RenderListItem[], total: number } | string>} 返回一个包含列表和总数的对象,或在无数据时返回提示字符串。
|
|
775
798
|
*/
|
|
776
|
-
async getActiveUserStats(hours, guildId) {
|
|
799
|
+
async getActiveUserStats(hours, guildId, type) {
|
|
777
800
|
const since = new Date(Date.now() - hours * 3600 * 1e3);
|
|
801
|
+
const baseQuery = { timestamp: { $gte: since } };
|
|
802
|
+
if (type) baseQuery.type = type;
|
|
778
803
|
if (guildId) {
|
|
779
804
|
const usersInGuild = await this.ctx.database.get("analyse_user", { channelId: guildId }, ["uid", "userName"]);
|
|
780
805
|
if (usersInGuild.length === 0) return "暂无统计数据";
|
|
781
806
|
const uids = usersInGuild.map((u) => u.uid);
|
|
782
807
|
const userNameMap = new Map(usersInGuild.map((u) => [u.uid, u.userName]));
|
|
783
|
-
const
|
|
808
|
+
const query = { ...baseQuery, uid: { $in: uids } };
|
|
809
|
+
const stats = await this.ctx.database.select("analyse_rank").where(query).groupBy("uid", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count") }).orderBy("count", "desc").limit(100).execute();
|
|
784
810
|
if (stats.length === 0) return "暂无统计数据";
|
|
785
811
|
const total = stats.reduce((sum, record) => sum + record.count, 0);
|
|
786
812
|
const list = stats.map((item) => [userNameMap.get(item.uid) || `UID ${item.uid}`, item.count]);
|
|
787
813
|
return { list, total };
|
|
788
814
|
} else {
|
|
789
|
-
const msgStats = await this.ctx.database.select("analyse_rank").where(
|
|
815
|
+
const msgStats = await this.ctx.database.select("analyse_rank").where(baseQuery).project(["uid", "count"]).execute();
|
|
790
816
|
if (msgStats.length === 0) return "暂无统计数据";
|
|
791
817
|
const allUsers = await this.ctx.database.get("analyse_user", {}, ["uid", "userId", "userName"]);
|
|
792
818
|
const uidToUserMap = new Map(allUsers.map((u) => [u.uid, { userId: u.userId, userName: u.userName }]));
|
|
@@ -827,13 +853,13 @@ var WhoAt = class {
|
|
|
827
853
|
* @private
|
|
828
854
|
* @method setupCleanupTask
|
|
829
855
|
* @description 设置一个定时清理任务。
|
|
830
|
-
* 此任务会根据配置中的 `
|
|
856
|
+
* 此任务会根据配置中的 `atRetentionDays` 定期删除过期的@记录,以防止数据库膨胀。
|
|
831
857
|
*/
|
|
832
858
|
setupCleanupTask() {
|
|
833
|
-
if (this.config.
|
|
859
|
+
if (this.config.atRetentionDays > 0) {
|
|
834
860
|
this.ctx.cron("0 0 * * *", async () => {
|
|
835
861
|
try {
|
|
836
|
-
const cutoffDate = new Date(Date.now() - this.config.
|
|
862
|
+
const cutoffDate = new Date(Date.now() - this.config.atRetentionDays * import_koishi4.Time.day);
|
|
837
863
|
await this.ctx.database.remove("analyse_at", { timestamp: { $lt: cutoffDate } });
|
|
838
864
|
} catch (error) {
|
|
839
865
|
this.ctx.logger.error("清理 @ 历史记录出错:", error);
|
|
@@ -896,12 +922,15 @@ var Config = import_koishi5.Schema.intersect([
|
|
|
896
922
|
}).description("监听配置"),
|
|
897
923
|
import_koishi5.Schema.object({
|
|
898
924
|
enableCmdStat: import_koishi5.Schema.boolean().default(true).description("启用命令统计"),
|
|
899
|
-
enableMsgStat: import_koishi5.Schema.boolean().default(true).description("启用消息统计")
|
|
900
|
-
|
|
901
|
-
|
|
925
|
+
enableMsgStat: import_koishi5.Schema.boolean().default(true).description("启用消息统计")
|
|
926
|
+
}).description("统计配置"),
|
|
927
|
+
import_koishi5.Schema.object({
|
|
928
|
+
enableRankStat: import_koishi5.Schema.boolean().default(true).description("启用发言排行"),
|
|
929
|
+
rankRetentionDays: import_koishi5.Schema.number().min(0).default(31).description("记录保留天数")
|
|
930
|
+
}).description("发言排行配置"),
|
|
902
931
|
import_koishi5.Schema.object({
|
|
903
932
|
enableWhoAt: import_koishi5.Schema.boolean().default(true).description("启用 @ 记录"),
|
|
904
|
-
|
|
933
|
+
atRetentionDays: import_koishi5.Schema.number().min(0).default(7).description("记录保留天数")
|
|
905
934
|
}).description("@ 记录配置")
|
|
906
935
|
]);
|
|
907
936
|
function apply(ctx, config) {
|