koishi-plugin-chat-analyse 0.4.4 → 0.4.6
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/Data.d.ts +19 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +217 -34
- package/package.json +1 -1
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/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");
|
|
@@ -198,29 +208,40 @@ var Collector = class _Collector {
|
|
|
198
208
|
if (this.pendingUserRequests.has(cacheKey)) return this.pendingUserRequests.get(cacheKey);
|
|
199
209
|
const promise = (async () => {
|
|
200
210
|
try {
|
|
201
|
-
const
|
|
202
|
-
if (
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
this.userCache.set(cacheKey, cachedUser2);
|
|
206
|
-
return cachedUser2;
|
|
211
|
+
const [dbUser] = await this.ctx.database.get("analyse_user", { channelId, userId });
|
|
212
|
+
if (dbUser && dbUser.userName && dbUser.channelName) {
|
|
213
|
+
this.userCache.set(cacheKey, dbUser);
|
|
214
|
+
return dbUser;
|
|
207
215
|
}
|
|
208
216
|
const [guild, member] = await Promise.all([
|
|
209
217
|
guildId ? bot.getGuild(guildId).catch(() => null) : Promise.resolve(null),
|
|
210
218
|
guildId ? bot.getGuildMember(guildId, userId).catch(() => null) : Promise.resolve(null)
|
|
211
219
|
]);
|
|
212
220
|
const user = !member ? await bot.getUser(userId).catch(() => null) : null;
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
221
|
+
const fetchedUserName = member?.nick || member?.name || user?.name || "";
|
|
222
|
+
const fetchedChannelName = guild?.name || "";
|
|
223
|
+
if (dbUser) {
|
|
224
|
+
const needsUpdate = !dbUser.userName && fetchedUserName || !dbUser.channelName && fetchedChannelName;
|
|
225
|
+
if (needsUpdate) {
|
|
226
|
+
dbUser.userName = dbUser.userName || fetchedUserName;
|
|
227
|
+
dbUser.channelName = dbUser.channelName || fetchedChannelName;
|
|
228
|
+
await this.ctx.database.set("analyse_user", { uid: dbUser.uid }, {
|
|
229
|
+
userName: dbUser.userName,
|
|
230
|
+
channelName: dbUser.channelName
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
if (dbUser.userName && dbUser.channelName) this.userCache.set(cacheKey, dbUser);
|
|
234
|
+
return dbUser;
|
|
235
|
+
} else {
|
|
236
|
+
const createdUser = await this.ctx.database.create("analyse_user", {
|
|
237
|
+
channelId,
|
|
238
|
+
userId,
|
|
239
|
+
userName: fetchedUserName,
|
|
240
|
+
channelName: fetchedChannelName
|
|
241
|
+
});
|
|
242
|
+
if (createdUser.userName && createdUser.channelName) this.userCache.set(cacheKey, createdUser);
|
|
243
|
+
return createdUser;
|
|
244
|
+
}
|
|
224
245
|
} catch (error) {
|
|
225
246
|
this.ctx.logger.error(`创建或获取用户(${cacheKey})失败:`, error);
|
|
226
247
|
return null;
|
|
@@ -884,8 +905,9 @@ var WhoAt = class {
|
|
|
884
905
|
const userInfoMap = new Map(users.map((u) => [u.uid, { name: u.userName, id: u.userId }]));
|
|
885
906
|
const messageElements = records.map((record) => {
|
|
886
907
|
const senderInfo = userInfoMap.get(record.uid);
|
|
887
|
-
const userId = senderInfo
|
|
888
|
-
const
|
|
908
|
+
const userId = senderInfo.id;
|
|
909
|
+
const userName = senderInfo.name || userId;
|
|
910
|
+
const authorElement = (0, import_koishi4.h)("author", { userId, name: userName });
|
|
889
911
|
const contentElement = import_koishi4.h.text(record.content);
|
|
890
912
|
return (0, import_koishi4.h)("message", {}, [authorElement, contentElement]);
|
|
891
913
|
});
|
|
@@ -900,6 +922,165 @@ var WhoAt = class {
|
|
|
900
922
|
}
|
|
901
923
|
};
|
|
902
924
|
|
|
925
|
+
// src/Data.ts
|
|
926
|
+
var import_koishi5 = require("koishi");
|
|
927
|
+
var fs = __toESM(require("fs/promises"));
|
|
928
|
+
var path = __toESM(require("path"));
|
|
929
|
+
var ALL_TABLES = [
|
|
930
|
+
"analyse_user",
|
|
931
|
+
"analyse_cmd",
|
|
932
|
+
"analyse_msg",
|
|
933
|
+
"analyse_rank",
|
|
934
|
+
"analyse_at",
|
|
935
|
+
"analyse_cache"
|
|
936
|
+
];
|
|
937
|
+
var Data = class {
|
|
938
|
+
constructor(ctx) {
|
|
939
|
+
this.ctx = ctx;
|
|
940
|
+
this.dataDir = path.join(this.ctx.baseDir, "data", "chat-analyse");
|
|
941
|
+
}
|
|
942
|
+
static {
|
|
943
|
+
__name(this, "Data");
|
|
944
|
+
}
|
|
945
|
+
dataDir;
|
|
946
|
+
/**
|
|
947
|
+
* @public
|
|
948
|
+
* @method registerCommands
|
|
949
|
+
* @description 在 'analyse.admin' 命令下注册所有数据管理相关的子命令。
|
|
950
|
+
* @param {Command} analyse - '.admin' 命令实例。
|
|
951
|
+
*/
|
|
952
|
+
registerCommands(analyse) {
|
|
953
|
+
analyse.subcommand(".backup", "备份统计数据", { authority: 4 }).action(async () => {
|
|
954
|
+
try {
|
|
955
|
+
await fs.mkdir(this.dataDir, { recursive: true });
|
|
956
|
+
const allUsers = await this.ctx.database.get("analyse_user", {});
|
|
957
|
+
const uidToUserInfoMap = new Map(allUsers.map((u) => [u.uid, u]));
|
|
958
|
+
for (const tableName of ALL_TABLES) {
|
|
959
|
+
const filepath = path.join(this.dataDir, `${tableName}.json`);
|
|
960
|
+
let dataToExport;
|
|
961
|
+
if (tableName === "analyse_user") {
|
|
962
|
+
dataToExport = allUsers.map(({ uid, ...rest }) => rest);
|
|
963
|
+
} else {
|
|
964
|
+
const records = await this.ctx.database.get(tableName, {});
|
|
965
|
+
dataToExport = records.map((record) => {
|
|
966
|
+
const userInfo = uidToUserInfoMap.get(record.uid);
|
|
967
|
+
if (!userInfo) return null;
|
|
968
|
+
const { uid, ...restOfRecord } = record;
|
|
969
|
+
return {
|
|
970
|
+
userId: userInfo.userId,
|
|
971
|
+
channelId: userInfo.channelId,
|
|
972
|
+
...restOfRecord
|
|
973
|
+
};
|
|
974
|
+
}).filter(Boolean);
|
|
975
|
+
}
|
|
976
|
+
await fs.writeFile(filepath, JSON.stringify(dataToExport, null, 2));
|
|
977
|
+
}
|
|
978
|
+
return `数据备份成功`;
|
|
979
|
+
} catch (error) {
|
|
980
|
+
this.ctx.logger.error("数据备份失败:", error);
|
|
981
|
+
return "数据备份失败";
|
|
982
|
+
}
|
|
983
|
+
});
|
|
984
|
+
analyse.subcommand(".restore", "恢复统计数据", { authority: 4 }).action(async () => {
|
|
985
|
+
const BATCH_SIZE = 100;
|
|
986
|
+
try {
|
|
987
|
+
const userTablePath = path.join(this.dataDir, "analyse_user.json");
|
|
988
|
+
try {
|
|
989
|
+
const usersToImport = JSON.parse(await fs.readFile(userTablePath, "utf-8"));
|
|
990
|
+
if (Array.isArray(usersToImport) && usersToImport.length > 0) {
|
|
991
|
+
for (let i = 0; i < usersToImport.length; i += BATCH_SIZE) {
|
|
992
|
+
const batch = usersToImport.slice(i, i + BATCH_SIZE);
|
|
993
|
+
await this.ctx.database.upsert("analyse_user", batch);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
} catch (e) {
|
|
997
|
+
if (e.code !== "ENOENT") throw e;
|
|
998
|
+
this.ctx.logger.warn("无用户数据可恢复");
|
|
999
|
+
}
|
|
1000
|
+
const allUsers = await this.ctx.database.get("analyse_user", {});
|
|
1001
|
+
const userToUidMap = new Map(allUsers.map((u) => [`${u.channelId}:${u.userId}`, u.uid]));
|
|
1002
|
+
for (const tableName of ALL_TABLES.filter((t) => t !== "analyse_user")) {
|
|
1003
|
+
const filepath = path.join(this.dataDir, `${tableName}.json`);
|
|
1004
|
+
try {
|
|
1005
|
+
const recordsToImport = JSON.parse(await fs.readFile(filepath, "utf-8"));
|
|
1006
|
+
if (Array.isArray(recordsToImport) && recordsToImport.length > 0) {
|
|
1007
|
+
const recordsWithUid = recordsToImport.map((r) => {
|
|
1008
|
+
const uid = userToUidMap.get(`${r.channelId}:${r.userId}`);
|
|
1009
|
+
if (!uid) return null;
|
|
1010
|
+
const { userId, channelId, ...rest } = r;
|
|
1011
|
+
return { uid, ...rest };
|
|
1012
|
+
}).filter(Boolean);
|
|
1013
|
+
if (recordsWithUid.length > 0) {
|
|
1014
|
+
for (let i = 0; i < recordsWithUid.length; i += BATCH_SIZE) {
|
|
1015
|
+
const batch = recordsWithUid.slice(i, i + BATCH_SIZE);
|
|
1016
|
+
await this.ctx.database.upsert(tableName, batch);
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
} catch (e) {
|
|
1021
|
+
if (e.code !== "ENOENT") throw e;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
return `数据恢复成功`;
|
|
1025
|
+
} catch (error) {
|
|
1026
|
+
this.ctx.logger.error("数据恢复失败:", error);
|
|
1027
|
+
return "数据恢复失败";
|
|
1028
|
+
}
|
|
1029
|
+
});
|
|
1030
|
+
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 }) => {
|
|
1031
|
+
if (!options.table && !options.guild && !options.user && !options.all && !options.days) return "请提供清理条件";
|
|
1032
|
+
try {
|
|
1033
|
+
if (options.all) {
|
|
1034
|
+
for (const tableName of ALL_TABLES) await this.ctx.database.remove(tableName, {});
|
|
1035
|
+
return "已清除所有聊天分析数据";
|
|
1036
|
+
}
|
|
1037
|
+
let tablesToClear;
|
|
1038
|
+
if (options.table) {
|
|
1039
|
+
if (!ALL_TABLES.includes(options.table)) return `无效表名: ${options.table}`;
|
|
1040
|
+
tablesToClear = [options.table];
|
|
1041
|
+
} else {
|
|
1042
|
+
tablesToClear = ALL_TABLES.filter((t) => t !== "analyse_user");
|
|
1043
|
+
}
|
|
1044
|
+
const queryParts = { query: {}, desc: "" };
|
|
1045
|
+
const descParts = [];
|
|
1046
|
+
if (options.guild || options.user) {
|
|
1047
|
+
const uidsToClear = [];
|
|
1048
|
+
const scopeDesc = [];
|
|
1049
|
+
if (options.guild) {
|
|
1050
|
+
uidsToClear.push(...(await this.ctx.database.get("analyse_user", { channelId: options.guild })).map((u) => u.uid));
|
|
1051
|
+
scopeDesc.push(`群组 ${options.guild} `);
|
|
1052
|
+
}
|
|
1053
|
+
if (options.user) {
|
|
1054
|
+
const userId = import_koishi5.Element.select(options.user, "at")[0]?.attrs.id || options.user;
|
|
1055
|
+
uidsToClear.push(...(await this.ctx.database.get("analyse_user", { userId })).map((u) => u.uid));
|
|
1056
|
+
scopeDesc.push(`用户 ${userId} `);
|
|
1057
|
+
}
|
|
1058
|
+
const uniqueUids = [...new Set(uidsToClear)];
|
|
1059
|
+
if (uniqueUids.length === 0) return "未找到该用户";
|
|
1060
|
+
queryParts.query.uid = { $in: uniqueUids };
|
|
1061
|
+
descParts.push(scopeDesc.join("、"));
|
|
1062
|
+
}
|
|
1063
|
+
if (options.days && options.days > 0) {
|
|
1064
|
+
queryParts.query.timestamp = { $lt: new Date(Date.now() - options.days * import_koishi5.Time.day) };
|
|
1065
|
+
descParts.push(`超过 ${options.days} 天`);
|
|
1066
|
+
}
|
|
1067
|
+
for (const tableName of tablesToClear) {
|
|
1068
|
+
const finalQuery = { ...queryParts.query };
|
|
1069
|
+
if (tableName === "analyse_user" && finalQuery.timestamp) delete finalQuery.timestamp;
|
|
1070
|
+
await this.ctx.database.remove(tableName, finalQuery);
|
|
1071
|
+
}
|
|
1072
|
+
const targetStr = options.table ? `表 ${options.table} ` : "所有表";
|
|
1073
|
+
const conditionStr = descParts.join(" 且 ");
|
|
1074
|
+
const finalDescription = conditionStr ? `${targetStr} 中${conditionStr}的数据` : `${targetStr}的全部统计数据`;
|
|
1075
|
+
return `已成功清理${finalDescription}`;
|
|
1076
|
+
} catch (error) {
|
|
1077
|
+
this.ctx.logger.error("数据清理失败:", error);
|
|
1078
|
+
return "数据清理失败";
|
|
1079
|
+
}
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
};
|
|
1083
|
+
|
|
903
1084
|
// src/index.ts
|
|
904
1085
|
var usage = `
|
|
905
1086
|
<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);">
|
|
@@ -915,22 +1096,23 @@ var usage = `
|
|
|
915
1096
|
`;
|
|
916
1097
|
var name = "chat-analyse";
|
|
917
1098
|
var using = ["database", "puppeteer", "cron"];
|
|
918
|
-
var Config =
|
|
919
|
-
|
|
920
|
-
enableListener:
|
|
921
|
-
enableOriRecord:
|
|
1099
|
+
var Config = import_koishi6.Schema.intersect([
|
|
1100
|
+
import_koishi6.Schema.object({
|
|
1101
|
+
enableListener: import_koishi6.Schema.boolean().default(true).description("启用消息监听"),
|
|
1102
|
+
enableOriRecord: import_koishi6.Schema.boolean().default(true).description("启用原始记录")
|
|
922
1103
|
}).description("监听配置"),
|
|
923
|
-
|
|
924
|
-
enableCmdStat:
|
|
925
|
-
enableMsgStat:
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
1104
|
+
import_koishi6.Schema.object({
|
|
1105
|
+
enableCmdStat: import_koishi6.Schema.boolean().default(true).description("启用命令统计"),
|
|
1106
|
+
enableMsgStat: import_koishi6.Schema.boolean().default(true).description("启用消息统计"),
|
|
1107
|
+
enableData: import_koishi6.Schema.boolean().default(false).description("启用数据管理")
|
|
1108
|
+
}).description("功能配置"),
|
|
1109
|
+
import_koishi6.Schema.object({
|
|
1110
|
+
enableRankStat: import_koishi6.Schema.boolean().default(true).description("启用发言排行"),
|
|
1111
|
+
rankRetentionDays: import_koishi6.Schema.number().min(0).default(31).description("记录保留天数")
|
|
930
1112
|
}).description("发言排行配置"),
|
|
931
|
-
|
|
932
|
-
enableWhoAt:
|
|
933
|
-
atRetentionDays:
|
|
1113
|
+
import_koishi6.Schema.object({
|
|
1114
|
+
enableWhoAt: import_koishi6.Schema.boolean().default(true).description("启用 @ 记录"),
|
|
1115
|
+
atRetentionDays: import_koishi6.Schema.number().min(0).default(7).description("记录保留天数")
|
|
934
1116
|
}).description("@ 记录配置")
|
|
935
1117
|
]);
|
|
936
1118
|
function apply(ctx, config) {
|
|
@@ -938,6 +1120,7 @@ function apply(ctx, config) {
|
|
|
938
1120
|
const analyse = ctx.command("analyse", "聊天记录分析");
|
|
939
1121
|
new Stat(ctx, config).registerCommands(analyse);
|
|
940
1122
|
if (config.enableWhoAt) new WhoAt(ctx, config).registerCommand(analyse);
|
|
1123
|
+
if (config.enableData) new Data(ctx).registerCommands(analyse);
|
|
941
1124
|
}
|
|
942
1125
|
__name(apply, "apply");
|
|
943
1126
|
// Annotate the CommonJS export names for ESM import in node:
|