@nestim/koishi-plugin-qq-group-manager 1.1.4 → 1.2.0
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/CHANGELOG.md +299 -0
- package/lib/ai/engine.d.ts +74 -0
- package/lib/ai/engine.js +525 -0
- package/lib/ai/memory.d.ts +30 -0
- package/lib/ai/memory.js +89 -0
- package/lib/ai/prompt.d.ts +36 -0
- package/lib/ai/prompt.js +125 -0
- package/lib/ai/provider.d.ts +48 -0
- package/lib/ai/provider.js +194 -0
- package/lib/ai/state.d.ts +53 -0
- package/lib/ai/state.js +62 -0
- package/lib/ai/trigger.d.ts +28 -0
- package/lib/ai/trigger.js +41 -0
- package/lib/ai/vision.d.ts +15 -0
- package/lib/ai/vision.js +64 -0
- package/lib/core/names.d.ts +48 -0
- package/lib/core/names.js +144 -0
- package/lib/core/text.d.ts +47 -0
- package/lib/core/text.js +284 -0
- package/lib/index.d.ts +263 -54
- package/lib/index.js +19 -13
- package/lib/service.d.ts +574 -153
- package/lib/service.js +56 -1221
- package/package.json +18 -6
- package/readme.md +27 -13
- package/src/ai/engine.ts +568 -0
- package/src/ai/memory.ts +104 -0
- package/src/ai/prompt.ts +142 -0
- package/src/ai/provider.ts +221 -0
- package/src/ai/state.ts +91 -0
- package/src/ai/trigger.ts +60 -0
- package/src/ai/vision.ts +81 -0
- package/src/core/names.ts +158 -0
- package/src/core/text.ts +332 -0
- package/src/index.ts +186 -0
- package/src/service.js +3327 -0
- package/tsconfig.json +24 -0
- package/lib/commands.d.ts +0 -4
- package/lib/commands.js +0 -18
- package/lib/types.d.ts +0 -23
- package/lib/types.js +0 -2
package/src/service.js
ADDED
|
@@ -0,0 +1,3327 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.QQGroupManagerService = void 0;
|
|
7
|
+
const koishi_1 = require("koishi");
|
|
8
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
9
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
10
|
+
const { AiEngine } = require("./ai/engine");
|
|
11
|
+
let PLUGIN_VERSION = 'unknown';
|
|
12
|
+
try {
|
|
13
|
+
PLUGIN_VERSION = require('../package.json').version || 'unknown';
|
|
14
|
+
}
|
|
15
|
+
catch { /* ignore */ }
|
|
16
|
+
class QQGroupManagerService extends koishi_1.Service {
|
|
17
|
+
ctx;
|
|
18
|
+
config;
|
|
19
|
+
_logger;
|
|
20
|
+
unauthorizedMuteAttempts = new Map();
|
|
21
|
+
repeatStates = new Map();
|
|
22
|
+
pendingJoinRequests = new Map();
|
|
23
|
+
pendingJoinRequestFlags = new Map();
|
|
24
|
+
violationRecords = new Map();
|
|
25
|
+
_imageDataUrlCache = new Map();
|
|
26
|
+
/** 记忆库写锁:串行化「读整档→改→整写」,防止并发写互相覆盖 */
|
|
27
|
+
_memoryWriteLock = Promise.resolve();
|
|
28
|
+
/** 待审入群申请的落盘去抖定时器 */
|
|
29
|
+
_pendingJoinSaveTimer = null;
|
|
30
|
+
/** 待审单落盘串行化(防止 dispose 与去抖写同时进行) */
|
|
31
|
+
_pendingJoinWriteChain = Promise.resolve();
|
|
32
|
+
/** 待审单落盘 helper */
|
|
33
|
+
runPendingJoinWriteLocked(task) {
|
|
34
|
+
const run = this._pendingJoinWriteChain.then(() => task());
|
|
35
|
+
this._pendingJoinWriteChain = run.then(() => undefined, () => undefined);
|
|
36
|
+
return run;
|
|
37
|
+
}
|
|
38
|
+
/** 安全读取布尔配置(字段缺失/未定义时返回默认值) */
|
|
39
|
+
cfgBool(key, def) {
|
|
40
|
+
const v = this.config ? this.config[key] : undefined;
|
|
41
|
+
return typeof v === 'boolean' ? v : def;
|
|
42
|
+
}
|
|
43
|
+
/** 事件里的操作者 QQ(踢人事件用) */
|
|
44
|
+
eventOperatorId(session) {
|
|
45
|
+
return String((session && (session.operatorId || session.userId)) || '');
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* 把任意形态的 ID 归一成纯数字 QQ 号,便于比较。
|
|
49
|
+
* 兼容 'onebot:12345'、12345(number)、'12345'。
|
|
50
|
+
* selfId 取自 session.bot.selfId(session.selfId 在 Koishi 里通常不存在)。
|
|
51
|
+
*/
|
|
52
|
+
normalizeQqForCompare(value) {
|
|
53
|
+
const raw = String(value ?? '').trim();
|
|
54
|
+
if (!raw)
|
|
55
|
+
return '';
|
|
56
|
+
const tail = raw.includes(':') ? raw.slice(raw.lastIndexOf(':') + 1) : raw;
|
|
57
|
+
const digits = tail.replace(/\D/g, '');
|
|
58
|
+
return digits || '';
|
|
59
|
+
}
|
|
60
|
+
/** bot 自身 QQ */
|
|
61
|
+
selfQqForCompare(session) {
|
|
62
|
+
return this.normalizeQqForCompare(session?.bot?.selfId ?? session?.selfId);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* 求「被移出群聊的人」的 QQ,并标记身份是否可确证。
|
|
66
|
+
*
|
|
67
|
+
* 字段语义(Koishi onebot):
|
|
68
|
+
* - `session.targetId` 存在时,就是被移出的人,最可信;
|
|
69
|
+
* - `session.userId` 在移出事件里通常是**操作者**(bot 自己踢人时就是 bot),
|
|
70
|
+
* 只有没有 targetId 时才退而用它,且仅当它与操作者不同(=当时是被踢者)才可采信;
|
|
71
|
+
* - 永远排除 bot 自己。
|
|
72
|
+
*
|
|
73
|
+
* 返回 `{ id, certain }`。`certain=false` 表示只是猜测,宁可漏记也不误拉黑。
|
|
74
|
+
*/
|
|
75
|
+
resolveRemovedMemberId(session) {
|
|
76
|
+
const rawTarget = this.normalizeQqForCompare(session?.targetId);
|
|
77
|
+
if (rawTarget)
|
|
78
|
+
return { id: rawTarget, certain: true };
|
|
79
|
+
const id = this.normalizeQqForCompare(session?.userId);
|
|
80
|
+
if (!id)
|
|
81
|
+
return { id: '', certain: false };
|
|
82
|
+
const operator = this.normalizeQqForCompare(this.eventOperatorId(session));
|
|
83
|
+
if (id === operator && operator !== this.selfQqForCompare(session))
|
|
84
|
+
return { id: '', certain: false };
|
|
85
|
+
return { id, certain: false };
|
|
86
|
+
}
|
|
87
|
+
/** 踢人后记入黑名单(供自动踢人/手动踢人复用) */
|
|
88
|
+
async recordKickToBlacklist(session, qq) {
|
|
89
|
+
if (!this.cfgBool('banRecordOnKick', true))
|
|
90
|
+
return;
|
|
91
|
+
if (!this.resolveBlacklistEnabled(session))
|
|
92
|
+
return;
|
|
93
|
+
const id = String(qq || '').trim();
|
|
94
|
+
if (!/^\d{5,12}$/.test(id))
|
|
95
|
+
return;
|
|
96
|
+
const r = await this.addToBlacklist(session, id, '');
|
|
97
|
+
this._logger.info(`[ban] 踢出后${r.ok ? '已加入' : '未加入'}黑名单 qq=${id} | ${this.sessionTag(session)}`);
|
|
98
|
+
if (r.ok) {
|
|
99
|
+
try {
|
|
100
|
+
await session.send(this.styleText(`已将 ${id} 加入黑名单`));
|
|
101
|
+
}
|
|
102
|
+
catch { /* 忽略发送失败 */ }
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* 群成员被移出 → 记入本群黑名单。
|
|
107
|
+
*
|
|
108
|
+
* 只在「明确判定为被踢」时记录。历史 bug:原先写的是
|
|
109
|
+
* `if (session.subtype && session.subtype !== 'passive') return;`,
|
|
110
|
+
* subtype 缺失(undefined)时会继续往下走,把**主动退群**的人也当被踢记进黑名单,
|
|
111
|
+
* 并且会误用 session.userId(可能是踢人者/事件消费者)。
|
|
112
|
+
* 现在改为白名单式判定:只有 subtype === 'passive' 才处理。
|
|
113
|
+
*/
|
|
114
|
+
async handleMemberRemoved(session) {
|
|
115
|
+
if (!this.isPlatformAllowed(session.platform))
|
|
116
|
+
return;
|
|
117
|
+
if (!session.guildId)
|
|
118
|
+
return;
|
|
119
|
+
// 需求:只对「被踢」拉黑,主动退群永远不拉黑。
|
|
120
|
+
// 判定采用白名单:subtype 必须是明确的被动踢出语义。
|
|
121
|
+
// 主动退群(leave/quit)与缺失/未知值一律不记录——
|
|
122
|
+
// 宁可漏记被踢者(可由 [ban] 手动补),也绝不误拉黑主动退群的人。
|
|
123
|
+
const subtype = String(session.subtype ?? '').toLowerCase();
|
|
124
|
+
const kicked = subtype === 'passive' || subtype === 'kick';
|
|
125
|
+
if (!kicked) {
|
|
126
|
+
const who = this.normalizeQqForCompare(session.targetId || session.userId) || '未知';
|
|
127
|
+
const reason = subtype === 'leave' || subtype === 'quit'
|
|
128
|
+
? '主动退群'
|
|
129
|
+
: `subtype=${subtype || '缺失'},无法确证为被踢`;
|
|
130
|
+
this._logger.info(`[ban] 不拉黑:${reason} qq=${who} | ${this.sessionTag(session)}`);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const self = this.selfQqForCompare(session);
|
|
134
|
+
const operator = this.normalizeQqForCompare(this.eventOperatorId(session));
|
|
135
|
+
const resolved = this.resolveRemovedMemberId(session);
|
|
136
|
+
const qq = resolved.id;
|
|
137
|
+
// bot 自己被踢:不记录(原判断用 session.selfId,取不到值导致 bot 可能把自己拉黑)
|
|
138
|
+
if (qq && self && qq === self) {
|
|
139
|
+
this._logger.info(`[ban] bot 自身被移出群聊,不记黑名单 | ${this.sessionTag(session)}`);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
// 没能确证被踢者身份时,只记日志不写黑名单,避免误拉黑
|
|
143
|
+
if (!qq || (!resolved.certain && operator && operator !== self)) {
|
|
144
|
+
this._logger.warn(`[ban] 无法确证被踢者(targetId 缺失且 userId 落在操作者上),已跳过记录以免误拉黑 | ${this.sessionTag(session)}`);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
this._logger.info(`[ban] 检测到踢人事件 被踢者=${qq} 操作者=${operator || '未知'} 来源=${resolved.certain ? 'targetId' : 'userId'} | ${this.sessionTag(session)}`);
|
|
148
|
+
await this.recordKickToBlacklist(session, qq);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* 有人入群 → 比对黑名单,命中则踢出并提示。
|
|
152
|
+
*/
|
|
153
|
+
async handleMemberAdded(session) {
|
|
154
|
+
if (!this.isPlatformAllowed(session.platform))
|
|
155
|
+
return;
|
|
156
|
+
if (!session.guildId)
|
|
157
|
+
return;
|
|
158
|
+
if (!this.cfgBool('banKickOnJoin', true))
|
|
159
|
+
return;
|
|
160
|
+
if (!this.resolveBlacklistEnabled(session))
|
|
161
|
+
return;
|
|
162
|
+
const qq = String(session.targetId || session.userId || '').trim();
|
|
163
|
+
if (!/^\d{5,12}$/.test(qq))
|
|
164
|
+
return;
|
|
165
|
+
if (!(await this.isBlacklisted(session, qq)))
|
|
166
|
+
return;
|
|
167
|
+
|
|
168
|
+
const onebot = this.getOneBotApi(session);
|
|
169
|
+
const groupId = this.toGroupId(session);
|
|
170
|
+
if (!onebot?.setGroupKick || groupId == null) {
|
|
171
|
+
this._logger.warn(`[ban] 命中黑名单 qq=${qq} 但缺少踢人接口 | ${this.sessionTag(session)}`);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
await onebot.setGroupKick(groupId, Number(qq), true);
|
|
176
|
+
await session.send(this.styleText('已将黑名单成员移除群聊。'));
|
|
177
|
+
this._logger.info(`[ban] 入群命中黑名单,已踢出 qq=${qq} | ${this.sessionTag(session)}`);
|
|
178
|
+
}
|
|
179
|
+
catch (e) {
|
|
180
|
+
this._logger.warn(`[ban] 踢出黑名单成员失败 qq=${qq}: ${String(e)}`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
constructor(ctx, config) {
|
|
184
|
+
super(ctx, 'nestimQqGroupManager', true);
|
|
185
|
+
this.ctx = ctx;
|
|
186
|
+
this.config = config;
|
|
187
|
+
this._logger = ctx.logger('nestim-qq-group-manager');
|
|
188
|
+
this.ai = new AiEngine(this);
|
|
189
|
+
this._logger.info(`[qqgm] v${PLUGIN_VERSION} 已加载 | ai=single-call+pass | ctx=${this.config.aiContextWindow || 30}`);
|
|
190
|
+
ctx.on('message', (session) => this.handleGroupModeration(session));
|
|
191
|
+
ctx.on('guild-member-request', (session) => this.handleGuildMemberRequest(session));
|
|
192
|
+
// 被踢出群(含群主/管理员踢人)→ 记入本群黑名单
|
|
193
|
+
ctx.on('guild-member-deleted', (session) => {
|
|
194
|
+
this.handleMemberRemoved(session).catch((e) => this._logger.warn(`处理退群事件失败: ${String(e)}`));
|
|
195
|
+
});
|
|
196
|
+
// 入群 → 比对黑名单
|
|
197
|
+
ctx.on('guild-member-added', (session) => {
|
|
198
|
+
this.handleMemberAdded(session).catch((e) => this._logger.warn(`处理入群事件失败: ${String(e)}`));
|
|
199
|
+
});
|
|
200
|
+
// 启动即恢复上次未处理的待审入群申请(重启不再丢单),并清掉已过期编号
|
|
201
|
+
try {
|
|
202
|
+
this.loadPendingJoinRequests();
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
this._logger.warn(`[join-review] 恢复待审单失败: ${String(error)}`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
isPlatformAllowed(platform) {
|
|
209
|
+
if (!platform)
|
|
210
|
+
return false;
|
|
211
|
+
const list = Array.isArray(this.config && this.config.platformFilter)
|
|
212
|
+
? this.config.platformFilter
|
|
213
|
+
: ['onebot'];
|
|
214
|
+
return list.includes(platform);
|
|
215
|
+
}
|
|
216
|
+
sessionTag(session) {
|
|
217
|
+
if (!session)
|
|
218
|
+
return 'platform=unknown user=unknown guild=unknown';
|
|
219
|
+
return `platform=${session.platform ?? 'unknown'} user=${session.userId ?? 'unknown'} guild=${session.guildId ?? 'private'}`;
|
|
220
|
+
}
|
|
221
|
+
styleText(text) {
|
|
222
|
+
return this.config.responseStyle === 'meow' ? `喵~ ${text}` : text;
|
|
223
|
+
}
|
|
224
|
+
getMessageText(session) {
|
|
225
|
+
const raw = session?.content ?? '';
|
|
226
|
+
return raw
|
|
227
|
+
.replace(/\[CQ:[^\]]+\]/g, ' ')
|
|
228
|
+
.replace(/<[^>]+>/g, ' ')
|
|
229
|
+
.replace(/\s+/g, ' ')
|
|
230
|
+
.trim();
|
|
231
|
+
}
|
|
232
|
+
aiGroupKey(session) {
|
|
233
|
+
if (!session?.guildId)
|
|
234
|
+
return '';
|
|
235
|
+
return `${session.platform ?? 'unknown'}:${session.guildId}`;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* 统一的三态开关解析:单个群设置优先,未设置时跟随全局。
|
|
239
|
+
*
|
|
240
|
+
* 规则(这是本插件的核心约定):
|
|
241
|
+
* 1) 单个群**显式设置**了该值 → 无条件以它为准,**不受全局开关影响**
|
|
242
|
+
* (所以全局关着,某个群单独打开也能生效)
|
|
243
|
+
* 2) 单个群**未设置**(undefined)→ 跟随全局
|
|
244
|
+
*
|
|
245
|
+
* 注意:用 `!== undefined` 判断,这样 `false` 也算"已设置",
|
|
246
|
+
* 不会被 `??` 或 `||` 误判为"未设置"。
|
|
247
|
+
*/
|
|
248
|
+
resolveSwitch(rule, ruleKey, globalKey) {
|
|
249
|
+
if (rule && rule[ruleKey] !== undefined)
|
|
250
|
+
return rule[ruleKey];
|
|
251
|
+
return this.config[globalKey];
|
|
252
|
+
}
|
|
253
|
+
extractAiMessageText(session) {
|
|
254
|
+
const text = this.getMessageText(session)
|
|
255
|
+
.replace(/\s+/g, ' ')
|
|
256
|
+
.trim();
|
|
257
|
+
return text;
|
|
258
|
+
}
|
|
259
|
+
// ============ 黑名单(按群独立存储:banMember_<群号>.md) ============
|
|
260
|
+
/**
|
|
261
|
+
* 解析本群黑名单文件路径。
|
|
262
|
+
* 文件名由模板推导:banMember.md -> banMember_<群号>.md
|
|
263
|
+
* 这样每个群一份独立文件,可在 Explorer 中分别查看/编辑。
|
|
264
|
+
*/
|
|
265
|
+
getBlacklistFilePath(session) {
|
|
266
|
+
const base = (this.ctx && this.ctx.baseDir) || process.cwd();
|
|
267
|
+
const groupId = this.normalizeGuildId(session && session.guildId) || 'unknown';
|
|
268
|
+
const tpl = (this.config.blacklistFileName || 'banMember.md').trim();
|
|
269
|
+
const dot = tpl.lastIndexOf('.');
|
|
270
|
+
const baseName = dot > 0 ? tpl.slice(0, dot) : tpl;
|
|
271
|
+
const ext = dot > 0 ? tpl.slice(dot) : '';
|
|
272
|
+
return node_path_1.default.resolve(base, `${baseName}_${groupId}${ext}`);
|
|
273
|
+
}
|
|
274
|
+
async readBlacklistFile(session) {
|
|
275
|
+
try {
|
|
276
|
+
return await node_fs_1.default.promises.readFile(this.getBlacklistFilePath(session), 'utf8');
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
return '';
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
async writeBlacklistFile(session, content) {
|
|
283
|
+
await node_fs_1.default.promises.writeFile(this.getBlacklistFilePath(session), String(content), 'utf8');
|
|
284
|
+
}
|
|
285
|
+
/** 解析 banMember.md -> [{qq, name, at}],按 QQ 去重 */
|
|
286
|
+
parseBlacklist(content) {
|
|
287
|
+
const out = [];
|
|
288
|
+
const seen = new Set();
|
|
289
|
+
const lines = String(content || '').split(/\r?\n/);
|
|
290
|
+
let cur = null;
|
|
291
|
+
const flush = () => {
|
|
292
|
+
if (cur && cur.qq && !seen.has(cur.qq)) {
|
|
293
|
+
seen.add(cur.qq);
|
|
294
|
+
out.push(cur);
|
|
295
|
+
}
|
|
296
|
+
cur = null;
|
|
297
|
+
};
|
|
298
|
+
for (const line of lines) {
|
|
299
|
+
const m = line.match(/^##\s*(\d{5,12})\s*(?:·\s*(.*))?\s*$/);
|
|
300
|
+
if (m) {
|
|
301
|
+
flush();
|
|
302
|
+
cur = { qq: m[1], name: (m[2] || '').trim(), at: '' };
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (!cur)
|
|
306
|
+
continue;
|
|
307
|
+
const t = line.match(/^-\s*加入时间\s*[::]\s*(.*)$/);
|
|
308
|
+
if (t)
|
|
309
|
+
cur.at = t[1].trim();
|
|
310
|
+
}
|
|
311
|
+
flush();
|
|
312
|
+
return out;
|
|
313
|
+
}
|
|
314
|
+
/** 序列化(保持人类可读,便于在 Explorer 里直接改) */
|
|
315
|
+
serializeBlacklist(entries, groupId) {
|
|
316
|
+
const lines = [
|
|
317
|
+
`# 黑名单成员(群 ${groupId || '未知'})`,
|
|
318
|
+
'',
|
|
319
|
+
'> 每个条目以 `---` 分隔。格式:`## QQ号 · 备注`,`- 加入时间:` 记录时间。',
|
|
320
|
+
'> 本文件仅对应该群,可直接用控制台左侧「探索器 Explorer」编辑。',
|
|
321
|
+
'',
|
|
322
|
+
];
|
|
323
|
+
for (const e of entries) {
|
|
324
|
+
lines.push('---', '', `## ${e.qq}${e.name ? ' · ' + e.name : ''}`, `- 加入时间: ${e.at || ''}`, '');
|
|
325
|
+
}
|
|
326
|
+
return lines.join('\n');
|
|
327
|
+
}
|
|
328
|
+
async getBlacklist(session) {
|
|
329
|
+
return this.parseBlacklist(await this.readBlacklistFile(session));
|
|
330
|
+
}
|
|
331
|
+
async isBlacklisted(session, qq) {
|
|
332
|
+
const id = String(qq ?? '').trim();
|
|
333
|
+
if (!id)
|
|
334
|
+
return false;
|
|
335
|
+
return (await this.getBlacklist(session)).some((e) => e.qq === id);
|
|
336
|
+
}
|
|
337
|
+
/** 加入本群黑名单。返回 { ok, message } */
|
|
338
|
+
async addToBlacklist(session, qq, name) {
|
|
339
|
+
const id = String(qq ?? '').trim();
|
|
340
|
+
if (!/^\d{5,12}$/.test(id))
|
|
341
|
+
return { ok: false, message: 'QQ 号格式不正确。' };
|
|
342
|
+
const list = await this.getBlacklist(session);
|
|
343
|
+
if (list.some((e) => e.qq === id))
|
|
344
|
+
return { ok: false, message: '该成员已在黑名单中。' };
|
|
345
|
+
const stamp = new Date().toLocaleString('zh-CN', { hour12: false });
|
|
346
|
+
list.push({ qq: id, name: String(name ?? '').trim(), at: stamp });
|
|
347
|
+
await this.writeBlacklistFile(session, this.serializeBlacklist(list, this.normalizeGuildId(session && session.guildId)));
|
|
348
|
+
return { ok: true, message: `已将 ${id} 加入黑名单` };
|
|
349
|
+
}
|
|
350
|
+
/** 从本群黑名单移除。返回 { ok, message } */
|
|
351
|
+
async removeFromBlacklist(session, qq) {
|
|
352
|
+
const id = String(qq ?? '').trim();
|
|
353
|
+
const list = await this.getBlacklist(session);
|
|
354
|
+
const next = list.filter((e) => e.qq !== id);
|
|
355
|
+
if (next.length === list.length)
|
|
356
|
+
return { ok: false, message: `删除失败,未找到人员 ${id}` };
|
|
357
|
+
await this.writeBlacklistFile(session, this.serializeBlacklist(next, this.normalizeGuildId(session && session.guildId)));
|
|
358
|
+
return { ok: true, message: `已将 ${id} 移出黑名单` };
|
|
359
|
+
}
|
|
360
|
+
/** 该群是否启用黑名单(单群设置优先,未设置跟随全局) */
|
|
361
|
+
resolveBlacklistEnabled(session) {
|
|
362
|
+
const currentGuild = this.normalizeGuildId(session && session.guildId);
|
|
363
|
+
const rule = this.config.groupRules.find((item) => this.normalizeGuildId(item.guildId) === currentGuild);
|
|
364
|
+
return this.resolveSwitch(rule, 'blacklistEnabled', 'enableBlacklist');
|
|
365
|
+
}
|
|
366
|
+
/** 取群成员信息(用于校验"必须是群内人员"并拿到昵称) */
|
|
367
|
+
/**
|
|
368
|
+
* 提取本条消息中 @ 到的目标 QQ 号(@ 可代替 QQ 号作为指令目标)。
|
|
369
|
+
* 支持三种来源:CQ 码 [CQ:at,qq=xxx]、Koishi 的 at 元素、content 里的 <at id="xxx"/>。
|
|
370
|
+
* 排除 @全体成员 与 @机器人自身。
|
|
371
|
+
*/
|
|
372
|
+
extractMentionedTargets(session) {
|
|
373
|
+
const out = [];
|
|
374
|
+
const push = (v) => {
|
|
375
|
+
const s = String(v == null ? '' : v).trim();
|
|
376
|
+
if (!s || s === 'all' || s === '0')
|
|
377
|
+
return;
|
|
378
|
+
const self = String(session?.bot?.selfId ?? '');
|
|
379
|
+
if (self && s === self)
|
|
380
|
+
return;
|
|
381
|
+
if (!out.includes(s))
|
|
382
|
+
out.push(s);
|
|
383
|
+
};
|
|
384
|
+
const content = session?.content || '';
|
|
385
|
+
// CQ 码
|
|
386
|
+
for (const chunk of content.match(/\[CQ:at,[^\]]*\]/gi) || []) {
|
|
387
|
+
const m = chunk.match(/(?:qq|id)=([^,\]]+)/i);
|
|
388
|
+
if (m)
|
|
389
|
+
push(decodeURIComponent(m[1]));
|
|
390
|
+
}
|
|
391
|
+
// Koishi at 元素
|
|
392
|
+
for (const el of session?.elements || []) {
|
|
393
|
+
if (String(el?.type || '').toLowerCase() !== 'at')
|
|
394
|
+
continue;
|
|
395
|
+
push(el.attrs?.qq ?? el.attrs?.id ?? el.qq ?? el.id);
|
|
396
|
+
}
|
|
397
|
+
// HTML 形式
|
|
398
|
+
for (const tag of content.match(/<at\b[^>]*\/?>/gi) || []) {
|
|
399
|
+
const m = tag.match(/(?:id|qq)\s*=\s*"([^"]*)"/i) || tag.match(/(?:id|qq)\s*=\s*'([^']*)'/i);
|
|
400
|
+
if (m)
|
|
401
|
+
push(m[1]);
|
|
402
|
+
}
|
|
403
|
+
return out;
|
|
404
|
+
}
|
|
405
|
+
async fetchGroupMember(session, qq) {
|
|
406
|
+
const onebot = this.getOneBotApi(session);
|
|
407
|
+
const groupId = this.toGroupId(session);
|
|
408
|
+
const uid = Number(qq);
|
|
409
|
+
if (!onebot?.getGroupMemberInfo || groupId == null || !Number.isFinite(uid))
|
|
410
|
+
return null;
|
|
411
|
+
try {
|
|
412
|
+
const info = await onebot.getGroupMemberInfo(groupId, uid, true);
|
|
413
|
+
if (!info)
|
|
414
|
+
return null;
|
|
415
|
+
return {
|
|
416
|
+
qq: String(uid),
|
|
417
|
+
name: String(info.card || info.nickname || info.nick || '').trim(),
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
catch {
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
// ============ 记忆库 ============
|
|
425
|
+
getMemoryFilePath() {
|
|
426
|
+
const base = (this.ctx && this.ctx.baseDir) || process.cwd();
|
|
427
|
+
const name = (this.config.memoryFileName || 'Memory.md').trim();
|
|
428
|
+
return node_path_1.default.resolve(base, name);
|
|
429
|
+
}
|
|
430
|
+
async readMemoryFile() {
|
|
431
|
+
const p = this.getMemoryFilePath();
|
|
432
|
+
try {
|
|
433
|
+
return await node_fs_1.default.promises.readFile(p, 'utf8');
|
|
434
|
+
}
|
|
435
|
+
catch {
|
|
436
|
+
return '';
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
async writeMemoryFile(content) {
|
|
440
|
+
const p = this.getMemoryFilePath();
|
|
441
|
+
await node_fs_1.default.promises.writeFile(p, String(content), 'utf8');
|
|
442
|
+
}
|
|
443
|
+
extractMemoryBlocks(content) {
|
|
444
|
+
return String(content)
|
|
445
|
+
.split(/\r?\n---\r?\n/)
|
|
446
|
+
.map((b) => b.trim())
|
|
447
|
+
.filter(Boolean);
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* 记忆库写互斥:把「读整档 → 改 → 整写」串行化。
|
|
451
|
+
* 并发保存时后一次读到的才是前一次写完的内容,不会互相覆盖丢条目。
|
|
452
|
+
* 记忆属于低频写,一把 promise 队列足够,无需文件锁。
|
|
453
|
+
*/
|
|
454
|
+
runMemoryWriteLocked(task) {
|
|
455
|
+
const run = this._memoryWriteLock.then(() => task());
|
|
456
|
+
// 锁链本身永不 reject,失败只回传给调用方,避免一次失败卡死后续写入
|
|
457
|
+
this._memoryWriteLock = run.then(() => undefined, () => undefined);
|
|
458
|
+
return run;
|
|
459
|
+
}
|
|
460
|
+
async saveMemoryToFile(userId, content) {
|
|
461
|
+
return this.runMemoryWriteLocked(async () => {
|
|
462
|
+
const now = new Date();
|
|
463
|
+
const stamp = now.toLocaleString('zh-CN', { hour12: false });
|
|
464
|
+
const block = `## ${stamp} · 用户 ${userId || 'unknown'}\n${String(content).trim()}`;
|
|
465
|
+
const existing = (await this.readMemoryFile()).trim();
|
|
466
|
+
const next = existing ? `${existing}\n\n---\n\n${block}\n` : `${block}\n`;
|
|
467
|
+
await this.writeMemoryFile(next);
|
|
468
|
+
return block;
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
async searchMemory(keyword, limit = 8) {
|
|
472
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
|
|
473
|
+
const kw = String(keyword || '').trim();
|
|
474
|
+
if (!kw)
|
|
475
|
+
return blocks.slice(-limit);
|
|
476
|
+
return blocks.filter((b) => b.includes(kw)).slice(-limit);
|
|
477
|
+
}
|
|
478
|
+
/** 按关键词删除记忆条目(含该关键词的整条记忆块)。返回 { ok, removed, message } */
|
|
479
|
+
async deleteMemoryByKeyword(keyword) {
|
|
480
|
+
const kw = String(keyword ?? '').trim();
|
|
481
|
+
if (!kw)
|
|
482
|
+
return { ok: false, removed: 0, message: '关键词为空。' };
|
|
483
|
+
// 同样走写锁:删除与保存并发时不会互相覆盖
|
|
484
|
+
return this.runMemoryWriteLocked(async () => {
|
|
485
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
|
|
486
|
+
if (!blocks.length)
|
|
487
|
+
return { ok: false, removed: 0, message: '记忆库为空。' };
|
|
488
|
+
const kept = blocks.filter((b) => !b.includes(kw));
|
|
489
|
+
const removed = blocks.length - kept.length;
|
|
490
|
+
if (!removed)
|
|
491
|
+
return { ok: false, removed: 0, message: `未找到包含「${kw}」的记忆` };
|
|
492
|
+
const content = kept.length ? kept.join('\n\n---\n\n') + '\n' : '';
|
|
493
|
+
await this.writeMemoryFile(content);
|
|
494
|
+
return { ok: true, removed, message: `已删除 ${removed} 条` };
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
getDisplayName(session) {
|
|
498
|
+
// 群名片优先(author.nick = sender.card),其次 QQ 昵称,最后 QQ 号;
|
|
499
|
+
// author.nickname 在 onebot 适配器里恒为 undefined,不再作为一级。
|
|
500
|
+
return session.author?.nick?.trim()
|
|
501
|
+
|| session.author?.name?.trim()
|
|
502
|
+
|| session.username?.trim()
|
|
503
|
+
|| session.userId
|
|
504
|
+
|| 'unknown';
|
|
505
|
+
}
|
|
506
|
+
splitAiReplyParts(text) {
|
|
507
|
+
const source = text.trim();
|
|
508
|
+
if (!source)
|
|
509
|
+
return [];
|
|
510
|
+
const chunks = source
|
|
511
|
+
.split(/\n+/g)
|
|
512
|
+
.flatMap((line) => line.match(/[^。!?!?;;]+[。!?!?;;]?/g) ?? [line])
|
|
513
|
+
.map((item) => item.trim().replace(/[。;;]+$/g, '').trim())
|
|
514
|
+
.filter(Boolean);
|
|
515
|
+
if (!chunks.length)
|
|
516
|
+
return [source];
|
|
517
|
+
const maxParts = 4;
|
|
518
|
+
if (chunks.length <= maxParts)
|
|
519
|
+
return chunks;
|
|
520
|
+
return [
|
|
521
|
+
...chunks.slice(0, maxParts - 1),
|
|
522
|
+
chunks.slice(maxParts - 1).join(' '),
|
|
523
|
+
];
|
|
524
|
+
}
|
|
525
|
+
async waitHumanLikeDelay(minMs = 420, maxMs = 1100) {
|
|
526
|
+
const lower = Math.max(0, minMs);
|
|
527
|
+
const upper = Math.max(lower, maxMs);
|
|
528
|
+
const delay = Math.floor(Math.random() * (upper - lower + 1)) + lower;
|
|
529
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
530
|
+
}
|
|
531
|
+
extractImageUrls(session) {
|
|
532
|
+
if (!this.config.aiEnableImageRecognition)
|
|
533
|
+
return [];
|
|
534
|
+
const maxCount = Math.max(0, this.config.aiImageMaxCount || 0);
|
|
535
|
+
if (!maxCount)
|
|
536
|
+
return [];
|
|
537
|
+
return this.extractMessageImageUrls(session, maxCount);
|
|
538
|
+
}
|
|
539
|
+
isImageReference(value) {
|
|
540
|
+
if (!value || typeof value !== 'string')
|
|
541
|
+
return false;
|
|
542
|
+
const v = value.trim();
|
|
543
|
+
if (!v)
|
|
544
|
+
return false;
|
|
545
|
+
if (/^https?:\/\//i.test(v))
|
|
546
|
+
return true;
|
|
547
|
+
if (/^data:image\//i.test(v))
|
|
548
|
+
return true;
|
|
549
|
+
if (/^base64:\/\//i.test(v))
|
|
550
|
+
return true;
|
|
551
|
+
if (/^file:\/\//i.test(v))
|
|
552
|
+
return true;
|
|
553
|
+
if (/^[A-Za-z]:[\\/]/.test(v) || v.startsWith('/'))
|
|
554
|
+
return true;
|
|
555
|
+
// NapCat 常见:纯文件名 / hash.jpg
|
|
556
|
+
if (/^[0-9A-Fa-f]{16,}\.[A-Za-z0-9]{2,5}$/.test(v))
|
|
557
|
+
return true;
|
|
558
|
+
return false;
|
|
559
|
+
}
|
|
560
|
+
extractImageCandidates(session, maxCount = 6) {
|
|
561
|
+
const out = [];
|
|
562
|
+
for (const item of this.extractImageElements(session)) {
|
|
563
|
+
for (const candidate of [item.url, item.ref]) {
|
|
564
|
+
if (!this.isImageReference(candidate))
|
|
565
|
+
continue;
|
|
566
|
+
if (!out.includes(candidate))
|
|
567
|
+
out.push(candidate);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return out.slice(0, Math.max(1, maxCount));
|
|
571
|
+
}
|
|
572
|
+
detectImageMime(buffer, fallback = 'image/jpeg') {
|
|
573
|
+
if (!buffer || buffer.length < 12)
|
|
574
|
+
return fallback;
|
|
575
|
+
const b = buffer;
|
|
576
|
+
if (b[0] === 0xFF && b[1] === 0xD8 && b[2] === 0xFF)
|
|
577
|
+
return 'image/jpeg';
|
|
578
|
+
if (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4E && b[3] === 0x47)
|
|
579
|
+
return 'image/png';
|
|
580
|
+
if (b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46)
|
|
581
|
+
return 'image/gif';
|
|
582
|
+
if (b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46
|
|
583
|
+
&& b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50)
|
|
584
|
+
return 'image/webp';
|
|
585
|
+
if (b[0] === 0x42 && b[1] === 0x4D)
|
|
586
|
+
return 'image/bmp';
|
|
587
|
+
return fallback;
|
|
588
|
+
}
|
|
589
|
+
async resolveImageReferenceToDataUrl(ref, session) {
|
|
590
|
+
const value = String(ref ?? '').trim();
|
|
591
|
+
if (!value)
|
|
592
|
+
return '';
|
|
593
|
+
// 已经是 data URL,直接沿用
|
|
594
|
+
if (/^data:image\//i.test(value)) {
|
|
595
|
+
return value.length > 64 * 1024 * 1024 ? '' : value;
|
|
596
|
+
}
|
|
597
|
+
try {
|
|
598
|
+
let finalUrl = value;
|
|
599
|
+
let headers = {};
|
|
600
|
+
if (/^base64:\/\//i.test(value)) {
|
|
601
|
+
// Koishi/OneBot 常见形态:base64://<裸base64>
|
|
602
|
+
const raw = value.replace(/^base64:\/\//i, '');
|
|
603
|
+
const buffer = Buffer.from(raw, 'base64');
|
|
604
|
+
if (!buffer.length)
|
|
605
|
+
return '';
|
|
606
|
+
return `data:${this.detectImageMime(buffer)};base64,${buffer.toString('base64')}`;
|
|
607
|
+
}
|
|
608
|
+
if (/^https?:\/\//i.test(value)) {
|
|
609
|
+
// OneBot 的 get_image 能把 file_id 换成可访问链接
|
|
610
|
+
const direct = await this.fetchImageAsDataUrl(value, headers);
|
|
611
|
+
if (direct)
|
|
612
|
+
return direct;
|
|
613
|
+
return '';
|
|
614
|
+
}
|
|
615
|
+
// 其余形态(file_id / 文件名 / 本地路径)交给 get_image 解析
|
|
616
|
+
const onebot = this.getOneBotApi(session);
|
|
617
|
+
if (onebot?.getImage) {
|
|
618
|
+
const resolved = await onebot.getImage(value).catch(() => null);
|
|
619
|
+
const url = resolved?.url || resolved?.file || resolved?.filename || '';
|
|
620
|
+
const isLocal = url && !/^https?:\/\//i.test(url) && !/^data:/i.test(url);
|
|
621
|
+
if (isLocal) {
|
|
622
|
+
try {
|
|
623
|
+
finalUrl = String(url).replace(/^file:\/\//i, '');
|
|
624
|
+
}
|
|
625
|
+
catch {
|
|
626
|
+
finalUrl = '';
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
else if (url) {
|
|
630
|
+
const dataUrl = await this.fetchImageAsDataUrl(url, headers);
|
|
631
|
+
if (dataUrl)
|
|
632
|
+
return dataUrl;
|
|
633
|
+
}
|
|
634
|
+
if (finalUrl && finalUrl !== value && !/^https?:\/\//i.test(finalUrl)) {
|
|
635
|
+
try {
|
|
636
|
+
const buffer = await node_fs_1.default.promises.readFile(finalUrl);
|
|
637
|
+
if (buffer.length)
|
|
638
|
+
return `data:${this.detectImageMime(buffer)};base64,${buffer.toString('base64')}`;
|
|
639
|
+
}
|
|
640
|
+
catch {
|
|
641
|
+
return '';
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
if (/^file:\/\//i.test(value) || /^[A-Za-z]:[\\/]/.test(value) || value.startsWith('/')) {
|
|
646
|
+
const localPath = value.replace(/^file:\/\//i, '');
|
|
647
|
+
const buffer = await node_fs_1.default.promises.readFile(localPath).catch(() => null);
|
|
648
|
+
if (buffer?.length)
|
|
649
|
+
return `data:${this.detectImageMime(buffer)};base64,${buffer.toString('base64')}`;
|
|
650
|
+
}
|
|
651
|
+
return '';
|
|
652
|
+
}
|
|
653
|
+
catch (error) {
|
|
654
|
+
this._logger.warn(`[img-fetch] resolve failed: ${String(error)} ref=${value.slice(0, 120)} | ${this.sessionTag(session)}`);
|
|
655
|
+
return '';
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
async fetchImageAsDataUrl(url, extraHeaders = {}) {
|
|
659
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
660
|
+
const cached = this._imageDataUrlCache?.get(url);
|
|
661
|
+
if (cached !== undefined)
|
|
662
|
+
return cached;
|
|
663
|
+
if (!this._imageDataUrlCache)
|
|
664
|
+
this._imageDataUrlCache = new Map();
|
|
665
|
+
const controller = new AbortController();
|
|
666
|
+
const timeout = setTimeout(() => controller.abort(), 12_000);
|
|
667
|
+
try {
|
|
668
|
+
const response = await fetch(url, {
|
|
669
|
+
headers: {
|
|
670
|
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) NapCat/QQ',
|
|
671
|
+
Accept: 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
|
|
672
|
+
...extraHeaders,
|
|
673
|
+
},
|
|
674
|
+
redirect: 'follow',
|
|
675
|
+
signal: controller.signal,
|
|
676
|
+
});
|
|
677
|
+
if (!response.ok) {
|
|
678
|
+
this._logger.warn(`[img-fetch] http ${response.status} url=${url.slice(0, 140)}`);
|
|
679
|
+
this.rememberImageDataUrl(url, '');
|
|
680
|
+
return '';
|
|
681
|
+
}
|
|
682
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
683
|
+
const buffer = Buffer.from(arrayBuffer);
|
|
684
|
+
if (!buffer.length) {
|
|
685
|
+
this.rememberImageDataUrl(url, '');
|
|
686
|
+
return '';
|
|
687
|
+
}
|
|
688
|
+
if (buffer.length > MAX_BYTES) {
|
|
689
|
+
this._logger.warn(`[img-fetch] image too large (${buffer.length} bytes) url=${url.slice(0, 140)}`);
|
|
690
|
+
this.rememberImageDataUrl(url, '');
|
|
691
|
+
return '';
|
|
692
|
+
}
|
|
693
|
+
const mime = this.detectImageMime(buffer, response.headers.get('content-type')?.split(';')[0] || 'image/jpeg');
|
|
694
|
+
const dataUrl = `data:${mime};base64,${buffer.toString('base64')}`;
|
|
695
|
+
this.rememberImageDataUrl(url, dataUrl);
|
|
696
|
+
return dataUrl;
|
|
697
|
+
}
|
|
698
|
+
catch (error) {
|
|
699
|
+
this._logger.warn(`[img-fetch] download failed: ${String(error)} url=${url.slice(0, 140)}`);
|
|
700
|
+
this.rememberImageDataUrl(url, '');
|
|
701
|
+
return '';
|
|
702
|
+
}
|
|
703
|
+
finally {
|
|
704
|
+
clearTimeout(timeout);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
rememberImageDataUrl(url, dataUrl) {
|
|
708
|
+
if (!this._imageDataUrlCache)
|
|
709
|
+
this._imageDataUrlCache = new Map();
|
|
710
|
+
if (this._imageDataUrlCache.size > 64)
|
|
711
|
+
this._imageDataUrlCache.clear();
|
|
712
|
+
this._imageDataUrlCache.set(url, dataUrl);
|
|
713
|
+
}
|
|
714
|
+
async resolveImagesForModel(refs, session, maxCount) {
|
|
715
|
+
const limit = Math.max(1, maxCount || 1);
|
|
716
|
+
const out = [];
|
|
717
|
+
for (const ref of refs) {
|
|
718
|
+
if (out.length >= limit)
|
|
719
|
+
break;
|
|
720
|
+
const candidates = Array.isArray(ref) ? ref : [ref];
|
|
721
|
+
for (const candidate of candidates) {
|
|
722
|
+
const dataUrl = await this.resolveImageReferenceToDataUrl(candidate, session);
|
|
723
|
+
if (dataUrl) {
|
|
724
|
+
out.push(dataUrl);
|
|
725
|
+
break;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
return out;
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* 把 extractImageElements 的结构化条目解析为可直接喂给模型的 data URL。
|
|
733
|
+
* 每个条目会依次尝试:原始 URL -> 本地文件名(走 OneBot get_image)。
|
|
734
|
+
*/
|
|
735
|
+
async resolveVisualItemsForModel(items, session, maxCount) {
|
|
736
|
+
const limit = Math.max(1, maxCount || 1);
|
|
737
|
+
const out = [];
|
|
738
|
+
for (const item of items) {
|
|
739
|
+
if (out.length >= limit)
|
|
740
|
+
break;
|
|
741
|
+
const attempts = [];
|
|
742
|
+
if (item.url)
|
|
743
|
+
attempts.push(item.url);
|
|
744
|
+
if (item.ref && item.ref !== item.url)
|
|
745
|
+
attempts.push(item.ref);
|
|
746
|
+
for (const candidate of attempts) {
|
|
747
|
+
const dataUrl = await this.resolveImageReferenceToDataUrl(candidate, session);
|
|
748
|
+
if (dataUrl) {
|
|
749
|
+
out.push(dataUrl);
|
|
750
|
+
break;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
return out;
|
|
755
|
+
}
|
|
756
|
+
isImageSendableUrl(value) {
|
|
757
|
+
if (!value || typeof value !== 'string')
|
|
758
|
+
return false;
|
|
759
|
+
const v = value.trim();
|
|
760
|
+
if (/^https?:\/\//i.test(v))
|
|
761
|
+
return true;
|
|
762
|
+
if (/^data:image\//i.test(v))
|
|
763
|
+
return true;
|
|
764
|
+
return false;
|
|
765
|
+
}
|
|
766
|
+
decodeHtmlEntities(value) {
|
|
767
|
+
if (typeof value !== 'string' || !value)
|
|
768
|
+
return '';
|
|
769
|
+
return value
|
|
770
|
+
.replace(/&/gi, '&')
|
|
771
|
+
.replace(/</gi, '<')
|
|
772
|
+
.replace(/>/gi, '>')
|
|
773
|
+
.replace(/"/gi, '"')
|
|
774
|
+
.replace(/�?39;/g, "'")
|
|
775
|
+
.replace(/'/gi, "'")
|
|
776
|
+
.replace(///gi, '/')
|
|
777
|
+
.replace(/�?38;/g, '&');
|
|
778
|
+
}
|
|
779
|
+
parseHtmlTagParams(tag) {
|
|
780
|
+
const params = {};
|
|
781
|
+
const re = /([a-zA-Z][\w-]*)\s*=\s*"([^"]*)"|([a-zA-Z][\w-]*)\s*=\s*'([^']*)'/g;
|
|
782
|
+
let m;
|
|
783
|
+
while ((m = re.exec(tag))) {
|
|
784
|
+
const key = (m[1] || m[3] || '').toLowerCase();
|
|
785
|
+
const raw = m[2] !== undefined ? m[2] : m[4];
|
|
786
|
+
if (!key)
|
|
787
|
+
continue;
|
|
788
|
+
params[key.replace(/-/g, '')] = this.decodeHtmlEntities(raw);
|
|
789
|
+
}
|
|
790
|
+
return params;
|
|
791
|
+
}
|
|
792
|
+
extractImageElements(session) {
|
|
793
|
+
const items = [];
|
|
794
|
+
const seen = new Set();
|
|
795
|
+
const push = (url, ref, sticker) => {
|
|
796
|
+
const u = this.decodeHtmlEntities(url || '').trim();
|
|
797
|
+
const r = (ref || '').trim();
|
|
798
|
+
const key = u || r;
|
|
799
|
+
if (!key || seen.has(key))
|
|
800
|
+
return;
|
|
801
|
+
seen.add(key);
|
|
802
|
+
items.push({
|
|
803
|
+
url: u,
|
|
804
|
+
ref: r,
|
|
805
|
+
sticker: !!sticker,
|
|
806
|
+
sendable: this.isImageSendableUrl(u),
|
|
807
|
+
});
|
|
808
|
+
};
|
|
809
|
+
const isStickerParams = (params) => {
|
|
810
|
+
const sub = String(params.subtype ?? params.subType ?? params['sub-type'] ?? '');
|
|
811
|
+
const summary = String(params.summary ?? '');
|
|
812
|
+
return sub === '1' || /动画表情|表情|贴纸|sticker|mface/i.test(summary);
|
|
813
|
+
};
|
|
814
|
+
// 1) CQ 码形态
|
|
815
|
+
const content = session?.content ?? '';
|
|
816
|
+
for (const chunk of content.match(/\[CQ:image,[^\]]*\]/gi) ?? []) {
|
|
817
|
+
const params = this.parseCqImageParams(chunk);
|
|
818
|
+
push(params.url || params.src || params.file, params.file_id || params.file || params.id, isStickerParams(params));
|
|
819
|
+
}
|
|
820
|
+
// 2) koishi onebot 适配器的 HTML 形态:<img src="..." summary="[动画表情]" .../>
|
|
821
|
+
for (const tag of content.match(/<img\b[^>]*\/?>/gi) ?? []) {
|
|
822
|
+
const attrs = this.parseHtmlTagParams(tag);
|
|
823
|
+
push(attrs.src || attrs.url || attrs.file, attrs.file || attrs.fileid, isStickerParams(attrs));
|
|
824
|
+
}
|
|
825
|
+
// 3) 元素形态:type 可能是 image / img / face / sticker / mface
|
|
826
|
+
for (const element of session?.elements ?? []) {
|
|
827
|
+
const type = String(element?.type ?? '').toLowerCase();
|
|
828
|
+
const attrs = element?.attrs ?? {};
|
|
829
|
+
const rawAttrs = {};
|
|
830
|
+
for (const k of Object.keys(attrs)) rawAttrs[String(k).toLowerCase().replace(/-/g, '')] = attrs[k];
|
|
831
|
+
const isImgLike = type === 'img' || type === 'image';
|
|
832
|
+
const isStickerLike = type === 'face' || type === 'sticker' || type === 'mface';
|
|
833
|
+
if (!isImgLike && !isStickerLike)
|
|
834
|
+
continue;
|
|
835
|
+
const url = element?.url || element?.src
|
|
836
|
+
|| attrs.url || attrs.src
|
|
837
|
+
|| attrs.image || attrs.href || '';
|
|
838
|
+
const ref = element?.file || element?.fileId || element?.file_id || element?.id
|
|
839
|
+
|| attrs.file || attrs.fileid || attrs.file_id || attrs.id || '';
|
|
840
|
+
const sticker = isStickerLike || isStickerParams(rawAttrs) || isStickerParams(attrs);
|
|
841
|
+
push(url, ref, sticker);
|
|
842
|
+
}
|
|
843
|
+
return items;
|
|
844
|
+
}
|
|
845
|
+
extractImageUrlsFromSession(session, maxCount = 4) {
|
|
846
|
+
return this.extractImageElements(session)
|
|
847
|
+
.filter((item) => item.sendable)
|
|
848
|
+
.map((item) => item.url)
|
|
849
|
+
.slice(0, Math.max(1, maxCount));
|
|
850
|
+
}
|
|
851
|
+
hasAnyImageElement(session) {
|
|
852
|
+
if (!session)
|
|
853
|
+
return false;
|
|
854
|
+
if (this.extractImageElements(session).length)
|
|
855
|
+
return true;
|
|
856
|
+
const content = session.content ?? '';
|
|
857
|
+
return /\[CQ:image,/i.test(content)
|
|
858
|
+
|| /<img\b/i.test(content)
|
|
859
|
+
|| (session.elements ?? []).some((el) => {
|
|
860
|
+
const t = String(el?.type ?? '').toLowerCase();
|
|
861
|
+
return t === 'img' || t === 'image' || t === 'face' || t === 'sticker' || t === 'mface';
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
hasStickerContent(session) {
|
|
865
|
+
if (!session)
|
|
866
|
+
return false;
|
|
867
|
+
if (/\[CQ:(face|mface|sticker),/i.test(session.content ?? ''))
|
|
868
|
+
return true;
|
|
869
|
+
return this.extractImageElements(session).some((item) => item.sticker);
|
|
870
|
+
}
|
|
871
|
+
extractMessageImageUrls(session, maxCount = 4) {
|
|
872
|
+
return this.extractImageUrlsFromSession(session, maxCount);
|
|
873
|
+
}
|
|
874
|
+
extractImageFingerprintKeys(session, maxCount = 6) {
|
|
875
|
+
const keys = [];
|
|
876
|
+
const content = session.content ?? '';
|
|
877
|
+
const pushKey = (value) => {
|
|
878
|
+
const key = value.trim();
|
|
879
|
+
if (!key)
|
|
880
|
+
return;
|
|
881
|
+
keys.push(key);
|
|
882
|
+
};
|
|
883
|
+
const hashPattern = /([A-Fa-f0-9]{32})/g;
|
|
884
|
+
let hashMatch;
|
|
885
|
+
while ((hashMatch = hashPattern.exec(content))) {
|
|
886
|
+
pushKey(`hash:${hashMatch[1].toUpperCase()}`);
|
|
887
|
+
if (keys.length >= maxCount)
|
|
888
|
+
return [...new Set(keys)];
|
|
889
|
+
}
|
|
890
|
+
const cqPattern = /\[CQ:image,[^\]]*\]/gi;
|
|
891
|
+
const cqList = content.match(cqPattern) ?? [];
|
|
892
|
+
for (const chunk of cqList) {
|
|
893
|
+
const file = chunk.match(/file=([^,\]]+)/i)?.[1];
|
|
894
|
+
const id = chunk.match(/(?:file_id|id)=([^,\]]+)/i)?.[1];
|
|
895
|
+
const md5 = chunk.match(/md5=([^,\]]+)/i)?.[1];
|
|
896
|
+
const url = chunk.match(/(?:url|src)=([^,\]]+)/i)?.[1];
|
|
897
|
+
let key = '';
|
|
898
|
+
if (md5)
|
|
899
|
+
key = `md5:${decodeURIComponent(md5).toUpperCase()}`;
|
|
900
|
+
else if (file)
|
|
901
|
+
key = `file:${decodeURIComponent(file)}`;
|
|
902
|
+
else if (id)
|
|
903
|
+
key = `id:${decodeURIComponent(id)}`;
|
|
904
|
+
else if (url) {
|
|
905
|
+
const u = decodeURIComponent(url);
|
|
906
|
+
const hash = u.match(/([A-Fa-f0-9]{32})/)?.[1];
|
|
907
|
+
if (hash)
|
|
908
|
+
key = `hash:${hash.toUpperCase()}`;
|
|
909
|
+
else {
|
|
910
|
+
try {
|
|
911
|
+
const parsed = new URL(u);
|
|
912
|
+
key = `urlp:${parsed.origin}${parsed.pathname}`;
|
|
913
|
+
}
|
|
914
|
+
catch {
|
|
915
|
+
key = `url:${u.split('?')[0]}`;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
if (!key && file) {
|
|
920
|
+
const hash = decodeURIComponent(file).match(/([A-Fa-f0-9]{32})/)?.[1];
|
|
921
|
+
if (hash)
|
|
922
|
+
key = `hash:${hash.toUpperCase()}`;
|
|
923
|
+
}
|
|
924
|
+
if (!key)
|
|
925
|
+
continue;
|
|
926
|
+
pushKey(key);
|
|
927
|
+
if (keys.length >= maxCount)
|
|
928
|
+
return [...new Set(keys)];
|
|
929
|
+
}
|
|
930
|
+
const htmlImgPattern = /<img\b[^>]*src=["']([^"']+)["'][^>]*>/gi;
|
|
931
|
+
let htmlMatch;
|
|
932
|
+
while ((htmlMatch = htmlImgPattern.exec(content))) {
|
|
933
|
+
const src = htmlMatch[1] || '';
|
|
934
|
+
const hash = src.match(/([A-Fa-f0-9]{32})/)?.[1];
|
|
935
|
+
if (hash) {
|
|
936
|
+
pushKey(`hash:${hash.toUpperCase()}`);
|
|
937
|
+
}
|
|
938
|
+
else if (src) {
|
|
939
|
+
try {
|
|
940
|
+
const parsed = new URL(src);
|
|
941
|
+
pushKey(`urlp:${parsed.origin}${parsed.pathname}`);
|
|
942
|
+
}
|
|
943
|
+
catch {
|
|
944
|
+
pushKey(`url:${src.split('?')[0]}`);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
if (keys.length >= maxCount)
|
|
948
|
+
return [...new Set(keys)];
|
|
949
|
+
}
|
|
950
|
+
const elements = session.elements ?? [];
|
|
951
|
+
for (const element of elements) {
|
|
952
|
+
if (element.type !== 'image')
|
|
953
|
+
continue;
|
|
954
|
+
const file = (typeof element.file === 'string' && element.file)
|
|
955
|
+
|| (typeof element.attrs?.file === 'string' && element.attrs.file);
|
|
956
|
+
const id = (typeof element.id === 'string' && element.id)
|
|
957
|
+
|| (typeof element.attrs?.id === 'string' && element.attrs.id)
|
|
958
|
+
|| (typeof element.attrs?.file_id === 'string' && element.attrs.file_id);
|
|
959
|
+
const md5 = typeof element.attrs?.md5 === 'string' ? element.attrs.md5 : '';
|
|
960
|
+
const url = (typeof element.url === 'string' && element.url)
|
|
961
|
+
|| (typeof element.src === 'string' && element.src)
|
|
962
|
+
|| (typeof element.attrs?.url === 'string' && element.attrs.url)
|
|
963
|
+
|| (typeof element.attrs?.src === 'string' && element.attrs.src);
|
|
964
|
+
let key = '';
|
|
965
|
+
if (md5)
|
|
966
|
+
key = `md5:${md5.toUpperCase()}`;
|
|
967
|
+
else if (file)
|
|
968
|
+
key = `file:${file}`;
|
|
969
|
+
else if (id)
|
|
970
|
+
key = `id:${id}`;
|
|
971
|
+
else if (url) {
|
|
972
|
+
const hash = url.match(/([A-Fa-f0-9]{32})/)?.[1];
|
|
973
|
+
if (hash)
|
|
974
|
+
key = `hash:${hash.toUpperCase()}`;
|
|
975
|
+
else {
|
|
976
|
+
try {
|
|
977
|
+
const parsed = new URL(url);
|
|
978
|
+
key = `urlp:${parsed.origin}${parsed.pathname}`;
|
|
979
|
+
}
|
|
980
|
+
catch {
|
|
981
|
+
key = `url:${url.split('?')[0]}`;
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
if (!key && file) {
|
|
986
|
+
const hash = file.match(/([A-Fa-f0-9]{32})/)?.[1];
|
|
987
|
+
if (hash)
|
|
988
|
+
key = `hash:${hash.toUpperCase()}`;
|
|
989
|
+
}
|
|
990
|
+
if (!key)
|
|
991
|
+
continue;
|
|
992
|
+
pushKey(key);
|
|
993
|
+
if (keys.length >= maxCount)
|
|
994
|
+
break;
|
|
995
|
+
}
|
|
996
|
+
return [...new Set(keys)].slice(0, maxCount);
|
|
997
|
+
}
|
|
998
|
+
normalizeRepeatText(text) {
|
|
999
|
+
return text
|
|
1000
|
+
.replace(/<img\b[^>]*>/gi, '[图片]')
|
|
1001
|
+
.replace(/\[CQ:image,[^\]]*\]/gi, '[图片]')
|
|
1002
|
+
.replace(/\s+/g, ' ')
|
|
1003
|
+
.trim();
|
|
1004
|
+
}
|
|
1005
|
+
buildRepeatPayload(session) {
|
|
1006
|
+
const text = this.normalizeRepeatText(this.extractAiMessageText(session));
|
|
1007
|
+
const images = this.extractMessageImageUrls(session, 6);
|
|
1008
|
+
const imageKeys = this.extractImageFingerprintKeys(session, 6);
|
|
1009
|
+
const normalizedText = text.replace(/\s+/g, ' ').trim();
|
|
1010
|
+
const textCore = normalizedText.replace(/\[图片\]/g, '').trim();
|
|
1011
|
+
const signature = imageKeys.length
|
|
1012
|
+
? `img:${imageKeys.join('|')}|txt:${textCore}`
|
|
1013
|
+
: `txt:${normalizedText}`;
|
|
1014
|
+
const rawImageSegments = (session.content ?? '').match(/\[CQ:image,[^\]]+\]/gi) ?? [];
|
|
1015
|
+
const sendRefs = this.extractImageSendRefs(session);
|
|
1016
|
+
return { signature, text: normalizedText, images, imageKeys, rawImageSegments, sendRefs };
|
|
1017
|
+
}
|
|
1018
|
+
parseCqImageParams(chunk) {
|
|
1019
|
+
const body = chunk.replace(/^\[CQ:image,?/i, '').replace(/\]$/i, '');
|
|
1020
|
+
const params = {};
|
|
1021
|
+
for (const part of body.split(',')) {
|
|
1022
|
+
const idx = part.indexOf('=');
|
|
1023
|
+
if (idx <= 0)
|
|
1024
|
+
continue;
|
|
1025
|
+
const key = part.slice(0, idx).trim().toLowerCase();
|
|
1026
|
+
const value = part.slice(idx + 1).trim();
|
|
1027
|
+
if (!key || !value)
|
|
1028
|
+
continue;
|
|
1029
|
+
try {
|
|
1030
|
+
params[key] = decodeURIComponent(value);
|
|
1031
|
+
}
|
|
1032
|
+
catch {
|
|
1033
|
+
params[key] = value;
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
return params;
|
|
1037
|
+
}
|
|
1038
|
+
extractImageRefsFromRawMessage(raw, maxCount = 6) {
|
|
1039
|
+
const refs = [];
|
|
1040
|
+
const push = (value) => {
|
|
1041
|
+
if (typeof value !== 'string')
|
|
1042
|
+
return;
|
|
1043
|
+
const v = value.trim();
|
|
1044
|
+
if (!v)
|
|
1045
|
+
return;
|
|
1046
|
+
refs.push(v);
|
|
1047
|
+
};
|
|
1048
|
+
const parseString = (text) => {
|
|
1049
|
+
const cqPattern = /\[CQ:image,[^\]]*\]/gi;
|
|
1050
|
+
for (const chunk of text.match(cqPattern) ?? []) {
|
|
1051
|
+
const params = this.parseCqImageParams(chunk);
|
|
1052
|
+
if (params.file_id)
|
|
1053
|
+
push(params.file_id);
|
|
1054
|
+
if (params.id)
|
|
1055
|
+
push(params.id);
|
|
1056
|
+
if (params.file)
|
|
1057
|
+
push(params.file);
|
|
1058
|
+
if (params.url)
|
|
1059
|
+
push(params.url);
|
|
1060
|
+
if (params.src)
|
|
1061
|
+
push(params.src);
|
|
1062
|
+
if (refs.length >= maxCount)
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
const htmlImgPattern = /<img\b[^>]*src=["']([^"']+)["'][^>]*>/gi;
|
|
1066
|
+
let htmlMatch;
|
|
1067
|
+
while ((htmlMatch = htmlImgPattern.exec(text))) {
|
|
1068
|
+
push(htmlMatch[1]);
|
|
1069
|
+
if (refs.length >= maxCount)
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
};
|
|
1073
|
+
const walk = (value) => {
|
|
1074
|
+
if (refs.length >= maxCount || value == null)
|
|
1075
|
+
return;
|
|
1076
|
+
if (typeof value === 'string') {
|
|
1077
|
+
parseString(value);
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
if (Array.isArray(value)) {
|
|
1081
|
+
for (const item of value) {
|
|
1082
|
+
walk(item);
|
|
1083
|
+
if (refs.length >= maxCount)
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
if (typeof value !== 'object')
|
|
1089
|
+
return;
|
|
1090
|
+
const node = value;
|
|
1091
|
+
const candidates = [
|
|
1092
|
+
node.url,
|
|
1093
|
+
node.src,
|
|
1094
|
+
node.file,
|
|
1095
|
+
node.id,
|
|
1096
|
+
node.file_id,
|
|
1097
|
+
node.data?.url,
|
|
1098
|
+
node.data?.src,
|
|
1099
|
+
node.data?.file,
|
|
1100
|
+
node.data?.id,
|
|
1101
|
+
node.data?.file_id,
|
|
1102
|
+
node.attrs?.url,
|
|
1103
|
+
node.attrs?.src,
|
|
1104
|
+
node.attrs?.file,
|
|
1105
|
+
node.attrs?.id,
|
|
1106
|
+
node.attrs?.file_id,
|
|
1107
|
+
];
|
|
1108
|
+
for (const item of candidates) {
|
|
1109
|
+
push(item);
|
|
1110
|
+
if (refs.length >= maxCount)
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
walk(node.message);
|
|
1114
|
+
walk(node.raw_message);
|
|
1115
|
+
walk(node.content);
|
|
1116
|
+
};
|
|
1117
|
+
walk(raw);
|
|
1118
|
+
return [...new Set(refs)].slice(0, maxCount);
|
|
1119
|
+
}
|
|
1120
|
+
extractImageSegmentsFromRawMessage(raw, maxCount = 6) {
|
|
1121
|
+
const segments = [];
|
|
1122
|
+
const push = (value) => {
|
|
1123
|
+
const v = value.trim();
|
|
1124
|
+
if (!v)
|
|
1125
|
+
return;
|
|
1126
|
+
segments.push(v);
|
|
1127
|
+
};
|
|
1128
|
+
const parseString = (text) => {
|
|
1129
|
+
const cqPattern = /\[CQ:image,[^\]]+\]/gi;
|
|
1130
|
+
for (const chunk of text.match(cqPattern) ?? []) {
|
|
1131
|
+
push(chunk);
|
|
1132
|
+
if (segments.length >= maxCount)
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
const walk = (value) => {
|
|
1137
|
+
if (segments.length >= maxCount || value == null)
|
|
1138
|
+
return;
|
|
1139
|
+
if (typeof value === 'string') {
|
|
1140
|
+
parseString(value);
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
if (Array.isArray(value)) {
|
|
1144
|
+
for (const item of value) {
|
|
1145
|
+
walk(item);
|
|
1146
|
+
if (segments.length >= maxCount)
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
if (typeof value !== 'object')
|
|
1152
|
+
return;
|
|
1153
|
+
const node = value;
|
|
1154
|
+
walk(node.message);
|
|
1155
|
+
walk(node.raw_message);
|
|
1156
|
+
walk(node.content);
|
|
1157
|
+
};
|
|
1158
|
+
walk(raw);
|
|
1159
|
+
return [...new Set(segments)].slice(0, maxCount);
|
|
1160
|
+
}
|
|
1161
|
+
extractImageSendRefs(session, maxCount = 6) {
|
|
1162
|
+
const refs = [];
|
|
1163
|
+
const pushRef = (value) => {
|
|
1164
|
+
const v = String(value ?? '').trim();
|
|
1165
|
+
if (!v)
|
|
1166
|
+
return;
|
|
1167
|
+
refs.push(v);
|
|
1168
|
+
};
|
|
1169
|
+
// 统一走 extractImageElements:同时覆盖 CQ 与 koishi HTML(<img>) 两种形态
|
|
1170
|
+
for (const item of this.extractImageElements(session)) {
|
|
1171
|
+
pushRef(item.ref);
|
|
1172
|
+
pushRef(item.url);
|
|
1173
|
+
if (refs.length >= maxCount)
|
|
1174
|
+
return [...new Set(refs)].slice(0, maxCount);
|
|
1175
|
+
}
|
|
1176
|
+
const content = session.content ?? '';
|
|
1177
|
+
const cqPattern = /\[CQ:image,[^\]]*\]/gi;
|
|
1178
|
+
for (const chunk of content.match(cqPattern) ?? []) {
|
|
1179
|
+
const params = this.parseCqImageParams(chunk);
|
|
1180
|
+
if (params.file_id)
|
|
1181
|
+
pushRef(params.file_id);
|
|
1182
|
+
if (params.id)
|
|
1183
|
+
pushRef(params.id);
|
|
1184
|
+
if (params.file)
|
|
1185
|
+
pushRef(params.file);
|
|
1186
|
+
if (params.url)
|
|
1187
|
+
pushRef(params.url);
|
|
1188
|
+
if (params.src)
|
|
1189
|
+
pushRef(params.src);
|
|
1190
|
+
if (refs.length >= maxCount)
|
|
1191
|
+
return [...new Set(refs)].slice(0, maxCount);
|
|
1192
|
+
}
|
|
1193
|
+
return [...new Set(refs)].slice(0, maxCount);
|
|
1194
|
+
}
|
|
1195
|
+
async fetchMessageImagePayload(session, maxCount = 6) {
|
|
1196
|
+
if (!this.config.repeaterEnableGetMsgRefetch)
|
|
1197
|
+
return { segments: [], refs: [] };
|
|
1198
|
+
if (session.platform !== 'onebot')
|
|
1199
|
+
return { segments: [], refs: [] };
|
|
1200
|
+
const messageId = session.messageId;
|
|
1201
|
+
if (!messageId)
|
|
1202
|
+
return { segments: [], refs: [] };
|
|
1203
|
+
const onebot = this.getOneBotApi(session);
|
|
1204
|
+
if (!onebot?.getMsg)
|
|
1205
|
+
return { segments: [], refs: [] };
|
|
1206
|
+
try {
|
|
1207
|
+
const data = await onebot.getMsg(messageId);
|
|
1208
|
+
return {
|
|
1209
|
+
segments: this.extractImageSegmentsFromRawMessage(data, maxCount),
|
|
1210
|
+
refs: this.extractImageRefsFromRawMessage(data, maxCount),
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
catch (error) {
|
|
1214
|
+
this._logger.warn(`[repeater] get_msg refetch failed: ${String(error)} | ${this.sessionTag(session)} messageId=${messageId}`);
|
|
1215
|
+
return { segments: [], refs: [] };
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
async sendImageRef(session, ref) {
|
|
1219
|
+
const value = ref.trim();
|
|
1220
|
+
if (!value)
|
|
1221
|
+
return false;
|
|
1222
|
+
const isHttp = /^https?:\/\//i.test(value);
|
|
1223
|
+
if (isHttp)
|
|
1224
|
+
return false;
|
|
1225
|
+
try {
|
|
1226
|
+
await session.send((0, koishi_1.h)('image', { src: value, cache: 0 }));
|
|
1227
|
+
return true;
|
|
1228
|
+
}
|
|
1229
|
+
catch (error) {
|
|
1230
|
+
this._logger.warn(`[repeater] send-image-by-file-failed: ${String(error)} | ${this.sessionTag(session)} ref=${value}`);
|
|
1231
|
+
}
|
|
1232
|
+
try {
|
|
1233
|
+
await session.send(koishi_1.h.image(value));
|
|
1234
|
+
return true;
|
|
1235
|
+
}
|
|
1236
|
+
catch {
|
|
1237
|
+
return false;
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
async handleRepeater(session) {
|
|
1241
|
+
if (!this.config.enableRepeater)
|
|
1242
|
+
return;
|
|
1243
|
+
if (!session.guildId || !session.userId)
|
|
1244
|
+
return;
|
|
1245
|
+
if (session.userId === session.bot?.selfId)
|
|
1246
|
+
return;
|
|
1247
|
+
const groupKey = this.aiGroupKey(session);
|
|
1248
|
+
if (!groupKey)
|
|
1249
|
+
return;
|
|
1250
|
+
const payload = this.buildRepeatPayload(session);
|
|
1251
|
+
if (!payload.signature || (!payload.text && !payload.images.length && !payload.rawImageSegments.length && !payload.sendRefs.length && !payload.imageKeys.length))
|
|
1252
|
+
return;
|
|
1253
|
+
const now = Date.now();
|
|
1254
|
+
const prev = this.repeatStates.get(groupKey);
|
|
1255
|
+
const next = prev && prev.signature === payload.signature
|
|
1256
|
+
? { ...prev, count: prev.count + 1, updatedAt: now }
|
|
1257
|
+
: { signature: payload.signature, count: 1, updatedAt: now, lastRepeatedSignature: prev?.lastRepeatedSignature, lastRepeatedAt: prev?.lastRepeatedAt };
|
|
1258
|
+
this.repeatStates.set(groupKey, next);
|
|
1259
|
+
const threshold = Math.max(2, this.config.repeaterThreshold || 3);
|
|
1260
|
+
if (next.count < threshold)
|
|
1261
|
+
return;
|
|
1262
|
+
const cooldownMs = Math.max(1, this.config.repeaterCooldownSeconds || 90) * 1000;
|
|
1263
|
+
const isSameAsLast = next.lastRepeatedSignature === payload.signature;
|
|
1264
|
+
if (isSameAsLast && next.lastRepeatedAt && now - next.lastRepeatedAt < cooldownMs)
|
|
1265
|
+
return;
|
|
1266
|
+
const meaningfulText = payload.text.replace(/\[图片\]/g, '').replace(/\s+/g, '').trim();
|
|
1267
|
+
if (meaningfulText) {
|
|
1268
|
+
const parts = this.splitAiReplyParts(payload.text);
|
|
1269
|
+
let first = true;
|
|
1270
|
+
for (const part of parts) {
|
|
1271
|
+
if (!first)
|
|
1272
|
+
await this.waitHumanLikeDelay(350, 900);
|
|
1273
|
+
await session.send(koishi_1.h.text(part));
|
|
1274
|
+
first = false;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
let imageSent = false;
|
|
1278
|
+
let sendAttemptCount = 0;
|
|
1279
|
+
let sendSuccessCount = 0;
|
|
1280
|
+
let resolvedSegmentsFromGetMsg = 0;
|
|
1281
|
+
let resolvedRefsFromGetMsg = 0;
|
|
1282
|
+
const sentRefSet = new Set();
|
|
1283
|
+
const trySendRef = async (raw) => {
|
|
1284
|
+
const ref = raw.trim();
|
|
1285
|
+
if (!ref || /^https?:\/\//i.test(ref))
|
|
1286
|
+
return false;
|
|
1287
|
+
if (sentRefSet.has(ref))
|
|
1288
|
+
return false;
|
|
1289
|
+
sentRefSet.add(ref);
|
|
1290
|
+
await this.waitHumanLikeDelay(420, 980);
|
|
1291
|
+
sendAttemptCount += 1;
|
|
1292
|
+
if (await this.sendImageRef(session, ref)) {
|
|
1293
|
+
imageSent = true;
|
|
1294
|
+
sendSuccessCount += 1;
|
|
1295
|
+
return true;
|
|
1296
|
+
}
|
|
1297
|
+
return false;
|
|
1298
|
+
};
|
|
1299
|
+
for (const segment of payload.rawImageSegments) {
|
|
1300
|
+
const params = this.parseCqImageParams(segment);
|
|
1301
|
+
const refs = [params.file_id, params.id, params.file, params.url, params.src].filter(Boolean);
|
|
1302
|
+
for (const ref of refs) {
|
|
1303
|
+
await trySendRef(ref);
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
if (!imageSent) {
|
|
1307
|
+
for (const ref of payload.sendRefs) {
|
|
1308
|
+
await trySendRef(ref);
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
if (!imageSent && payload.imageKeys.length) {
|
|
1312
|
+
const fetched = await this.fetchMessageImagePayload(session, 6);
|
|
1313
|
+
resolvedSegmentsFromGetMsg = fetched.segments.length;
|
|
1314
|
+
resolvedRefsFromGetMsg = fetched.refs.length;
|
|
1315
|
+
for (const segment of fetched.segments) {
|
|
1316
|
+
const params = this.parseCqImageParams(segment);
|
|
1317
|
+
const file = params.file || '';
|
|
1318
|
+
const fileId = params.file_id || params.id || '';
|
|
1319
|
+
if (fileId)
|
|
1320
|
+
await trySendRef(fileId);
|
|
1321
|
+
if (file && !/^https?:\/\//i.test(file))
|
|
1322
|
+
await trySendRef(file);
|
|
1323
|
+
}
|
|
1324
|
+
for (const ref of fetched.refs) {
|
|
1325
|
+
await trySendRef(ref);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
const noSendableReason = !imageSent && payload.imageKeys.length ? 'no-sendable-image-payload' : '';
|
|
1329
|
+
const hadImages = payload.imageKeys.length > 0 || payload.sendRefs.length > 0;
|
|
1330
|
+
// 纯文字复读没有图片是正常的,不要误报"没有可发送的图片"
|
|
1331
|
+
if (!imageSent && (hadImages || !meaningfulText)) {
|
|
1332
|
+
this._logger.warn(`[repeater] triggered but no sendable image payload | ${this.sessionTag(session)} keys=${JSON.stringify(payload.imageKeys)} refs=${JSON.stringify(payload.sendRefs)}`);
|
|
1333
|
+
}
|
|
1334
|
+
this.repeatStates.set(groupKey, {
|
|
1335
|
+
...next,
|
|
1336
|
+
lastRepeatedSignature: payload.signature,
|
|
1337
|
+
lastRepeatedAt: now,
|
|
1338
|
+
});
|
|
1339
|
+
this.logCommandResult('repeater', { ok: true, message: `repeat triggered x${next.count}` }, session, {
|
|
1340
|
+
text: payload.text,
|
|
1341
|
+
images: payload.images.length,
|
|
1342
|
+
imageKeys: payload.imageKeys,
|
|
1343
|
+
sendRefs: payload.sendRefs,
|
|
1344
|
+
rawSegments: payload.rawImageSegments.length,
|
|
1345
|
+
resolvedSegmentsFromGetMsg,
|
|
1346
|
+
resolvedRefsFromGetMsg,
|
|
1347
|
+
sendAttemptCount,
|
|
1348
|
+
sendSuccessCount,
|
|
1349
|
+
reason: noSendableReason || undefined,
|
|
1350
|
+
});
|
|
1351
|
+
this.ai.note(`群内触发复读:${payload.text || '[图片消息]'} (${payload.images.length}张图)`, groupKey);
|
|
1352
|
+
}
|
|
1353
|
+
logAuth(stage, result, session) {
|
|
1354
|
+
if (!this.config.logAuthCheck)
|
|
1355
|
+
return;
|
|
1356
|
+
const level = result.ok ? 'info' : 'warn';
|
|
1357
|
+
this._logger[level](`[auth:${stage}] ${result.message} | ${this.sessionTag(session)}`);
|
|
1358
|
+
}
|
|
1359
|
+
logCommandResult(command, result, session, extra) {
|
|
1360
|
+
if (!this.config.logCommandResult)
|
|
1361
|
+
return;
|
|
1362
|
+
const level = result.ok ? 'info' : 'warn';
|
|
1363
|
+
const plan = result.plan ? JSON.stringify(result.plan) : '-';
|
|
1364
|
+
const payload = extra ? ` extra=${JSON.stringify(extra)}` : '';
|
|
1365
|
+
this._logger[level](`[cmd:${command}] ok=${result.ok} message="${result.message}" plan=${plan}${payload} | ${this.sessionTag(session)}`);
|
|
1366
|
+
}
|
|
1367
|
+
async authorizeCommand(command, session) {
|
|
1368
|
+
const result = await this.authorize(session);
|
|
1369
|
+
this.logAuth(command, result, session);
|
|
1370
|
+
return result;
|
|
1371
|
+
}
|
|
1372
|
+
async authorize(session) {
|
|
1373
|
+
if (!session) {
|
|
1374
|
+
return { ok: false, message: '缺少会话上下文。', userMessage: '权限不足或上下文不符合要求。' };
|
|
1375
|
+
}
|
|
1376
|
+
const platform = session.platform;
|
|
1377
|
+
if (!this.isPlatformAllowed(platform)) {
|
|
1378
|
+
return {
|
|
1379
|
+
ok: false,
|
|
1380
|
+
message: `当前平台 ${platform ?? 'unknown'} 未启用群管理。`,
|
|
1381
|
+
userMessage: '当前平台未启用群管理。',
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
const userId = session.userId;
|
|
1385
|
+
if (!userId) {
|
|
1386
|
+
return { ok: false, message: '无法识别当前账号。', userMessage: '权限不足或上下文不符合要求。' };
|
|
1387
|
+
}
|
|
1388
|
+
if (this.config.allowedUserIds.includes(userId)) {
|
|
1389
|
+
return { ok: true, message: '账号白名单通过。' };
|
|
1390
|
+
}
|
|
1391
|
+
if (!session.guildId) {
|
|
1392
|
+
return {
|
|
1393
|
+
ok: false,
|
|
1394
|
+
message: '当前账号不在白名单,且仅支持在群聊中按管理员权限使用。',
|
|
1395
|
+
userMessage: '仅支持群聊中按管理员权限使用。',
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
const role = await this.resolveMemberRole(session);
|
|
1399
|
+
if (!role) {
|
|
1400
|
+
return { ok: false, message: '无法获取群成员角色,权限校验失败。', userMessage: '权限校验失败。' };
|
|
1401
|
+
}
|
|
1402
|
+
if (role === 'owner' && this.config.allowGroupOwner) {
|
|
1403
|
+
return { ok: true, message: '群主权限通过。' };
|
|
1404
|
+
}
|
|
1405
|
+
if (role === 'admin' && this.config.allowGroupAdmin) {
|
|
1406
|
+
return { ok: true, message: '群管理员权限通过。' };
|
|
1407
|
+
}
|
|
1408
|
+
return {
|
|
1409
|
+
ok: false,
|
|
1410
|
+
message: '权限不足:仅账号白名单、群主或群管理员可执行。',
|
|
1411
|
+
userMessage: '权限不足:仅白名单、群主或群管理员可执行。',
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
async canUseAdminCommand(session) {
|
|
1415
|
+
if (!this.config.requireBotOwnerForAdmin) {
|
|
1416
|
+
const allowed = { ok: true, message: '已关闭 bot 群主限制,admin 子命令可用。' };
|
|
1417
|
+
this.logAuth('admin-visibility', allowed, session);
|
|
1418
|
+
return allowed;
|
|
1419
|
+
}
|
|
1420
|
+
if (!session) {
|
|
1421
|
+
const denied = { ok: false, message: '缺少会话上下文,admin 子命令不可用。', userMessage: '当前场景不可用该子命令。' };
|
|
1422
|
+
this.logAuth('admin-visibility', denied, session);
|
|
1423
|
+
return denied;
|
|
1424
|
+
}
|
|
1425
|
+
if (!session.guildId) {
|
|
1426
|
+
const denied = { ok: false, message: '当前不是群聊上下文,admin 子命令不可用。', userMessage: '请在群聊中使用该子命令。' };
|
|
1427
|
+
this.logAuth('admin-visibility', denied, session);
|
|
1428
|
+
return denied;
|
|
1429
|
+
}
|
|
1430
|
+
const botId = Number(session.bot?.selfId);
|
|
1431
|
+
if (!Number.isFinite(botId)) {
|
|
1432
|
+
const denied = { ok: false, message: `bot selfId 无法解析为数字: ${session.bot?.selfId ?? 'unknown'}`, userMessage: '当前场景不可用该子命令。' };
|
|
1433
|
+
this.logAuth('admin-visibility', denied, session);
|
|
1434
|
+
return denied;
|
|
1435
|
+
}
|
|
1436
|
+
const botRole = await this.getTargetRole(session, botId);
|
|
1437
|
+
// bot 只要具备群主或管理员身份,就有能力执行禁言/踢人等操作。
|
|
1438
|
+
// 此前要求必须是 owner,导致绝大多数群(bot 只是管理员)里群管指令全部不可用。
|
|
1439
|
+
if (botRole === 'owner' || botRole === 'admin') {
|
|
1440
|
+
const allowed = { ok: true, message: `bot(${botId}) 在当前群角色=${botRole},具备管理能力。` };
|
|
1441
|
+
this.logAuth('admin-visibility', allowed, session);
|
|
1442
|
+
return allowed;
|
|
1443
|
+
}
|
|
1444
|
+
const denied = {
|
|
1445
|
+
ok: false,
|
|
1446
|
+
message: `bot(${botId}) 在当前群角色=${botRole ?? 'unknown'},既不是群主也不是管理员,无法执行群管操作。`,
|
|
1447
|
+
userMessage: '当前群中 bot 既不是群主也不是管理员,无法执行群管操作。',
|
|
1448
|
+
};
|
|
1449
|
+
this.logAuth('admin-visibility', denied, session);
|
|
1450
|
+
return denied;
|
|
1451
|
+
}
|
|
1452
|
+
async isBotOwnerInGroup(session) {
|
|
1453
|
+
if (!session?.guildId || session.platform !== 'onebot')
|
|
1454
|
+
return false;
|
|
1455
|
+
const botId = Number(session.bot.selfId);
|
|
1456
|
+
if (!Number.isFinite(botId))
|
|
1457
|
+
return false;
|
|
1458
|
+
const role = await this.getTargetRole(session, botId);
|
|
1459
|
+
return role === 'owner';
|
|
1460
|
+
}
|
|
1461
|
+
async resolveMemberRole(session) {
|
|
1462
|
+
const authorRoles = session.author?.roles ?? [];
|
|
1463
|
+
for (const role of authorRoles) {
|
|
1464
|
+
const normalized = this.normalizeRole(role);
|
|
1465
|
+
if (normalized)
|
|
1466
|
+
return normalized;
|
|
1467
|
+
}
|
|
1468
|
+
const eventRole = session.event?.member?.role;
|
|
1469
|
+
if (eventRole === 'owner' || eventRole === 'admin' || eventRole === 'member') {
|
|
1470
|
+
return eventRole;
|
|
1471
|
+
}
|
|
1472
|
+
if (session.platform !== 'onebot')
|
|
1473
|
+
return null;
|
|
1474
|
+
const onebot = session.onebot;
|
|
1475
|
+
if (!onebot?.getGroupMemberInfo || !session.guildId || !session.userId)
|
|
1476
|
+
return null;
|
|
1477
|
+
const groupId = Number(session.guildId);
|
|
1478
|
+
const userId = Number(session.userId);
|
|
1479
|
+
if (!Number.isFinite(groupId) || !Number.isFinite(userId))
|
|
1480
|
+
return null;
|
|
1481
|
+
try {
|
|
1482
|
+
const info = await onebot.getGroupMemberInfo(groupId, userId, true);
|
|
1483
|
+
if (info.role === 'owner' || info.role === 'admin' || info.role === 'member') {
|
|
1484
|
+
return info.role;
|
|
1485
|
+
}
|
|
1486
|
+
return null;
|
|
1487
|
+
}
|
|
1488
|
+
catch {
|
|
1489
|
+
return null;
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
normalizeRole(input) {
|
|
1493
|
+
if (input === 'owner' || input === 'admin' || input === 'member') {
|
|
1494
|
+
return input;
|
|
1495
|
+
}
|
|
1496
|
+
if (!input || typeof input !== 'object')
|
|
1497
|
+
return null;
|
|
1498
|
+
const role = input;
|
|
1499
|
+
if (role.id === 'owner' || role.id === 'admin' || role.id === 'member')
|
|
1500
|
+
return role.id;
|
|
1501
|
+
if (role.name === 'owner' || role.name === 'admin' || role.name === 'member')
|
|
1502
|
+
return role.name;
|
|
1503
|
+
if (role.type === 'owner' || role.type === 'admin' || role.type === 'member')
|
|
1504
|
+
return role.type;
|
|
1505
|
+
return null;
|
|
1506
|
+
}
|
|
1507
|
+
parseTargetId(input) {
|
|
1508
|
+
const matched = input.match(/\d+/)?.[0];
|
|
1509
|
+
return matched ?? '';
|
|
1510
|
+
}
|
|
1511
|
+
randomMinutes(min = 1, max = 60) {
|
|
1512
|
+
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
1513
|
+
}
|
|
1514
|
+
parseDurationToken(token) {
|
|
1515
|
+
if (typeof token !== 'string')
|
|
1516
|
+
return null;
|
|
1517
|
+
// 只接受英文/数字单位([记忆] 新规:指令除自定义外不含汉字)
|
|
1518
|
+
const matched = String(token).trim().match(/^(\d+(?:\.\d+)?)\s*(min|mins|minute|minutes|m|hour|hours|h|day|days|d|week|weeks|w)?$/i);
|
|
1519
|
+
if (!matched)
|
|
1520
|
+
return null;
|
|
1521
|
+
const value = parseFloat(matched[1]);
|
|
1522
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
1523
|
+
return null;
|
|
1524
|
+
const unit = (matched[2] || '').toLowerCase();
|
|
1525
|
+
let factor = 1;
|
|
1526
|
+
if (unit === 'hour' || unit === 'hours' || unit === 'h') {
|
|
1527
|
+
factor = 60;
|
|
1528
|
+
}
|
|
1529
|
+
else if (unit === 'day' || unit === 'days' || unit === 'd') {
|
|
1530
|
+
factor = 24 * 60;
|
|
1531
|
+
}
|
|
1532
|
+
else if (unit === 'week' || unit === 'weeks' || unit === 'w') {
|
|
1533
|
+
factor = 7 * 24 * 60;
|
|
1534
|
+
}
|
|
1535
|
+
return { raw: String(token).trim(), value, hasUnit: !!unit, minutes: Math.ceil(value * factor) };
|
|
1536
|
+
}
|
|
1537
|
+
async looksLikeMemberInGroup(session, targetIdRaw) {
|
|
1538
|
+
const onebot = this.getOneBotApi(session);
|
|
1539
|
+
const groupId = this.toGroupId(session);
|
|
1540
|
+
const uid = Number(targetIdRaw);
|
|
1541
|
+
if (!onebot?.getGroupMemberInfo || groupId == null || !Number.isFinite(uid))
|
|
1542
|
+
return false;
|
|
1543
|
+
try {
|
|
1544
|
+
const info = await onebot.getGroupMemberInfo(groupId, uid, true);
|
|
1545
|
+
return !!(info && (info.user_id || info.userId || info.nickname || info.card));
|
|
1546
|
+
}
|
|
1547
|
+
catch {
|
|
1548
|
+
return false;
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
isPrivilegedUser(session, role) {
|
|
1552
|
+
if (!session?.userId)
|
|
1553
|
+
return false;
|
|
1554
|
+
if (this.config.allowedUserIds.includes(session.userId))
|
|
1555
|
+
return true;
|
|
1556
|
+
return role === 'owner' || role === 'admin';
|
|
1557
|
+
}
|
|
1558
|
+
recordUnauthorizedMuteAttempt(session) {
|
|
1559
|
+
const key = `${session.guildId}:${session.userId}`;
|
|
1560
|
+
const now = Date.now();
|
|
1561
|
+
const windowMinutes = Math.max(1, this.config.unauthorizedMuteWindowMinutes || 10);
|
|
1562
|
+
const windowMs = windowMinutes * 60 * 1000;
|
|
1563
|
+
const threshold = Math.max(1, this.config.unauthorizedMuteAttemptThreshold || 2);
|
|
1564
|
+
const previous = this.unauthorizedMuteAttempts.get(key);
|
|
1565
|
+
if (!previous || now - previous.updatedAt > windowMs) {
|
|
1566
|
+
this.unauthorizedMuteAttempts.set(key, { count: 1, updatedAt: now });
|
|
1567
|
+
return false;
|
|
1568
|
+
}
|
|
1569
|
+
const next = { count: previous.count + 1, updatedAt: now };
|
|
1570
|
+
this.unauthorizedMuteAttempts.set(key, next);
|
|
1571
|
+
if (next.count < threshold)
|
|
1572
|
+
return false;
|
|
1573
|
+
this.unauthorizedMuteAttempts.delete(key);
|
|
1574
|
+
return true;
|
|
1575
|
+
}
|
|
1576
|
+
async isRegularMember(session) {
|
|
1577
|
+
if (!session?.userId || !session.guildId || session.platform !== 'onebot')
|
|
1578
|
+
return false;
|
|
1579
|
+
if (this.config.allowedUserIds.includes(session.userId))
|
|
1580
|
+
return false;
|
|
1581
|
+
const role = await this.resolveMemberRole(session);
|
|
1582
|
+
return role === 'member';
|
|
1583
|
+
}
|
|
1584
|
+
async shouldSelfGag(session, target) {
|
|
1585
|
+
if (!this.config.enableSelfGag)
|
|
1586
|
+
return false;
|
|
1587
|
+
if (!session?.userId || !session.guildId || session.platform !== 'onebot')
|
|
1588
|
+
return false;
|
|
1589
|
+
if (this.config.allowedUserIds.includes(session.userId))
|
|
1590
|
+
return false;
|
|
1591
|
+
const targetId = target ? this.parseTargetId(target) : session.userId;
|
|
1592
|
+
if (!targetId || targetId !== session.userId)
|
|
1593
|
+
return false;
|
|
1594
|
+
return this.isRegularMember(session);
|
|
1595
|
+
}
|
|
1596
|
+
async selfGag(session, reason) {
|
|
1597
|
+
const groupId = this.toGroupId(session);
|
|
1598
|
+
const userIdRaw = session.userId ?? '';
|
|
1599
|
+
const userId = Number(userIdRaw);
|
|
1600
|
+
if (!userIdRaw || !Number.isFinite(userId)) {
|
|
1601
|
+
return { ok: false, message: '无法识别当前账号。' };
|
|
1602
|
+
}
|
|
1603
|
+
if (groupId == null) {
|
|
1604
|
+
return { ok: false, message: '请在群聊中执行该命令。' };
|
|
1605
|
+
}
|
|
1606
|
+
const onebot = this.getOneBotApi(session);
|
|
1607
|
+
if (!onebot?.setGroupBan) {
|
|
1608
|
+
return { ok: false, message: '当前会话不支持 OneBot 禁言接口。' };
|
|
1609
|
+
}
|
|
1610
|
+
const minutes = this.randomMinutes(1, 60);
|
|
1611
|
+
const duration = minutes * 60;
|
|
1612
|
+
const plan = {
|
|
1613
|
+
action: 'gag',
|
|
1614
|
+
groupId: String(groupId),
|
|
1615
|
+
targetId: userIdRaw,
|
|
1616
|
+
reason: reason ? `${reason}; minutes=${minutes}` : `minutes=${minutes}`,
|
|
1617
|
+
};
|
|
1618
|
+
try {
|
|
1619
|
+
await onebot.setGroupBan(groupId, userId, duration);
|
|
1620
|
+
return { ok: true, message: `已触发口球:${userIdRaw},随机禁言 ${minutes} 分钟`, plan };
|
|
1621
|
+
}
|
|
1622
|
+
catch (error) {
|
|
1623
|
+
return { ok: false, message: `口球失败: ${String(error)}`, plan };
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
async punishUnauthorizedMuteAttempt(session, target) {
|
|
1627
|
+
if (!this.config.enableUnauthorizedMutePunish)
|
|
1628
|
+
return null;
|
|
1629
|
+
if (!session?.userId || !session.guildId || session.platform !== 'onebot')
|
|
1630
|
+
return null;
|
|
1631
|
+
const targetId = target ? this.parseTargetId(target) : '';
|
|
1632
|
+
if (!targetId || targetId === session.userId)
|
|
1633
|
+
return null;
|
|
1634
|
+
const role = await this.resolveMemberRole(session);
|
|
1635
|
+
if (this.isPrivilegedUser(session, role))
|
|
1636
|
+
return null;
|
|
1637
|
+
if (!this.recordUnauthorizedMuteAttempt(session))
|
|
1638
|
+
return null;
|
|
1639
|
+
const onebot = this.getOneBotApi(session);
|
|
1640
|
+
const groupId = this.toGroupId(session);
|
|
1641
|
+
const userId = Number(session.userId);
|
|
1642
|
+
if (!onebot?.setGroupBan || groupId == null || !Number.isFinite(userId)) {
|
|
1643
|
+
return null;
|
|
1644
|
+
}
|
|
1645
|
+
const minMinutes = Math.max(1, this.config.unauthorizedMutePunishMinMinutes || 1);
|
|
1646
|
+
const maxMinutes = Math.max(minMinutes, this.config.unauthorizedMutePunishMaxMinutes || 10);
|
|
1647
|
+
const minutes = this.randomMinutes(minMinutes, maxMinutes);
|
|
1648
|
+
const duration = minutes * 60;
|
|
1649
|
+
const plan = {
|
|
1650
|
+
action: 'punish-unauthorized-mute',
|
|
1651
|
+
groupId: String(groupId),
|
|
1652
|
+
targetId: session.userId,
|
|
1653
|
+
reason: `illegal-mute-attempt; minutes=${minutes}`,
|
|
1654
|
+
};
|
|
1655
|
+
try {
|
|
1656
|
+
await onebot.setGroupBan(groupId, userId, duration);
|
|
1657
|
+
return { ok: false, message: `喵~ 乱用禁言指令,已口球 ${minutes} 分钟。`, plan };
|
|
1658
|
+
}
|
|
1659
|
+
catch (error) {
|
|
1660
|
+
return { ok: false, message: `喵~ 检测到乱用禁言指令,但惩罚执行失败:${String(error)}`, plan };
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
toGroupId(session) {
|
|
1664
|
+
const groupId = Number(session.guildId);
|
|
1665
|
+
if (!Number.isFinite(groupId))
|
|
1666
|
+
return null;
|
|
1667
|
+
return groupId;
|
|
1668
|
+
}
|
|
1669
|
+
getOneBotApi(session) {
|
|
1670
|
+
if (session.platform !== 'onebot')
|
|
1671
|
+
return null;
|
|
1672
|
+
const onebot = session.onebot;
|
|
1673
|
+
return onebot ?? null;
|
|
1674
|
+
}
|
|
1675
|
+
// ============ AI 引擎所需的宿主能力 ============
|
|
1676
|
+
/** 供 AI 引擎抽取图片结构 */
|
|
1677
|
+
extractImages(session) {
|
|
1678
|
+
return this.extractImageElements(session);
|
|
1679
|
+
}
|
|
1680
|
+
/** 供 AI 引擎把图片引用转成 data URL */
|
|
1681
|
+
resolveImage(ref, session) {
|
|
1682
|
+
return this.resolveImageReferenceToDataUrl(ref, session);
|
|
1683
|
+
}
|
|
1684
|
+
/** AI 回复发送:优先引用触发消息,失败则退化为纯文本 */
|
|
1685
|
+
async sendReply(session, text) {
|
|
1686
|
+
if (!text)
|
|
1687
|
+
return;
|
|
1688
|
+
if (session.messageId) {
|
|
1689
|
+
try {
|
|
1690
|
+
await session.send([koishi_1.h.quote(session.messageId), koishi_1.h.text(text)]);
|
|
1691
|
+
return;
|
|
1692
|
+
}
|
|
1693
|
+
catch (error) {
|
|
1694
|
+
this._logger.warn(`[ai] quote send failed, fallback to plain: ${String(error)} | ${this.sessionTag(session)}`);
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
await session.send(koishi_1.h.text(text));
|
|
1698
|
+
}
|
|
1699
|
+
extractTextForFilter(session) {
|
|
1700
|
+
const raw = (session.content ?? '')
|
|
1701
|
+
.replace(/<[^>]+>/g, ' ')
|
|
1702
|
+
.replace(/\[CQ:[^\]]+\]/g, ' ');
|
|
1703
|
+
return raw.trim();
|
|
1704
|
+
}
|
|
1705
|
+
hasTextContent(session) {
|
|
1706
|
+
const text = this.extractTextForFilter(session);
|
|
1707
|
+
if (text)
|
|
1708
|
+
return true;
|
|
1709
|
+
// 有的适配器把图片/表情放在 elements 里,content 可能没文字;检查是否有文字元素
|
|
1710
|
+
for (const el of session.elements ?? []) {
|
|
1711
|
+
if (el.type === 'text' && String(el.text ?? el.content ?? '').trim())
|
|
1712
|
+
return true;
|
|
1713
|
+
}
|
|
1714
|
+
return false;
|
|
1715
|
+
}
|
|
1716
|
+
hasImageOrFace(session) {
|
|
1717
|
+
const content = session.content ?? '';
|
|
1718
|
+
if (/\[CQ:(image|face|record|video|flash),/i.test(content))
|
|
1719
|
+
return true;
|
|
1720
|
+
if (/<img\b/i.test(content))
|
|
1721
|
+
return true;
|
|
1722
|
+
return (session.elements ?? []).some((el) => {
|
|
1723
|
+
const t = String(el?.type ?? '').toLowerCase();
|
|
1724
|
+
return t === 'img' || t === 'image' || t === 'face' || t === 'record' || t === 'video' || t === 'flash';
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
hasCardMessage(session) {
|
|
1728
|
+
const content = session.content ?? '';
|
|
1729
|
+
if (/\[CQ:(json|xml),/i.test(content))
|
|
1730
|
+
return true;
|
|
1731
|
+
const elements = session.elements ?? [];
|
|
1732
|
+
return elements.some((el) => el.type === 'json' || el.type === 'xml');
|
|
1733
|
+
}
|
|
1734
|
+
hasForwardMessage(session) {
|
|
1735
|
+
const content = session.content ?? '';
|
|
1736
|
+
if (/\[CQ:forward,/i.test(content))
|
|
1737
|
+
return true;
|
|
1738
|
+
const elements = session.elements ?? [];
|
|
1739
|
+
return elements.some((el) => el.type === 'forward');
|
|
1740
|
+
}
|
|
1741
|
+
normalizeGuildId(guildId) {
|
|
1742
|
+
if (!guildId)
|
|
1743
|
+
return '';
|
|
1744
|
+
const matched = guildId.match(/\d+/)?.[0];
|
|
1745
|
+
return matched ?? guildId;
|
|
1746
|
+
}
|
|
1747
|
+
resolveModerationPolicy(session) {
|
|
1748
|
+
const currentGuild = this.normalizeGuildId(session.guildId);
|
|
1749
|
+
const rule = this.config.groupRules.find((item) => this.normalizeGuildId(item.guildId) === currentGuild);
|
|
1750
|
+
if (!rule) {
|
|
1751
|
+
return {
|
|
1752
|
+
bannedWords: this.config.bannedWords,
|
|
1753
|
+
strongKeywords: this.config.strongKeywords ?? [],
|
|
1754
|
+
whitelistKeywords: [],
|
|
1755
|
+
whitelistOnlyOwners: false,
|
|
1756
|
+
blockCardMessage: this.config.blockCardMessage,
|
|
1757
|
+
blockForwardMessage: this.config.blockForwardMessage,
|
|
1758
|
+
autoDeleteViolation: this.config.autoDeleteViolation,
|
|
1759
|
+
sendViolationNotice: this.config.sendViolationNotice,
|
|
1760
|
+
enableAutoMute: this.config.enableAutoMute,
|
|
1761
|
+
autoMuteThreshold: this.config.autoMuteViolationThreshold,
|
|
1762
|
+
autoMuteMinutes: this.config.autoMuteMinutes,
|
|
1763
|
+
enableAutoKick: this.config.enableAutoKick,
|
|
1764
|
+
autoKickThreshold: this.config.autoKickViolationThreshold,
|
|
1765
|
+
violationWindowMinutes: this.config.autoViolationWindowMinutes,
|
|
1766
|
+
};
|
|
1767
|
+
}
|
|
1768
|
+
return {
|
|
1769
|
+
bannedWords: rule.bannedWords,
|
|
1770
|
+
strongKeywords: (Array.isArray(rule.strongKeywords) && rule.strongKeywords.length)
|
|
1771
|
+
? rule.strongKeywords
|
|
1772
|
+
: (this.config.strongKeywords ?? []),
|
|
1773
|
+
whitelistKeywords: rule.whitelistKeywords || [],
|
|
1774
|
+
whitelistOnlyOwners: rule.whitelistOnlyOwners === true,
|
|
1775
|
+
blockCardMessage: rule.blockCardMessage,
|
|
1776
|
+
blockForwardMessage: rule.blockForwardMessage,
|
|
1777
|
+
autoDeleteViolation: rule.autoDeleteViolation,
|
|
1778
|
+
sendViolationNotice: rule.sendViolationNotice,
|
|
1779
|
+
enableAutoMute: rule.autoMuteEnabled ?? this.config.enableAutoMute,
|
|
1780
|
+
autoMuteThreshold: rule.autoMuteThreshold ?? this.config.autoMuteViolationThreshold,
|
|
1781
|
+
autoMuteMinutes: rule.autoMuteMinutes ?? this.config.autoMuteMinutes,
|
|
1782
|
+
enableAutoKick: rule.autoKickEnabled ?? this.config.enableAutoKick,
|
|
1783
|
+
autoKickThreshold: rule.autoKickThreshold ?? this.config.autoKickViolationThreshold,
|
|
1784
|
+
violationWindowMinutes: rule.autoViolationWindowMinutes ?? this.config.autoViolationWindowMinutes,
|
|
1785
|
+
};
|
|
1786
|
+
}
|
|
1787
|
+
/**
|
|
1788
|
+
* 违禁词分档默认分值(可通过配置用 "关键词|分值" 或 {keyword,score} 覆盖)
|
|
1789
|
+
* 设计原则:单独出现时属于强广告特征的词给高分(可独立触发),
|
|
1790
|
+
* 需要组合才能确认的弱特征词给低分(需多条累计)。
|
|
1791
|
+
*/
|
|
1792
|
+
static DEFAULT_BANNED_WORD_SCORES = {
|
|
1793
|
+
// 显式广告行为(单条精确命中即可接近/达到阈值)
|
|
1794
|
+
'加群': 50, '拉人': 50, '拉群': 50, '互推': 50, '引流': 55,
|
|
1795
|
+
'加微信': 55, '加v': 50, '加V': 50, '加qq': 50, '加QQ': 50,
|
|
1796
|
+
'扫码进群': 80, '进群领': 60, '加我好友': 50, '私信我': 50,
|
|
1797
|
+
'点击链接': 50, '刷单': 60, '躺赚': 60, '日结': 50,
|
|
1798
|
+
// 需要组合确认的运营/营销词
|
|
1799
|
+
'邀请你': 35, '问卷': 30, '兼职': 40, '赚钱': 35, '赚米': 35,
|
|
1800
|
+
'返利': 45, '代理': 30, '招人': 35, '零成本': 40, '速来': 30,
|
|
1801
|
+
'福利群': 45, '红包群': 45, '活动群': 40, '转发群': 40,
|
|
1802
|
+
'免费领': 50, '免费送': 45, '领红包': 40, '抢红包': 35, '领福利': 40,
|
|
1803
|
+
'点击查看': 35, '名额有限': 35,
|
|
1804
|
+
};
|
|
1805
|
+
static DEFAULT_BANNED_WORD_SCORE = 40;
|
|
1806
|
+
normalizeBannedWordEntry(entry) {
|
|
1807
|
+
const raw = String(entry ?? '').trim();
|
|
1808
|
+
if (!raw)
|
|
1809
|
+
return null;
|
|
1810
|
+
let keyword = raw;
|
|
1811
|
+
let score = null;
|
|
1812
|
+
// 支持 "关键词|分值"、全角竖线、逗号分隔
|
|
1813
|
+
const m = raw.match(/^(.+?)\s*[||,,::]\s*(\d{1,3})$/);
|
|
1814
|
+
if (m) {
|
|
1815
|
+
keyword = m[1].trim();
|
|
1816
|
+
const parsed = parseInt(m[2], 10);
|
|
1817
|
+
if (Number.isFinite(parsed))
|
|
1818
|
+
score = Math.max(0, Math.min(100, parsed));
|
|
1819
|
+
}
|
|
1820
|
+
if (!keyword)
|
|
1821
|
+
return null;
|
|
1822
|
+
if (score === null) {
|
|
1823
|
+
const table = this.constructor.DEFAULT_BANNED_WORD_SCORES || {};
|
|
1824
|
+
const hit = Object.keys(table).find((k) => k.toLowerCase() === keyword.toLowerCase());
|
|
1825
|
+
score = hit ? table[hit] : this.constructor.DEFAULT_BANNED_WORD_SCORE;
|
|
1826
|
+
}
|
|
1827
|
+
return { keyword, score };
|
|
1828
|
+
}
|
|
1829
|
+
normalizeBannedWordList(list) {
|
|
1830
|
+
const out = [];
|
|
1831
|
+
const seen = new Set();
|
|
1832
|
+
for (const entry of list ?? []) {
|
|
1833
|
+
let keyword;
|
|
1834
|
+
let score;
|
|
1835
|
+
if (entry && typeof entry === 'object') {
|
|
1836
|
+
keyword = String(entry.keyword ?? entry.word ?? entry.text ?? '').trim();
|
|
1837
|
+
const parsed = Number(entry.score ?? entry.weight ?? NaN);
|
|
1838
|
+
score = Number.isFinite(parsed) ? Math.max(0, Math.min(100, parsed)) : null;
|
|
1839
|
+
if (keyword && score === null) {
|
|
1840
|
+
const table = this.constructor.DEFAULT_BANNED_WORD_SCORES || {};
|
|
1841
|
+
const hit = Object.keys(table).find((k) => k.toLowerCase() === keyword.toLowerCase());
|
|
1842
|
+
score = hit ? table[hit] : this.constructor.DEFAULT_BANNED_WORD_SCORE;
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
else {
|
|
1846
|
+
const norm = this.normalizeBannedWordEntry(entry);
|
|
1847
|
+
if (!norm)
|
|
1848
|
+
continue;
|
|
1849
|
+
keyword = norm.keyword;
|
|
1850
|
+
score = norm.score;
|
|
1851
|
+
}
|
|
1852
|
+
if (!keyword)
|
|
1853
|
+
continue;
|
|
1854
|
+
const key = keyword.toLowerCase();
|
|
1855
|
+
if (seen.has(key))
|
|
1856
|
+
continue;
|
|
1857
|
+
seen.add(key);
|
|
1858
|
+
out.push({ keyword, score });
|
|
1859
|
+
}
|
|
1860
|
+
return out;
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* 顺序子序列匹配:关键词的字符按顺序出现在文本中即命中,允许中间隔词。
|
|
1864
|
+
* 返回匹配跨度与紧凑度(跨度越接近词长,置信度越高)。
|
|
1865
|
+
*/
|
|
1866
|
+
/**
|
|
1867
|
+
* 模糊命中的最低置信度门槛。
|
|
1868
|
+
* 短关键词(2~4 字)极易被无关文本凑齐(如「领导说…红色包装袋」凑出「领红包」),
|
|
1869
|
+
* 因此对短词要求更高的置信度;长词本身信息量足,门槛可放宽。
|
|
1870
|
+
*/
|
|
1871
|
+
minBannedWordConfidence(keywordLength) {
|
|
1872
|
+
if (keywordLength <= 1)
|
|
1873
|
+
return 1;
|
|
1874
|
+
if (keywordLength <= 2)
|
|
1875
|
+
return 0.6;
|
|
1876
|
+
if (keywordLength <= 4)
|
|
1877
|
+
return 0.65;
|
|
1878
|
+
if (keywordLength <= 6)
|
|
1879
|
+
return 0.55;
|
|
1880
|
+
return 0.45;
|
|
1881
|
+
}
|
|
1882
|
+
subsequenceMatch(text, keyword) {
|
|
1883
|
+
if (!text || !keyword)
|
|
1884
|
+
return null;
|
|
1885
|
+
const first = text.indexOf(keyword);
|
|
1886
|
+
if (first >= 0) {
|
|
1887
|
+
return { start: first, end: first + keyword.length, span: keyword.length, ratio: 1, exact: true };
|
|
1888
|
+
}
|
|
1889
|
+
const chars = Array.from(keyword);
|
|
1890
|
+
let pos = 0;
|
|
1891
|
+
let start = -1;
|
|
1892
|
+
let end = -1;
|
|
1893
|
+
for (let i = 0; i < chars.length; i++) {
|
|
1894
|
+
const idx = text.indexOf(chars[i], pos);
|
|
1895
|
+
if (idx < 0) {
|
|
1896
|
+
// 单个字符找不到即判定不命中
|
|
1897
|
+
return null;
|
|
1898
|
+
}
|
|
1899
|
+
if (i === 0)
|
|
1900
|
+
start = idx;
|
|
1901
|
+
end = idx;
|
|
1902
|
+
pos = idx + 1;
|
|
1903
|
+
}
|
|
1904
|
+
const span = end - start + 1;
|
|
1905
|
+
const overflow = span - chars.length;
|
|
1906
|
+
// 分散过滤:隔得太开(跨度超过词长 + 8 或 3 倍词长)视为偶然凑齐
|
|
1907
|
+
if (span > chars.length * 3 || overflow > 8) {
|
|
1908
|
+
return null;
|
|
1909
|
+
}
|
|
1910
|
+
// 置信度按「词长归一化的溢出」衰减:短词对间隔更敏感
|
|
1911
|
+
// 例:领红包(len3) 在「领xxx元红包」(span6,overflow3) → 1-0.25*1 = 0.75
|
|
1912
|
+
const confidence = Math.max(0.25, 1 - 0.25 * (overflow / chars.length));
|
|
1913
|
+
// 短词需要更高置信度才算命中,避免无关文本偶然凑齐字符
|
|
1914
|
+
if (confidence < this.minBannedWordConfidence(chars.length)) {
|
|
1915
|
+
return null;
|
|
1916
|
+
}
|
|
1917
|
+
return { start, end: end + 1, span, overflow, ratio: chars.length / span, confidence, exact: false };
|
|
1918
|
+
}
|
|
1919
|
+
evaluateBannedWords(text, policy) {
|
|
1920
|
+
const words = this.normalizeBannedWordList(policy?.bannedWords ?? []);
|
|
1921
|
+
const evaluations = [];
|
|
1922
|
+
let total = 0;
|
|
1923
|
+
for (const { keyword, score } of words) {
|
|
1924
|
+
if (!keyword || keyword.length < 1)
|
|
1925
|
+
continue;
|
|
1926
|
+
const match = this.subsequenceMatch(text, keyword);
|
|
1927
|
+
if (!match)
|
|
1928
|
+
continue;
|
|
1929
|
+
const confidence = match.exact ? 1 : (match.confidence ?? 0.3);
|
|
1930
|
+
const gained = Math.round(score * Math.min(1, confidence) * 100) / 100;
|
|
1931
|
+
if (gained <= 0)
|
|
1932
|
+
continue;
|
|
1933
|
+
total += gained;
|
|
1934
|
+
evaluations.push({
|
|
1935
|
+
keyword,
|
|
1936
|
+
score,
|
|
1937
|
+
confidence: Math.round(Math.min(1, confidence) * 100) / 100,
|
|
1938
|
+
gained,
|
|
1939
|
+
span: match.span,
|
|
1940
|
+
exact: !!match.exact,
|
|
1941
|
+
});
|
|
1942
|
+
}
|
|
1943
|
+
evaluations.sort((a, b) => b.gained - a.gained);
|
|
1944
|
+
return { total: Math.round(total * 100) / 100, evaluations };
|
|
1945
|
+
}
|
|
1946
|
+
/**
|
|
1947
|
+
* 违禁词白名单豁免检查。
|
|
1948
|
+
*
|
|
1949
|
+
* 用于「校学生会招新」这类特殊场景:招新文案本身会包含“加群”“群号”等
|
|
1950
|
+
* 违禁词,但只要命中白名单关键词(如“宣传部”“纪检部”),就整条跳过违禁词评分。
|
|
1951
|
+
*
|
|
1952
|
+
* 返回 { keyword, reason } 表示命中并豁免;返回 null 表示未命中。
|
|
1953
|
+
*/
|
|
1954
|
+
async checkWhitelistBypass(session, policy, text) {
|
|
1955
|
+
const keywords = (policy?.whitelistKeywords ?? [])
|
|
1956
|
+
.map((w) => String(w ?? '').trim())
|
|
1957
|
+
.filter(Boolean);
|
|
1958
|
+
if (!keywords.length || !text)
|
|
1959
|
+
return null;
|
|
1960
|
+
const hit = keywords.find((kw) => text.includes(kw));
|
|
1961
|
+
if (!hit)
|
|
1962
|
+
return null;
|
|
1963
|
+
// 可选的权限收紧:仅群主/管理员可用白名单
|
|
1964
|
+
if (policy.whitelistOnlyOwners) {
|
|
1965
|
+
const role = await this.resolveMemberRole(session);
|
|
1966
|
+
if (role !== 'owner' && role !== 'admin') {
|
|
1967
|
+
this._logger.info(`[whitelist] 命中「${hit}」但发送者非群主/管理员(role=${role}),不豁免 | ${this.sessionTag(session)}`);
|
|
1968
|
+
return null;
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
return { keyword: hit, reason: 'whitelist' };
|
|
1972
|
+
}
|
|
1973
|
+
async detectViolation(session, policy, type = 'message') {
|
|
1974
|
+
// 纯图片/表情/贴纸(无实际文字内容)的消息不作为违规处理,避免表情包被当成违禁词
|
|
1975
|
+
if (type === 'message' && this.hasImageOrFace(session) && !this.hasTextContent(session)) {
|
|
1976
|
+
return null;
|
|
1977
|
+
}
|
|
1978
|
+
if (policy.blockCardMessage && this.hasCardMessage(session)) {
|
|
1979
|
+
return { type: 'card', detail: '检测到卡片消息(json/xml)' };
|
|
1980
|
+
}
|
|
1981
|
+
if (policy.blockForwardMessage && this.hasForwardMessage(session)) {
|
|
1982
|
+
return { type: 'forward', detail: '检测到合并转发消息(forward)' };
|
|
1983
|
+
}
|
|
1984
|
+
const text = this.extractTextForFilter(session);
|
|
1985
|
+
if (!text)
|
|
1986
|
+
return null;
|
|
1987
|
+
const threshold = Math.max(1, Math.min(100, Number(this.config.bannedWordScoreThreshold ?? 70)));
|
|
1988
|
+
// 强关键词:在【白名单豁免之前】判定。命中即可触发管控,白名单不豁免。
|
|
1989
|
+
// 用于「有没有美女」这类与招新无关的骚扰/找对象话术——即使消息里带了
|
|
1990
|
+
// 「宣传部」等白名单词也照样命中,堵住「附一个白名单词即可绕过管控」的漏洞。
|
|
1991
|
+
const strong = this.evaluateBannedWords(text, { bannedWords: policy?.strongKeywords ?? [] });
|
|
1992
|
+
if (strong.total >= threshold) {
|
|
1993
|
+
const strongTop = strong.evaluations.slice(0, 4)
|
|
1994
|
+
.map((item) => `${item.keyword}(+${item.gained}${item.exact ? '' : `/${item.confidence}`})`)
|
|
1995
|
+
.join(' ');
|
|
1996
|
+
this._logger.info(`[strong] 强关键词评分 ${strong.total}/${threshold}(无视白名单):${strongTop} | ${this.sessionTag(session)}`);
|
|
1997
|
+
return {
|
|
1998
|
+
type: 'banned-word',
|
|
1999
|
+
detail: `强关键词评分 ${strong.total}/${threshold}(无视白名单):${strongTop}`,
|
|
2000
|
+
assessment: strong,
|
|
2001
|
+
strong: true,
|
|
2002
|
+
};
|
|
2003
|
+
}
|
|
2004
|
+
// 白名单豁免:命中白名单关键词则跳过违禁词评分(招新等允许的宣传场景)。
|
|
2005
|
+
// 注意:卡片/合并转发的拦截在上面已判定,白名单只豁免「违禁词」,不放过卡片类消息。
|
|
2006
|
+
const bypass = await this.checkWhitelistBypass(session, policy, text);
|
|
2007
|
+
if (bypass) {
|
|
2008
|
+
this._logger.info(`[whitelist] 命中「${bypass.keyword}」,跳过违禁词管控 | ${this.sessionTag(session)}`);
|
|
2009
|
+
return null;
|
|
2010
|
+
}
|
|
2011
|
+
const assessment = this.evaluateBannedWords(text, policy);
|
|
2012
|
+
if (assessment.total >= threshold) {
|
|
2013
|
+
const top = assessment.evaluations.slice(0, 4)
|
|
2014
|
+
.map((item) => `${item.keyword}(+${item.gained}${item.exact ? '' : `/${item.confidence}`})`)
|
|
2015
|
+
.join(' ');
|
|
2016
|
+
return {
|
|
2017
|
+
type: 'banned-word',
|
|
2018
|
+
detail: `违禁词评分 ${assessment.total}/${threshold}:${top}`,
|
|
2019
|
+
assessment,
|
|
2020
|
+
};
|
|
2021
|
+
}
|
|
2022
|
+
return null;
|
|
2023
|
+
}
|
|
2024
|
+
async deleteMessage(session) {
|
|
2025
|
+
const onebot = this.getOneBotApi(session);
|
|
2026
|
+
const messageId = session.messageId;
|
|
2027
|
+
if (!onebot?.deleteMsg || !messageId)
|
|
2028
|
+
return false;
|
|
2029
|
+
try {
|
|
2030
|
+
await onebot.deleteMsg(messageId);
|
|
2031
|
+
return true;
|
|
2032
|
+
}
|
|
2033
|
+
catch (error) {
|
|
2034
|
+
this._logger.warn(`[moderation] 撤回失败: ${String(error)} | ${this.sessionTag(session)}`);
|
|
2035
|
+
return false;
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
async shouldExemptViolationPunish(session) {
|
|
2039
|
+
if (!session?.userId || !session.guildId || session.platform !== 'onebot')
|
|
2040
|
+
return true;
|
|
2041
|
+
if (session.bot?.selfId && session.userId === String(session.bot.selfId))
|
|
2042
|
+
return true;
|
|
2043
|
+
if (this.config.allowedUserIds.includes(session.userId))
|
|
2044
|
+
return true;
|
|
2045
|
+
const role = await this.resolveMemberRole(session);
|
|
2046
|
+
return role === 'owner' || role === 'admin';
|
|
2047
|
+
}
|
|
2048
|
+
recordViolation(session, policy) {
|
|
2049
|
+
const key = `${session.guildId}:${session.userId}`;
|
|
2050
|
+
const windowMs = Math.max(1, policy.violationWindowMinutes || 60) * 60 * 1000;
|
|
2051
|
+
const now = Date.now();
|
|
2052
|
+
const prev = this.violationRecords.get(key);
|
|
2053
|
+
let count = 1;
|
|
2054
|
+
if (prev && now - prev.lastAt <= windowMs) {
|
|
2055
|
+
count = (prev.count || 0) + 1;
|
|
2056
|
+
}
|
|
2057
|
+
this.violationRecords.set(key, { count, lastAt: now });
|
|
2058
|
+
return count;
|
|
2059
|
+
}
|
|
2060
|
+
clearViolationRecord(session) {
|
|
2061
|
+
this.violationRecords.delete(`${session.guildId}:${session.userId}`);
|
|
2062
|
+
}
|
|
2063
|
+
async autoModerationPunish(session, policy) {
|
|
2064
|
+
if (session.platform !== 'onebot')
|
|
2065
|
+
return null;
|
|
2066
|
+
if (await this.shouldExemptViolationPunish(session))
|
|
2067
|
+
return null;
|
|
2068
|
+
const count = this.recordViolation(session, policy);
|
|
2069
|
+
const onebot = this.getOneBotApi(session);
|
|
2070
|
+
const groupId = this.toGroupId(session);
|
|
2071
|
+
const userId = Number(session.userId);
|
|
2072
|
+
if (!onebot?.setGroupBan || groupId == null || !Number.isFinite(userId)) {
|
|
2073
|
+
return { ok: false, action: 'none', count, message: '当前会话不支持自动处理接口,仅记录违规计数。' };
|
|
2074
|
+
}
|
|
2075
|
+
const kickThreshold = Math.max(1, Math.floor(policy.autoKickThreshold || 5));
|
|
2076
|
+
const muteThreshold = Math.max(1, Math.floor(policy.autoMuteThreshold || 3));
|
|
2077
|
+
if (policy.enableAutoKick && count >= kickThreshold && onebot?.setGroupKick) {
|
|
2078
|
+
try {
|
|
2079
|
+
await onebot.setGroupKick(groupId, userId, false);
|
|
2080
|
+
this.clearViolationRecord(session);
|
|
2081
|
+
// 触发踢出 → 加入本群黑名单
|
|
2082
|
+
await this.recordKickToBlacklist(session, String(userId));
|
|
2083
|
+
return { ok: true, action: 'auto-kick', count, message: `累计违规 ${count} 次,已自动移出群聊。` };
|
|
2084
|
+
}
|
|
2085
|
+
catch (error) {
|
|
2086
|
+
return { ok: false, action: 'auto-kick', count, message: `自动移出群聊失败: ${String(error)}` };
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
if (policy.enableAutoMute && count >= muteThreshold) {
|
|
2090
|
+
const requested = Math.max(1, Math.floor(policy.autoMuteMinutes || 10));
|
|
2091
|
+
const minutes = Math.min(requested, 43200);
|
|
2092
|
+
const duration = minutes * 60;
|
|
2093
|
+
try {
|
|
2094
|
+
await onebot.setGroupBan(groupId, userId, duration);
|
|
2095
|
+
return { ok: true, action: 'auto-mute', count, minutes, message: `累计违规 ${count} 次,已自动禁言 ${minutes} 分钟。` };
|
|
2096
|
+
}
|
|
2097
|
+
catch (error) {
|
|
2098
|
+
return { ok: false, action: 'auto-mute', count, message: `自动禁言失败: ${String(error)}` };
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
return { ok: true, action: 'none', count, message: `累计违规 ${count} 次(自动禁言线 ${muteThreshold} 次 / 自动踢人线 ${kickThreshold} 次)。` };
|
|
2102
|
+
}
|
|
2103
|
+
/**
|
|
2104
|
+
* 自定义命令处理器:整条消息与触发词完全一致(忽略首尾空白)即回复预设内容。
|
|
2105
|
+
* 触发词约定用方括号包裹(如 [签到])。命中后返回 true,调用方据此跳过后续
|
|
2106
|
+
* 违禁词管控与 AI 回复(自定义命令完全不走 AI)。
|
|
2107
|
+
*/
|
|
2108
|
+
async handleCustomCommand(session) {
|
|
2109
|
+
const list = Array.isArray(this.config.customCommands) ? this.config.customCommands : [];
|
|
2110
|
+
if (!list.length)
|
|
2111
|
+
return false;
|
|
2112
|
+
const text = this.getMessageText(session).trim();
|
|
2113
|
+
if (!text)
|
|
2114
|
+
return false;
|
|
2115
|
+
|
|
2116
|
+
const guildId = this.normalizeGuildId(session.guildId);
|
|
2117
|
+
const cmd = list.find((c) => {
|
|
2118
|
+
if (!c || c.enabled === false)
|
|
2119
|
+
return false;
|
|
2120
|
+
const trigger = String(c.trigger ?? '').trim();
|
|
2121
|
+
if (!trigger || trigger !== text)
|
|
2122
|
+
return false;
|
|
2123
|
+
const groups = (c.groups ?? []).map((g) => this.normalizeGuildId(g)).filter(Boolean);
|
|
2124
|
+
return !groups.length || groups.includes(guildId);
|
|
2125
|
+
});
|
|
2126
|
+
if (!cmd)
|
|
2127
|
+
return false;
|
|
2128
|
+
|
|
2129
|
+
// 冷却
|
|
2130
|
+
const cd = Number(cmd.cooldownSeconds || 0);
|
|
2131
|
+
if (cd > 0) {
|
|
2132
|
+
const key = `${guildId}:${cmd.trigger}`;
|
|
2133
|
+
if (!this._customCmdAt)
|
|
2134
|
+
this._customCmdAt = new Map();
|
|
2135
|
+
const last = this._customCmdAt.get(key) ?? 0;
|
|
2136
|
+
const left = Math.ceil((cd * 1000 - (Date.now() - last)) / 1000);
|
|
2137
|
+
if (left > 0) {
|
|
2138
|
+
if (cmd.logHit !== false)
|
|
2139
|
+
this._logger.info(`[custom-cmd] 「${cmd.trigger}」冷却中(剩余 ${left}s) | ${this.sessionTag(session)}`);
|
|
2140
|
+
return true; // 命中但冷却中,同样不交给 AI
|
|
2141
|
+
}
|
|
2142
|
+
this._customCmdAt.set(key, Date.now());
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
const replies = (cmd.replies ?? []).map((r) => String(r ?? '')).filter(Boolean);
|
|
2146
|
+
if (!replies.length) {
|
|
2147
|
+
this._logger.warn(`[custom-cmd] 「${cmd.trigger}」未配置回复内容 | ${this.sessionTag(session)}`);
|
|
2148
|
+
return true;
|
|
2149
|
+
}
|
|
2150
|
+
|
|
2151
|
+
// 多回复:随机 或 轮换
|
|
2152
|
+
let raw;
|
|
2153
|
+
if (replies.length === 1) {
|
|
2154
|
+
raw = replies[0];
|
|
2155
|
+
}
|
|
2156
|
+
else if (cmd.randomReply === true) {
|
|
2157
|
+
raw = replies[Math.floor(Math.random() * replies.length)];
|
|
2158
|
+
}
|
|
2159
|
+
else {
|
|
2160
|
+
const key = `${guildId}:${cmd.trigger}`;
|
|
2161
|
+
if (!this._customCmdIdx)
|
|
2162
|
+
this._customCmdIdx = new Map();
|
|
2163
|
+
const i = (this._customCmdIdx.get(key) ?? 0) % replies.length;
|
|
2164
|
+
this._customCmdIdx.set(key, i + 1);
|
|
2165
|
+
raw = replies[i];
|
|
2166
|
+
}
|
|
2167
|
+
|
|
2168
|
+
try {
|
|
2169
|
+
const parts = [];
|
|
2170
|
+
if (cmd.quote && session.messageId)
|
|
2171
|
+
parts.push(koishi_1.h.quote(session.messageId));
|
|
2172
|
+
// 变量占位符:{user} 昵称 / {at} @发送者 / {group} 群号
|
|
2173
|
+
const name = this.getDisplayName(session);
|
|
2174
|
+
let seg = raw;
|
|
2175
|
+
let guard = 0;
|
|
2176
|
+
while (guard++ < 20) {
|
|
2177
|
+
const atIdx = seg.indexOf('{at}');
|
|
2178
|
+
const userIdx = seg.indexOf('{user}');
|
|
2179
|
+
const groupIdx = seg.indexOf('{group}');
|
|
2180
|
+
const cands = [
|
|
2181
|
+
atIdx >= 0 ? { i: atIdx, k: 'at' } : null,
|
|
2182
|
+
userIdx >= 0 ? { i: userIdx, k: 'user' } : null,
|
|
2183
|
+
groupIdx >= 0 ? { i: groupIdx, k: 'group' } : null,
|
|
2184
|
+
].filter(Boolean).sort((a, b) => a.i - b.i);
|
|
2185
|
+
if (!cands.length)
|
|
2186
|
+
break;
|
|
2187
|
+
const first = cands[0];
|
|
2188
|
+
if (first.k === 'at') {
|
|
2189
|
+
if (seg.slice(0, first.i))
|
|
2190
|
+
parts.push(koishi_1.h.text(seg.slice(0, first.i)));
|
|
2191
|
+
parts.push(koishi_1.h.at(session.userId));
|
|
2192
|
+
seg = seg.slice(first.i + 4);
|
|
2193
|
+
}
|
|
2194
|
+
else if (first.k === 'user') {
|
|
2195
|
+
if (seg.slice(0, first.i))
|
|
2196
|
+
parts.push(koishi_1.h.text(seg.slice(0, first.i)));
|
|
2197
|
+
parts.push(koishi_1.h.text(name));
|
|
2198
|
+
seg = seg.slice(first.i + 6);
|
|
2199
|
+
}
|
|
2200
|
+
else {
|
|
2201
|
+
if (seg.slice(0, first.i))
|
|
2202
|
+
parts.push(koishi_1.h.text(seg.slice(0, first.i)));
|
|
2203
|
+
parts.push(koishi_1.h.text(String(session.guildId ?? '')));
|
|
2204
|
+
seg = seg.slice(first.i + 7);
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
if (seg)
|
|
2208
|
+
parts.push(koishi_1.h.text(seg));
|
|
2209
|
+
if (!parts.length)
|
|
2210
|
+
parts.push(koishi_1.h.text(raw));
|
|
2211
|
+
|
|
2212
|
+
await session.send(parts);
|
|
2213
|
+
if (cmd.logHit !== false)
|
|
2214
|
+
this._logger.info(`[custom-cmd] 命中「${cmd.trigger}」已回复 | ${this.sessionTag(session)}`);
|
|
2215
|
+
}
|
|
2216
|
+
catch (error) {
|
|
2217
|
+
this._logger.warn(`[custom-cmd] 「${cmd.trigger}」回复失败: ${String(error)} | ${this.sessionTag(session)}`);
|
|
2218
|
+
}
|
|
2219
|
+
return true;
|
|
2220
|
+
}
|
|
2221
|
+
/**
|
|
2222
|
+
* 读取指令前缀配置(带默认值)。
|
|
2223
|
+
*/
|
|
2224
|
+
cmdPrefix(key, def) {
|
|
2225
|
+
const v = this.config ? this.config[key] : undefined;
|
|
2226
|
+
return (typeof v === 'string' && v.trim()) ? v.trim() : def;
|
|
2227
|
+
}
|
|
2228
|
+
/**
|
|
2229
|
+
* 统一指令路由器:所有指令均为「方括号直连」语法,如 [mute] 12345 10 广告。
|
|
2230
|
+
* 命中并处理返回 true(不再走后续管控与 AI)。
|
|
2231
|
+
*/
|
|
2232
|
+
async routeBracketCommand(session) {
|
|
2233
|
+
const raw = (session.content || '').replace(/<at\b[^>]*\/?>/gi, ' ').trim();
|
|
2234
|
+
if (!raw.startsWith('['))
|
|
2235
|
+
return false;
|
|
2236
|
+
const m = raw.match(/^\[([^\]\s]+)\]\s*([\s\S]*)$/);
|
|
2237
|
+
if (!m)
|
|
2238
|
+
return false;
|
|
2239
|
+
const name = `[${m[1]}]`;
|
|
2240
|
+
const rest = (m[2] || '').trim();
|
|
2241
|
+
// @ 到的目标(可代替 QQ 号)
|
|
2242
|
+
const mentions = this.extractMentionedTargets(session);
|
|
2243
|
+
|
|
2244
|
+
// 菜单:单独发送 [bot]
|
|
2245
|
+
if (name === this.cmdPrefix('command', '[bot]')) {
|
|
2246
|
+
if (!rest) {
|
|
2247
|
+
await this.sendCommandMenu(session);
|
|
2248
|
+
return true;
|
|
2249
|
+
}
|
|
2250
|
+
return false;
|
|
2251
|
+
}
|
|
2252
|
+
if (name === this.cmdPrefix('cmdMute', '[mute]'))
|
|
2253
|
+
return this.execMute(session, rest, mentions);
|
|
2254
|
+
if (name === this.cmdPrefix('cmdUnmute', '[unmute]'))
|
|
2255
|
+
return this.execUnmute(session, rest, mentions);
|
|
2256
|
+
if (name === this.cmdPrefix('cmdKick', '[kick]'))
|
|
2257
|
+
return this.execKick(session, rest, mentions);
|
|
2258
|
+
// 记忆:统一使用 [memory](旧 [记忆] 写法已废弃)
|
|
2259
|
+
if (name === this.cmdPrefix('cmdMemory', '[memory]'))
|
|
2260
|
+
return this.execMemory(session, rest);
|
|
2261
|
+
if (name === this.cmdPrefix('cmdBan', '[ban]'))
|
|
2262
|
+
return this.execBanAdd(session, rest, mentions);
|
|
2263
|
+
if (name === this.cmdPrefix('cmdUnban', '[unban]'))
|
|
2264
|
+
return this.execUnban(session, rest, mentions);
|
|
2265
|
+
if (name === this.cmdPrefix('cmdBanList', '[banlist]')) {
|
|
2266
|
+
await this.execBanList(session);
|
|
2267
|
+
return true;
|
|
2268
|
+
}
|
|
2269
|
+
if (name === this.cmdPrefix('cmdCustom', '[custom]')) {
|
|
2270
|
+
await this.sendCustomCommandList(session);
|
|
2271
|
+
return true;
|
|
2272
|
+
}
|
|
2273
|
+
// 插件信息:单独发送 [Version]
|
|
2274
|
+
if (name === this.cmdPrefix('cmdVersion', '[Version]')) {
|
|
2275
|
+
await this.sendVersionInfo(session);
|
|
2276
|
+
return true;
|
|
2277
|
+
}
|
|
2278
|
+
return false;
|
|
2279
|
+
}
|
|
2280
|
+
/**
|
|
2281
|
+
* 指令菜单:行首用中文介绍功能名称,指令本身保持英文([记忆] 新规)。
|
|
2282
|
+
* 记忆查询紧跟在记忆保存之后;冒号后留一个空行,避免标题与条目挤在一起。
|
|
2283
|
+
*/
|
|
2284
|
+
async sendCommandMenu(session) {
|
|
2285
|
+
const P = (k, d) => this.cmdPrefix(k, d);
|
|
2286
|
+
const lines = [
|
|
2287
|
+
'禁言 ' + P('cmdMute', '[mute]') + ' qq time reason',
|
|
2288
|
+
'解除禁言 ' + P('cmdUnmute', '[unmute]') + ' qq reason',
|
|
2289
|
+
'记忆保存 ' + P('cmdMemory', '[memory]') + ' content',
|
|
2290
|
+
'记忆查询 ' + P('cmdMemory', '[memory]') + ' search keyword',
|
|
2291
|
+
'拉黑 ' + P('cmdBan', '[ban]') + ' qq reason',
|
|
2292
|
+
'解除拉黑 ' + P('cmdUnban', '[unban]') + ' qq reason',
|
|
2293
|
+
'黑名单查询 ' + P('cmdBanList', '[banlist]'),
|
|
2294
|
+
'自定义指令集 ' + P('cmdCustom', '[custom]'),
|
|
2295
|
+
'踢人 ' + P('cmdKick', '[kick]') + ' qq reason',
|
|
2296
|
+
'插件信息 ' + P('cmdVersion', '[Version]'),
|
|
2297
|
+
];
|
|
2298
|
+
await session.send(this.styleText(
|
|
2299
|
+
'可用指令:\n\n' + lines.join('\n')
|
|
2300
|
+
));
|
|
2301
|
+
}
|
|
2302
|
+
/** 自定义指令集:列出当前生效的自定义命令;没有配置时明确提示暂无指令 */
|
|
2303
|
+
async sendCustomCommandList(session) {
|
|
2304
|
+
const list = (Array.isArray(this.config.customCommands) ? this.config.customCommands : [])
|
|
2305
|
+
.filter((c) => c && c.enabled !== false && String(c.trigger || '').trim());
|
|
2306
|
+
if (!list.length) {
|
|
2307
|
+
await session.send(this.styleText('目前还没有指令。'));
|
|
2308
|
+
return;
|
|
2309
|
+
}
|
|
2310
|
+
const lines = list.map((c) => `${String(c.trigger).trim()} → ${(c.replies || []).length} 条回复`);
|
|
2311
|
+
await session.send(this.styleText(`自定义指令集(共 ${list.length} 条):\n${lines.join('\n')}`));
|
|
2312
|
+
}
|
|
2313
|
+
/**
|
|
2314
|
+
* [Version]:查看插件信息(当前版本、作者、仓库与 npm 地址)。
|
|
2315
|
+
* 版本号与仓库地址从 package.json 读取,避免发版时忘记同步。
|
|
2316
|
+
*/
|
|
2317
|
+
async sendVersionInfo(session) {
|
|
2318
|
+
let version = 'unknown';
|
|
2319
|
+
let repoUrl = '';
|
|
2320
|
+
let npmUrl = 'https://www.npmjs.com/package/@nestim/koishi-plugin-qq-group-manager';
|
|
2321
|
+
try {
|
|
2322
|
+
const pkg = require('../package.json');
|
|
2323
|
+
if (pkg && pkg.version)
|
|
2324
|
+
version = String(pkg.version);
|
|
2325
|
+
const rawRepo = (pkg && pkg.repository && pkg.repository.url) || '';
|
|
2326
|
+
repoUrl = String(rawRepo).replace(/^git\+/, '').replace(/\.git$/, '');
|
|
2327
|
+
const rawHome = (pkg && pkg.homepage) || '';
|
|
2328
|
+
if (!repoUrl && rawHome)
|
|
2329
|
+
repoUrl = String(rawHome).replace(/#.*$/, '');
|
|
2330
|
+
}
|
|
2331
|
+
catch (error) {
|
|
2332
|
+
this._logger.warn(`[version] 读取 package.json 失败: ${String(error)}`);
|
|
2333
|
+
}
|
|
2334
|
+
const lines = [
|
|
2335
|
+
'【插件信息】',
|
|
2336
|
+
`当前版本:${version}`,
|
|
2337
|
+
'作者:Nestim',
|
|
2338
|
+
];
|
|
2339
|
+
if (repoUrl)
|
|
2340
|
+
lines.push(`GitHub:${repoUrl}`);
|
|
2341
|
+
lines.push(`npm:${npmUrl}`);
|
|
2342
|
+
await session.send(this.styleText(lines.join('\n')));
|
|
2343
|
+
this.logCommandResult('version', { ok: true, message: 'version info sent' }, session, { version });
|
|
2344
|
+
}
|
|
2345
|
+
/** 权限不足提示 */
|
|
2346
|
+
async denyAdmin(session, message) {
|
|
2347
|
+
await session.send(this.styleText(message || '你没有权限执行该操作。'));
|
|
2348
|
+
return true;
|
|
2349
|
+
}
|
|
2350
|
+
/**
|
|
2351
|
+
* 群管指令的统一鉴权(两步):
|
|
2352
|
+
* ① authorizeCommand —— 判定「谁在操作」:账号白名单 / 群主 / 群管理员;
|
|
2353
|
+
* ② canUseAdminCommand —— 确认「bot 在该群是否具备管理能力」。
|
|
2354
|
+
*
|
|
2355
|
+
* 此前方括号指令只做了第②步,导致 allowedUserIds / allowGroupOwner /
|
|
2356
|
+
* allowGroupAdmin 对 mute/unmute/kick/ban/unban 完全失效:配置里允许群主操作,
|
|
2357
|
+
* 但只要 bot 不是群主就会被拒;反过来当 bot 是群主时,任何群成员都能踢人。
|
|
2358
|
+
*/
|
|
2359
|
+
async authorizeModerationAction(command, session) {
|
|
2360
|
+
const auth = await this.authorizeCommand(command, session);
|
|
2361
|
+
if (!auth.ok) {
|
|
2362
|
+
this._logger.warn(`[auth:${command}] 拒绝(操作者权限不足): ${auth.message} | ${this.sessionTag(session)}`);
|
|
2363
|
+
return { ok: false, message: auth.userMessage || '你没有权限执行该操作。' };
|
|
2364
|
+
}
|
|
2365
|
+
const capability = await this.canUseAdminCommand(session);
|
|
2366
|
+
if (!capability.ok) {
|
|
2367
|
+
this._logger.warn(`[auth:${command}] 拒绝(bot 无管理能力): ${capability.message} | ${this.sessionTag(session)}`);
|
|
2368
|
+
return { ok: false, message: capability.userMessage || '你没有权限执行该操作。' };
|
|
2369
|
+
}
|
|
2370
|
+
return { ok: true, message: auth.message };
|
|
2371
|
+
}
|
|
2372
|
+
/** [mute] qq号|@某人 时长 [原因] */
|
|
2373
|
+
async execMute(session, rest, mentions = []) {
|
|
2374
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
2375
|
+
// 目标:优先取显式 qq号(纯数字),否则用 @ 到的第一个人
|
|
2376
|
+
let target = '';
|
|
2377
|
+
let consumed = 0;
|
|
2378
|
+
if (tokens[0] && /^\d{5,12}$/.test(tokens[0])) {
|
|
2379
|
+
target = tokens[0];
|
|
2380
|
+
consumed = 1;
|
|
2381
|
+
}
|
|
2382
|
+
else if (mentions.length) {
|
|
2383
|
+
target = mentions[0];
|
|
2384
|
+
consumed = 0; // @ 不在 tokens 里(已从 content 剥离)
|
|
2385
|
+
}
|
|
2386
|
+
if (!target) {
|
|
2387
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdMute', '[mute]')} qq|@user duration [reason](时长如 10 / 10m / 1h / 1d)`));
|
|
2388
|
+
return true;
|
|
2389
|
+
}
|
|
2390
|
+
const remaining = tokens.slice(consumed);
|
|
2391
|
+
let minutes = null;
|
|
2392
|
+
let reason = '';
|
|
2393
|
+
if (remaining[0]) {
|
|
2394
|
+
const d = this.parseDurationToken(remaining[0]);
|
|
2395
|
+
if (d) {
|
|
2396
|
+
minutes = d.minutes;
|
|
2397
|
+
reason = remaining.slice(1).join(' ');
|
|
2398
|
+
}
|
|
2399
|
+
else {
|
|
2400
|
+
reason = remaining.join(' ');
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
if (minutes == null) {
|
|
2404
|
+
await session.send(this.styleText('请给出有效的禁言时长,例如:10 / 10m / 1h / 1d。'));
|
|
2405
|
+
return true;
|
|
2406
|
+
}
|
|
2407
|
+
const auth = await this.authorizeModerationAction('mute', session);
|
|
2408
|
+
if (!auth.ok)
|
|
2409
|
+
return this.denyAdmin(session, auth.message);
|
|
2410
|
+
const r = await this.mute(session, target, minutes, reason);
|
|
2411
|
+
await session.send(this.styleText(r.message));
|
|
2412
|
+
this._logger.info(`[cmd:mute] target=${target} minutes=${minutes} byMention=${consumed === 0 && !!mentions.length} | ${this.sessionTag(session)}`);
|
|
2413
|
+
return true;
|
|
2414
|
+
}
|
|
2415
|
+
/** [unmute] qq号|@某人 [原因] */
|
|
2416
|
+
async execUnmute(session, rest, mentions = []) {
|
|
2417
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
2418
|
+
let target = '';
|
|
2419
|
+
let consumed = 0;
|
|
2420
|
+
if (tokens[0] && /^\d{5,12}$/.test(tokens[0])) {
|
|
2421
|
+
target = tokens[0];
|
|
2422
|
+
consumed = 1;
|
|
2423
|
+
}
|
|
2424
|
+
else if (mentions.length) {
|
|
2425
|
+
target = mentions[0];
|
|
2426
|
+
}
|
|
2427
|
+
if (!target) {
|
|
2428
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdUnmute', '[unmute]')} qq号|@某人 原因(原因选填)`));
|
|
2429
|
+
return true;
|
|
2430
|
+
}
|
|
2431
|
+
const auth = await this.authorizeModerationAction('unmute', session);
|
|
2432
|
+
if (!auth.ok)
|
|
2433
|
+
return this.denyAdmin(session, auth.message);
|
|
2434
|
+
const r = await this.unmute(session, target, tokens.slice(consumed).join(' '));
|
|
2435
|
+
await session.send(this.styleText(r.message));
|
|
2436
|
+
this._logger.info(`[cmd:unmute] target=${target} | ${this.sessionTag(session)}`);
|
|
2437
|
+
return true;
|
|
2438
|
+
}
|
|
2439
|
+
/** [kick] qq号|@某人 [原因] */
|
|
2440
|
+
async execKick(session, rest, mentions = []) {
|
|
2441
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
2442
|
+
let target = '';
|
|
2443
|
+
let consumed = 0;
|
|
2444
|
+
if (tokens[0] && /^\d{5,12}$/.test(tokens[0])) {
|
|
2445
|
+
target = tokens[0];
|
|
2446
|
+
consumed = 1;
|
|
2447
|
+
}
|
|
2448
|
+
else if (mentions.length) {
|
|
2449
|
+
target = mentions[0];
|
|
2450
|
+
}
|
|
2451
|
+
if (!target) {
|
|
2452
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdKick', '[kick]')} qq号|@某人 原因(原因选填)`));
|
|
2453
|
+
return true;
|
|
2454
|
+
}
|
|
2455
|
+
const auth = await this.authorizeModerationAction('kick', session);
|
|
2456
|
+
if (!auth.ok)
|
|
2457
|
+
return this.denyAdmin(session, auth.message);
|
|
2458
|
+
const r = await this.kick(session, target, false, tokens.slice(consumed).join(' '));
|
|
2459
|
+
await session.send(this.styleText(r.message));
|
|
2460
|
+
this._logger.info(`[cmd:kick] target=${target} | ${this.sessionTag(session)}`);
|
|
2461
|
+
return true;
|
|
2462
|
+
}
|
|
2463
|
+
/** [memory] content / [memory] list / [memory] search keyword / [memory] delete keyword */
|
|
2464
|
+
async execMemory(session, rest) {
|
|
2465
|
+
if (!this.config.enableMemory) {
|
|
2466
|
+
await session.send(this.styleText('记忆库未启用。'));
|
|
2467
|
+
return true;
|
|
2468
|
+
}
|
|
2469
|
+
const sub = rest.trim();
|
|
2470
|
+
if (!sub) {
|
|
2471
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdMemory', '[memory]')} content 保存|${this.cmdPrefix('cmdMemory', '[memory]')} list 列出|${this.cmdPrefix('cmdMemory', '[memory]')} search keyword 查询|${this.cmdPrefix('cmdMemory', '[memory]')} delete keyword 删除`));
|
|
2472
|
+
return true;
|
|
2473
|
+
}
|
|
2474
|
+
const delMatch = sub.match(/^(?:delete|del)\s*([\s\S]*)$/i);
|
|
2475
|
+
if (delMatch) {
|
|
2476
|
+
const keyword = delMatch[1].trim();
|
|
2477
|
+
if (!keyword) {
|
|
2478
|
+
await session.send(this.styleText('请给出要删除的关键词。'));
|
|
2479
|
+
return true;
|
|
2480
|
+
}
|
|
2481
|
+
const results = await this.searchMemory(keyword, 8);
|
|
2482
|
+
if (!results.length) {
|
|
2483
|
+
await session.send(this.styleText(`删除失败,未找到包含「${keyword}」的记忆。`));
|
|
2484
|
+
return true;
|
|
2485
|
+
}
|
|
2486
|
+
const r = await this.deleteMemoryByKeyword(keyword);
|
|
2487
|
+
await session.send(this.styleText(r.ok ? `已删除 ${r.removed} 条记忆。` : `删除失败:${r.message}`));
|
|
2488
|
+
return true;
|
|
2489
|
+
}
|
|
2490
|
+
if (/^(?:list|all)$/i.test(sub)) {
|
|
2491
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
|
|
2492
|
+
if (!blocks.length) {
|
|
2493
|
+
await session.send(this.styleText('记忆库为空。'));
|
|
2494
|
+
return true;
|
|
2495
|
+
}
|
|
2496
|
+
const show = blocks.slice(-10).map((b, i) => `${i + 1}. ${b.replace(/\n+/g, ' ').trim()}`).join('\n');
|
|
2497
|
+
await session.send(this.styleText(`记忆库共 ${blocks.length} 条(显示最近 10 条):\n${show}`));
|
|
2498
|
+
return true;
|
|
2499
|
+
}
|
|
2500
|
+
// 查询:[memory] search 关键词 / [memory] query 关键词 / [memory] find 关键词
|
|
2501
|
+
const queryMatch = sub.match(/^(?:search|query|find)\s*[::]?\s*([\s\S]*)$/i);
|
|
2502
|
+
if (queryMatch) {
|
|
2503
|
+
const keyword = queryMatch[1].trim();
|
|
2504
|
+
const results = await this.searchMemory(keyword, 8);
|
|
2505
|
+
if (!results.length) {
|
|
2506
|
+
await session.send(this.styleText(keyword ? `没有找到包含「${keyword}」的记忆。` : '记忆库为空或没有可显示的记录。'));
|
|
2507
|
+
return true;
|
|
2508
|
+
}
|
|
2509
|
+
const reply = results.map((b, i) => `${i + 1}. ${b.replace(/\n+/g, ' ').trim()}`).join('\n');
|
|
2510
|
+
await session.send(this.styleText(keyword ? `包含「${keyword}」的记忆:\n${reply}` : `最近的记忆:\n${reply}`));
|
|
2511
|
+
this._logger.info(`[cmd:memory] 查询 keyword=${keyword || '-'} 命中=${results.length} | ${this.sessionTag(session)}`);
|
|
2512
|
+
return true;
|
|
2513
|
+
}
|
|
2514
|
+
// 保存
|
|
2515
|
+
try {
|
|
2516
|
+
await this.saveMemoryToFile(session.userId, sub);
|
|
2517
|
+
await session.send(this.styleText('已记住。'));
|
|
2518
|
+
this.logCommandResult('memory-save', { ok: true, message: 'memory saved' }, session, { content: sub });
|
|
2519
|
+
}
|
|
2520
|
+
catch (error) {
|
|
2521
|
+
await session.send(this.styleText(`记忆保存失败: ${String(error)}`));
|
|
2522
|
+
}
|
|
2523
|
+
return true;
|
|
2524
|
+
}
|
|
2525
|
+
/** [ban] qq号|@某人 [原因](兼容旧的 [ban] add qq号) */
|
|
2526
|
+
async execBanAdd(session, rest, mentions = []) {
|
|
2527
|
+
if (!this.resolveBlacklistEnabled(session)) {
|
|
2528
|
+
await session.send(this.styleText('本群未启用黑名单系统。'));
|
|
2529
|
+
return true;
|
|
2530
|
+
}
|
|
2531
|
+
const auth = await this.authorizeModerationAction('ban', session);
|
|
2532
|
+
if (!auth.ok)
|
|
2533
|
+
return this.denyAdmin(session, auth.message);
|
|
2534
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
2535
|
+
let qq = '';
|
|
2536
|
+
let reason = '';
|
|
2537
|
+
if (/^(?:add)$/i.test(tokens[0] || '')) {
|
|
2538
|
+
qq = tokens[1] || '';
|
|
2539
|
+
reason = tokens.slice(2).join(' ');
|
|
2540
|
+
}
|
|
2541
|
+
else if (tokens[0] && /^\d{5,12}$/.test(tokens[0])) {
|
|
2542
|
+
qq = tokens[0];
|
|
2543
|
+
reason = tokens.slice(1).join(' ');
|
|
2544
|
+
}
|
|
2545
|
+
else if (mentions.length) {
|
|
2546
|
+
qq = mentions[0];
|
|
2547
|
+
reason = tokens.join(' '); // @ 已从 content 剥离,剩余全是原因
|
|
2548
|
+
}
|
|
2549
|
+
if (!/^\d{5,12}$/.test(qq)) {
|
|
2550
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdBan', '[ban]')} qq号|@某人 原因(原因选填)`));
|
|
2551
|
+
return true;
|
|
2552
|
+
}
|
|
2553
|
+
const member = await this.fetchGroupMember(session, qq);
|
|
2554
|
+
if (!member) {
|
|
2555
|
+
await session.send(this.styleText('增加失败,未找到群内人员。'));
|
|
2556
|
+
return true;
|
|
2557
|
+
}
|
|
2558
|
+
const r = await this.addToBlacklist(session, member.qq, member.name);
|
|
2559
|
+
await session.send(this.styleText(r.ok
|
|
2560
|
+
? `已将 ${member.qq}${member.name ? ' · ' + member.name : ''} 加入黑名单${reason ? `(原因:${reason})` : ''}`
|
|
2561
|
+
: `增加失败:${r.message}`));
|
|
2562
|
+
this._logger.info(`[cmd:ban] qq=${member.qq} reason=${reason || '-'} ok=${r.ok} | ${this.sessionTag(session)}`);
|
|
2563
|
+
return true;
|
|
2564
|
+
}
|
|
2565
|
+
/** [unban] qq号|@某人 [原因] */
|
|
2566
|
+
async execUnban(session, rest, mentions = []) {
|
|
2567
|
+
if (!this.resolveBlacklistEnabled(session)) {
|
|
2568
|
+
await session.send(this.styleText('本群未启用黑名单系统。'));
|
|
2569
|
+
return true;
|
|
2570
|
+
}
|
|
2571
|
+
const auth = await this.authorizeModerationAction('unban', session);
|
|
2572
|
+
if (!auth.ok)
|
|
2573
|
+
return this.denyAdmin(session, auth.message);
|
|
2574
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
2575
|
+
let qq = '';
|
|
2576
|
+
let reason = '';
|
|
2577
|
+
if (tokens[0] && /^\d{5,12}$/.test(tokens[0])) {
|
|
2578
|
+
qq = tokens[0];
|
|
2579
|
+
reason = tokens.slice(1).join(' ');
|
|
2580
|
+
}
|
|
2581
|
+
else if (mentions.length) {
|
|
2582
|
+
qq = mentions[0];
|
|
2583
|
+
reason = tokens.join(' ');
|
|
2584
|
+
}
|
|
2585
|
+
if (!/^\d{5,12}$/.test(qq)) {
|
|
2586
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdUnban', '[unban]')} qq号|@某人 原因(原因选填)`));
|
|
2587
|
+
return true;
|
|
2588
|
+
}
|
|
2589
|
+
const r = await this.removeFromBlacklist(session, qq);
|
|
2590
|
+
await session.send(this.styleText(r.ok && reason ? `${r.message}(原因:${reason})` : r.message));
|
|
2591
|
+
this._logger.info(`[cmd:unban] qq=${qq} reason=${reason || '-'} ok=${r.ok} | ${this.sessionTag(session)}`);
|
|
2592
|
+
return true;
|
|
2593
|
+
}
|
|
2594
|
+
/** [banlist] */
|
|
2595
|
+
async execBanList(session) {
|
|
2596
|
+
if (!this.resolveBlacklistEnabled(session)) {
|
|
2597
|
+
await session.send(this.styleText('本群未启用黑名单系统。'));
|
|
2598
|
+
return;
|
|
2599
|
+
}
|
|
2600
|
+
const auth = await this.authorizeCommand('banlist', session);
|
|
2601
|
+
if (!auth.ok) {
|
|
2602
|
+
await session.send(this.styleText(auth.userMessage || '你没有权限执行该操作。'));
|
|
2603
|
+
return;
|
|
2604
|
+
}
|
|
2605
|
+
const list = await this.getBlacklist(session);
|
|
2606
|
+
if (!list.length) {
|
|
2607
|
+
await session.send(this.styleText('本群黑名单为空。'));
|
|
2608
|
+
return;
|
|
2609
|
+
}
|
|
2610
|
+
const lines = list.map((e, i) => `${i + 1}. ${e.qq}${e.name ? ' · ' + e.name : ''}${e.at ? `(${e.at})` : ''}`);
|
|
2611
|
+
await session.send(this.styleText(`本群黑名单共 ${list.length} 人:\n${lines.join('\n')}`));
|
|
2612
|
+
}
|
|
2613
|
+
/**
|
|
2614
|
+
* 黑名单指令(旧式 [ban] list / add / delete 兼容入口)。
|
|
2615
|
+
*/
|
|
2616
|
+
async handleBanCommand(session) {
|
|
2617
|
+
const prefix = String(this.config.banCommand || '[ban]').trim();
|
|
2618
|
+
if (!prefix)
|
|
2619
|
+
return false;
|
|
2620
|
+
const raw = (session.content || '').replace(/<at\b[^>]*\/?>/gi, ' ').trim();
|
|
2621
|
+
if (!raw.startsWith(prefix))
|
|
2622
|
+
return false;
|
|
2623
|
+
|
|
2624
|
+
const rest = raw.slice(prefix.length).trim();
|
|
2625
|
+
const parts = rest.split(/\s+/).filter(Boolean);
|
|
2626
|
+
const sub = (parts[0] || '').toLowerCase();
|
|
2627
|
+
const arg = parts[1] || '';
|
|
2628
|
+
|
|
2629
|
+
// 是否启用(单群设置优先,未设置跟随全局)
|
|
2630
|
+
if (!this.resolveBlacklistEnabled(session)) {
|
|
2631
|
+
await session.send(this.styleText('本群未启用黑名单系统。'));
|
|
2632
|
+
return true;
|
|
2633
|
+
}
|
|
2634
|
+
|
|
2635
|
+
const isAdmin = await this.canUseAdminCommand(session).then((r) => r && r.ok).catch(() => false);
|
|
2636
|
+
|
|
2637
|
+
if (sub === 'list') {
|
|
2638
|
+
const list = await this.getBlacklist(session);
|
|
2639
|
+
if (!list.length) {
|
|
2640
|
+
await session.send(this.styleText('本群黑名单为空。'));
|
|
2641
|
+
return true;
|
|
2642
|
+
}
|
|
2643
|
+
const lines = list.map((e, i) => `${i + 1}. ${e.qq}${e.name ? ' · ' + e.name : ''}${e.at ? `(${e.at})` : ''}`);
|
|
2644
|
+
await session.send(this.styleText(`本群黑名单共 ${list.length} 人:\n${lines.join('\n')}`));
|
|
2645
|
+
return true;
|
|
2646
|
+
}
|
|
2647
|
+
|
|
2648
|
+
if (sub === 'add') {
|
|
2649
|
+
if (!isAdmin) {
|
|
2650
|
+
await session.send(this.styleText('你没有权限操作黑名单。'));
|
|
2651
|
+
return true;
|
|
2652
|
+
}
|
|
2653
|
+
if (!/^\d{5,12}$/.test(arg)) {
|
|
2654
|
+
await session.send(this.styleText(`用法:${prefix} add QQ号`));
|
|
2655
|
+
return true;
|
|
2656
|
+
}
|
|
2657
|
+
// 必须是群内人员
|
|
2658
|
+
const member = await this.fetchGroupMember(session, arg);
|
|
2659
|
+
if (!member) {
|
|
2660
|
+
await session.send(this.styleText('增加失败,未找到群内人员。'));
|
|
2661
|
+
return true;
|
|
2662
|
+
}
|
|
2663
|
+
const r = await this.addToBlacklist(session, member.qq, member.name);
|
|
2664
|
+
await session.send(this.styleText(r.ok ? `已将 ${member.qq} 加入黑名单` : `增加失败:${r.message}`));
|
|
2665
|
+
this._logger.info(`[ban] add qq=${member.qq} ok=${r.ok} | ${this.sessionTag(session)}`);
|
|
2666
|
+
return true;
|
|
2667
|
+
}
|
|
2668
|
+
|
|
2669
|
+
if (sub === 'delete' || sub === 'del') {
|
|
2670
|
+
if (!isAdmin) {
|
|
2671
|
+
await session.send(this.styleText('你没有权限操作黑名单。'));
|
|
2672
|
+
return true;
|
|
2673
|
+
}
|
|
2674
|
+
if (!/^\d{5,12}$/.test(arg)) {
|
|
2675
|
+
await session.send(this.styleText(`用法:${prefix} delete QQ号`));
|
|
2676
|
+
return true;
|
|
2677
|
+
}
|
|
2678
|
+
const r = await this.removeFromBlacklist(session, arg);
|
|
2679
|
+
await session.send(this.styleText(r.message));
|
|
2680
|
+
this._logger.info(`[ban] delete qq=${arg} ok=${r.ok} | ${this.sessionTag(session)}`);
|
|
2681
|
+
return true;
|
|
2682
|
+
}
|
|
2683
|
+
|
|
2684
|
+
await session.send(this.styleText(`用法:${prefix} list | ${prefix} add QQ号 | ${prefix} delete QQ号`));
|
|
2685
|
+
return true;
|
|
2686
|
+
}
|
|
2687
|
+
async handleGroupModeration(session) {
|
|
2688
|
+
if (!this.isPlatformAllowed(session.platform))
|
|
2689
|
+
return;
|
|
2690
|
+
// AI 上下文先记录:被管控/被指令拦截的消息也要进上下文(指令类由引擎自行忽略)
|
|
2691
|
+
try {
|
|
2692
|
+
await this.ai.record(session);
|
|
2693
|
+
}
|
|
2694
|
+
catch (error) {
|
|
2695
|
+
this._logger.warn(`[ai] record failed: ${String(error)}`);
|
|
2696
|
+
}
|
|
2697
|
+
// 注:旧的 [记忆] 文本入口已停用,记忆功能统一由 routeBracketCommand 处理,只认 [memory]
|
|
2698
|
+
// 统一方括号指令路由([mute]/[unmute]/[kick]/[memory]/[ban]/[unban]/[banlist]/[custom]/[bot])
|
|
2699
|
+
if (await this.routeBracketCommand(session))
|
|
2700
|
+
return;
|
|
2701
|
+
// 兼容旧入口
|
|
2702
|
+
if (await this.handleBanCommand(session))
|
|
2703
|
+
return;
|
|
2704
|
+
// 自定义命令优先于违禁词管控与 AI:命中后直接结束本轮处理
|
|
2705
|
+
if (await this.handleCustomCommand(session))
|
|
2706
|
+
return;
|
|
2707
|
+
if (!session.guildId)
|
|
2708
|
+
return;
|
|
2709
|
+
if (session.userId && session.bot?.selfId && session.userId === session.bot.selfId)
|
|
2710
|
+
return;
|
|
2711
|
+
if (await this.handleJoinRequestReviewMessage(session))
|
|
2712
|
+
return;
|
|
2713
|
+
if (session.platform === 'onebot') {
|
|
2714
|
+
const policy = this.resolveModerationPolicy(session);
|
|
2715
|
+
const violation = await this.detectViolation(session, policy);
|
|
2716
|
+
if (violation) {
|
|
2717
|
+
let deleted = false;
|
|
2718
|
+
if (policy.autoDeleteViolation) {
|
|
2719
|
+
deleted = await this.deleteMessage(session);
|
|
2720
|
+
}
|
|
2721
|
+
const scoreInfo = violation.assessment
|
|
2722
|
+
? ` score=${violation.assessment.total} hits=${violation.assessment.evaluations.map((item) => `${item.keyword}:${item.gained}${item.exact ? '' : '/fuzzy'}`).join(',')}`
|
|
2723
|
+
: '';
|
|
2724
|
+
this._logger.warn(`[moderation] type=${violation.type} detail="${violation.detail}"${scoreInfo} deleted=${deleted} | ${this.sessionTag(session)}`);
|
|
2725
|
+
if (policy.sendViolationNotice) {
|
|
2726
|
+
const notice = violation.type === 'banned-word'
|
|
2727
|
+
? `检测到违禁内容(评分 ${violation.assessment?.total ?? '-'}),消息已处理。`
|
|
2728
|
+
: violation.type === 'card'
|
|
2729
|
+
? '卡片消息不被允许,消息已处理。'
|
|
2730
|
+
: '合并转发消息不被允许,消息已处理。';
|
|
2731
|
+
try {
|
|
2732
|
+
await session.send(this.styleText(notice));
|
|
2733
|
+
}
|
|
2734
|
+
catch {
|
|
2735
|
+
// ignore notice failures
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
// 自动管控:累计违规达到阈值后自动禁言/自动踢人
|
|
2739
|
+
if (policy.enableAutoMute || policy.enableAutoKick) {
|
|
2740
|
+
try {
|
|
2741
|
+
const punish = await this.autoModerationPunish(session, policy);
|
|
2742
|
+
if (punish) {
|
|
2743
|
+
this._logger.info(`[auto-moderation] action=${punish.action} ok=${punish.ok} count=${punish.count} | ${this.sessionTag(session)}`);
|
|
2744
|
+
if (punish.action !== 'none') {
|
|
2745
|
+
if (policy.sendViolationNotice) {
|
|
2746
|
+
try {
|
|
2747
|
+
await session.send(this.styleText(punish.message));
|
|
2748
|
+
}
|
|
2749
|
+
catch {
|
|
2750
|
+
// ignore notice failures
|
|
2751
|
+
}
|
|
2752
|
+
}
|
|
2753
|
+
else if (!punish.ok) {
|
|
2754
|
+
this._logger.warn(`[auto-moderation] ${punish.message} | ${this.sessionTag(session)}`);
|
|
2755
|
+
}
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
catch (error) {
|
|
2760
|
+
this._logger.warn(`[auto-moderation] failed: ${String(error)} | ${this.sessionTag(session)}`);
|
|
2761
|
+
}
|
|
2762
|
+
}
|
|
2763
|
+
return;
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
try {
|
|
2767
|
+
await this.handleRepeater(session);
|
|
2768
|
+
}
|
|
2769
|
+
catch (error) {
|
|
2770
|
+
this._logger.warn(`[repeater] failed: ${String(error)} | ${this.sessionTag(session)}`);
|
|
2771
|
+
}
|
|
2772
|
+
await this.ai.handle(session);
|
|
2773
|
+
}
|
|
2774
|
+
/**
|
|
2775
|
+
* 待审入群申请的落盘文件路径。
|
|
2776
|
+
* 与 Memory.md 同目录(ctx.baseDir),可用 Koishi 控制台「探索器 Explorer」直接查看。
|
|
2777
|
+
*/
|
|
2778
|
+
getPendingJoinFilePath() {
|
|
2779
|
+
const base = (this.ctx && this.ctx.baseDir) || process.cwd();
|
|
2780
|
+
const name = (this.config.pendingJoinFileName || 'JoinRequests.md').trim();
|
|
2781
|
+
return node_path_1.default.resolve(base, name);
|
|
2782
|
+
}
|
|
2783
|
+
buildPendingJoinFileContent() {
|
|
2784
|
+
const now = new Date().toLocaleString('zh-CN', { hour12: false });
|
|
2785
|
+
const items = [...this.pendingJoinRequests.values()];
|
|
2786
|
+
const lines = [
|
|
2787
|
+
'# 待审入群申请(插件自动维护,可删除本文件重置)',
|
|
2788
|
+
'',
|
|
2789
|
+
`更新时间:${now}`,
|
|
2790
|
+
`待审数量:${items.length}`,
|
|
2791
|
+
`有效期:${Math.max(1, this.config.joinRequestReviewTtlMinutes || 30)} 分钟`,
|
|
2792
|
+
'',
|
|
2793
|
+
];
|
|
2794
|
+
if (items.length) {
|
|
2795
|
+
lines.push('| 编号 | 群号 | 申请人 | 验证信息 | 申请时间 |', '| --- | --- | --- | --- | --- |');
|
|
2796
|
+
for (const item of items) {
|
|
2797
|
+
const comment = String(item.comment || '').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
|
|
2798
|
+
const created = new Date(item.createdAt).toLocaleString('zh-CN', { hour12: false });
|
|
2799
|
+
lines.push(`| ${item.code} | ${item.guildId} | ${item.userId} | ${comment} | ${created} |`);
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
else {
|
|
2803
|
+
lines.push('(当前没有待审核的入群申请)');
|
|
2804
|
+
}
|
|
2805
|
+
// 机器可读区段:启动时据此恢复内存 Map
|
|
2806
|
+
lines.push('', '<!-- PENDING-JOIN-REQUESTS:JSON -->', '```json', JSON.stringify(items), '```');
|
|
2807
|
+
return lines.join('\n') + '\n';
|
|
2808
|
+
}
|
|
2809
|
+
/** 立即把待审单写入 MD(供 dispose / 去抖到期调用) */
|
|
2810
|
+
async persistPendingJoinRequestsNow() {
|
|
2811
|
+
const p = this.getPendingJoinFilePath();
|
|
2812
|
+
try {
|
|
2813
|
+
await this.runPendingJoinWriteLocked(async () => {
|
|
2814
|
+
await node_fs_1.default.promises.writeFile(p, this.buildPendingJoinFileContent(), 'utf8');
|
|
2815
|
+
});
|
|
2816
|
+
}
|
|
2817
|
+
catch (error) {
|
|
2818
|
+
this._logger.warn(`[join-review] 待审单落盘失败: ${String(error)}`);
|
|
2819
|
+
}
|
|
2820
|
+
}
|
|
2821
|
+
/** 去抖落盘:入群申请是低频事件,合并多次写入避免频繁 I/O */
|
|
2822
|
+
schedulePendingJoinPersist(delayMs = 500) {
|
|
2823
|
+
if (this._pendingJoinSaveTimer)
|
|
2824
|
+
clearTimeout(this._pendingJoinSaveTimer);
|
|
2825
|
+
this._pendingJoinSaveTimer = setTimeout(() => {
|
|
2826
|
+
this._pendingJoinSaveTimer = null;
|
|
2827
|
+
this.persistPendingJoinRequestsNow().catch(() => { /* 已内部记录日志 */ });
|
|
2828
|
+
}, delayMs);
|
|
2829
|
+
if (typeof this._pendingJoinSaveTimer.unref === 'function')
|
|
2830
|
+
this._pendingJoinSaveTimer.unref();
|
|
2831
|
+
}
|
|
2832
|
+
/** 卸载/重启前的同步兜底:写失败只记日志,不阻塞退出 */
|
|
2833
|
+
flushPendingJoinRequests() {
|
|
2834
|
+
if (this._pendingJoinSaveTimer) {
|
|
2835
|
+
clearTimeout(this._pendingJoinSaveTimer);
|
|
2836
|
+
this._pendingJoinSaveTimer = null;
|
|
2837
|
+
}
|
|
2838
|
+
try {
|
|
2839
|
+
node_fs_1.default.writeFileSync(this.getPendingJoinFilePath(), this.buildPendingJoinFileContent(), 'utf8');
|
|
2840
|
+
}
|
|
2841
|
+
catch (error) {
|
|
2842
|
+
this._logger.warn(`[join-review] 退出前落盘待审单失败: ${String(error)}`);
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
/**
|
|
2846
|
+
* 启动时从 MD 恢复待审单,并顺手清掉已过期的编号。
|
|
2847
|
+
* 这样重启不再丢审核单;超过 TTL 的自然失效。
|
|
2848
|
+
*/
|
|
2849
|
+
loadPendingJoinRequests() {
|
|
2850
|
+
const p = this.getPendingJoinFilePath();
|
|
2851
|
+
let raw;
|
|
2852
|
+
try {
|
|
2853
|
+
if (!node_fs_1.default.existsSync(p))
|
|
2854
|
+
return;
|
|
2855
|
+
raw = node_fs_1.default.readFileSync(p, 'utf8');
|
|
2856
|
+
}
|
|
2857
|
+
catch (error) {
|
|
2858
|
+
this._logger.warn(`[join-review] 读取待审单文件失败: ${String(error)}`);
|
|
2859
|
+
return;
|
|
2860
|
+
}
|
|
2861
|
+
const match = raw.match(/<!-- PENDING-JOIN-REQUESTS:JSON -->\s*```json\s*([\s\S]*?)```/);
|
|
2862
|
+
if (!match) {
|
|
2863
|
+
this._logger.warn(`[join-review] 待审单文件缺少数据区段,已忽略: ${p}`);
|
|
2864
|
+
return;
|
|
2865
|
+
}
|
|
2866
|
+
let records = [];
|
|
2867
|
+
try {
|
|
2868
|
+
const parsed = JSON.parse(match[1].trim());
|
|
2869
|
+
if (Array.isArray(parsed))
|
|
2870
|
+
records = parsed;
|
|
2871
|
+
}
|
|
2872
|
+
catch (error) {
|
|
2873
|
+
this._logger.warn(`[join-review] 待审单数据区段解析失败: ${String(error)}`);
|
|
2874
|
+
return;
|
|
2875
|
+
}
|
|
2876
|
+
let restored = 0;
|
|
2877
|
+
let dropped = 0;
|
|
2878
|
+
for (const item of records) {
|
|
2879
|
+
const code = String(item?.code || '').trim().toUpperCase();
|
|
2880
|
+
const flag = String(item?.flag || '').trim();
|
|
2881
|
+
const guildId = String(item?.guildId || '').trim();
|
|
2882
|
+
const userId = String(item?.userId || '').trim();
|
|
2883
|
+
const createdAt = Number(item?.createdAt);
|
|
2884
|
+
if (!code || !flag || !guildId || !userId || !Number.isFinite(createdAt)) {
|
|
2885
|
+
dropped += 1;
|
|
2886
|
+
continue;
|
|
2887
|
+
}
|
|
2888
|
+
this.pendingJoinRequests.set(code, {
|
|
2889
|
+
code,
|
|
2890
|
+
flag,
|
|
2891
|
+
guildId,
|
|
2892
|
+
userId,
|
|
2893
|
+
comment: String(item?.comment || ''),
|
|
2894
|
+
createdAt,
|
|
2895
|
+
});
|
|
2896
|
+
this.pendingJoinRequestFlags.set(flag, code);
|
|
2897
|
+
restored += 1;
|
|
2898
|
+
}
|
|
2899
|
+
// 清理过期项(沿用 TTL 配置)
|
|
2900
|
+
this.cleanupPendingJoinRequests();
|
|
2901
|
+
const alive = this.pendingJoinRequests.size;
|
|
2902
|
+
dropped += restored - alive;
|
|
2903
|
+
if (records.length) {
|
|
2904
|
+
this._logger.info(`[join-review] 已恢复待审入群申请 ${alive} 条(读取 ${records.length} 条,过期/无效 ${Math.max(0, dropped)} 条)`);
|
|
2905
|
+
}
|
|
2906
|
+
if (alive !== records.length)
|
|
2907
|
+
this.schedulePendingJoinPersist();
|
|
2908
|
+
}
|
|
2909
|
+
cleanupPendingJoinRequests() {
|
|
2910
|
+
const ttlMs = Math.max(1, this.config.joinRequestReviewTtlMinutes || 30) * 60 * 1000;
|
|
2911
|
+
const now = Date.now();
|
|
2912
|
+
for (const [code, item] of this.pendingJoinRequests) {
|
|
2913
|
+
if (now - item.createdAt <= ttlMs)
|
|
2914
|
+
continue;
|
|
2915
|
+
this.pendingJoinRequests.delete(code);
|
|
2916
|
+
this.pendingJoinRequestFlags.delete(item.flag);
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
generateJoinRequestCode() {
|
|
2920
|
+
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
|
2921
|
+
for (let i = 0; i < 16; i += 1) {
|
|
2922
|
+
let code = '';
|
|
2923
|
+
for (let j = 0; j < 6; j += 1) {
|
|
2924
|
+
code += chars[Math.floor(Math.random() * chars.length)];
|
|
2925
|
+
}
|
|
2926
|
+
if (!this.pendingJoinRequests.has(code))
|
|
2927
|
+
return code;
|
|
2928
|
+
}
|
|
2929
|
+
return `${Date.now().toString(36).toUpperCase().slice(-6)}`;
|
|
2930
|
+
}
|
|
2931
|
+
parseJoinRequestReviewText(text) {
|
|
2932
|
+
let source = String(text).trim();
|
|
2933
|
+
if (!source)
|
|
2934
|
+
return null;
|
|
2935
|
+
// 去掉可能的命令前缀(如 [bot])
|
|
2936
|
+
source = source.replace(/^\[[^\]]+\]\s*/, '').trim();
|
|
2937
|
+
// 只接受英文触发词([记忆] 新规):approve [编号] [理由] / reject [编号] [理由],编号可省略
|
|
2938
|
+
const approveMatch = source.match(/^(approve|ok|yes|accept|pass)\s*(?:join|request)?\s*#?([A-Za-z0-9]{4,12})?\s*([\s\S]*)$/i);
|
|
2939
|
+
if (approveMatch) {
|
|
2940
|
+
return { approve: true, code: approveMatch[2] ? approveMatch[2].toUpperCase() : '', reason: (approveMatch[3] || '').trim() };
|
|
2941
|
+
}
|
|
2942
|
+
const rejectMatch = source.match(/^(reject|deny|no|refuse)\s*(?:join|request)?\s*#?([A-Za-z0-9]{4,12})?\s*([\s\S]*)$/i);
|
|
2943
|
+
if (rejectMatch) {
|
|
2944
|
+
return { approve: false, code: rejectMatch[2] ? rejectMatch[2].toUpperCase() : '', reason: (rejectMatch[3] || '').trim() };
|
|
2945
|
+
}
|
|
2946
|
+
return null;
|
|
2947
|
+
}
|
|
2948
|
+
async handleJoinRequestReviewMessage(session) {
|
|
2949
|
+
if (!this.resolveJoinReviewEnabled(session))
|
|
2950
|
+
return false;
|
|
2951
|
+
if (session.platform !== 'onebot' || !session.guildId)
|
|
2952
|
+
return false;
|
|
2953
|
+
const parsed = this.parseJoinRequestReviewText(this.getMessageText(session));
|
|
2954
|
+
if (!parsed)
|
|
2955
|
+
return false;
|
|
2956
|
+
const auth = await this.authorizeCommand('review-join-request', session);
|
|
2957
|
+
if (!auth.ok)
|
|
2958
|
+
return false;
|
|
2959
|
+
const result = await this.reviewJoinRequestDecision(session, parsed.code, parsed.approve, parsed.reason);
|
|
2960
|
+
this.logCommandResult('review-join-request', result, session, { code: parsed.code, approve: parsed.approve, from: 'message' });
|
|
2961
|
+
await session.send(this.styleText(result.message));
|
|
2962
|
+
return true;
|
|
2963
|
+
}
|
|
2964
|
+
resolveJoinReviewEnabled(session) {
|
|
2965
|
+
const guildId = this.normalizeGuildId(session?.guildId);
|
|
2966
|
+
const rule = this.config.groupRules?.find((item) => this.normalizeGuildId(item.guildId) === guildId);
|
|
2967
|
+
if (typeof rule?.enableJoinRequestReview === 'boolean')
|
|
2968
|
+
return rule.enableJoinRequestReview;
|
|
2969
|
+
return !!this.config.enableJoinRequestReview;
|
|
2970
|
+
}
|
|
2971
|
+
async fetchStrangerInfo(bot, userId) {
|
|
2972
|
+
if (!bot || !userId)
|
|
2973
|
+
return null;
|
|
2974
|
+
// 兼容不同 OneBot 适配器的方法命名
|
|
2975
|
+
try {
|
|
2976
|
+
if (typeof bot.getStrangerInfo === 'function')
|
|
2977
|
+
return await bot.getStrangerInfo(userId, true);
|
|
2978
|
+
}
|
|
2979
|
+
catch { /* ignore */ }
|
|
2980
|
+
try {
|
|
2981
|
+
if (typeof bot.get_stranger_info === 'function')
|
|
2982
|
+
return await bot.get_stranger_info(userId, true);
|
|
2983
|
+
}
|
|
2984
|
+
catch { /* ignore */ }
|
|
2985
|
+
return null;
|
|
2986
|
+
}
|
|
2987
|
+
buildJoinRequestPrompt(applicant, extra) {
|
|
2988
|
+
const lines = [
|
|
2989
|
+
'检测到新的入群申请,请管理员审核:',
|
|
2990
|
+
`QQ号:${applicant.userId}`,
|
|
2991
|
+
];
|
|
2992
|
+
if (extra?.nickname)
|
|
2993
|
+
lines.push(`昵称:${extra.nickname}`);
|
|
2994
|
+
if (extra?.sex)
|
|
2995
|
+
lines.push(`性别:${extra.sex}`);
|
|
2996
|
+
if (extra?.age !== undefined && extra.age !== '')
|
|
2997
|
+
lines.push(`年龄:${extra.age}`);
|
|
2998
|
+
if (extra?.level)
|
|
2999
|
+
lines.push(`QQ等级:${extra.level}`);
|
|
3000
|
+
lines.push(`验证信息:${applicant.comment || '(无)'}`);
|
|
3001
|
+
lines.push(`approve: approve [reason] | reject: reject [reason]`);
|
|
3002
|
+
return lines.join('\n');
|
|
3003
|
+
}
|
|
3004
|
+
async handleGuildMemberRequest(session) {
|
|
3005
|
+
if (!this.resolveJoinReviewEnabled(session))
|
|
3006
|
+
return;
|
|
3007
|
+
if (!this.isPlatformAllowed(session.platform))
|
|
3008
|
+
return;
|
|
3009
|
+
if (session.platform !== 'onebot')
|
|
3010
|
+
return;
|
|
3011
|
+
if (!session.guildId || !session.messageId || !session.userId)
|
|
3012
|
+
return;
|
|
3013
|
+
this.cleanupPendingJoinRequests();
|
|
3014
|
+
if (this.pendingJoinRequestFlags.has(session.messageId))
|
|
3015
|
+
return;
|
|
3016
|
+
const code = this.generateJoinRequestCode();
|
|
3017
|
+
const item = {
|
|
3018
|
+
code,
|
|
3019
|
+
flag: session.messageId,
|
|
3020
|
+
guildId: session.guildId,
|
|
3021
|
+
userId: session.userId,
|
|
3022
|
+
comment: (session.content || '').trim(),
|
|
3023
|
+
createdAt: Date.now(),
|
|
3024
|
+
};
|
|
3025
|
+
this.pendingJoinRequests.set(code, item);
|
|
3026
|
+
this.pendingJoinRequestFlags.set(item.flag, code);
|
|
3027
|
+
// 落盘待审单:重启后仍可审核
|
|
3028
|
+
this.schedulePendingJoinPersist();
|
|
3029
|
+
// 尽力获取申请者信息(昵称/性别/年龄/等级/头像)
|
|
3030
|
+
let extra = {};
|
|
3031
|
+
const bot = this.getOneBotApi(session);
|
|
3032
|
+
const info = await this.fetchStrangerInfo(bot, session.userId);
|
|
3033
|
+
if (info) {
|
|
3034
|
+
const nickname = info.nickname || info.card || info.name || '';
|
|
3035
|
+
let sex = info.sex || info.gender || '';
|
|
3036
|
+
if (sex === 'male')
|
|
3037
|
+
sex = '男';
|
|
3038
|
+
else if (sex === 'female')
|
|
3039
|
+
sex = '女';
|
|
3040
|
+
else if (sex === 'unknown' || sex === '')
|
|
3041
|
+
sex = '未知';
|
|
3042
|
+
const level = (info.level !== undefined && info.level !== null) ? String(info.level) : '';
|
|
3043
|
+
extra = {
|
|
3044
|
+
nickname,
|
|
3045
|
+
sex: sex || '',
|
|
3046
|
+
age: info.age,
|
|
3047
|
+
level,
|
|
3048
|
+
avatarUrl: `https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(session.userId)}&s=640`,
|
|
3049
|
+
};
|
|
3050
|
+
}
|
|
3051
|
+
const prompt = this.buildJoinRequestPrompt(item, extra);
|
|
3052
|
+
try {
|
|
3053
|
+
if (extra?.avatarUrl) {
|
|
3054
|
+
// 直接把头像图片发到群里,而不是给链接
|
|
3055
|
+
await session.send([koishi_1.h.text(this.styleText(prompt)), koishi_1.h.image(extra.avatarUrl)]);
|
|
3056
|
+
}
|
|
3057
|
+
else {
|
|
3058
|
+
await session.send(this.styleText(prompt));
|
|
3059
|
+
}
|
|
3060
|
+
this.logCommandResult('join-request', { ok: true, message: 'join request notice sent' }, session, { target: item.userId });
|
|
3061
|
+
}
|
|
3062
|
+
catch (error) {
|
|
3063
|
+
this.logCommandResult('join-request', { ok: false, message: `join request notice failed: ${String(error)}` }, session, { target: item.userId });
|
|
3064
|
+
}
|
|
3065
|
+
}
|
|
3066
|
+
async reviewJoinRequestDecision(session, code, approve, reason) {
|
|
3067
|
+
this.cleanupPendingJoinRequests();
|
|
3068
|
+
let item;
|
|
3069
|
+
const key = (code || '').trim().toUpperCase();
|
|
3070
|
+
if (key) {
|
|
3071
|
+
item = this.pendingJoinRequests.get(key);
|
|
3072
|
+
if (!item)
|
|
3073
|
+
return { ok: false, message: `未找到审核编号 ${key},可能已处理或已过期。` };
|
|
3074
|
+
if (session.guildId !== item.guildId)
|
|
3075
|
+
return { ok: false, message: `审核编号 ${key} 不属于当前群。` };
|
|
3076
|
+
}
|
|
3077
|
+
else {
|
|
3078
|
+
// 无编号:取当前群最近一条待审核申请
|
|
3079
|
+
const candidates = [...this.pendingJoinRequests.values()].filter((x) => x.guildId === session.guildId);
|
|
3080
|
+
if (!candidates.length)
|
|
3081
|
+
return { ok: false, message: '当前没有待审核的入群申请。' };
|
|
3082
|
+
item = candidates[candidates.length - 1];
|
|
3083
|
+
}
|
|
3084
|
+
const plan = {
|
|
3085
|
+
action: approve ? 'approve-join-request' : 'reject-join-request',
|
|
3086
|
+
groupId: item.guildId,
|
|
3087
|
+
targetId: item.userId,
|
|
3088
|
+
reason: `${reason || ''}`,
|
|
3089
|
+
};
|
|
3090
|
+
if (this.config.dryRun)
|
|
3091
|
+
return this.createDryRunResult(plan);
|
|
3092
|
+
const bot = session.bot;
|
|
3093
|
+
if (!bot?.handleGuildMemberRequest) {
|
|
3094
|
+
return { ok: false, message: '当前适配器不支持处理入群申请。', plan };
|
|
3095
|
+
}
|
|
3096
|
+
try {
|
|
3097
|
+
await bot.handleGuildMemberRequest(item.flag, approve, reason || '');
|
|
3098
|
+
this.pendingJoinRequests.delete(item.code);
|
|
3099
|
+
this.pendingJoinRequestFlags.delete(item.flag);
|
|
3100
|
+
// 处理完立即更新落盘,避免重启后又被当成待审
|
|
3101
|
+
this.schedulePendingJoinPersist();
|
|
3102
|
+
return {
|
|
3103
|
+
ok: true,
|
|
3104
|
+
message: approve
|
|
3105
|
+
? `已放行入群申请:${item.userId}`
|
|
3106
|
+
: `已拒绝入群申请:${item.userId}`,
|
|
3107
|
+
plan,
|
|
3108
|
+
};
|
|
3109
|
+
}
|
|
3110
|
+
catch (error) {
|
|
3111
|
+
return { ok: false, message: `处理入群申请失败: ${String(error)}`, plan };
|
|
3112
|
+
}
|
|
3113
|
+
}
|
|
3114
|
+
async formatTargetDisplay(session, targetId, rawTarget) {
|
|
3115
|
+
if (!targetId)
|
|
3116
|
+
return '';
|
|
3117
|
+
const fromAt = rawTarget?.match(/name="([^"]+)"/)?.[1]?.trim();
|
|
3118
|
+
if (!session?.guildId || session.platform !== 'onebot') {
|
|
3119
|
+
return fromAt ? `${fromAt}(${targetId})` : targetId;
|
|
3120
|
+
}
|
|
3121
|
+
const onebot = this.getOneBotApi(session);
|
|
3122
|
+
const groupId = this.toGroupId(session);
|
|
3123
|
+
const uid = Number(targetId);
|
|
3124
|
+
if (!onebot?.getGroupMemberInfo || groupId == null || !Number.isFinite(uid)) {
|
|
3125
|
+
return fromAt ? `${fromAt}(${targetId})` : targetId;
|
|
3126
|
+
}
|
|
3127
|
+
try {
|
|
3128
|
+
const info = await onebot.getGroupMemberInfo(groupId, uid, true);
|
|
3129
|
+
const name = info.card?.trim() || info.nickname?.trim() || fromAt;
|
|
3130
|
+
return name ? `${name}(${targetId})` : targetId;
|
|
3131
|
+
}
|
|
3132
|
+
catch {
|
|
3133
|
+
return fromAt ? `${fromAt}(${targetId})` : targetId;
|
|
3134
|
+
}
|
|
3135
|
+
}
|
|
3136
|
+
async getTargetRole(session, targetId) {
|
|
3137
|
+
const onebot = this.getOneBotApi(session);
|
|
3138
|
+
const groupId = this.toGroupId(session);
|
|
3139
|
+
if (!onebot?.getGroupMemberInfo || groupId == null)
|
|
3140
|
+
return null;
|
|
3141
|
+
try {
|
|
3142
|
+
const info = await onebot.getGroupMemberInfo(groupId, targetId, true);
|
|
3143
|
+
if (info.role === 'owner' || info.role === 'admin' || info.role === 'member')
|
|
3144
|
+
return info.role;
|
|
3145
|
+
return null;
|
|
3146
|
+
}
|
|
3147
|
+
catch {
|
|
3148
|
+
return null;
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
createDryRunResult(plan) {
|
|
3152
|
+
return {
|
|
3153
|
+
ok: true,
|
|
3154
|
+
message: 'dry-run: no action executed',
|
|
3155
|
+
plan,
|
|
3156
|
+
};
|
|
3157
|
+
}
|
|
3158
|
+
async planDemoAction(groupId, reason) {
|
|
3159
|
+
const plan = {
|
|
3160
|
+
action: 'demo',
|
|
3161
|
+
groupId,
|
|
3162
|
+
reason,
|
|
3163
|
+
};
|
|
3164
|
+
return {
|
|
3165
|
+
ok: true,
|
|
3166
|
+
message: this.config.dryRun ? 'dry-run: no action executed' : 'action executor not implemented yet',
|
|
3167
|
+
plan,
|
|
3168
|
+
};
|
|
3169
|
+
}
|
|
3170
|
+
async kick(session, target, rejectAddRequest = false, reason) {
|
|
3171
|
+
const targetIdRaw = this.parseTargetId(target);
|
|
3172
|
+
const targetId = Number(targetIdRaw);
|
|
3173
|
+
const groupId = this.toGroupId(session);
|
|
3174
|
+
if (!targetIdRaw || !Number.isFinite(targetId)) {
|
|
3175
|
+
return { ok: false, message: '目标 QQ 号无效。' };
|
|
3176
|
+
}
|
|
3177
|
+
if (groupId == null) {
|
|
3178
|
+
return { ok: false, message: '请在群聊中执行该命令。' };
|
|
3179
|
+
}
|
|
3180
|
+
const plan = {
|
|
3181
|
+
action: 'kick',
|
|
3182
|
+
groupId: String(groupId),
|
|
3183
|
+
targetId: targetIdRaw,
|
|
3184
|
+
reason,
|
|
3185
|
+
};
|
|
3186
|
+
if (this.config.dryRun)
|
|
3187
|
+
return this.createDryRunResult(plan);
|
|
3188
|
+
const onebot = this.getOneBotApi(session);
|
|
3189
|
+
if (!onebot?.setGroupKick) {
|
|
3190
|
+
return { ok: false, message: '当前会话不支持 OneBot 踢人接口。' };
|
|
3191
|
+
}
|
|
3192
|
+
const role = await this.getTargetRole(session, targetId);
|
|
3193
|
+
if (role === 'owner') {
|
|
3194
|
+
return { ok: false, message: '不能对群主执行踢人操作。' };
|
|
3195
|
+
}
|
|
3196
|
+
try {
|
|
3197
|
+
await onebot.setGroupKick(groupId, targetId, rejectAddRequest);
|
|
3198
|
+
// 手动踢出 → 加入本群黑名单
|
|
3199
|
+
await this.recordKickToBlacklist(session, targetIdRaw);
|
|
3200
|
+
return { ok: true, message: `已执行踢人: ${targetIdRaw}`, plan };
|
|
3201
|
+
}
|
|
3202
|
+
catch (error) {
|
|
3203
|
+
return { ok: false, message: `踢人失败: ${String(error)}`, plan };
|
|
3204
|
+
}
|
|
3205
|
+
}
|
|
3206
|
+
async mute(session, target, minutes, reason) {
|
|
3207
|
+
const targetIdRaw = this.parseTargetId(target);
|
|
3208
|
+
const targetId = Number(targetIdRaw);
|
|
3209
|
+
const groupId = this.toGroupId(session);
|
|
3210
|
+
if (!targetIdRaw || !Number.isFinite(targetId)) {
|
|
3211
|
+
return { ok: false, message: '目标 QQ 号无效。' };
|
|
3212
|
+
}
|
|
3213
|
+
if (groupId == null) {
|
|
3214
|
+
return { ok: false, message: '请在群聊中执行该命令。' };
|
|
3215
|
+
}
|
|
3216
|
+
if (!Number.isFinite(minutes) || minutes <= 0) {
|
|
3217
|
+
return { ok: false, message: '禁言时长必须为正整数分钟(上限 30 天)。' };
|
|
3218
|
+
}
|
|
3219
|
+
const requestedMinutes = Math.floor(minutes);
|
|
3220
|
+
const capped = requestedMinutes > 43200;
|
|
3221
|
+
const effectiveMinutes = Math.min(requestedMinutes, 43200);
|
|
3222
|
+
const duration = effectiveMinutes * 60;
|
|
3223
|
+
const plan = {
|
|
3224
|
+
action: 'mute',
|
|
3225
|
+
groupId: String(groupId),
|
|
3226
|
+
targetId: targetIdRaw,
|
|
3227
|
+
reason: reason ? `${reason}; minutes=${requestedMinutes}` : `minutes=${requestedMinutes}`,
|
|
3228
|
+
};
|
|
3229
|
+
if (this.config.dryRun)
|
|
3230
|
+
return this.createDryRunResult(plan);
|
|
3231
|
+
const onebot = this.getOneBotApi(session);
|
|
3232
|
+
if (!onebot?.setGroupBan) {
|
|
3233
|
+
return { ok: false, message: '当前会话不支持 OneBot 禁言接口。' };
|
|
3234
|
+
}
|
|
3235
|
+
if (this.config.allowedUserIds.includes(targetIdRaw)) {
|
|
3236
|
+
const actorRole = await this.resolveMemberRole(session);
|
|
3237
|
+
const bypass = this.config.allowAdminBypassWhitelistMute && (actorRole === 'owner' || actorRole === 'admin');
|
|
3238
|
+
if (!bypass) {
|
|
3239
|
+
return { ok: false, message: '目标账号在白名单保护中,禁止禁言。' };
|
|
3240
|
+
}
|
|
3241
|
+
}
|
|
3242
|
+
const role = await this.getTargetRole(session, targetId);
|
|
3243
|
+
if (role === 'owner') {
|
|
3244
|
+
return { ok: false, message: '喵~ 群主无法被禁言。' };
|
|
3245
|
+
}
|
|
3246
|
+
if (role === 'admin' && !await this.isBotOwnerInGroup(session)) {
|
|
3247
|
+
return { ok: false, message: '喵~ bot 不是群主,不能对管理员禁言。' };
|
|
3248
|
+
}
|
|
3249
|
+
try {
|
|
3250
|
+
await onebot.setGroupBan(groupId, targetId, duration);
|
|
3251
|
+
const capNote = capped ? '(已按 30 天上限处理)' : '';
|
|
3252
|
+
return { ok: true, message: `已执行禁言: ${targetIdRaw}, ${effectiveMinutes} 分钟${capNote}`, plan };
|
|
3253
|
+
}
|
|
3254
|
+
catch (error) {
|
|
3255
|
+
return { ok: false, message: `禁言失败: ${String(error)}`, plan };
|
|
3256
|
+
}
|
|
3257
|
+
}
|
|
3258
|
+
async unmute(session, target, reason) {
|
|
3259
|
+
const targetIdRaw = this.parseTargetId(target);
|
|
3260
|
+
const targetId = Number(targetIdRaw);
|
|
3261
|
+
const groupId = this.toGroupId(session);
|
|
3262
|
+
if (!targetIdRaw || !Number.isFinite(targetId)) {
|
|
3263
|
+
return { ok: false, message: '目标 QQ 号无效。' };
|
|
3264
|
+
}
|
|
3265
|
+
if (groupId == null) {
|
|
3266
|
+
return { ok: false, message: '请在群聊中执行该命令。' };
|
|
3267
|
+
}
|
|
3268
|
+
const plan = {
|
|
3269
|
+
action: 'unmute',
|
|
3270
|
+
groupId: String(groupId),
|
|
3271
|
+
targetId: targetIdRaw,
|
|
3272
|
+
reason,
|
|
3273
|
+
};
|
|
3274
|
+
if (this.config.dryRun)
|
|
3275
|
+
return this.createDryRunResult(plan);
|
|
3276
|
+
const onebot = this.getOneBotApi(session);
|
|
3277
|
+
if (!onebot?.setGroupBan) {
|
|
3278
|
+
return { ok: false, message: '当前会话不支持 OneBot 禁言接口。' };
|
|
3279
|
+
}
|
|
3280
|
+
const role = await this.getTargetRole(session, targetId);
|
|
3281
|
+
if (role === 'owner') {
|
|
3282
|
+
return { ok: false, message: '不能对群主执行解禁言操作。' };
|
|
3283
|
+
}
|
|
3284
|
+
try {
|
|
3285
|
+
await onebot.setGroupBan(groupId, targetId, 0);
|
|
3286
|
+
return { ok: true, message: `已执行解禁言: ${targetIdRaw}`, plan };
|
|
3287
|
+
}
|
|
3288
|
+
catch (error) {
|
|
3289
|
+
return { ok: false, message: `解禁言失败: ${String(error)}`, plan };
|
|
3290
|
+
}
|
|
3291
|
+
}
|
|
3292
|
+
async setAdmin(session, target, enable, reason) {
|
|
3293
|
+
const targetIdRaw = this.parseTargetId(target);
|
|
3294
|
+
const targetId = Number(targetIdRaw);
|
|
3295
|
+
const groupId = this.toGroupId(session);
|
|
3296
|
+
if (!targetIdRaw || !Number.isFinite(targetId)) {
|
|
3297
|
+
return { ok: false, message: '目标 QQ 号无效。' };
|
|
3298
|
+
}
|
|
3299
|
+
if (groupId == null) {
|
|
3300
|
+
return { ok: false, message: '请在群聊中执行该命令。' };
|
|
3301
|
+
}
|
|
3302
|
+
const plan = {
|
|
3303
|
+
action: enable ? 'set-admin' : 'unset-admin',
|
|
3304
|
+
groupId: String(groupId),
|
|
3305
|
+
targetId: targetIdRaw,
|
|
3306
|
+
reason,
|
|
3307
|
+
};
|
|
3308
|
+
if (this.config.dryRun)
|
|
3309
|
+
return this.createDryRunResult(plan);
|
|
3310
|
+
const onebot = this.getOneBotApi(session);
|
|
3311
|
+
if (!onebot?.setGroupAdmin) {
|
|
3312
|
+
return { ok: false, message: '当前会话不支持 OneBot 设管理接口。' };
|
|
3313
|
+
}
|
|
3314
|
+
const role = await this.getTargetRole(session, targetId);
|
|
3315
|
+
if (role === 'owner') {
|
|
3316
|
+
return { ok: false, message: '群主不需要设置管理员。' };
|
|
3317
|
+
}
|
|
3318
|
+
try {
|
|
3319
|
+
await onebot.setGroupAdmin(groupId, targetId, enable);
|
|
3320
|
+
return { ok: true, message: enable ? `已设置管理员: ${targetIdRaw}` : `已取消管理员: ${targetIdRaw}`, plan };
|
|
3321
|
+
}
|
|
3322
|
+
catch (error) {
|
|
3323
|
+
return { ok: false, message: `设置管理员失败: ${String(error)}`, plan };
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
}
|
|
3327
|
+
exports.QQGroupManagerService = QQGroupManagerService;
|