koishi-plugin-chat-analyse 0.4.3 → 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.
@@ -23,7 +23,7 @@ declare module 'koishi' {
23
23
  };
24
24
  analyse_rank: {
25
25
  uid: number;
26
- hour: Date;
26
+ type: string;
27
27
  count: number;
28
28
  timestamp: Date;
29
29
  };
@@ -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.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
- hour: "timestamp",
95
+ type: "string",
96
96
  count: "unsigned",
97
97
  timestamp: "timestamp"
98
- }, { primary: ["uid", "hour"] });
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 key = `${uid}:${type}`;
155
- const existing = this.msgStatBuffer.get(key);
156
- if (existing) {
157
- existing.count++;
158
- existing.timestamp = messageTime;
146
+ const msgKey = `${uid}:${type}`;
147
+ const existingMsg = this.msgStatBuffer.get(msgKey);
148
+ if (existingMsg) {
149
+ existingMsg.count++;
150
+ existingMsg.timestamp = messageTime;
159
151
  } else {
160
- this.msgStatBuffer.set(key, { uid, type, count: 1, timestamp: messageTime });
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++;
158
+ } else {
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 sanitizedContent = this.sanitizeContent(elements);
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
- hour: item.hour,
299
- count: import_koishi.$.add(import_koishi.$.ifNull(row.count, 0), item.count),
300
- timestamp: item.timestamp
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
  }
@@ -563,7 +563,7 @@ var Stat = class {
563
563
  this.ctx.cron("0 0 * * *", async () => {
564
564
  try {
565
565
  const cutoffDate = new Date(Date.now() - this.config.rankRetentionDays * import_koishi3.Time.day);
566
- await this.ctx.database.remove("analyse_rank", { hour: { $lt: cutoffDate } });
566
+ await this.ctx.database.remove("analyse_rank", { timestamp: { $lt: cutoffDate } });
567
567
  } catch (error) {
568
568
  this.ctx.logger.error("清理发言排行历史记录出错:", error);
569
569
  }
@@ -621,17 +621,17 @@ var Stat = class {
621
621
  });
622
622
  }
623
623
  if (this.config.enableRankStat) {
624
- analyse.subcommand(".rank", "用户发言排行").option("guild", "-g <guildId:string> 指定群组").option("all", "-a 展示全局统计").option("hours", "-h <hours:number> 指定时长", { fallback: 24 }).action(async ({ session, options }) => {
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 }) => {
625
625
  const guildId = options.all ? void 0 : options.guild || session.guildId;
626
626
  if (!guildId && !options.all) return "请提供查询范围";
627
627
  try {
628
- const stats = await this.getActiveUserStats(options.hours, guildId);
628
+ const stats = await this.getActiveUserStats(options.hours, guildId, options.type);
629
629
  if (typeof stats === "string") return stats;
630
630
  const listWithPercentage = stats.list.map((row) => [
631
631
  ...row,
632
632
  stats.total > 0 ? `${(row[1] / stats.total * 100).toFixed(2)}%` : "0.00%"
633
633
  ]);
634
- 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 });
635
635
  const renderData = { title, time: /* @__PURE__ */ new Date(), total: stats.total, list: listWithPercentage };
636
636
  const result = await this.renderer.renderList(renderData, ["用户", "总计发言", "占比"]);
637
637
  return Buffer.isBuffer(result) ? import_koishi3.Element.image(result, "image/png") : result;
@@ -711,8 +711,11 @@ var Stat = class {
711
711
  const guild = await this.ctx.database.get("analyse_user", { channelId: guildId }, ["channelName"]);
712
712
  scopeText = guild[0]?.channelName || guildId;
713
713
  }
714
- if (options.main === "排行") return `${scopeText}${options.timeRange}小时消息排行`;
715
- if (options.main === "消息" && options.subtype) return `${scopeText}"${options.subtype}"消息统计`;
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}”消息统计`;
716
719
  return `${scopeText}${options.main}统计`;
717
720
  }
718
721
  /**
@@ -790,22 +793,26 @@ var Stat = class {
790
793
  * @description 从数据库中获取并聚合指定时间范围内的活跃用户排行数据。
791
794
  * @param {number} hours - 查询过去的小时数。
792
795
  * @param {string} [guildId] - (可选) 要查询的群组 ID。若不提供,则进行全局排行。
796
+ * @param {string} [type] - (可选) 要筛选的消息类型。
793
797
  * @returns {Promise<{ list: RenderListItem[], total: number } | string>} 返回一个包含列表和总数的对象,或在无数据时返回提示字符串。
794
798
  */
795
- async getActiveUserStats(hours, guildId) {
799
+ async getActiveUserStats(hours, guildId, type) {
796
800
  const since = new Date(Date.now() - hours * 3600 * 1e3);
801
+ const baseQuery = { timestamp: { $gte: since } };
802
+ if (type) baseQuery.type = type;
797
803
  if (guildId) {
798
804
  const usersInGuild = await this.ctx.database.get("analyse_user", { channelId: guildId }, ["uid", "userName"]);
799
805
  if (usersInGuild.length === 0) return "暂无统计数据";
800
806
  const uids = usersInGuild.map((u) => u.uid);
801
807
  const userNameMap = new Map(usersInGuild.map((u) => [u.uid, u.userName]));
802
- const stats = await this.ctx.database.select("analyse_rank").where({ uid: { $in: uids }, hour: { $gte: since } }).groupBy("uid", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count") }).orderBy("count", "desc").limit(100).execute();
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();
803
810
  if (stats.length === 0) return "暂无统计数据";
804
811
  const total = stats.reduce((sum, record) => sum + record.count, 0);
805
812
  const list = stats.map((item) => [userNameMap.get(item.uid) || `UID ${item.uid}`, item.count]);
806
813
  return { list, total };
807
814
  } else {
808
- const msgStats = await this.ctx.database.select("analyse_rank").where({ hour: { $gte: since } }).project(["uid", "count"]).execute();
815
+ const msgStats = await this.ctx.database.select("analyse_rank").where(baseQuery).project(["uid", "count"]).execute();
809
816
  if (msgStats.length === 0) return "暂无统计数据";
810
817
  const allUsers = await this.ctx.database.get("analyse_user", {}, ["uid", "userId", "userName"]);
811
818
  const uidToUserMap = new Map(allUsers.map((u) => [u.uid, { userId: u.userId, userName: u.userName }]));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-chat-analyse",
3
3
  "description": "聊天记录分析",
4
- "version": "0.4.3",
4
+ "version": "0.4.4",
5
5
  "contributors": [
6
6
  "Yis_Rime <yis_rime@outlook.com>"
7
7
  ],