@zhin.js/plugin-group-suite 1.0.1 → 1.1.2
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/README.md +42 -58
- package/commands/checkin/index.js +11 -0
- package/commands/checkin/index.ts +12 -0
- package/commands/forget/index.js +10 -0
- package/commands/forget/index.ts +12 -0
- package/commands/keyword-add/[keyword]/index.js +16 -0
- package/commands/keyword-add/[keyword]/index.ts +16 -0
- package/commands/keyword-list/index.js +14 -0
- package/commands/keyword-list/index.ts +14 -0
- package/commands/keyword-remove/[keyword]/index.js +16 -0
- package/commands/keyword-remove/[keyword]/index.ts +15 -0
- package/commands/mypoints/index.js +10 -0
- package/commands/mypoints/index.ts +12 -0
- package/commands/mystats/index.js +10 -0
- package/commands/mystats/index.ts +12 -0
- package/commands/rank/index.js +11 -0
- package/commands/rank/index.ts +12 -0
- package/commands/stats/index.js +14 -0
- package/commands/stats/index.ts +21 -0
- package/commands/stats-rank/index.js +13 -0
- package/commands/stats-rank/index.ts +20 -0
- package/commands/stats-week/index.js +13 -0
- package/commands/stats-week/index.ts +20 -0
- package/commands/teach/index.js +11 -0
- package/commands/teach/index.ts +12 -0
- package/commands/teach-list/[[page]]/index.js +13 -0
- package/commands/teach-list/[[page]]/index.ts +14 -0
- package/commands/teach-regex/index.js +11 -0
- package/commands/teach-regex/index.ts +12 -0
- package/lib/checkin-lib.d.ts +27 -0
- package/lib/checkin-lib.d.ts.map +1 -0
- package/lib/checkin-lib.js +133 -0
- package/lib/checkin-lib.js.map +1 -0
- package/lib/config.d.ts +4 -57
- package/lib/config.d.ts.map +1 -1
- package/lib/config.js +18 -40
- package/lib/config.js.map +1 -1
- package/lib/db-store.d.ts +5 -0
- package/lib/db-store.d.ts.map +1 -0
- package/lib/db-store.js +11 -0
- package/lib/db-store.js.map +1 -0
- package/lib/index.d.ts +9 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +7 -29
- package/lib/index.js.map +1 -1
- package/lib/keyword-store.d.ts +5 -0
- package/lib/keyword-store.d.ts.map +1 -0
- package/lib/keyword-store.js +17 -0
- package/lib/keyword-store.js.map +1 -0
- package/lib/memory-store.d.ts +31 -0
- package/lib/memory-store.d.ts.map +1 -0
- package/lib/memory-store.js +63 -0
- package/lib/memory-store.js.map +1 -0
- package/lib/runtime-state.d.ts +24 -0
- package/lib/runtime-state.d.ts.map +1 -0
- package/lib/runtime-state.js +15 -0
- package/lib/runtime-state.js.map +1 -0
- package/lib/shared-runtime.d.ts +26 -0
- package/lib/shared-runtime.d.ts.map +1 -0
- package/lib/shared-runtime.js +34 -0
- package/lib/shared-runtime.js.map +1 -0
- package/lib/stats-lib.d.ts +39 -0
- package/lib/stats-lib.d.ts.map +1 -0
- package/lib/stats-lib.js +172 -0
- package/lib/stats-lib.js.map +1 -0
- package/lib/tables.d.ts +4 -0
- package/lib/tables.d.ts.map +1 -0
- package/lib/tables.js +40 -0
- package/lib/tables.js.map +1 -0
- package/lib/teach-lib.d.ts +23 -0
- package/lib/teach-lib.d.ts.map +1 -0
- package/lib/teach-lib.js +228 -0
- package/lib/teach-lib.js.map +1 -0
- package/middlewares/keyword-reply/index.js +36 -0
- package/middlewares/keyword-reply/index.ts +37 -0
- package/middlewares/stats-count/index.js +20 -0
- package/middlewares/stats-count/index.ts +22 -0
- package/middlewares/teach-reply/index.js +21 -0
- package/middlewares/teach-reply/index.ts +22 -0
- package/package.json +57 -14
- package/plugin.js +38 -0
- package/schema.json +17 -0
- package/skills/checkin/tools/checkin_query/index.js +42 -0
- package/skills/checkin/tools/checkin_query/index.ts +41 -0
- package/skills/checkin/tools/checkin_rank/index.js +34 -0
- package/skills/checkin/tools/checkin_rank/index.ts +34 -0
- package/skills/group-daily-analysis/SKILL.md +11 -4
- package/skills/group-daily-analysis/tools/group_announce/index.js +14 -0
- package/skills/group-daily-analysis/tools/group_announce/index.ts +14 -0
- package/skills/group-daily-analysis/tools/stats_query/index.js +35 -0
- package/skills/group-daily-analysis/tools/stats_query/index.ts +36 -0
- package/skills/group-daily-analysis/tools/stats_user/index.js +50 -0
- package/skills/group-daily-analysis/tools/stats_user/index.ts +46 -0
- package/src/checkin-lib.ts +167 -0
- package/src/config.ts +23 -57
- package/src/db-store.ts +19 -0
- package/src/index.ts +39 -33
- package/src/keyword-store.ts +18 -0
- package/src/memory-store.ts +90 -0
- package/src/runtime-state.ts +41 -0
- package/src/shared-runtime.ts +44 -0
- package/src/stats-lib.ts +198 -0
- package/src/tables.ts +46 -0
- package/src/teach-lib.ts +294 -0
- package/lib/admin.d.ts +0 -4
- package/lib/admin.d.ts.map +0 -1
- package/lib/admin.js +0 -123
- package/lib/admin.js.map +0 -1
- package/lib/checkin.d.ts +0 -5
- package/lib/checkin.d.ts.map +0 -1
- package/lib/checkin.js +0 -168
- package/lib/checkin.js.map +0 -1
- package/lib/daily-analysis.d.ts +0 -7
- package/lib/daily-analysis.d.ts.map +0 -1
- package/lib/daily-analysis.js +0 -334
- package/lib/daily-analysis.js.map +0 -1
- package/lib/shared.d.ts +0 -25
- package/lib/shared.d.ts.map +0 -1
- package/lib/shared.js +0 -40
- package/lib/shared.js.map +0 -1
- package/lib/stats.d.ts +0 -12
- package/lib/stats.d.ts.map +0 -1
- package/lib/stats.js +0 -256
- package/lib/stats.js.map +0 -1
- package/lib/teach.d.ts +0 -4
- package/lib/teach.d.ts.map +0 -1
- package/lib/teach.js +0 -294
- package/lib/teach.js.map +0 -1
- package/plugin.yml +0 -3
- package/src/admin.ts +0 -145
- package/src/checkin.ts +0 -196
- package/src/daily-analysis.ts +0 -458
- package/src/shared.ts +0 -51
- package/src/stats.ts +0 -297
- package/src/teach.ts +0 -307
- package/tools/checkin-query/checkin-query.tool.md +0 -11
- package/tools/checkin-query/handler.ts +0 -22
- package/tools/checkin-rank/checkin-rank.tool.md +0 -11
- package/tools/checkin-rank/handler.ts +0 -16
- package/tools/stats-query/handler.ts +0 -31
- package/tools/stats-query/stats-query.tool.md +0 -16
- package/tools/stats-user/handler.ts +0 -28
- package/tools/stats-user/stats-user.tool.md +0 -12
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { defineAgentTool } from '@zhin.js/tool';
|
|
2
|
+
import { getStatsModel } from '../../../../src/db-store.js';
|
|
3
|
+
import { groupSuiteRuntimeToken } from '../../../../src/runtime-state.js';
|
|
4
|
+
import { todayStr } from '../../../../src/shared-runtime.js';
|
|
5
|
+
import { flushStatsBuffer, weekStartStr } from '../../../../src/stats-lib.js';
|
|
6
|
+
|
|
7
|
+
export default defineAgentTool<{ user_id: string; group_id?: string }>({
|
|
8
|
+
description: '查询指定用户在当前群或指定群的消息统计',
|
|
9
|
+
inputSchema: {
|
|
10
|
+
type: 'object',
|
|
11
|
+
properties: {
|
|
12
|
+
user_id: { type: 'string', description: '用户 ID' },
|
|
13
|
+
group_id: { type: 'string', description: '群 ID;省略时使用当前 IM 会话' },
|
|
14
|
+
},
|
|
15
|
+
required: ['user_id'],
|
|
16
|
+
},
|
|
17
|
+
requiresApproval: 'never',
|
|
18
|
+
async execute({ user_id: userId, group_id: requestedGroupId }, context) {
|
|
19
|
+
const runtime = context.use(groupSuiteRuntimeToken);
|
|
20
|
+
await flushStatsBuffer(runtime);
|
|
21
|
+
const model = getStatsModel(runtime.db);
|
|
22
|
+
if (!model) return '统计数据库尚未就绪';
|
|
23
|
+
const groupId = requestedGroupId
|
|
24
|
+
?? (context.origin.kind === 'im' && context.origin.scope !== 'private'
|
|
25
|
+
? context.origin.sceneId
|
|
26
|
+
: '');
|
|
27
|
+
const rows = await model.select().where({
|
|
28
|
+
user_id: userId,
|
|
29
|
+
...(groupId ? { group_id: groupId } : {}),
|
|
30
|
+
});
|
|
31
|
+
if (rows.length === 0) return `用户 ${userId} 暂无消息记录`;
|
|
32
|
+
const today = todayStr();
|
|
33
|
+
const weekStart = weekStartStr();
|
|
34
|
+
let todayCount = 0;
|
|
35
|
+
let weekCount = 0;
|
|
36
|
+
let totalCount = 0;
|
|
37
|
+
for (const row of rows) {
|
|
38
|
+
const count = Number(row.count ?? 0);
|
|
39
|
+
totalCount += count;
|
|
40
|
+
if (String(row.date) >= weekStart) weekCount += count;
|
|
41
|
+
if (row.date === today) todayCount += count;
|
|
42
|
+
}
|
|
43
|
+
const name = String(rows[0]!.user_name ?? userId);
|
|
44
|
+
return `${name} 的统计\n今日: ${todayCount}条\n本周: ${weekCount}条\n总计: ${totalCount}条\n活跃天数: ${rows.length}天`;
|
|
45
|
+
},
|
|
46
|
+
});
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import type { GroupSuiteConfig } from './config.js';
|
|
2
|
+
import { getCheckinModel } from './db-store.js';
|
|
3
|
+
import {
|
|
4
|
+
randomInt,
|
|
5
|
+
resolveContextKey,
|
|
6
|
+
resolveSender,
|
|
7
|
+
todayStr,
|
|
8
|
+
ts,
|
|
9
|
+
yesterdayStr,
|
|
10
|
+
} from './shared-runtime.js';
|
|
11
|
+
import type { GroupSuiteRuntime } from './runtime-state.js';
|
|
12
|
+
|
|
13
|
+
async function getOrCreateUser(
|
|
14
|
+
model: any,
|
|
15
|
+
userId: string,
|
|
16
|
+
userName: string,
|
|
17
|
+
ctxType: string,
|
|
18
|
+
ctxId: string,
|
|
19
|
+
): Promise<Record<string, unknown> | null> {
|
|
20
|
+
const rows = (await model.select().where({
|
|
21
|
+
user_id: userId,
|
|
22
|
+
context_type: ctxType,
|
|
23
|
+
context_id: ctxId,
|
|
24
|
+
})) as Record<string, unknown>[];
|
|
25
|
+
if (rows.length > 0) return rows[0];
|
|
26
|
+
|
|
27
|
+
await model.insert({
|
|
28
|
+
user_id: userId,
|
|
29
|
+
user_name: userName,
|
|
30
|
+
points: 0,
|
|
31
|
+
total_checkins: 0,
|
|
32
|
+
streak: 0,
|
|
33
|
+
max_streak: 0,
|
|
34
|
+
last_checkin: '',
|
|
35
|
+
context_type: ctxType,
|
|
36
|
+
context_id: ctxId,
|
|
37
|
+
created_at: ts(),
|
|
38
|
+
updated_at: ts(),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const created = (await model.select().where({
|
|
42
|
+
user_id: userId,
|
|
43
|
+
context_type: ctxType,
|
|
44
|
+
context_id: ctxId,
|
|
45
|
+
})) as Record<string, unknown>[];
|
|
46
|
+
return created[0] ?? null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 同一 user_id+context 的签到串行化(per-user promise 链),
|
|
51
|
+
* 避免 check-then-act 竞态导致连发两条都签到成功。
|
|
52
|
+
*/
|
|
53
|
+
function serializedCheckin<T>(
|
|
54
|
+
chains: Map<string, Promise<unknown>>,
|
|
55
|
+
key: string,
|
|
56
|
+
task: () => Promise<T>,
|
|
57
|
+
): Promise<T> {
|
|
58
|
+
const prev = chains.get(key) ?? Promise.resolve();
|
|
59
|
+
const next = prev.then(task, task);
|
|
60
|
+
chains.set(key, next);
|
|
61
|
+
return next.finally(() => {
|
|
62
|
+
if (chains.get(key) === next) chains.delete(key);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function doCheckin(
|
|
67
|
+
input: { sender?: { readonly id: string; readonly name?: string }; target?: string; metadata?: Readonly<Record<string, unknown>> },
|
|
68
|
+
cfg: GroupSuiteConfig,
|
|
69
|
+
runtime: GroupSuiteRuntime,
|
|
70
|
+
): Promise<string> {
|
|
71
|
+
const M = getCheckinModel(runtime.db);
|
|
72
|
+
if (!M) return '签到数据库尚未就绪,请稍后重试';
|
|
73
|
+
|
|
74
|
+
const { id: userId, name: userName } = resolveSender(input);
|
|
75
|
+
if (!userId) return '无法获取用户信息';
|
|
76
|
+
|
|
77
|
+
const { type: ctxType, id: ctxId } = resolveContextKey(input);
|
|
78
|
+
return serializedCheckin(runtime.checkinChains, `${userId}:${ctxType}:${ctxId}`, async () => {
|
|
79
|
+
const user = await getOrCreateUser(M, userId, userName, ctxType, ctxId);
|
|
80
|
+
if (!user) return '签到失败,请重试';
|
|
81
|
+
|
|
82
|
+
const today = todayStr();
|
|
83
|
+
if (user.last_checkin === today) {
|
|
84
|
+
return `你今天已经签到过了哦~\n当前积分: ${user.points}\n连续签到: ${user.streak} 天`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const isConsecutive = user.last_checkin === yesterdayStr();
|
|
88
|
+
const newStreak = isConsecutive ? Number(user.streak) + 1 : 1;
|
|
89
|
+
const base = randomInt(cfg.basePointsMin, cfg.basePointsMax);
|
|
90
|
+
const bonus = Math.min(newStreak * cfg.streakBonus, cfg.streakCap);
|
|
91
|
+
const earned = base + bonus;
|
|
92
|
+
const newPoints = Number(user.points || 0) + earned;
|
|
93
|
+
|
|
94
|
+
await M.update({
|
|
95
|
+
points: newPoints,
|
|
96
|
+
total_checkins: Number(user.total_checkins || 0) + 1,
|
|
97
|
+
streak: newStreak,
|
|
98
|
+
max_streak: Math.max(Number(user.max_streak || 0), newStreak),
|
|
99
|
+
last_checkin: today,
|
|
100
|
+
user_name: userName,
|
|
101
|
+
updated_at: ts(),
|
|
102
|
+
}).where({
|
|
103
|
+
user_id: userId,
|
|
104
|
+
context_type: ctxType,
|
|
105
|
+
context_id: ctxId,
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
const lines = [`签到成功!`, `基础积分: +${base}`];
|
|
109
|
+
if (bonus > 0) lines.push(`连续奖励: +${bonus} (连续${newStreak}天)`);
|
|
110
|
+
lines.push(`本次获得: +${earned}`, `当前积分: ${newPoints}`);
|
|
111
|
+
return lines.join('\n');
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function myPoints(
|
|
116
|
+
input: { sender?: { readonly id: string; readonly name?: string }; target?: string; metadata?: Readonly<Record<string, unknown>> },
|
|
117
|
+
runtime: GroupSuiteRuntime,
|
|
118
|
+
): Promise<string> {
|
|
119
|
+
const M = getCheckinModel(runtime.db);
|
|
120
|
+
if (!M) return '签到数据库尚未就绪';
|
|
121
|
+
const { id: userId } = resolveSender(input);
|
|
122
|
+
const { type: ctxType, id: ctxId } = resolveContextKey(input);
|
|
123
|
+
const rows = (await M.select().where({
|
|
124
|
+
user_id: userId,
|
|
125
|
+
context_type: ctxType,
|
|
126
|
+
context_id: ctxId,
|
|
127
|
+
})) as Record<string, unknown>[];
|
|
128
|
+
if (rows.length === 0) return '你还没有签到记录哦,发送「checkin」开始吧!';
|
|
129
|
+
const u = rows[0];
|
|
130
|
+
const checkedToday = u.last_checkin === todayStr();
|
|
131
|
+
return [
|
|
132
|
+
`${u.user_name || '用户'} 的积分信息`,
|
|
133
|
+
`积分: ${u.points}`,
|
|
134
|
+
`累计签到: ${u.total_checkins} 天`,
|
|
135
|
+
`连续签到: ${u.streak} 天`,
|
|
136
|
+
`最长连续: ${u.max_streak} 天`,
|
|
137
|
+
checkedToday ? '今日已签到 ✓' : '今日未签到',
|
|
138
|
+
].join('\n');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export async function pointsRank(
|
|
142
|
+
input: { sender?: { readonly id: string; readonly name?: string }; target?: string; metadata?: Readonly<Record<string, unknown>> },
|
|
143
|
+
cfg: GroupSuiteConfig,
|
|
144
|
+
runtime: GroupSuiteRuntime,
|
|
145
|
+
): Promise<string> {
|
|
146
|
+
const M = getCheckinModel(runtime.db);
|
|
147
|
+
if (!M) return '签到数据库尚未就绪';
|
|
148
|
+
const { type: ctxType, id: ctxId } = resolveContextKey(input);
|
|
149
|
+
const all = (await M.select().where(
|
|
150
|
+
ctxType === 'global'
|
|
151
|
+
? { context_type: 'global' }
|
|
152
|
+
: { context_type: ctxType, context_id: ctxId },
|
|
153
|
+
)) as Record<string, unknown>[];
|
|
154
|
+
if (all.length === 0) return '还没有人签到过哦~';
|
|
155
|
+
const sorted = all.sort((a, b) => Number(b.points || 0) - Number(a.points || 0));
|
|
156
|
+
const top = sorted.slice(0, cfg.rankSize);
|
|
157
|
+
const medals = ['🥇', '🥈', '🥉'];
|
|
158
|
+
const lines = top.map((u, i) => {
|
|
159
|
+
const prefix = i < 3 ? medals[i] : `${i + 1}.`;
|
|
160
|
+
return `${prefix} ${u.user_name || u.user_id} — ${u.points}分 (${u.total_checkins}天)`;
|
|
161
|
+
});
|
|
162
|
+
const title = ctxType === 'group' ? '本群积分排行' : '全局积分排行';
|
|
163
|
+
const { id: userId } = resolveSender(input);
|
|
164
|
+
const myRank = sorted.findIndex((u) => u.user_id === userId);
|
|
165
|
+
const footer = myRank >= 0 ? `\n你的排名: 第${myRank + 1}名` : '';
|
|
166
|
+
return `${title}\n${lines.join('\n')}${footer}`;
|
|
167
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -1,68 +1,34 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
/** 扁平 groupSuite 配置(单层字段,默认值覆盖多数场景) */
|
|
4
|
-
export const groupSuiteSchema = Schema.object({
|
|
5
|
-
welcome: Schema.string()
|
|
6
|
-
.default("欢迎新成员加入本群!")
|
|
7
|
-
.description("入群欢迎语"),
|
|
8
|
-
recallNotify: Schema.boolean()
|
|
9
|
-
.default(true)
|
|
10
|
-
.description("群消息撤回时是否提示"),
|
|
11
|
-
keywordReply: Schema.boolean()
|
|
12
|
-
.default(false)
|
|
13
|
-
.description("内置关键词回复(默认关闭,用 teach 问答)"),
|
|
14
|
-
noticeAdapters: Schema.list(Schema.string())
|
|
15
|
-
.default(["icqq"])
|
|
16
|
-
.description("处理 notice 的适配器(欢迎/撤回)"),
|
|
17
|
-
|
|
18
|
-
basePointsMin: Schema.number().default(10).min(1).max(100),
|
|
19
|
-
basePointsMax: Schema.number().default(30).min(1).max(200),
|
|
20
|
-
streakBonus: Schema.number().default(5).min(0).max(100),
|
|
21
|
-
streakCap: Schema.number().default(50).min(0).max(500),
|
|
22
|
-
|
|
23
|
-
rankSize: Schema.number()
|
|
24
|
-
.default(10)
|
|
25
|
-
.min(3)
|
|
26
|
-
.max(50)
|
|
27
|
-
.description("签到排行与消息统计排行显示人数"),
|
|
28
|
-
statsRetentionDays: Schema.number().default(90).min(7).max(365),
|
|
29
|
-
|
|
30
|
-
analysisDays: Schema.number().default(1).min(1).max(30),
|
|
31
|
-
autoAnalysisEnabled: Schema.boolean().default(false),
|
|
32
|
-
autoAnalysisCron: Schema.string().default("0 9 * * *"),
|
|
33
|
-
analysisGroups: Schema.list(Schema.string())
|
|
34
|
-
.default([])
|
|
35
|
-
.description("启用群日报的群 ID 白名单(空=不限制)"),
|
|
36
|
-
analysisGroupsBlock: Schema.list(Schema.string())
|
|
37
|
-
.default([])
|
|
38
|
-
.description("禁用群日报的群 ID"),
|
|
39
|
-
analysisMaxMessages: Schema.number().default(500).min(100).max(5000),
|
|
40
|
-
|
|
41
|
-
teachMaxPerGroup: Schema.number().default(200).min(1).max(1000),
|
|
42
|
-
teachCooldownMs: Schema.number().default(3000).min(0).max(60000),
|
|
43
|
-
teachAllowRegex: Schema.boolean().default(true),
|
|
44
|
-
teachPageSize: Schema.number().default(10).min(5).max(50),
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
export type GroupSuiteConfig = {
|
|
48
|
-
welcome: string;
|
|
49
|
-
recallNotify: boolean;
|
|
1
|
+
export interface GroupSuiteConfig {
|
|
50
2
|
keywordReply: boolean;
|
|
51
|
-
noticeAdapters: string[];
|
|
52
3
|
basePointsMin: number;
|
|
53
4
|
basePointsMax: number;
|
|
54
5
|
streakBonus: number;
|
|
55
6
|
streakCap: number;
|
|
56
7
|
rankSize: number;
|
|
57
|
-
statsRetentionDays: number;
|
|
58
|
-
analysisDays: number;
|
|
59
|
-
autoAnalysisEnabled: boolean;
|
|
60
|
-
autoAnalysisCron: string;
|
|
61
|
-
analysisGroups: string[];
|
|
62
|
-
analysisGroupsBlock: string[];
|
|
63
|
-
analysisMaxMessages: number;
|
|
64
8
|
teachMaxPerGroup: number;
|
|
65
9
|
teachCooldownMs: number;
|
|
66
10
|
teachAllowRegex: boolean;
|
|
67
11
|
teachPageSize: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_GROUP_SUITE_CONFIG: GroupSuiteConfig = {
|
|
15
|
+
keywordReply: false,
|
|
16
|
+
basePointsMin: 10,
|
|
17
|
+
basePointsMax: 30,
|
|
18
|
+
streakBonus: 5,
|
|
19
|
+
streakCap: 50,
|
|
20
|
+
rankSize: 10,
|
|
21
|
+
teachMaxPerGroup: 200,
|
|
22
|
+
teachCooldownMs: 3000,
|
|
23
|
+
teachAllowRegex: true,
|
|
24
|
+
teachPageSize: 10,
|
|
68
25
|
};
|
|
26
|
+
|
|
27
|
+
export function resolveGroupSuiteConfig(
|
|
28
|
+
raw: Partial<GroupSuiteConfig> | undefined,
|
|
29
|
+
): GroupSuiteConfig {
|
|
30
|
+
return {
|
|
31
|
+
...DEFAULT_GROUP_SUITE_CONFIG,
|
|
32
|
+
...raw,
|
|
33
|
+
};
|
|
34
|
+
}
|
package/src/db-store.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CHECKIN_TABLE,
|
|
3
|
+
STATS_TABLE,
|
|
4
|
+
TEACH_TABLE,
|
|
5
|
+
type GroupSuiteMemoryDb,
|
|
6
|
+
type GroupSuiteModel,
|
|
7
|
+
} from './memory-store.js';
|
|
8
|
+
|
|
9
|
+
export function getCheckinModel(db: GroupSuiteMemoryDb): GroupSuiteModel | undefined {
|
|
10
|
+
return db.models.get(CHECKIN_TABLE);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function getTeachModel(db: GroupSuiteMemoryDb): GroupSuiteModel | undefined {
|
|
14
|
+
return db.models.get(TEACH_TABLE);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function getStatsModel(db: GroupSuiteMemoryDb): GroupSuiteModel | undefined {
|
|
18
|
+
return db.models.get(STATS_TABLE);
|
|
19
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,33 +1,39 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
1
|
+
export {
|
|
2
|
+
DEFAULT_GROUP_SUITE_CONFIG,
|
|
3
|
+
resolveGroupSuiteConfig,
|
|
4
|
+
} from './config.js';
|
|
5
|
+
export type { GroupSuiteConfig } from './config.js';
|
|
6
|
+
export { doCheckin, myPoints, pointsRank } from './checkin-lib.js';
|
|
7
|
+
export {
|
|
8
|
+
addKeyword,
|
|
9
|
+
listKeywords,
|
|
10
|
+
matchKeyword,
|
|
11
|
+
removeKeyword,
|
|
12
|
+
} from './keyword-store.js';
|
|
13
|
+
export {
|
|
14
|
+
getCheckinModel,
|
|
15
|
+
getStatsModel,
|
|
16
|
+
getTeachModel,
|
|
17
|
+
} from './db-store.js';
|
|
18
|
+
export {
|
|
19
|
+
createGroupSuiteRuntime,
|
|
20
|
+
groupSuiteRuntimeToken,
|
|
21
|
+
resolveGroupSuiteRuntime,
|
|
22
|
+
} from './runtime-state.js';
|
|
23
|
+
export type { GroupSuiteRuntime, PendingStatsIncrement } from './runtime-state.js';
|
|
24
|
+
export {
|
|
25
|
+
parseTeachPair,
|
|
26
|
+
teachAdd,
|
|
27
|
+
teachForget,
|
|
28
|
+
teachList,
|
|
29
|
+
tryTeachReply,
|
|
30
|
+
} from './teach-lib.js';
|
|
31
|
+
export {
|
|
32
|
+
flushStatsBuffer,
|
|
33
|
+
monthStartStr,
|
|
34
|
+
myStatsText,
|
|
35
|
+
queryStats,
|
|
36
|
+
recordMessage,
|
|
37
|
+
statsRankText,
|
|
38
|
+
weekStartStr,
|
|
39
|
+
} from './stats-lib.js';
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export function addKeyword(keyword: string, reply: string, store: Map<string, string>): void {
|
|
2
|
+
store.set(keyword, reply);
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function removeKeyword(keyword: string, store: Map<string, string>): boolean {
|
|
6
|
+
return store.delete(keyword);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function listKeywords(store: Map<string, string>): Array<[string, string]> {
|
|
10
|
+
return Array.from(store.entries());
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function matchKeyword(text: string, store: Map<string, string>): string | null {
|
|
14
|
+
for (const [keyword, reply] of store) {
|
|
15
|
+
if (text.includes(keyword)) return reply;
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory group-suite models used when no DatabaseHost is available.
|
|
3
|
+
*
|
|
4
|
+
* 模型表面与 `@zhin.js/plugin-runtime` 的 DatabaseHostModel 结构兼容
|
|
5
|
+
* (where 返回 PromiseLike,host 侧是链式 Selection),
|
|
6
|
+
* plugin.ts 可把 PluginDatabaseHost 直接当 GroupSuiteMemoryDb 用。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type GroupSuiteRow = Record<string, unknown>;
|
|
10
|
+
|
|
11
|
+
export interface GroupSuiteModel {
|
|
12
|
+
select: (...fields: string[]) => {
|
|
13
|
+
where: (query: Record<string, unknown>) => PromiseLike<GroupSuiteRow[]>;
|
|
14
|
+
then: <TResult1 = GroupSuiteRow[], TResult2 = never>(
|
|
15
|
+
onfulfilled?: ((value: GroupSuiteRow[]) => TResult1 | PromiseLike<TResult1>) | null,
|
|
16
|
+
onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,
|
|
17
|
+
) => Promise<TResult1 | TResult2>;
|
|
18
|
+
};
|
|
19
|
+
insert: (row: Record<string, unknown>) => Promise<unknown>;
|
|
20
|
+
delete: () => { where: (query: Record<string, unknown>) => Promise<unknown> };
|
|
21
|
+
update: (patch: Record<string, unknown>) => {
|
|
22
|
+
where: (query: Record<string, unknown>) => Promise<unknown>;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function createMemoryModel(): GroupSuiteModel {
|
|
27
|
+
const rows: GroupSuiteRow[] = [];
|
|
28
|
+
let nextId = 1;
|
|
29
|
+
|
|
30
|
+
function matches(row: Record<string, unknown>, query: Record<string, unknown>): boolean {
|
|
31
|
+
return Object.entries(query).every(([key, value]) => row[key] === value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function all(): GroupSuiteRow[] {
|
|
35
|
+
return rows.map((row) => ({ ...row }));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
select: () => {
|
|
40
|
+
const promise = Promise.resolve(all());
|
|
41
|
+
return {
|
|
42
|
+
where: async (query: Record<string, unknown>) =>
|
|
43
|
+
rows.filter((row) => matches(row, query)).map((row) => ({ ...row })),
|
|
44
|
+
then: (onfulfilled, onrejected) => promise.then(onfulfilled, onrejected),
|
|
45
|
+
};
|
|
46
|
+
},
|
|
47
|
+
insert: async (row: Record<string, unknown>) => {
|
|
48
|
+
const withId: GroupSuiteRow = { id: String(nextId++), ...row };
|
|
49
|
+
rows.push(withId);
|
|
50
|
+
return { ...withId };
|
|
51
|
+
},
|
|
52
|
+
delete: () => ({
|
|
53
|
+
where: async (query: Record<string, unknown>) => {
|
|
54
|
+
for (let i = rows.length - 1; i >= 0; i -= 1) {
|
|
55
|
+
if (matches(rows[i]!, query)) rows.splice(i, 1);
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
}),
|
|
59
|
+
update: (patch: Record<string, unknown>) => ({
|
|
60
|
+
where: async (query: Record<string, unknown>) => {
|
|
61
|
+
for (const row of rows) {
|
|
62
|
+
if (matches(row, query)) Object.assign(row, patch);
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
}),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface GroupSuiteMemoryDb {
|
|
70
|
+
models: {
|
|
71
|
+
get: (name: string) => GroupSuiteModel | undefined;
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export const CHECKIN_TABLE = 'checkin_records';
|
|
76
|
+
export const TEACH_TABLE = 'teach_qa';
|
|
77
|
+
export const STATS_TABLE = 'message_stats';
|
|
78
|
+
|
|
79
|
+
export function createInMemoryGroupSuiteDb(): GroupSuiteMemoryDb {
|
|
80
|
+
const models = new Map<string, GroupSuiteModel>([
|
|
81
|
+
[CHECKIN_TABLE, createMemoryModel()],
|
|
82
|
+
[TEACH_TABLE, createMemoryModel()],
|
|
83
|
+
[STATS_TABLE, createMemoryModel()],
|
|
84
|
+
]);
|
|
85
|
+
return {
|
|
86
|
+
models: {
|
|
87
|
+
get: (name: string) => models.get(name),
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { createToken, type Token } from 'zhin.js';
|
|
2
|
+
import type { GroupSuiteMemoryDb } from './memory-store.js';
|
|
3
|
+
|
|
4
|
+
export interface PendingStatsIncrement {
|
|
5
|
+
user_id: string;
|
|
6
|
+
user_name: string;
|
|
7
|
+
group_id: string;
|
|
8
|
+
date: string;
|
|
9
|
+
count: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** All mutable state owned by one group-suite plugin instance. */
|
|
13
|
+
export interface GroupSuiteRuntime {
|
|
14
|
+
readonly db: GroupSuiteMemoryDb;
|
|
15
|
+
readonly keywords: Map<string, string>;
|
|
16
|
+
readonly teachCooldowns: Map<string, number>;
|
|
17
|
+
readonly statsBuffer: Map<string, PendingStatsIncrement>;
|
|
18
|
+
readonly checkinChains: Map<string, Promise<unknown>>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const groupSuiteRuntimeToken = createToken<GroupSuiteRuntime>(
|
|
22
|
+
'zhin.group-suite.runtime',
|
|
23
|
+
'Owner-scoped Group Suite database and ephemeral state',
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
export function createGroupSuiteRuntime(db: GroupSuiteMemoryDb): GroupSuiteRuntime {
|
|
27
|
+
return {
|
|
28
|
+
db,
|
|
29
|
+
keywords: new Map(),
|
|
30
|
+
teachCooldowns: new Map(),
|
|
31
|
+
statsBuffer: new Map(),
|
|
32
|
+
checkinChains: new Map(),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function resolveGroupSuiteRuntime(context: {
|
|
37
|
+
readonly owner?: unknown;
|
|
38
|
+
use<T>(token: Token<T>): T;
|
|
39
|
+
}): GroupSuiteRuntime {
|
|
40
|
+
return context.use(groupSuiteRuntimeToken);
|
|
41
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export function todayStr(): string {
|
|
2
|
+
const d = new Date();
|
|
3
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export function yesterdayStr(): string {
|
|
7
|
+
const d = new Date();
|
|
8
|
+
d.setDate(d.getDate() - 1);
|
|
9
|
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function ts(): string {
|
|
13
|
+
return new Date().toISOString();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function randomInt(min: number, max: number): number {
|
|
17
|
+
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Runtime Message → group/global context */
|
|
21
|
+
export function resolveContextKey(input: {
|
|
22
|
+
conversation?: { readonly kind?: string; readonly id?: string };
|
|
23
|
+
metadata?: Readonly<Record<string, unknown>>;
|
|
24
|
+
}): { type: string; id: string } {
|
|
25
|
+
const meta = input.metadata ?? {};
|
|
26
|
+
const channelType = String(meta.type ?? meta.channelType ?? '');
|
|
27
|
+
if (channelType === 'group' || channelType === 'guild' || channelType === 'channel') {
|
|
28
|
+
return { type: 'group', id: String(meta.channelId ?? input.conversation?.id ?? '') };
|
|
29
|
+
}
|
|
30
|
+
if (input.conversation && channelType !== 'private') {
|
|
31
|
+
return { type: 'group', id: String(input.conversation.id ?? '') };
|
|
32
|
+
}
|
|
33
|
+
return { type: 'global', id: '' };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function resolveSender(input: {
|
|
37
|
+
sender?: { readonly id: string; readonly name?: string };
|
|
38
|
+
metadata?: Readonly<Record<string, unknown>>;
|
|
39
|
+
}): { id: string; name: string } {
|
|
40
|
+
const meta = input.metadata ?? {};
|
|
41
|
+
const id = input.sender?.id ?? String(meta.senderId ?? '');
|
|
42
|
+
const name = input.sender?.name ?? String(meta.senderName ?? meta.name ?? '用户');
|
|
43
|
+
return { id, name };
|
|
44
|
+
}
|