koishi-plugin-group-analysis-mx 1.5.1 → 1.5.3

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/index.js CHANGED
@@ -22,7 +22,6 @@ const drawing_1 = require("./service/drawing");
22
22
  const message_1 = require("./service/message");
23
23
  const plugin_1 = require("./plugin");
24
24
  const cron_1 = require("./cron");
25
- const dashboard_1 = require("./dashboard");
26
25
  __exportStar(require("./config"), exports);
27
26
  __exportStar(require("./service/message"), exports);
28
27
  function apply(ctx, config) {
@@ -42,7 +41,6 @@ function apply(ctx, config) {
42
41
  ctx.inject(['group_analysis'], (ctx) => {
43
42
  ctx.effect(() => scheduleAutoAnalysis(ctx, config));
44
43
  ctx.effect(() => scheduleAutoComic(ctx, config));
45
- (0, dashboard_1.setupDashboard)(ctx);
46
44
  });
47
45
  }
48
46
  function scheduleAutoAnalysis(ctx, config) {
@@ -915,14 +915,19 @@ class AnalysisService extends koishi_1.Service {
915
915
  }
916
916
  // 金句:LLM 输入用 [user_id],这里按 ID 精确回填完整昵称(含 emoji),并补全头像。
917
917
  if (Array.isArray(goldenQuotes)) {
918
- // id → 完整昵称(群名片优先,回退消息昵称)
918
+ // 官方 bot 的 userId 可能是 openid(长十六进制串),不能直接当昵称显示
919
+ const isOpenId = (v) => { const x = String(v || '').trim(); if (!x) return false; if (/^\d+$/.test(x)) return false; return /^[0-9A-Fa-f]{16,}$/.test(x) || x.length > 12; };
920
+ // id → 完整昵称(群名片优先,回退消息昵称;跳过 openid 形式)
919
921
  const idToNickname = new Map();
920
922
  for (const msg of messages) {
921
- if (msg.userId && msg.username)
922
- idToNickname.set(String(msg.userId), msg.username);
923
+ const un = msg.username ? String(msg.username) : '';
924
+ if (msg.userId && un && un !== String(msg.userId) && !isOpenId(un))
925
+ idToNickname.set(String(msg.userId), un);
926
+ }
927
+ for (const [uid, gname] of groupNicknameMap) {
928
+ if (gname)
929
+ idToNickname.set(uid, gname);
923
930
  }
924
- for (const [uid, gname] of groupNicknameMap)
925
- idToNickname.set(uid, gname);
926
931
  goldenQuotes.forEach((quote) => {
927
932
  if (quote && quote.sender) {
928
933
  const uid = String(quote.sender).replace(/[\[\]]/g, '').trim();
@@ -940,6 +945,8 @@ class AnalysisService extends koishi_1.Service {
940
945
  '';
941
946
  if (realName)
942
947
  quote.sender = realName;
948
+ else if (isOpenId(quote.sender) || String(quote.sender).length > 12)
949
+ quote.sender = '群友';
943
950
  if (!quote.avatar) {
944
951
  quote.avatar =
945
952
  nicknameAvatarMap.get(quote.sender) ||
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-group-analysis-mx",
3
3
  "description": "群聊分析插件 - 生成精美群聊统计报告,支持 AI 话题总结(独立版,不依赖 ChatLuna)",
4
- "version": "1.5.1",
4
+ "version": "1.5.3",
5
5
  "main": "lib/index.js",
6
6
  "module": "lib/index.mjs",
7
7
  "typings": "lib/index.d.ts",
package/lib/dashboard.js DELETED
@@ -1,63 +0,0 @@
1
- "use strict";
2
- /**
3
- * 群分析 Web 控制台:注册 /group-analysis 页面 + 数据接口。
4
- * 页面在浏览器打开(不经过 puppeteer),因此 emoji/字体不受容器影响。
5
- */
6
- const fs = require('fs');
7
- const path = require('path');
8
-
9
- function setupDashboard(ctx) {
10
- const router = ctx.router;
11
- if (!router) {
12
- ctx.logger.warn('未检测到 http 服务(ctx.router),群分析控制台页面不可用。');
13
- return;
14
- }
15
- const htmlPath = path.join(__dirname, '..', 'resources', 'dashboard.html');
16
-
17
- // 页面
18
- router.get('/group-analysis', async (c) => {
19
- try {
20
- c.type = 'html';
21
- c.body = fs.readFileSync(htmlPath, 'utf8');
22
- }
23
- catch (e) {
24
- c.status = 500;
25
- c.body = '页面文件缺失: ' + e.message;
26
- }
27
- });
28
-
29
- // 总览数据(基础版:从内存统计取,后续接真实记录)
30
- router.get('/group-analysis/api/overview', async (c) => {
31
- const s = ctx.group_analysis?._dashboardStats || {};
32
- c.type = 'application/json';
33
- c.body = {
34
- todayRuns: s.todayRuns || 0,
35
- totalRuns: s.totalRuns || 0,
36
- successRate: s.successRate != null ? s.successRate : 100,
37
- avgSeconds: s.avgSeconds || 0,
38
- todayTokens: s.todayTokens || 0,
39
- monthTokens: s.monthTokens || 0,
40
- todayGroups: s.todayGroups || 0,
41
- running: s.running || 0,
42
- apiCalls: s.apiCalls || 0,
43
- apiTrend: s.apiTrend || [],
44
- tokenTrend: s.tokenTrend || [],
45
- vendors: s.vendors || []
46
- };
47
- });
48
-
49
- // 手动触发一次分析(对所有已启用群)
50
- router.post('/group-analysis/api/run', async (c) => {
51
- try {
52
- await ctx.group_analysis.executeAutoAnalysisForEnabledGroups();
53
- c.type = 'application/json';
54
- c.body = { ok: true };
55
- }
56
- catch (e) {
57
- c.type = 'application/json';
58
- c.body = { ok: false, error: e.message };
59
- }
60
- });
61
- }
62
-
63
- module.exports = { setupDashboard };
@@ -1,210 +0,0 @@
1
- <!doctype html>
2
- <html lang="zh-CN">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>群分析插件控制台</title>
7
- <style>
8
- :root{
9
- --bg:#f3f5f8; --card:#fff; --line:#e8edf3; --text:#1f2a37; --sub:#7a8699;
10
- --blue:#3b82f6; --blue2:#6366f1; --green:#22c55e; --orange:#f59e0b; --red:#ef4444;
11
- --radius:14px;
12
- }
13
- *{box-sizing:border-box;margin:0;padding:0}
14
- body{font-family:-apple-system,'Segoe UI','Noto Sans SC','Microsoft YaHei',sans-serif;background:var(--bg);color:var(--text);font-size:14px}
15
- header{background:var(--card);border-bottom:1px solid var(--line);padding:14px 26px;display:flex;align-items:center;gap:14px;flex-wrap:wrap}
16
- .logo{width:40px;height:40px;border-radius:10px;background:linear-gradient(135deg,var(--blue),var(--blue2));display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:18px}
17
- .title{font-size:20px;font-weight:700}
18
- .subtitle{font-size:12px;color:var(--sub);margin-top:2px}
19
- .head-right{margin-left:auto;display:flex;gap:10px}
20
- .btn{padding:8px 16px;border-radius:8px;border:1px solid var(--line);background:#fff;color:var(--text);cursor:pointer;font-size:13px}
21
- .btn.primary{background:linear-gradient(135deg,var(--blue),var(--blue2));color:#fff;border:none}
22
- nav{background:var(--card);border-bottom:1px solid var(--line);padding:0 26px;display:flex;gap:26px;overflow-x:auto}
23
- nav button{background:none;border:none;padding:14px 2px;font-size:14px;color:var(--sub);cursor:pointer;border-bottom:2px solid transparent}
24
- nav button.active{color:var(--blue);border-bottom-color:var(--blue);font-weight:600}
25
- main{padding:22px 26px 40px;max-width:1600px;margin:0 auto}
26
- .view{display:none}
27
- .view.active{display:block}
28
- .cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:14px;margin-bottom:18px}
29
- .card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px 18px}
30
- .card .label{font-size:12px;color:var(--sub);margin-bottom:8px}
31
- .card .value{font-size:28px;font-weight:700}
32
- .card .meta{font-size:11px;color:var(--sub);margin-top:6px}
33
- .chart-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:14px;margin-bottom:18px}
34
- .chart-card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:14px 16px}
35
- .chart-card h3{font-size:13px;font-weight:600;color:var(--text);margin-bottom:10px;display:flex;align-items:center;gap:8px}
36
- .chart-card h3::before{content:'';width:4px;height:14px;border-radius:2px;background:var(--blue)}
37
- .chart-card .hint{font-size:11px;color:var(--sub);font-weight:400;margin-left:auto}
38
- .empty{color:var(--sub);text-align:center;padding:26px 0;font-size:13px}
39
- .tasks{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px 18px;min-height:160px}
40
- .tasks h2{font-size:15px;margin-bottom:12px}
41
- table{width:100%;border-collapse:collapse}
42
- th,td{text-align:left;padding:10px 12px;border-bottom:1px solid var(--line);font-size:13px}
43
- th{color:var(--sub);font-weight:500;font-size:12px}
44
- .pill{display:inline-block;padding:2px 10px;border-radius:999px;font-size:12px;background:#eef3fb;color:#3b6ea5}
45
- .pill.ok{background:#e9f9ef;color:#1e8e4e}
46
- .pill.warn{background:#fff6e5;color:#b76e00}
47
- .pill.err{background:#fdecec;color:#c0392b}
48
- </style>
49
- </head>
50
- <body>
51
- <header>
52
- <div class="logo">群</div>
53
- <div>
54
- <div class="title">群分析插件控制台</div>
55
- <div class="subtitle">查看群分析记录、执行进度与大模型消耗统计</div>
56
- </div>
57
- <div class="head-right">
58
- <button class="btn primary" onclick="runAnalysis()">手动执行分析</button>
59
- <button class="btn" onclick="refresh()">刷新</button>
60
- </div>
61
- </header>
62
- <nav id="nav">
63
- <button class="active" data-view="overview">运行总览</button>
64
- <button data-view="records">分析记录</button>
65
- <button data-view="stats">统计与消耗</button>
66
- <button data-view="reports">历史报告</button>
67
- <button data-view="logs">运行日志</button>
68
- <button data-view="config">配置中心</button>
69
- <button data-view="data">数据管理</button>
70
- </nav>
71
- <main>
72
- <!-- 运行总览 -->
73
- <section class="view active" id="view-overview">
74
- <div class="cards" id="overviewCards"></div>
75
- <div class="chart-row">
76
- <div class="chart-card">
77
- <h3>分析行为与 Token 消耗可观测趋势 <span class="hint" id="apiCountHint"></span></h3>
78
- <div id="chartApi"></div>
79
- </div>
80
- <div class="chart-card">
81
- <h3>Token 消耗趋势 <span class="hint" id="tokenHint"></span></h3>
82
- <div id="chartToken"></div>
83
- </div>
84
- <div class="chart-card">
85
- <h3>服务商消耗占比 <span class="hint" id="vendorHint"></span></h3>
86
- <div id="chartVendor"></div>
87
- </div>
88
- </div>
89
- <div class="tasks">
90
- <h2>正在执行中的分析任务 <span id="taskCount" style="color:var(--sub);font-size:12px">0 运行中</span></h2>
91
- <div class="empty" id="taskEmpty">
92
- <div style="font-size:32px;margin-bottom:8px">📂</div>
93
- 暂无正在执行的后台分析任务<br>
94
- <button class="btn" style="margin-top:12px" onclick="runAnalysis()">手动触发一次分析</button>
95
- </div>
96
- </div>
97
- </section>
98
- <section class="view" id="view-records"><div class="tasks"><h2>分析记录</h2><div class="empty">暂无记录</div></div></section>
99
- <section class="view" id="view-stats"><div class="tasks"><h2>统计与消耗</h2><div class="empty">数据待接入</div></div></section>
100
- <section class="view" id="view-reports"><div class="tasks"><h2>历史报告</h2><div class="empty">暂无历史报告</div></div></section>
101
- <section class="view" id="view-logs"><div class="tasks"><h2>运行日志</h2><div class="empty">暂无日志</div></div></section>
102
- <section class="view" id="view-config"><div class="tasks"><h2>配置中心</h2><div class="empty">请在 Koishi 控制台修改插件配置</div></div></section>
103
- <section class="view" id="view-data"><div class="tasks"><h2>数据管理</h2><div class="empty">数据管理功能开发中</div></div></section>
104
- </main>
105
- <script>
106
- const API = location.pathname.replace(/\/$/,'');
107
- let stats = null;
108
-
109
- async function fetchJson(url){
110
- try { const r = await fetch(url, {headers:{'Accept':'application/json'}}); if(!r.ok) throw new Error(r.status); return await r.json(); }
111
- catch(e){ return null; }
112
- }
113
-
114
- function fmt(n){ return n==null?'0':(n>=10000?n.toLocaleString():String(n)); }
115
-
116
- function renderOverview(){
117
- const el = document.getElementById('overviewCards');
118
- const d = stats || {};
119
- const cards = [
120
- ['今日分析次数', d.todayRuns ?? 0, '覆盖 ' + (d.todayGroups ?? 0) + ' 个群聊'],
121
- ['历史总运行', d.totalRuns ?? 0, '成功率 ' + (d.successRate != null ? d.successRate + '%' : '100%')],
122
- ['平均耗时', (d.avgSeconds ?? 0) + 's', '平均单次分析耗时'],
123
- ['今日模型消耗', fmt(d.todayTokens ?? 0), '今日大模型消耗总量'],
124
- ['30天模型消耗', fmt(d.monthTokens ?? 0), '近 30 天累计消耗总量'],
125
- ['今日分析群聊', d.todayGroups ?? 0, '今日已分析群数'],
126
- ];
127
- el.innerHTML = cards.map(([label,value,meta]) => `
128
- <div class="card"><div class="label">${label}</div><div class="value">${value}</div><div class="meta">${meta}</div></div>`).join('');
129
- }
130
-
131
- function svgLine(points,{w=320,h=150,color='#3b82f6'}={}){
132
- if(!points || !points.length) return '<div class="empty">暂无数据</div>';
133
- const max = Math.max(...points.map(p=>p.v),1);
134
- const step = w/(points.length-1||1);
135
- const path = points.map((p,i)=>`${i===0?'M':'L'}${(i*step).toFixed(1)},${(h-p.v/max*(h-20)-10).toFixed(1)}`).join(' ');
136
- const area = path + ` L${w},${h} L0,${h} Z`;
137
- return `<svg viewBox="0 0 ${w} ${h}" width="100%" height="150" preserveAspectRatio="none">
138
- <defs><linearGradient id="g1" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stop-color="${color}" stop-opacity=".35"/><stop offset="100%" stop-color="${color}" stop-opacity="0"/></linearGradient></defs>
139
- <path d="${area}" fill="url(#g1)"/>
140
- <path d="${path}" fill="none" stroke="${color}" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/>
141
- ${points.map((p,i)=>`<circle cx="${(i*step).toFixed(1)}" cy="${(h-p.v/max*(h-20)-10).toFixed(1)}" r="3" fill="${color}"><title>${p.label}: ${p.v}</title></circle>`).join('')}
142
- </svg>`;
143
- }
144
-
145
- function svgBars(data,{w=320,h=150,color='#3b82f6'}={}){
146
- if(!data || !data.length) return '<div class="empty">暂无数据</div>';
147
- const max = Math.max(...data.map(d=>d.v),1);
148
- const bw = (w/data.length)*0.55;
149
- return `<svg viewBox="0 0 ${w} ${h}" width="100%" height="150" preserveAspectRatio="none">
150
- ${data.map((d,i)=>{const bh=(d.v/max)*(h-24);return `<rect x="${i*(w/data.length)+(w/data.length-bw)/2}" y="${h-10-bh}" width="${bw}" height="${Math.max(bh,1)}" rx="4" fill="${color}" opacity=".85"><title>${d.label}: ${d.v}</title></rect>`}).join('')}
151
- </svg>`;
152
- }
153
-
154
- function svgDonut(data,{size=150,colors=['#3b82f6','#8b5cf6','#22c55e','#f59e0b','#ef4444']}={}){
155
- const total = (data||[]).reduce((s,d)=>s+d.v,0);
156
- if(!total) return '<div class="empty">暂无数据</div>';
157
- let acc = 0; const r=54, c=75, sw=18;
158
- const segs = data.map((d,i)=>{
159
- const frac = d.v/total;
160
- const start = acc*Math.PI*2 - Math.PI/2;
161
- acc += frac;
162
- const end = acc*Math.PI*2 - Math.PI/2;
163
- const large = frac>0.5?1:0;
164
- const x1=c+r*Math.cos(start), y1=c+r*Math.sin(start), x2=c+r*Math.cos(end), y2=c+r*Math.sin(end);
165
- return `<path d="M${x1},${y1} A${r},${r} 0 ${large} 1 ${x2},${y2}" fill="none" stroke="${colors[i%colors.length]}" stroke-width="${sw}" stroke-linecap="butt"><title>${d.label}: ${d.v}</title></path>`;
166
- }).join('');
167
- return `<svg viewBox="0 0 150 150" width="150" height="150">${segs}<circle cx="75" cy="75" r="${r-sw/2}" fill="none"/></svg>`;
168
- }
169
-
170
- function renderCharts(){
171
- const d = stats || {};
172
- document.getElementById('apiCountHint').textContent = (d.apiCalls ?? 0) + ' 次';
173
- document.getElementById('tokenHint').textContent = fmt(d.monthTokens ?? 0);
174
- document.getElementById('vendorHint').textContent = (d.vendors?.length ?? 0) + ' 个渠道';
175
- document.getElementById('chartApi').innerHTML = svgLine(d.apiTrend || []);
176
- document.getElementById('chartToken').innerHTML = svgBars((d.tokenTrend||[]).map(t=>({label:t.label,v:t.v})));
177
- document.getElementById('chartVendor').innerHTML = svgDonut((d.vendors||[]).map(v=>({label:v.label,v:v.v})));
178
- }
179
-
180
- async function refresh(){
181
- stats = await fetchJson(API + '/api/overview');
182
- renderOverview(); renderCharts();
183
- const t = document.getElementById('taskCount');
184
- const empty = document.getElementById('taskEmpty');
185
- const running = stats?.running ?? 0;
186
- t.textContent = running + ' 运行中';
187
- empty.style.display = running > 0 ? 'none' : '';
188
- }
189
-
190
- async function runAnalysis(){
191
- const r = await fetch(API + '/api/run', {method:'POST'});
192
- const j = r.ok ? await r.json().catch(()=>null) : null;
193
- alert(j?.ok ? '已触发分析任务' : '触发失败,请查看日志');
194
- refresh();
195
- }
196
-
197
- document.querySelectorAll('#nav button').forEach(btn=>{
198
- btn.onclick = () => {
199
- document.querySelectorAll('#nav button').forEach(b=>b.classList.remove('active'));
200
- btn.classList.add('active');
201
- document.querySelectorAll('.view').forEach(v=>v.classList.remove('active'));
202
- document.getElementById('view-' + btn.dataset.view).classList.add('active');
203
- };
204
- });
205
-
206
- refresh();
207
- setInterval(refresh, 30000);
208
- </script>
209
- </body>
210
- </html>