koishi-plugin-chat-analyse 0.4.3 → 0.4.5
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/Data.d.ts +19 -0
- package/lib/Manager.d.ts +56 -0
- package/lib/Stat.d.ts +1 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +222 -44
- package/package.json +1 -1
package/lib/Collector.d.ts
CHANGED
package/lib/Data.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Context, Command } from 'koishi';
|
|
2
|
+
/**
|
|
3
|
+
* @class Data
|
|
4
|
+
* @description
|
|
5
|
+
* 提供数据备份、恢复和清理的管理功能,恢复逻辑采用分批处理以优化性能。
|
|
6
|
+
* 清理功能支持按表、时间范围和用户范围进行精确操作。
|
|
7
|
+
*/
|
|
8
|
+
export declare class Data {
|
|
9
|
+
private ctx;
|
|
10
|
+
private dataDir;
|
|
11
|
+
constructor(ctx: Context);
|
|
12
|
+
/**
|
|
13
|
+
* @public
|
|
14
|
+
* @method registerCommands
|
|
15
|
+
* @description 在 'analyse.admin' 命令下注册所有数据管理相关的子命令。
|
|
16
|
+
* @param {Command} analyse - '.admin' 命令实例。
|
|
17
|
+
*/
|
|
18
|
+
registerCommands(analyse: Command): void;
|
|
19
|
+
}
|
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
|
@@ -100,6 +100,7 @@ export declare class Stat {
|
|
|
100
100
|
* @description 从数据库中获取并聚合指定时间范围内的活跃用户排行数据。
|
|
101
101
|
* @param {number} hours - 查询过去的小时数。
|
|
102
102
|
* @param {string} [guildId] - (可选) 要查询的群组 ID。若不提供,则进行全局排行。
|
|
103
|
+
* @param {string} [type] - (可选) 要筛选的消息类型。
|
|
103
104
|
* @returns {Promise<{ list: RenderListItem[], total: number } | string>} 返回一个包含列表和总数的对象,或在无数据时返回提示字符串。
|
|
104
105
|
*/
|
|
105
106
|
private getActiveUserStats;
|
package/lib/index.d.ts
CHANGED
package/lib/index.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
1
2
|
var __defProp = Object.defineProperty;
|
|
2
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
4
6
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
7
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
6
8
|
var __export = (target, all) => {
|
|
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
@@ -27,7 +37,7 @@ __export(src_exports, {
|
|
|
27
37
|
using: () => using
|
|
28
38
|
});
|
|
29
39
|
module.exports = __toCommonJS(src_exports);
|
|
30
|
-
var
|
|
40
|
+
var import_koishi6 = require("koishi");
|
|
31
41
|
|
|
32
42
|
// src/Collector.ts
|
|
33
43
|
var import_koishi = require("koishi");
|
|
@@ -92,10 +102,10 @@ var Collector = class _Collector {
|
|
|
92
102
|
}, { primary: ["uid", "type"] });
|
|
93
103
|
this.ctx.model.extend("analyse_rank", {
|
|
94
104
|
uid: "unsigned",
|
|
95
|
-
|
|
105
|
+
type: "string",
|
|
96
106
|
count: "unsigned",
|
|
97
107
|
timestamp: "timestamp"
|
|
98
|
-
}, { primary: ["uid", "
|
|
108
|
+
}, { primary: ["uid", "timestamp", "type"] });
|
|
99
109
|
if (this.config.enableOriRecord) {
|
|
100
110
|
this.ctx.model.extend("analyse_cache", {
|
|
101
111
|
id: "unsigned",
|
|
@@ -141,29 +151,29 @@ var Collector = class _Collector {
|
|
|
141
151
|
}
|
|
142
152
|
}
|
|
143
153
|
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
154
|
const uniqueElementTypes = new Set(elements.map((e) => e.type));
|
|
153
155
|
for (const type of uniqueElementTypes) {
|
|
154
|
-
const
|
|
155
|
-
const
|
|
156
|
-
if (
|
|
157
|
-
|
|
158
|
-
|
|
156
|
+
const msgKey = `${uid}:${type}`;
|
|
157
|
+
const existingMsg = this.msgStatBuffer.get(msgKey);
|
|
158
|
+
if (existingMsg) {
|
|
159
|
+
existingMsg.count++;
|
|
160
|
+
existingMsg.timestamp = messageTime;
|
|
159
161
|
} else {
|
|
160
|
-
this.msgStatBuffer.set(
|
|
162
|
+
this.msgStatBuffer.set(msgKey, { uid, type, count: 1, timestamp: messageTime });
|
|
163
|
+
}
|
|
164
|
+
const rankKey = `${uid}:${hourStart.toISOString()}:${type}`;
|
|
165
|
+
const existingRank = this.rankStatBuffer.get(rankKey);
|
|
166
|
+
if (existingRank) {
|
|
167
|
+
existingRank.count++;
|
|
168
|
+
} else {
|
|
169
|
+
this.rankStatBuffer.set(rankKey, { uid, timestamp: hourStart, type, count: 1 });
|
|
161
170
|
}
|
|
162
171
|
}
|
|
163
172
|
if (this.config.enableWhoAt) {
|
|
164
173
|
const atElements = elements.filter((e) => e.type === "at");
|
|
165
174
|
if (atElements.length > 0) {
|
|
166
|
-
const
|
|
175
|
+
const contentElements = elements.filter((e) => e.type !== "at");
|
|
176
|
+
const sanitizedContent = this.sanitizeContent(contentElements);
|
|
167
177
|
for (const atElement of atElements) {
|
|
168
178
|
const targetId = atElement.attrs.id;
|
|
169
179
|
if (targetId && targetId !== userId) this.whoAtBuffer.push({ uid, target: targetId, content: sanitizedContent, timestamp: messageTime });
|
|
@@ -295,9 +305,9 @@ var Collector = class _Collector {
|
|
|
295
305
|
"analyse_rank",
|
|
296
306
|
(row) => rankBufferToFlush.map((item) => ({
|
|
297
307
|
uid: item.uid,
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
308
|
+
timestamp: item.timestamp,
|
|
309
|
+
type: item.type,
|
|
310
|
+
count: import_koishi.$.add(import_koishi.$.ifNull(row.count, 0), item.count)
|
|
301
311
|
}))
|
|
302
312
|
);
|
|
303
313
|
}
|
|
@@ -563,7 +573,7 @@ var Stat = class {
|
|
|
563
573
|
this.ctx.cron("0 0 * * *", async () => {
|
|
564
574
|
try {
|
|
565
575
|
const cutoffDate = new Date(Date.now() - this.config.rankRetentionDays * import_koishi3.Time.day);
|
|
566
|
-
await this.ctx.database.remove("analyse_rank", {
|
|
576
|
+
await this.ctx.database.remove("analyse_rank", { timestamp: { $lt: cutoffDate } });
|
|
567
577
|
} catch (error) {
|
|
568
578
|
this.ctx.logger.error("清理发言排行历史记录出错:", error);
|
|
569
579
|
}
|
|
@@ -621,17 +631,17 @@ var Stat = class {
|
|
|
621
631
|
});
|
|
622
632
|
}
|
|
623
633
|
if (this.config.enableRankStat) {
|
|
624
|
-
analyse.subcommand(".rank", "用户发言排行").option("guild", "-g <guildId:string> 指定群组").option("
|
|
634
|
+
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 }) => {
|
|
625
635
|
const guildId = options.all ? void 0 : options.guild || session.guildId;
|
|
626
636
|
if (!guildId && !options.all) return "请提供查询范围";
|
|
627
637
|
try {
|
|
628
|
-
const stats = await this.getActiveUserStats(options.hours, guildId);
|
|
638
|
+
const stats = await this.getActiveUserStats(options.hours, guildId, options.type);
|
|
629
639
|
if (typeof stats === "string") return stats;
|
|
630
640
|
const listWithPercentage = stats.list.map((row) => [
|
|
631
641
|
...row,
|
|
632
642
|
stats.total > 0 ? `${(row[1] / stats.total * 100).toFixed(2)}%` : "0.00%"
|
|
633
643
|
]);
|
|
634
|
-
const title = await this.generateTitle(guildId, void 0, { main: "排行", timeRange: options.hours });
|
|
644
|
+
const title = await this.generateTitle(guildId, void 0, { main: "排行", timeRange: options.hours, subtype: options.type });
|
|
635
645
|
const renderData = { title, time: /* @__PURE__ */ new Date(), total: stats.total, list: listWithPercentage };
|
|
636
646
|
const result = await this.renderer.renderList(renderData, ["用户", "总计发言", "占比"]);
|
|
637
647
|
return Buffer.isBuffer(result) ? import_koishi3.Element.image(result, "image/png") : result;
|
|
@@ -711,8 +721,11 @@ var Stat = class {
|
|
|
711
721
|
const guild = await this.ctx.database.get("analyse_user", { channelId: guildId }, ["channelName"]);
|
|
712
722
|
scopeText = guild[0]?.channelName || guildId;
|
|
713
723
|
}
|
|
714
|
-
if (options.main === "排行")
|
|
715
|
-
|
|
724
|
+
if (options.main === "排行") {
|
|
725
|
+
const typeText = options.subtype ? `“${options.subtype}”` : "";
|
|
726
|
+
return `${scopeText}${options.timeRange}小时${typeText}消息排行`;
|
|
727
|
+
}
|
|
728
|
+
if (options.main === "消息" && options.subtype) return `${scopeText}“${options.subtype}”消息统计`;
|
|
716
729
|
return `${scopeText}${options.main}统计`;
|
|
717
730
|
}
|
|
718
731
|
/**
|
|
@@ -790,22 +803,26 @@ var Stat = class {
|
|
|
790
803
|
* @description 从数据库中获取并聚合指定时间范围内的活跃用户排行数据。
|
|
791
804
|
* @param {number} hours - 查询过去的小时数。
|
|
792
805
|
* @param {string} [guildId] - (可选) 要查询的群组 ID。若不提供,则进行全局排行。
|
|
806
|
+
* @param {string} [type] - (可选) 要筛选的消息类型。
|
|
793
807
|
* @returns {Promise<{ list: RenderListItem[], total: number } | string>} 返回一个包含列表和总数的对象,或在无数据时返回提示字符串。
|
|
794
808
|
*/
|
|
795
|
-
async getActiveUserStats(hours, guildId) {
|
|
809
|
+
async getActiveUserStats(hours, guildId, type) {
|
|
796
810
|
const since = new Date(Date.now() - hours * 3600 * 1e3);
|
|
811
|
+
const baseQuery = { timestamp: { $gte: since } };
|
|
812
|
+
if (type) baseQuery.type = type;
|
|
797
813
|
if (guildId) {
|
|
798
814
|
const usersInGuild = await this.ctx.database.get("analyse_user", { channelId: guildId }, ["uid", "userName"]);
|
|
799
815
|
if (usersInGuild.length === 0) return "暂无统计数据";
|
|
800
816
|
const uids = usersInGuild.map((u) => u.uid);
|
|
801
817
|
const userNameMap = new Map(usersInGuild.map((u) => [u.uid, u.userName]));
|
|
802
|
-
const
|
|
818
|
+
const query = { ...baseQuery, uid: { $in: uids } };
|
|
819
|
+
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();
|
|
803
820
|
if (stats.length === 0) return "暂无统计数据";
|
|
804
821
|
const total = stats.reduce((sum, record) => sum + record.count, 0);
|
|
805
822
|
const list = stats.map((item) => [userNameMap.get(item.uid) || `UID ${item.uid}`, item.count]);
|
|
806
823
|
return { list, total };
|
|
807
824
|
} else {
|
|
808
|
-
const msgStats = await this.ctx.database.select("analyse_rank").where(
|
|
825
|
+
const msgStats = await this.ctx.database.select("analyse_rank").where(baseQuery).project(["uid", "count"]).execute();
|
|
809
826
|
if (msgStats.length === 0) return "暂无统计数据";
|
|
810
827
|
const allUsers = await this.ctx.database.get("analyse_user", {}, ["uid", "userId", "userName"]);
|
|
811
828
|
const uidToUserMap = new Map(allUsers.map((u) => [u.uid, { userId: u.userId, userName: u.userName }]));
|
|
@@ -893,6 +910,165 @@ var WhoAt = class {
|
|
|
893
910
|
}
|
|
894
911
|
};
|
|
895
912
|
|
|
913
|
+
// src/Data.ts
|
|
914
|
+
var import_koishi5 = require("koishi");
|
|
915
|
+
var fs = __toESM(require("fs/promises"));
|
|
916
|
+
var path = __toESM(require("path"));
|
|
917
|
+
var ALL_TABLES = [
|
|
918
|
+
"analyse_user",
|
|
919
|
+
"analyse_cmd",
|
|
920
|
+
"analyse_msg",
|
|
921
|
+
"analyse_rank",
|
|
922
|
+
"analyse_at",
|
|
923
|
+
"analyse_cache"
|
|
924
|
+
];
|
|
925
|
+
var Data = class {
|
|
926
|
+
constructor(ctx) {
|
|
927
|
+
this.ctx = ctx;
|
|
928
|
+
this.dataDir = path.join(this.ctx.baseDir, "data", "chat-analyse");
|
|
929
|
+
}
|
|
930
|
+
static {
|
|
931
|
+
__name(this, "Data");
|
|
932
|
+
}
|
|
933
|
+
dataDir;
|
|
934
|
+
/**
|
|
935
|
+
* @public
|
|
936
|
+
* @method registerCommands
|
|
937
|
+
* @description 在 'analyse.admin' 命令下注册所有数据管理相关的子命令。
|
|
938
|
+
* @param {Command} analyse - '.admin' 命令实例。
|
|
939
|
+
*/
|
|
940
|
+
registerCommands(analyse) {
|
|
941
|
+
analyse.subcommand(".backup", "备份统计数据", { authority: 4 }).action(async () => {
|
|
942
|
+
try {
|
|
943
|
+
await fs.mkdir(this.dataDir, { recursive: true });
|
|
944
|
+
const allUsers = await this.ctx.database.get("analyse_user", {});
|
|
945
|
+
const uidToUserInfoMap = new Map(allUsers.map((u) => [u.uid, u]));
|
|
946
|
+
for (const tableName of ALL_TABLES) {
|
|
947
|
+
const filepath = path.join(this.dataDir, `${tableName}.json`);
|
|
948
|
+
let dataToExport;
|
|
949
|
+
if (tableName === "analyse_user") {
|
|
950
|
+
dataToExport = allUsers.map(({ uid, ...rest }) => rest);
|
|
951
|
+
} else {
|
|
952
|
+
const records = await this.ctx.database.get(tableName, {});
|
|
953
|
+
dataToExport = records.map((record) => {
|
|
954
|
+
const userInfo = uidToUserInfoMap.get(record.uid);
|
|
955
|
+
if (!userInfo) return null;
|
|
956
|
+
const { uid, ...restOfRecord } = record;
|
|
957
|
+
return {
|
|
958
|
+
userId: userInfo.userId,
|
|
959
|
+
channelId: userInfo.channelId,
|
|
960
|
+
...restOfRecord
|
|
961
|
+
};
|
|
962
|
+
}).filter(Boolean);
|
|
963
|
+
}
|
|
964
|
+
await fs.writeFile(filepath, JSON.stringify(dataToExport, null, 2));
|
|
965
|
+
}
|
|
966
|
+
return `数据备份成功`;
|
|
967
|
+
} catch (error) {
|
|
968
|
+
this.ctx.logger.error("数据备份失败:", error);
|
|
969
|
+
return "数据备份失败";
|
|
970
|
+
}
|
|
971
|
+
});
|
|
972
|
+
analyse.subcommand(".restore", "恢复统计数据", { authority: 4 }).action(async () => {
|
|
973
|
+
const BATCH_SIZE = 100;
|
|
974
|
+
try {
|
|
975
|
+
const userTablePath = path.join(this.dataDir, "analyse_user.json");
|
|
976
|
+
try {
|
|
977
|
+
const usersToImport = JSON.parse(await fs.readFile(userTablePath, "utf-8"));
|
|
978
|
+
if (Array.isArray(usersToImport) && usersToImport.length > 0) {
|
|
979
|
+
for (let i = 0; i < usersToImport.length; i += BATCH_SIZE) {
|
|
980
|
+
const batch = usersToImport.slice(i, i + BATCH_SIZE);
|
|
981
|
+
await this.ctx.database.upsert("analyse_user", batch);
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
} catch (e) {
|
|
985
|
+
if (e.code !== "ENOENT") throw e;
|
|
986
|
+
this.ctx.logger.warn("无用户数据可恢复");
|
|
987
|
+
}
|
|
988
|
+
const allUsers = await this.ctx.database.get("analyse_user", {});
|
|
989
|
+
const userToUidMap = new Map(allUsers.map((u) => [`${u.channelId}:${u.userId}`, u.uid]));
|
|
990
|
+
for (const tableName of ALL_TABLES.filter((t) => t !== "analyse_user")) {
|
|
991
|
+
const filepath = path.join(this.dataDir, `${tableName}.json`);
|
|
992
|
+
try {
|
|
993
|
+
const recordsToImport = JSON.parse(await fs.readFile(filepath, "utf-8"));
|
|
994
|
+
if (Array.isArray(recordsToImport) && recordsToImport.length > 0) {
|
|
995
|
+
const recordsWithUid = recordsToImport.map((r) => {
|
|
996
|
+
const uid = userToUidMap.get(`${r.channelId}:${r.userId}`);
|
|
997
|
+
if (!uid) return null;
|
|
998
|
+
const { userId, channelId, ...rest } = r;
|
|
999
|
+
return { uid, ...rest };
|
|
1000
|
+
}).filter(Boolean);
|
|
1001
|
+
if (recordsWithUid.length > 0) {
|
|
1002
|
+
for (let i = 0; i < recordsWithUid.length; i += BATCH_SIZE) {
|
|
1003
|
+
const batch = recordsWithUid.slice(i, i + BATCH_SIZE);
|
|
1004
|
+
await this.ctx.database.upsert(tableName, batch);
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
} catch (e) {
|
|
1009
|
+
if (e.code !== "ENOENT") throw e;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
return `数据恢复成功`;
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
this.ctx.logger.error("数据恢复失败:", error);
|
|
1015
|
+
return "数据恢复失败";
|
|
1016
|
+
}
|
|
1017
|
+
});
|
|
1018
|
+
analyse.subcommand(".clear", "清理统计数据", { authority: 4 }).option("table", "-t <table:string> 指定表").option("guild", "-g <guildId:string> 指定群组").option("user", "-u <user:string> 指定用户").option("days", "-d <days:number> 指定天数").option("all", "-a 清理全部数据").action(async ({ options }) => {
|
|
1019
|
+
if (!options.table && !options.guild && !options.user && !options.all && !options.days) return "请提供清理条件";
|
|
1020
|
+
try {
|
|
1021
|
+
if (options.all) {
|
|
1022
|
+
for (const tableName of ALL_TABLES) await this.ctx.database.remove(tableName, {});
|
|
1023
|
+
return "已清除所有聊天分析数据";
|
|
1024
|
+
}
|
|
1025
|
+
let tablesToClear;
|
|
1026
|
+
if (options.table) {
|
|
1027
|
+
if (!ALL_TABLES.includes(options.table)) return `无效表名: ${options.table}`;
|
|
1028
|
+
tablesToClear = [options.table];
|
|
1029
|
+
} else {
|
|
1030
|
+
tablesToClear = ALL_TABLES.filter((t) => t !== "analyse_user");
|
|
1031
|
+
}
|
|
1032
|
+
const queryParts = { query: {}, desc: "" };
|
|
1033
|
+
const descParts = [];
|
|
1034
|
+
if (options.guild || options.user) {
|
|
1035
|
+
const uidsToClear = [];
|
|
1036
|
+
const scopeDesc = [];
|
|
1037
|
+
if (options.guild) {
|
|
1038
|
+
uidsToClear.push(...(await this.ctx.database.get("analyse_user", { channelId: options.guild })).map((u) => u.uid));
|
|
1039
|
+
scopeDesc.push(`群组 ${options.guild} `);
|
|
1040
|
+
}
|
|
1041
|
+
if (options.user) {
|
|
1042
|
+
const userId = import_koishi5.Element.select(options.user, "at")[0]?.attrs.id || options.user;
|
|
1043
|
+
uidsToClear.push(...(await this.ctx.database.get("analyse_user", { userId })).map((u) => u.uid));
|
|
1044
|
+
scopeDesc.push(`用户 ${userId} `);
|
|
1045
|
+
}
|
|
1046
|
+
const uniqueUids = [...new Set(uidsToClear)];
|
|
1047
|
+
if (uniqueUids.length === 0) return "未找到该用户";
|
|
1048
|
+
queryParts.query.uid = { $in: uniqueUids };
|
|
1049
|
+
descParts.push(scopeDesc.join("、"));
|
|
1050
|
+
}
|
|
1051
|
+
if (options.days && options.days > 0) {
|
|
1052
|
+
queryParts.query.timestamp = { $lt: new Date(Date.now() - options.days * import_koishi5.Time.day) };
|
|
1053
|
+
descParts.push(`超过 ${options.days} 天`);
|
|
1054
|
+
}
|
|
1055
|
+
for (const tableName of tablesToClear) {
|
|
1056
|
+
const finalQuery = { ...queryParts.query };
|
|
1057
|
+
if (tableName === "analyse_user" && finalQuery.timestamp) delete finalQuery.timestamp;
|
|
1058
|
+
await this.ctx.database.remove(tableName, finalQuery);
|
|
1059
|
+
}
|
|
1060
|
+
const targetStr = options.table ? `表 ${options.table} ` : "所有表";
|
|
1061
|
+
const conditionStr = descParts.join(" 且 ");
|
|
1062
|
+
const finalDescription = conditionStr ? `${targetStr} 中${conditionStr}的数据` : `${targetStr}的全部统计数据`;
|
|
1063
|
+
return `已成功清理${finalDescription}`;
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
this.ctx.logger.error("数据清理失败:", error);
|
|
1066
|
+
return "数据清理失败";
|
|
1067
|
+
}
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
|
|
896
1072
|
// src/index.ts
|
|
897
1073
|
var usage = `
|
|
898
1074
|
<div style="border-radius: 10px; border: 1px solid #ddd; padding: 16px; margin-bottom: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
|
|
@@ -908,22 +1084,23 @@ var usage = `
|
|
|
908
1084
|
`;
|
|
909
1085
|
var name = "chat-analyse";
|
|
910
1086
|
var using = ["database", "puppeteer", "cron"];
|
|
911
|
-
var Config =
|
|
912
|
-
|
|
913
|
-
enableListener:
|
|
914
|
-
enableOriRecord:
|
|
1087
|
+
var Config = import_koishi6.Schema.intersect([
|
|
1088
|
+
import_koishi6.Schema.object({
|
|
1089
|
+
enableListener: import_koishi6.Schema.boolean().default(true).description("启用消息监听"),
|
|
1090
|
+
enableOriRecord: import_koishi6.Schema.boolean().default(true).description("启用原始记录")
|
|
915
1091
|
}).description("监听配置"),
|
|
916
|
-
|
|
917
|
-
enableCmdStat:
|
|
918
|
-
enableMsgStat:
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
1092
|
+
import_koishi6.Schema.object({
|
|
1093
|
+
enableCmdStat: import_koishi6.Schema.boolean().default(true).description("启用命令统计"),
|
|
1094
|
+
enableMsgStat: import_koishi6.Schema.boolean().default(true).description("启用消息统计"),
|
|
1095
|
+
enableData: import_koishi6.Schema.boolean().default(false).description("启用数据管理")
|
|
1096
|
+
}).description("功能配置"),
|
|
1097
|
+
import_koishi6.Schema.object({
|
|
1098
|
+
enableRankStat: import_koishi6.Schema.boolean().default(true).description("启用发言排行"),
|
|
1099
|
+
rankRetentionDays: import_koishi6.Schema.number().min(0).default(31).description("记录保留天数")
|
|
923
1100
|
}).description("发言排行配置"),
|
|
924
|
-
|
|
925
|
-
enableWhoAt:
|
|
926
|
-
atRetentionDays:
|
|
1101
|
+
import_koishi6.Schema.object({
|
|
1102
|
+
enableWhoAt: import_koishi6.Schema.boolean().default(true).description("启用 @ 记录"),
|
|
1103
|
+
atRetentionDays: import_koishi6.Schema.number().min(0).default(7).description("记录保留天数")
|
|
927
1104
|
}).description("@ 记录配置")
|
|
928
1105
|
]);
|
|
929
1106
|
function apply(ctx, config) {
|
|
@@ -931,6 +1108,7 @@ function apply(ctx, config) {
|
|
|
931
1108
|
const analyse = ctx.command("analyse", "聊天记录分析");
|
|
932
1109
|
new Stat(ctx, config).registerCommands(analyse);
|
|
933
1110
|
if (config.enableWhoAt) new WhoAt(ctx, config).registerCommand(analyse);
|
|
1111
|
+
if (config.enableData) new Data(ctx).registerCommands(analyse);
|
|
934
1112
|
}
|
|
935
1113
|
__name(apply, "apply");
|
|
936
1114
|
// Annotate the CommonJS export names for ESM import in node:
|