koishi-plugin-chat-analyse 1.3.0 → 1.3.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.
package/lib/Stat.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { Context, Command } from 'koishi';
2
+ import { Renderer } from './Renderer';
3
+ import { Config } from './index';
4
+ /**
5
+ * @class Stat
6
+ * @description 提供统一的统计查询服务。负责注册查询命令,从数据库获取数据,并调用渲染器生成图表。
7
+ */
8
+ export declare class Stat {
9
+ private ctx;
10
+ private config;
11
+ renderer: Renderer;
12
+ /**
13
+ * @param ctx - Koishi 的插件上下文。
14
+ * @param config - 插件的配置对象。
15
+ */
16
+ constructor(ctx: Context, config: Config);
17
+ /**
18
+ * @private @method parseScope
19
+ * @description 根据选项解析查询范围,返回 uids 和范围描述
20
+ */
21
+ private parseScope;
22
+ /**
23
+ * @public @method registerCommands
24
+ * @description 根据配置,动态地将子命令注册到主命令下。
25
+ * @param cmd - 主命令实例。
26
+ */
27
+ registerCommands(cmd: Command): void;
28
+ }
package/lib/index.js CHANGED
@@ -1808,141 +1808,168 @@ var Stat = class {
1808
1808
  __name(this, "Stat");
1809
1809
  }
1810
1810
  renderer;
1811
+ /**
1812
+ * @private @method parseScope
1813
+ * @description 根据选项解析查询范围,返回 uids 和范围描述
1814
+ */
1815
+ async parseScope(session, options) {
1816
+ const scopeDesc = { guildId: void 0, userId: void 0 };
1817
+ const query = {};
1818
+ if (options.all) return { uids: void 0, scopeDesc };
1819
+ if (options.user) scopeDesc.userId = import_koishi3.h.select(options.user, "at")[0]?.attrs.id ?? options.user.trim();
1820
+ if (options.guild) scopeDesc.guildId = options.guild;
1821
+ if (!scopeDesc.guildId && !scopeDesc.userId) scopeDesc.guildId = session.guildId;
1822
+ if (!scopeDesc.guildId && !scopeDesc.userId) return { error: "请指定查询范围", scopeDesc };
1823
+ if (scopeDesc.guildId) query.channelId = scopeDesc.guildId;
1824
+ if (scopeDesc.userId) query.userId = scopeDesc.userId;
1825
+ const users = await this.ctx.database.get("analyse_user", query, ["uid"]);
1826
+ if (users.length === 0) return { error: "暂无统计数据", scopeDesc };
1827
+ return { uids: users.map((u) => u.uid), scopeDesc };
1828
+ }
1811
1829
  /**
1812
1830
  * @public @method registerCommands
1813
1831
  * @description 根据配置,动态地将子命令注册到主命令下。
1814
1832
  * @param cmd - 主命令实例。
1815
1833
  */
1816
1834
  registerCommands(cmd) {
1817
- const createHandler = /* @__PURE__ */ __name((handler) => {
1818
- return async ({ session, options }) => {
1819
- const scope = await parseQueryScope(this.ctx, session, options);
1820
- if (scope.error) return scope.error;
1821
- try {
1822
- const result = await handler(scope, options);
1823
- if (typeof result === "string") return result;
1824
- for await (const buffer of result) await session.send(import_koishi3.h.image(buffer, "image/png"));
1825
- } catch (error) {
1826
- this.ctx.logger.error("图片渲染失败:", error);
1827
- return "图片渲染失败";
1828
- }
1829
- };
1830
- }, "createHandler");
1835
+ const handleAction = /* @__PURE__ */ __name(async (session, promise) => {
1836
+ try {
1837
+ const result = await promise;
1838
+ if (typeof result === "string") return result;
1839
+ for await (const buffer of result) await session.send(import_koishi3.h.image(buffer, "image/png"));
1840
+ } catch (error) {
1841
+ this.ctx.logger.error("图片渲染失败:", error);
1842
+ return "图片渲染失败";
1843
+ }
1844
+ }, "handleAction");
1831
1845
  if (this.config.enableCmdStat) {
1832
- cmd.subcommand("cmdstat", "命令统计").usage("查询命令统计,可指定查询范围,默认当前群组。").option("user", "-u <user:string> 指定用户").option("guild", "-g <guildId:string> 指定群组").option("separate", "-s 分离展示").option("all", "-a 全局").action(createHandler(async (scope, options) => {
1833
- const stats = await this.ctx.database.select("analyse_cmd").where({ uid: { $in: scope.uids } }).groupBy("command", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count"), lastUsed: /* @__PURE__ */ __name((row) => import_koishi3.$.max(row.timestamp), "lastUsed") }).orderBy("count", "desc").execute();
1846
+ cmd.subcommand("cmdstat", "命令统计").usage("查询命令统计,可指定查询范围,默认当前群组。").option("user", "-u <user:string> 指定用户").option("guild", "-g <guildId:string> 指定群组").option("separate", "-s 分离展示").option("all", "-a 全局统计").action(({ session, options }) => handleAction(session, (async () => {
1847
+ const scope = await this.parseScope(session, options);
1848
+ if (scope.error) return scope.error;
1849
+ const query = scope.uids ? { uid: { $in: scope.uids } } : {};
1850
+ const stats = await this.ctx.database.select("analyse_cmd").where(query).groupBy("command", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count"), lastUsed: /* @__PURE__ */ __name((row) => import_koishi3.$.max(row.timestamp), "lastUsed") }).orderBy("count", "desc").execute();
1834
1851
  if (stats.length === 0) return "暂无统计数据";
1835
1852
  let processedStats;
1836
1853
  if (options.separate) {
1837
1854
  processedStats = stats;
1838
1855
  } else {
1839
- const mergedStatsMap = /* @__PURE__ */ new Map();
1856
+ const merged = /* @__PURE__ */ new Map();
1840
1857
  for (const stat of stats) {
1841
- const mainCommand = stat.command.split(".")[0];
1842
- const existing = mergedStatsMap.get(mainCommand) || { count: 0, lastUsed: /* @__PURE__ */ new Date(0) };
1858
+ const mainCmd = stat.command.split(".")[0];
1859
+ const existing = merged.get(mainCmd) || { count: 0, lastUsed: /* @__PURE__ */ new Date(0) };
1843
1860
  existing.count += stat.count;
1844
1861
  if (stat.lastUsed > existing.lastUsed) existing.lastUsed = stat.lastUsed;
1845
- mergedStatsMap.set(mainCommand, existing);
1862
+ merged.set(mainCmd, existing);
1846
1863
  }
1847
- processedStats = Array.from(mergedStatsMap.entries()).map(([command, data]) => ({
1848
- command,
1849
- count: data.count,
1850
- lastUsed: data.lastUsed
1851
- })).sort((a, b) => b.count - a.count);
1864
+ processedStats = Array.from(merged.entries()).map(([command, data]) => ({ ...data, command })).sort((a, b) => b.count - a.count);
1852
1865
  }
1853
- const total = processedStats.reduce((sum, record) => sum + record.count, 0);
1866
+ const total = processedStats.reduce((sum, r) => sum + r.count, 0);
1854
1867
  const list = processedStats.map((item) => [item.command, item.count, item.lastUsed]);
1855
1868
  const title = await generateTitle(this.ctx, scope.scopeDesc, { main: "命令" });
1856
1869
  return this.renderer.renderList({ title, time: /* @__PURE__ */ new Date(), total, list }, ["命令", "次数", "最后使用"]);
1857
- }));
1870
+ })()));
1858
1871
  }
1859
1872
  if (this.config.enableMsgStat) {
1860
- cmd.subcommand("msgstat", "发言统计").usage("查询发言统计,可指定查询范围,默认当前群组。").option("user", "-u <user:string> 指定用户").option("guild", "-g <guildId:string> 指定群组").option("type", "-t <type:string> 指定类型").option("all", "-a 全局").action(createHandler(async (scope, options) => {
1861
- const { type } = options;
1862
- const query = { uid: { $in: scope.uids } };
1863
- if (type) query.type = type;
1864
- const users = await this.ctx.database.get("analyse_user", { uid: { $in: scope.uids } }, ["uid", "userName"]);
1865
- const userNameMap = new Map(users.map((u) => [u.uid, u.userName]));
1873
+ cmd.subcommand("msgstat", "发言统计").usage("查询发言统计,可指定查询范围,默认当前群组。").option("user", "-u <user:string> 指定用户").option("guild", "-g <guildId:string> 指定群组").option("type", "-t <type:string> 指定类型").option("all", "-a 全局统计").action(({ session, options }) => handleAction(session, (async () => {
1874
+ const scope = await this.parseScope(session, options);
1875
+ if (scope.error) return scope.error;
1876
+ const query = scope.uids ? { uid: { $in: scope.uids } } : {};
1877
+ if (options.type) query.type = options.type;
1878
+ const title = await generateTitle(this.ctx, scope.scopeDesc, { main: "发言", subtype: options.type });
1879
+ if (options.user && options.guild) {
1880
+ const stats2 = await this.ctx.database.select("analyse_msg").where(query).groupBy("type", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count"), lastUsed: /* @__PURE__ */ __name((row) => import_koishi3.$.max(row.timestamp), "lastUsed") }).orderBy("count", "desc").execute();
1881
+ if (stats2.length === 0) return "暂无统计数据";
1882
+ const total2 = stats2.reduce((sum, r) => sum + r.count, 0);
1883
+ const list2 = stats2.map((item) => [item.type, item.count, item.lastUsed]);
1884
+ return this.renderer.renderList({ title, time: /* @__PURE__ */ new Date(), total: total2, list: list2 }, ["类型", "条数", "最后发言"]);
1885
+ }
1886
+ if (options.user) {
1887
+ const userRecords = await this.ctx.database.get("analyse_user", { uid: { $in: scope.uids } });
1888
+ const uidToChannelMap = new Map(userRecords.map((u) => [u.uid, u.channelName || u.channelId]));
1889
+ const stats2 = await this.ctx.database.select("analyse_msg").where(query).groupBy("uid", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count"), lastUsed: /* @__PURE__ */ __name((row) => import_koishi3.$.max(row.timestamp), "lastUsed") }).orderBy("count", "desc").execute();
1890
+ if (stats2.length === 0) return "暂无统计数据";
1891
+ const total2 = stats2.reduce((sum, r) => sum + r.count, 0);
1892
+ const list2 = stats2.map((item) => [uidToChannelMap.get(item.uid) || `未知群组`, item.count, item.lastUsed]);
1893
+ return this.renderer.renderList({ title, time: /* @__PURE__ */ new Date(), total: total2, list: list2 }, ["群组", "条数", "最后发言"]);
1894
+ }
1866
1895
  const stats = await this.ctx.database.select("analyse_msg").where(query).groupBy("uid", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count"), lastUsed: /* @__PURE__ */ __name((row) => import_koishi3.$.max(row.timestamp), "lastUsed") }).orderBy("count", "desc").execute();
1867
1896
  if (stats.length === 0) return "暂无统计数据";
1897
+ const allUids = stats.map((s) => s.uid);
1898
+ const users = await this.ctx.database.get("analyse_user", { uid: { $in: allUids } }, ["uid", "userName"]);
1899
+ const userNameMap = new Map(users.map((u) => [u.uid, u.userName]));
1868
1900
  const total = stats.reduce((sum, r) => sum + r.count, 0);
1869
1901
  const list = stats.map((item) => [userNameMap.get(item.uid) || `UID ${item.uid}`, item.count, item.lastUsed]);
1870
- const title = await generateTitle(this.ctx, scope.scopeDesc, { main: "发言", subtype: type });
1871
- const headers = type ? ["用户", "条数", "最后发言"] : ["用户", "总计发言", "最后发言"];
1872
- return this.renderer.renderList({ title, time: /* @__PURE__ */ new Date(), total, list }, headers);
1873
- }));
1902
+ return this.renderer.renderList({ title, time: /* @__PURE__ */ new Date(), total, list }, ["用户", "总计发言", "最后发言"]);
1903
+ })()));
1874
1904
  }
1875
1905
  if (this.config.enableRankStat) {
1876
- cmd.subcommand("rankstat", "发言排行").usage("查询发言排行,可指定查询范围,默认当前群组。").option("guild", "-g <guildId:string> 指定群组").option("type", "-t <type:string> 指定类型").option("hours", "-o <hours:number> 指定时长", { fallback: 24 }).option("all", "-a 全局").action(createHandler(async (scope, options) => {
1877
- const { hours, type } = options;
1878
- const since = new Date(Date.now() - hours * import_koishi3.Time.hour);
1879
- const query = { uid: { $in: scope.uids }, timestamp: { $gte: since } };
1880
- if (type) query.type = type;
1881
- const rankStats = await this.ctx.database.select("analyse_rank").where(query).groupBy("uid", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count") }).orderBy("count", "desc").execute();
1882
- if (rankStats.length === 0) return "暂无统计数据";
1883
- const users = await this.ctx.database.get("analyse_user", { uid: { $in: scope.uids } }, ["uid", "userName"]);
1906
+ cmd.subcommand("rankstat", "发言排行").usage("查询发言排行,可指定查询范围,默认当前群组。").option("user", "-u <user:string> 指定用户").option("guild", "-g <guildId:string> 指定群组").option("type", "-t <type:string> 指定类型").option("duration", "-n <hours:number> 指定时长", { fallback: 24 }).option("offset", "-o <hours:number> 指定偏移").option("all", "-a 全局统计").action(({ session, options }) => handleAction(session, (async () => {
1907
+ const scope = await this.parseScope(session, options);
1908
+ if (scope.error) return scope.error;
1909
+ const until = new Date(Date.now() - options.offset * import_koishi3.Time.hour);
1910
+ const since = new Date(until.getTime() - options.duration * import_koishi3.Time.hour);
1911
+ const query = { timestamp: { $gte: since, $lt: until } };
1912
+ if (scope.uids) query.uid = { $in: scope.uids };
1913
+ if (options.type) query.type = options.type;
1914
+ const title = await generateTitle(this.ctx, scope.scopeDesc, { main: "发言排行", timeRange: options.duration, subtype: options.type });
1915
+ if (options.user && options.guild) {
1916
+ const stats2 = await this.ctx.database.select("analyse_rank").where(query).groupBy("type", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count") }).orderBy("count", "desc").execute();
1917
+ if (stats2.length === 0) return "暂无统计数据";
1918
+ const total2 = stats2.reduce((sum, r) => sum + r.count, 0);
1919
+ const list2 = stats2.map((r) => [r.type, r.count, total2 > 0 ? `${(r.count / total2 * 100).toFixed(2)}%` : "0.00%"]);
1920
+ return this.renderer.renderList({ title, time: /* @__PURE__ */ new Date(), total: total2, list: list2 }, ["类型", "条数", "占比"]);
1921
+ }
1922
+ if (options.user) {
1923
+ const userRecords = await this.ctx.database.get("analyse_user", { uid: { $in: scope.uids } });
1924
+ const uidToChannelMap = new Map(userRecords.map((u) => [u.uid, u.channelName || u.channelId]));
1925
+ const stats2 = await this.ctx.database.select("analyse_rank").where(query).groupBy("uid", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count") }).orderBy("count", "desc").execute();
1926
+ if (stats2.length === 0) return "暂无统计数据";
1927
+ const total2 = stats2.reduce((sum, r) => sum + r.count, 0);
1928
+ const list2 = stats2.map((r) => [uidToChannelMap.get(r.uid) || "未知群组", r.count, total2 > 0 ? `${(r.count / total2 * 100).toFixed(2)}%` : "0.00%"]);
1929
+ return this.renderer.renderList({ title, time: /* @__PURE__ */ new Date(), total: total2, list: list2 }, ["群组", "条数", "占比"]);
1930
+ }
1931
+ 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").execute();
1932
+ if (stats.length === 0) return "暂无统计数据";
1933
+ const allUids = stats.map((s) => s.uid);
1934
+ const users = await this.ctx.database.get("analyse_user", { uid: { $in: allUids } }, ["uid", "userName"]);
1884
1935
  const userNameMap = new Map(users.map((u) => [u.uid, u.userName]));
1885
- const total = rankStats.reduce((sum, record) => sum + record.count, 0);
1886
- const list = rankStats.map((item) => [userNameMap.get(item.uid) || `UID ${item.uid}`, item.count]);
1887
- const listWithPercentage = list.map((row) => [...row, total > 0 ? `${(row[1] / total * 100).toFixed(2)}%` : "0.00%"]);
1888
- const title = await generateTitle(this.ctx, scope.scopeDesc, { main: "发言排行", timeRange: hours, subtype: type });
1889
- return this.renderer.renderList({ title, time: /* @__PURE__ */ new Date(), total, list: listWithPercentage }, ["用户", "总计发言", "占比"]);
1890
- }));
1936
+ const total = stats.reduce((sum, r) => sum + r.count, 0);
1937
+ const list = stats.map((r) => [userNameMap.get(r.uid) || `UID ${r.uid}`, r.count, total > 0 ? `${(r.count / total * 100).toFixed(2)}%` : "0.00%"]);
1938
+ return this.renderer.renderList({ title, time: /* @__PURE__ */ new Date(), total, list }, ["用户", "总计发言", "占比"]);
1939
+ })()));
1891
1940
  }
1892
1941
  if (this.config.enableActivity) {
1893
- cmd.subcommand("activity", "活跃统计").usage("查询活跃统计,可指定查询范围,默认当前群组。").option("user", "-u <user:string> 指定用户").option("guild", "-g <guildId:string> 指定群组").option("hours", "-t <hours:number> 指定偏移时长").option("all", "-a 全局").option("days", "-d 切换至天数").action(createHandler(async (scope, options) => {
1894
- const { days, hours } = options;
1895
- if (days) {
1896
- const timeRangeInDays = 24;
1897
- const since = new Date(Date.now() - timeRangeInDays * import_koishi3.Time.day);
1898
- const stats = await this.ctx.database.select("analyse_rank").where({ uid: { $in: scope.uids }, timestamp: { $gte: since } }).project(["timestamp", "count"]).execute();
1899
- if (stats.length === 0) return "暂无统计数据";
1900
- const startOfToday = /* @__PURE__ */ new Date();
1901
- startOfToday.setHours(0, 0, 0, 0);
1902
- const dailyCounts = Array(timeRangeInDays).fill(0);
1903
- const dayLabels = Array(timeRangeInDays).fill("");
1904
- for (let i = 0; i < timeRangeInDays; i++) {
1905
- const d = new Date(startOfToday.getTime() - i * import_koishi3.Time.day);
1906
- dayLabels[timeRangeInDays - 1 - i] = String(d.getDate());
1907
- }
1908
- stats.forEach((stat) => {
1909
- const statDayStart = new Date(stat.timestamp);
1910
- statDayStart.setHours(0, 0, 0, 0);
1911
- const daysAgo = Math.round((startOfToday.getTime() - statDayStart.getTime()) / import_koishi3.Time.day);
1912
- if (daysAgo >= 0 && daysAgo < timeRangeInDays) {
1913
- const index = timeRangeInDays - 1 - daysAgo;
1914
- dailyCounts[index] += stat.count;
1915
- }
1916
- });
1917
- const totalMessages = dailyCounts.reduce((a, b) => a + b, 0);
1918
- const title = await generateTitle(this.ctx, scope.scopeDesc, { main: "活跃", timeRange: timeRangeInDays, timeUnit: "天" });
1919
- return this.renderer.renderCircadianChart({ title, time: /* @__PURE__ */ new Date(), total: totalMessages, data: dailyCounts, labels: dayLabels });
1920
- } else {
1921
- const timeWindowHours = 24;
1922
- const offsetHours = typeof hours === "number" ? hours : 0;
1923
- const now = /* @__PURE__ */ new Date();
1924
- const until = new Date(now.getTime() - offsetHours * import_koishi3.Time.hour);
1925
- const since = new Date(until.getTime() - timeWindowHours * import_koishi3.Time.hour);
1926
- const hourlyStats = await this.ctx.database.select("analyse_rank").where({ uid: { $in: scope.uids }, timestamp: { $gte: since, $lt: until } }).groupBy("timestamp", { count: /* @__PURE__ */ __name((row) => import_koishi3.$.sum(row.count), "count") }).execute();
1927
- if (hourlyStats.length === 0) return "暂无统计数据";
1928
- const processedCounts = Array(timeWindowHours).fill(0);
1929
- const hourLabels = Array(timeWindowHours).fill("");
1930
- for (let i = 0; i < timeWindowHours; i++) {
1931
- const d = new Date(until.getTime() - (i + 1) * import_koishi3.Time.hour);
1932
- hourLabels[timeWindowHours - 1 - i] = String(d.getHours());
1933
- }
1934
- hourlyStats.forEach((stat) => {
1935
- const hoursBeforeUntil = Math.floor((until.getTime() - stat.timestamp.getTime()) / import_koishi3.Time.hour);
1936
- if (hoursBeforeUntil >= 0 && hoursBeforeUntil < timeWindowHours) {
1937
- const index = timeWindowHours - 1 - hoursBeforeUntil;
1938
- processedCounts[index] += stat.count;
1939
- }
1940
- });
1941
- const totalMessages = processedCounts.reduce((a, b) => a + b, 0);
1942
- const title = await generateTitle(this.ctx, scope.scopeDesc, { main: "活跃", timeRange: timeWindowHours, timeUnit: "小时" });
1943
- return this.renderer.renderCircadianChart({ title, time: /* @__PURE__ */ new Date(), total: totalMessages, data: processedCounts, labels: hourLabels });
1942
+ cmd.subcommand("activity", "活跃统计").usage("查询活跃统计,可指定查询范围,默认当前群组。").option("user", "-u <user:string> 指定用户").option("guild", "-g <guildId:string> 指定群组").option("duration", "-n <units:number> 指定时长", { fallback: 24 }).option("offset", "-o <units:number> 指定偏移").option("days", "-d 切换至天").option("all", "-a 全局统计").action(({ session, options }) => handleAction(session, (async () => {
1943
+ const scope = await this.parseScope(session, options);
1944
+ if (scope.error) return scope.error;
1945
+ const timeUnit = options.days ? import_koishi3.Time.day : import_koishi3.Time.hour;
1946
+ const timeUnitName = options.days ? "天" : "小时";
1947
+ const points = options.days ? 24 : 24;
1948
+ const until = new Date(Date.now() - options.offset * timeUnit);
1949
+ const since = new Date(until.getTime() - options.duration * timeUnit);
1950
+ const query = { timestamp: { $gte: since, $lt: until } };
1951
+ if (scope.uids) query.uid = { $in: scope.uids };
1952
+ const stats = await this.ctx.database.select("analyse_rank").where(query).project(["timestamp", "count"]).execute();
1953
+ if (stats.length === 0) return "暂无统计数据";
1954
+ const counts = Array(points).fill(0);
1955
+ const labels = Array(points).fill("");
1956
+ const now = /* @__PURE__ */ new Date();
1957
+ now.setMinutes(0, 0, 0);
1958
+ for (let i = 0; i < points; i++) {
1959
+ const pointTime = new Date(until.getTime() - (i + 1) * timeUnit);
1960
+ labels[points - 1 - i] = options.days ? String(pointTime.getDate()) : String(pointTime.getHours());
1944
1961
  }
1945
- }));
1962
+ stats.forEach((stat) => {
1963
+ const diff = until.getTime() - stat.timestamp.getTime();
1964
+ const index = points - 1 - Math.floor(diff / timeUnit);
1965
+ if (index >= 0 && index < points) {
1966
+ counts[index] += stat.count;
1967
+ }
1968
+ });
1969
+ const total = counts.reduce((a, b) => a + b, 0);
1970
+ const title = await generateTitle(this.ctx, scope.scopeDesc, { main: "活跃", timeRange: options.duration, timeUnit: timeUnitName });
1971
+ return this.renderer.renderCircadianChart({ title, time: /* @__PURE__ */ new Date(), total, data: counts, labels });
1972
+ })()));
1946
1973
  }
1947
1974
  }
1948
1975
  };
@@ -1975,12 +2002,12 @@ var WhoAt = class {
1975
2002
  registerCommand(cmd) {
1976
2003
  cmd.subcommand("whoatme", "谁提及我").usage("查看最近提及我的消息,查看后自动删除。").action(async ({ session }) => {
1977
2004
  if (!session.userId) return "无法获取用户信息";
2005
+ const records = await this.ctx.database.get("analyse_at", { target: session.userId }, {
2006
+ sort: { timestamp: "asc" },
2007
+ limit: 100
2008
+ });
2009
+ if (records.length === 0) return "最近没有人提及您";
1978
2010
  try {
1979
- const records = await this.ctx.database.get("analyse_at", { target: session.userId }, {
1980
- sort: { timestamp: "asc" },
1981
- limit: 100
1982
- });
1983
- if (records.length === 0) return "最近没有人提及您";
1984
2011
  const uids = [...new Set(records.map((r) => r.uid))];
1985
2012
  const users = await this.ctx.database.get("analyse_user", { uid: { $in: uids } }, ["uid", "userName", "userId"]);
1986
2013
  const userInfoMap = new Map(users.map((u) => [u.uid, { name: u.userName, id: u.userId }]));
@@ -1989,9 +2016,9 @@ var WhoAt = class {
1989
2016
  const author = (0, import_koishi4.h)("author", { id: senderInfo.id, name: senderInfo.name });
1990
2017
  return (0, import_koishi4.h)("message", {}, [author, import_koishi4.h.text(record.content)]);
1991
2018
  });
2019
+ await session.send((0, import_koishi4.h)("message", { forward: true }, messageElements));
1992
2020
  const recordIdsToDelete = records.map((r) => r.id);
1993
2021
  await this.ctx.database.remove("analyse_at", { id: { $in: recordIdsToDelete } });
1994
- return (0, import_koishi4.h)("message", { forward: true }, messageElements);
1995
2022
  } catch (error) {
1996
2023
  this.ctx.logger.error("查询提及记录失败:", error);
1997
2024
  return "查询失败,请稍后重试";
@@ -2174,7 +2201,7 @@ var Analyse = class {
2174
2201
  */
2175
2202
  registerCommands(cmd) {
2176
2203
  if (this.config.enableWordCloud) {
2177
- cmd.subcommand("wordcloud", "生成词云").usage("基于聊天记录生成词云图,可指定范围,默认当前群组。").option("guild", "-g <guildId:string> 指定群组").option("user", "-u <user:string> 指定用户").option("hours", "-t <hours:number> 指定时长", { fallback: 24 }).option("all", "-a 全局").action(async ({ session, options }) => {
2204
+ cmd.subcommand("wordcloud", "生成词云").usage("基于聊天记录生成词云图,可指定范围,默认当前群组。").option("guild", "-g <guildId:string> 指定群组").option("user", "-u <user:string> 指定用户").option("hours", "-t <hours:number> 指定时长", { fallback: 24 }).action(async ({ session, options }) => {
2178
2205
  try {
2179
2206
  if (!this.jieba) return "Jieba 分词服务未就绪";
2180
2207
  const scope = await parseQueryScope(this.ctx, session, options);
@@ -2196,7 +2223,7 @@ var Analyse = class {
2196
2223
  const wordList = Array.from(wordCounts.entries()).sort((a, b) => b[1] - a[1]);
2197
2224
  const topWordsPreview = wordList.slice(0, 10).map((item) => item[0]).join(", ");
2198
2225
  session.send(`正在生成词云,热门词汇:${topWordsPreview}...`);
2199
- const title = await generateTitle(this.ctx, scope.scopeDesc, { main: "词云" });
2226
+ const title = await generateTitle(this.ctx, scope.scopeDesc, { main: "词云", timeRange: options.hours });
2200
2227
  const imageGenerator = this.renderer.renderWordCloud({ title, time: /* @__PURE__ */ new Date(), words: wordList });
2201
2228
  for await (const buffer of imageGenerator) await session.send(import_koishi6.h.image(buffer, "image/png"));
2202
2229
  } catch (error) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-chat-analyse",
3
3
  "description": "强大而全面的聊天数据分析,支持统计命令,发言,消息类型,活跃度,支持发言排行和生成词云",
4
- "version": "1.3.0",
4
+ "version": "1.3.1",
5
5
  "contributors": [
6
6
  "Yis_Rime <yis_rime@outlook.com>"
7
7
  ],
package/readme.md CHANGED
@@ -37,23 +37,58 @@
37
37
 
38
38
  | 指令 | 别名 | 描述 | 选项 |
39
39
  | --- | --- | --- | --- |
40
- | `analyse.cmdstat` | 命令统计 | 查询命令使用情况 | `-u <user>` (指定用户), `-g <guild>` (指定群组), `-a` (全局), `-h` (分离子指令) |
41
- | `analyse.msgstat` | 发言统计 | 查询用户发言统计 | `-u <user>`, `-g <guild>`, `-a` (全局), `-t <type>` (指定消息类型) |
42
- | `analyse.rankstat` | 发言排行 | 查询指定时间内的发言排行 | `-g <guild>`, `-a` (全局), `-t <type>`, `-h <hours>` (默认24小时) |
43
- | `analyse.activity` | 活跃统计 | 查询周期性活跃度图表 | `-u <user>`, `-g <guild>`, `-a` (全局), `-d` (按天), `-h <hours>` (小时偏移) |
44
- | `analyse.wordcloud` | 生成词云 | 基于聊天记录生成词云图 | `-u <user>`, `-g <guild>`, `-a` (全局), `-h <hours>` (默认24小时) |
40
+ | `analyse.cmdstat` | 命令统计 | 查询命令使用情况,展示方式根据选项变化 | `-u <user>`, `-g <guild>`, `-a` (全局), `-s` (分离子指令) |
41
+ | `analyse.msgstat` | 发言统计 | 查询用户发言统计,展示方式根据选项变化 | `-u <user>`, `-g <guild>`, `-a` (全局), `-t <type>` (指定消息类型) |
42
+ | `analyse.rankstat` | 发言排行 | 查询指定时间内的发言排行,展示方式根据选项变化 | `-u <user>`, `-g <guild>`, `-a` (全局), `-t <type>`, `-n <hours>`, `-o <hours>` |
43
+ | `analyse.activity` | 活跃统计 | 查询周期性活跃度图表 | `-u <user>`, `-g <guild>`, `-a` (全局), `-d` (按天), `-n <units>`, `-o <units>` |
44
+ | `analyse.wordcloud` | 生成词云 | 基于聊天记录生成词云图 | `-u <user>`, `-g <guild>`, `-t <hours>` (默认24小时) |
45
45
  | `analyse.whoatme` | 谁提及我 | 查看最近谁提及了您 | (无) |
46
46
  | `analyse.list` | 列出数据 | 列出已记录的频道和命令 | (无) |
47
47
  | `analyse.backup` | 备份数据 | 将所有数据备份为本地 JSON 文件 | (无) |
48
48
  | `analyse.restore` | 恢复数据 | 从本地 JSON 文件恢复数据 | (无) |
49
49
  | `analyse.clear` | 清除数据 | 根据条件精确清理数据 | `-t <table>`, `-g <guild>`, `-u <user>`, `-d <days>`, `-c <command>`, `-a` (全部) |
50
50
 
51
- **通用查询范围说明:**
51
+ ### 🔎 指令详解
52
52
 
53
- - 不带任何范围选项时,默认查询**当前群组**。
54
- - 使用 `-u <user>` 可指定用户 (支持 @某人)。
55
- - 使用 `-g <guild>` 可指定群组 ID。
56
- - 使用 `-a` 将忽略其他范围限制,查询**全局**数据。
53
+ #### `analyse.cmdstat` (命令统计)
54
+
55
+ - **`analyse cmdstat`**: 查询**当前群组**所有用户的命令统计。
56
+ - **`analyse cmdstat -u @用户`**: 查询**指定用户**在**所有群组**的命令统计。
57
+ - **`analyse cmdstat -g <群组ID>`**: 查询**指定群组**所有用户的命令统计。
58
+ - **`analyse cmdstat -u @用户 -g <群组ID>`**: 查询**指定用户**在**指定群组**的命令统计。
59
+ - **`analyse cmdstat -a`**: 查询**全局**(所有用户+所有群组)的命令统计。
60
+ - **选项 `-s`**: 分离展示子命令,不合并到主命令。
61
+
62
+ #### `analyse.msgstat` (发言统计)
63
+
64
+ - **`analyse msgstat`**: 查询**当前群组**的发言统计 (按**用户**展示)。
65
+ - **`analyse msgstat -u @用户`**: 查询**指定用户**的发言统计 (按**群组**展示)。
66
+ - **`analyse msgstat -g <群组ID>`**: 查询**指定群组**的发言统计 (按**用户**展示)。
67
+ - **`analyse msgstat -u @用户 -g <群组ID>`**: 查询**指定用户**在**指定群组**的发言统计 (按**消息类型**展示)。
68
+ - **`analyse msgstat -a`**: 查询**全局**发言统计 (按**用户**展示)。
69
+ - **选项 `-t <类型>`**: 筛选指定消息类型,不改变上述展示逻辑。
70
+
71
+ #### `analyse.rankstat` (发言排行)
72
+
73
+ - **`analyse rankstat`**: 查询**当前群组**的发言排行 (按**用户**排名)。
74
+ - **`analyse rankstat -u @用户`**: 查询**指定用户**的发言排行 (按**群组**排名)。
75
+ - **`analyse rankstat -g <群组ID>`**: 查询**指定群组**的发言排行 (按**用户**排名)。
76
+ - **`analyse rankstat -u @用户 -g <群组ID>`**: 查询**指定用户**在**指定群组**的发言排行 (按**消息类型**排名)。
77
+ - **`analyse rankstat -a`**: 查询**全局**发言排行 (按**用户**排名)。
78
+ - **选项 `-n <小时数>`**: 指定查询范围的时长,默认为 `24`。
79
+ - **选项 `-o <小时数>`**: 指定查询结束时间的偏移量(从现在往前推的小时数),默认为 `0`。
80
+ - **选项 `-t <类型>`**: 筛选指定消息类型,不改变上述展示逻辑。
81
+
82
+ #### `analyse.activity` (活跃统计)
83
+
84
+ - **`analyse activity`**: 查询**当前群组**的活跃度。
85
+ - **`analyse activity -u @用户`**: 查询**指定用户**在**所有群组**的活跃度。
86
+ - **`analyse activity -g <群组ID>`**: 查询**指定群组**的活跃度。
87
+ - **`analyse activity -u @用户 -g <群组ID>`**: 查询**指定用户**在**指定群组**的活跃度。
88
+ - **`analyse activity -a`**: 查询**全局**活跃度。
89
+ - **选项 `-n <数值>`**: 指定查询范围的时长,默认为 `24`。
90
+ - **选项 `-o <数值>`**: 指定查询结束时间的偏移量,默认为 `0`。
91
+ - **选项 `-d`**: 将 `-n` 和 `-o` 的单位从**小时**切换为**天**。
57
92
 
58
93
  ### 配置项
59
94
 
@@ -70,12 +105,12 @@
70
105
  - `enableMsgStat`: **启用消息统计**。 (默认: `true`)
71
106
  - `enableActivity`: **启用活跃统计**。 (默认: `true`)
72
107
  - `enableRankStat`: **启用发言排行**。 (默认: `true`)
73
- - `rankRetentionDays`: **排行保留天数**。发言排行数据的保留时长(天),`0` 为永久保留。 (默认: `31`)
108
+ - `rankRetentionDays`: **排行保留天数**。发言排行数据的保留时长(天),`0` 为永久保留。 (默认: `180`)
74
109
  - `enableWhoAt`: **启用提及记录**。 (默认: `true`)
75
- - `atRetentionDays`: **提及保留天数**。`whoatme` 数据的保留时长(天),`0` 为永久保留。 (默认: `7`)
110
+ - `atRetentionDays`: **提及保留天数**。`whoatme` 数据的保留时长(天),`0` 为永久保留。 (默认: `3`)
76
111
 
77
112
  #### 高级分析配置
78
113
 
79
114
  - `enableOriRecord`: **启用原始记录**。是否记录原始消息内容以供词云等功能使用。 (默认: `true`)
80
115
  - `enableWordCloud`: **启用词云生成**。 (默认: `true`)
81
- - `cacheRetentionDays`: **原始记录保留天数**。原始消息记录的保留时长(天),`0` 为永久保留。 (默认: `180`)
116
+ - `cacheRetentionDays`: **原始记录保留天数**。原始消息记录的保留时长(天),`0` 为永久保留。 (默认: `30`)