@nestim/koishi-plugin-qq-group-manager 0.1.6 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/commands.js +14 -166
- package/lib/index.d.ts +1 -3
- package/lib/index.js +39 -51
- package/lib/service.d.ts +7 -21
- package/lib/service.js +1047 -663
- package/package.json +2 -2
- package/readme.md +148 -29
package/lib/service.js
CHANGED
|
@@ -5,18 +5,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.QQGroupManagerService = void 0;
|
|
7
7
|
const koishi_1 = require("koishi");
|
|
8
|
-
const node_os_1 = __importDefault(require("node:os"));
|
|
9
8
|
const node_path_1 = __importDefault(require("node:path"));
|
|
10
9
|
const node_fs_1 = __importDefault(require("node:fs"));
|
|
11
|
-
const node_child_process_1 = require("node:child_process");
|
|
12
|
-
const node_util_1 = require("node:util");
|
|
13
|
-
const execFile = (0, node_util_1.promisify)(node_child_process_1.execFile);
|
|
14
10
|
class QQGroupManagerService extends koishi_1.Service {
|
|
15
11
|
ctx;
|
|
16
12
|
config;
|
|
17
13
|
_logger;
|
|
18
14
|
unauthorizedMuteAttempts = new Map();
|
|
19
|
-
menuPairings = new Map();
|
|
20
15
|
aiBuffers = new Map();
|
|
21
16
|
aiCounters = new Map();
|
|
22
17
|
aiLastReplyAt = new Map();
|
|
@@ -30,6 +25,96 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
30
25
|
pendingJoinRequestFlags = new Map();
|
|
31
26
|
violationRecords = new Map();
|
|
32
27
|
_imageDataUrlCache = new Map();
|
|
28
|
+
/** 记忆库写锁:串行化「读整档→改→整写」,防止并发写互相覆盖 */
|
|
29
|
+
_memoryWriteLock = Promise.resolve();
|
|
30
|
+
/** 待审入群申请的落盘去抖定时器 */
|
|
31
|
+
_pendingJoinSaveTimer = null;
|
|
32
|
+
/** 待审单落盘串行化(防止 dispose 与去抖写同时进行) */
|
|
33
|
+
_pendingJoinWriteChain = Promise.resolve();
|
|
34
|
+
/** 待审单落盘 helper */
|
|
35
|
+
runPendingJoinWriteLocked(task) {
|
|
36
|
+
const run = this._pendingJoinWriteChain.then(() => task());
|
|
37
|
+
this._pendingJoinWriteChain = run.then(() => undefined, () => undefined);
|
|
38
|
+
return run;
|
|
39
|
+
}
|
|
40
|
+
/** 安全读取布尔配置(字段缺失/未定义时返回默认值) */
|
|
41
|
+
cfgBool(key, def) {
|
|
42
|
+
const v = this.config ? this.config[key] : undefined;
|
|
43
|
+
return typeof v === 'boolean' ? v : def;
|
|
44
|
+
}
|
|
45
|
+
/** 事件里的操作者 QQ(踢人事件用) */
|
|
46
|
+
eventOperatorId(session) {
|
|
47
|
+
return String((session && (session.operatorId || session.userId)) || '');
|
|
48
|
+
}
|
|
49
|
+
/** 踢人后记入黑名单(供自动踢人/手动踢人复用) */
|
|
50
|
+
async recordKickToBlacklist(session, qq) {
|
|
51
|
+
if (!this.cfgBool('banRecordOnKick', true))
|
|
52
|
+
return;
|
|
53
|
+
if (!this.resolveBlacklistEnabled(session))
|
|
54
|
+
return;
|
|
55
|
+
const id = String(qq || '').trim();
|
|
56
|
+
if (!/^\d{5,12}$/.test(id))
|
|
57
|
+
return;
|
|
58
|
+
const r = await this.addToBlacklist(session, id, '');
|
|
59
|
+
this._logger.info(`[ban] 踢出后${r.ok ? '已加入' : '未加入'}黑名单 qq=${id} | ${this.sessionTag(session)}`);
|
|
60
|
+
if (r.ok) {
|
|
61
|
+
try {
|
|
62
|
+
await session.send(this.styleText(`已将 ${id} 加入黑名单`));
|
|
63
|
+
}
|
|
64
|
+
catch { /* 忽略发送失败 */ }
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* 群成员被移出(自己退群 or 被踢)→ 记入本群黑名单。
|
|
69
|
+
* 仅处理 subtype='passive'(被踢),主动退群不记。
|
|
70
|
+
*/
|
|
71
|
+
async handleMemberRemoved(session) {
|
|
72
|
+
if (!this.isPlatformAllowed(session.platform))
|
|
73
|
+
return;
|
|
74
|
+
if (!session.guildId)
|
|
75
|
+
return;
|
|
76
|
+
// 只记"被踢",自己退群不记
|
|
77
|
+
if (session.subtype && session.subtype !== 'passive')
|
|
78
|
+
return;
|
|
79
|
+
const qq = String(session.targetId || session.userId || '').trim();
|
|
80
|
+
if (qq === String(session.selfId || ''))
|
|
81
|
+
return;
|
|
82
|
+
this._logger.info(`[ban] 检测到踢人事件 qq=${qq} operator=${this.eventOperatorId(session)} | ${this.sessionTag(session)}`);
|
|
83
|
+
await this.recordKickToBlacklist(session, qq);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* 有人入群 → 比对黑名单,命中则踢出并提示。
|
|
87
|
+
*/
|
|
88
|
+
async handleMemberAdded(session) {
|
|
89
|
+
if (!this.isPlatformAllowed(session.platform))
|
|
90
|
+
return;
|
|
91
|
+
if (!session.guildId)
|
|
92
|
+
return;
|
|
93
|
+
if (!this.cfgBool('banKickOnJoin', true))
|
|
94
|
+
return;
|
|
95
|
+
if (!this.resolveBlacklistEnabled(session))
|
|
96
|
+
return;
|
|
97
|
+
const qq = String(session.targetId || session.userId || '').trim();
|
|
98
|
+
if (!/^\d{5,12}$/.test(qq))
|
|
99
|
+
return;
|
|
100
|
+
if (!(await this.isBlacklisted(session, qq)))
|
|
101
|
+
return;
|
|
102
|
+
|
|
103
|
+
const onebot = this.getOneBotApi(session);
|
|
104
|
+
const groupId = this.toGroupId(session);
|
|
105
|
+
if (!onebot?.setGroupKick || groupId == null) {
|
|
106
|
+
this._logger.warn(`[ban] 命中黑名单 qq=${qq} 但缺少踢人接口 | ${this.sessionTag(session)}`);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
await onebot.setGroupKick(groupId, Number(qq), true);
|
|
111
|
+
await session.send(this.styleText('已将黑名单成员移除群聊。'));
|
|
112
|
+
this._logger.info(`[ban] 入群命中黑名单,已踢出 qq=${qq} | ${this.sessionTag(session)}`);
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
this._logger.warn(`[ban] 踢出黑名单成员失败 qq=${qq}: ${String(e)}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
33
118
|
constructor(ctx, config) {
|
|
34
119
|
super(ctx, 'nestimQqGroupManager', true);
|
|
35
120
|
this.ctx = ctx;
|
|
@@ -37,9 +122,29 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
37
122
|
this._logger = ctx.logger('nestim-qq-group-manager');
|
|
38
123
|
ctx.on('message', (session) => this.handleGroupModeration(session));
|
|
39
124
|
ctx.on('guild-member-request', (session) => this.handleGuildMemberRequest(session));
|
|
125
|
+
// 被踢出群(含群主/管理员踢人)→ 记入本群黑名单
|
|
126
|
+
ctx.on('guild-member-deleted', (session) => {
|
|
127
|
+
this.handleMemberRemoved(session).catch((e) => this._logger.warn(`处理退群事件失败: ${String(e)}`));
|
|
128
|
+
});
|
|
129
|
+
// 入群 → 比对黑名单
|
|
130
|
+
ctx.on('guild-member-added', (session) => {
|
|
131
|
+
this.handleMemberAdded(session).catch((e) => this._logger.warn(`处理入群事件失败: ${String(e)}`));
|
|
132
|
+
});
|
|
133
|
+
// 启动即恢复上次未处理的待审入群申请(重启不再丢单),并清掉已过期编号
|
|
134
|
+
try {
|
|
135
|
+
this.loadPendingJoinRequests();
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
this._logger.warn(`[join-review] 恢复待审单失败: ${String(error)}`);
|
|
139
|
+
}
|
|
40
140
|
}
|
|
41
141
|
isPlatformAllowed(platform) {
|
|
42
|
-
|
|
142
|
+
if (!platform)
|
|
143
|
+
return false;
|
|
144
|
+
const list = Array.isArray(this.config && this.config.platformFilter)
|
|
145
|
+
? this.config.platformFilter
|
|
146
|
+
: ['onebot'];
|
|
147
|
+
return list.includes(platform);
|
|
43
148
|
}
|
|
44
149
|
sessionTag(session) {
|
|
45
150
|
if (!session)
|
|
@@ -49,137 +154,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
49
154
|
styleText(text) {
|
|
50
155
|
return this.config.responseStyle === 'meow' ? `喵~ ${text}` : text;
|
|
51
156
|
}
|
|
52
|
-
escapeHtml(source) {
|
|
53
|
-
return source
|
|
54
|
-
.replace(/&/g, '&')
|
|
55
|
-
.replace(/</g, '<')
|
|
56
|
-
.replace(/>/g, '>')
|
|
57
|
-
.replace(/"/g, '"')
|
|
58
|
-
.replace(/'/g, ''');
|
|
59
|
-
}
|
|
60
|
-
collectCategories(session) {
|
|
61
|
-
const list = this.ctx.$commander._commandList;
|
|
62
|
-
const available = session ? new Set(this.ctx.$commander.available(session)) : null;
|
|
63
|
-
const categories = new Map();
|
|
64
|
-
const getDesc = (command) => {
|
|
65
|
-
const key = `commands.${command.name}.description`;
|
|
66
|
-
const localized = session?.text?.(key);
|
|
67
|
-
if (typeof localized === 'string' && localized && localized !== key)
|
|
68
|
-
return localized;
|
|
69
|
-
const rawDesc = command.toJSON?.().description;
|
|
70
|
-
return typeof rawDesc === 'string' ? rawDesc : '';
|
|
71
|
-
};
|
|
72
|
-
const getRoot = (command) => {
|
|
73
|
-
let node = command;
|
|
74
|
-
while (node?.parent)
|
|
75
|
-
node = node.parent;
|
|
76
|
-
return node;
|
|
77
|
-
};
|
|
78
|
-
const getDepth = (command) => {
|
|
79
|
-
let depth = 0;
|
|
80
|
-
let node = command;
|
|
81
|
-
while (node?.parent) {
|
|
82
|
-
depth += 1;
|
|
83
|
-
node = node.parent;
|
|
84
|
-
}
|
|
85
|
-
return depth;
|
|
86
|
-
};
|
|
87
|
-
for (const command of list) {
|
|
88
|
-
if (!command.parent)
|
|
89
|
-
continue;
|
|
90
|
-
const root = getRoot(command);
|
|
91
|
-
if (!root)
|
|
92
|
-
continue;
|
|
93
|
-
if (available && !available.has(command.name) && !available.has(command.displayName || ''))
|
|
94
|
-
continue;
|
|
95
|
-
const key = root.name;
|
|
96
|
-
if (!categories.has(key)) {
|
|
97
|
-
categories.set(key, {
|
|
98
|
-
key,
|
|
99
|
-
title: root.displayName || key,
|
|
100
|
-
desc: getDesc(root),
|
|
101
|
-
children: [],
|
|
102
|
-
});
|
|
103
|
-
}
|
|
104
|
-
const category = categories.get(key);
|
|
105
|
-
if (!category)
|
|
106
|
-
continue;
|
|
107
|
-
const depth = getDepth(command);
|
|
108
|
-
if (depth !== 1)
|
|
109
|
-
continue;
|
|
110
|
-
const desc = getDesc(command);
|
|
111
|
-
const display = command.displayName || command.name;
|
|
112
|
-
category.children.push({ name: display, desc });
|
|
113
|
-
}
|
|
114
|
-
if (!categories.size) {
|
|
115
|
-
for (const command of list) {
|
|
116
|
-
if (command.parent)
|
|
117
|
-
continue;
|
|
118
|
-
categories.set(command.name, {
|
|
119
|
-
key: command.name,
|
|
120
|
-
title: command.displayName || command.name,
|
|
121
|
-
desc: getDesc(command),
|
|
122
|
-
children: [],
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
for (const category of categories.values()) {
|
|
127
|
-
category.children.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
|
|
128
|
-
}
|
|
129
|
-
const miscChildren = [];
|
|
130
|
-
for (const command of list) {
|
|
131
|
-
if (command.parent)
|
|
132
|
-
continue;
|
|
133
|
-
if (available && !available.has(command.name) && !available.has(command.displayName || ''))
|
|
134
|
-
continue;
|
|
135
|
-
const hasChildren = list.some((item) => item.parent === command);
|
|
136
|
-
if (hasChildren)
|
|
137
|
-
continue;
|
|
138
|
-
miscChildren.push({ name: command.displayName || command.name, desc: getDesc(command) });
|
|
139
|
-
}
|
|
140
|
-
if (miscChildren.length) {
|
|
141
|
-
miscChildren.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
|
|
142
|
-
categories.set('other', {
|
|
143
|
-
key: 'other',
|
|
144
|
-
title: '其它',
|
|
145
|
-
desc: '无父指令的功能集合',
|
|
146
|
-
children: miscChildren,
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
return [...categories.values()].sort((a, b) => {
|
|
150
|
-
if (a.key === 'other' && b.key !== 'other')
|
|
151
|
-
return 1;
|
|
152
|
-
if (b.key === 'other' && a.key !== 'other')
|
|
153
|
-
return -1;
|
|
154
|
-
return a.title.localeCompare(b.title, 'zh-CN');
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
resolveMenuCategory(keyword, session) {
|
|
158
|
-
const query = keyword?.trim().toLowerCase();
|
|
159
|
-
if (!query)
|
|
160
|
-
return null;
|
|
161
|
-
const norm = query.replace(/\s+/g, '');
|
|
162
|
-
const categories = this.collectCategories(session);
|
|
163
|
-
return categories.find((cat) => {
|
|
164
|
-
const k = cat.key.toLowerCase();
|
|
165
|
-
const t = cat.title.toLowerCase();
|
|
166
|
-
const tk = `${t}菜单`;
|
|
167
|
-
const kk = `${k}菜单`;
|
|
168
|
-
return k === norm || t === norm || tk === norm || kk === norm || k.includes(norm) || t.includes(norm);
|
|
169
|
-
}) ?? null;
|
|
170
|
-
}
|
|
171
|
-
pairingKey(session) {
|
|
172
|
-
if (!session?.userId)
|
|
173
|
-
return '';
|
|
174
|
-
const scope = session.guildId || session.channelId || 'private';
|
|
175
|
-
return `${session.platform}:${scope}:${session.userId}`;
|
|
176
|
-
}
|
|
177
|
-
armMenuPairing(session, ttlMs = 30_000) {
|
|
178
|
-
const key = this.pairingKey(session);
|
|
179
|
-
if (!key)
|
|
180
|
-
return;
|
|
181
|
-
this.menuPairings.set(key, Date.now() + ttlMs);
|
|
182
|
-
}
|
|
183
157
|
getMessageText(session) {
|
|
184
158
|
const raw = session?.content ?? '';
|
|
185
159
|
return raw
|
|
@@ -193,12 +167,26 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
193
167
|
return '';
|
|
194
168
|
return `${session.platform ?? 'unknown'}:${session.guildId}`;
|
|
195
169
|
}
|
|
170
|
+
/**
|
|
171
|
+
* 统一的三态开关解析:单个群设置优先,未设置时跟随全局。
|
|
172
|
+
*
|
|
173
|
+
* 规则(这是本插件的核心约定):
|
|
174
|
+
* 1) 单个群**显式设置**了该值 → 无条件以它为准,**不受全局开关影响**
|
|
175
|
+
* (所以全局关着,某个群单独打开也能生效)
|
|
176
|
+
* 2) 单个群**未设置**(undefined)→ 跟随全局
|
|
177
|
+
*
|
|
178
|
+
* 注意:用 `!== undefined` 判断,这样 `false` 也算"已设置",
|
|
179
|
+
* 不会被 `??` 或 `||` 误判为"未设置"。
|
|
180
|
+
*/
|
|
181
|
+
resolveSwitch(rule, ruleKey, globalKey) {
|
|
182
|
+
if (rule && rule[ruleKey] !== undefined)
|
|
183
|
+
return rule[ruleKey];
|
|
184
|
+
return this.config[globalKey];
|
|
185
|
+
}
|
|
196
186
|
resolveAiEnabled(session) {
|
|
197
187
|
const guildId = this.normalizeGuildId(session.guildId);
|
|
198
188
|
const rule = this.config.groupRules.find((item) => this.normalizeGuildId(item.guildId) === guildId);
|
|
199
|
-
|
|
200
|
-
return rule.enableAiReply;
|
|
201
|
-
return this.config.enableAiReply;
|
|
189
|
+
return this.resolveSwitch(rule, 'enableAiReply', 'enableAiReply');
|
|
202
190
|
}
|
|
203
191
|
extractAiMessageText(session) {
|
|
204
192
|
const text = this.getMessageText(session)
|
|
@@ -206,6 +194,172 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
206
194
|
.trim();
|
|
207
195
|
return text;
|
|
208
196
|
}
|
|
197
|
+
// ============ 黑名单(按群独立存储:banMember_<群号>.md) ============
|
|
198
|
+
/**
|
|
199
|
+
* 解析本群黑名单文件路径。
|
|
200
|
+
* 文件名由模板推导:banMember.md -> banMember_<群号>.md
|
|
201
|
+
* 这样每个群一份独立文件,可在 Explorer 中分别查看/编辑。
|
|
202
|
+
*/
|
|
203
|
+
getBlacklistFilePath(session) {
|
|
204
|
+
const base = (this.ctx && this.ctx.baseDir) || process.cwd();
|
|
205
|
+
const groupId = this.normalizeGuildId(session && session.guildId) || 'unknown';
|
|
206
|
+
const tpl = (this.config.blacklistFileName || 'banMember.md').trim();
|
|
207
|
+
const dot = tpl.lastIndexOf('.');
|
|
208
|
+
const baseName = dot > 0 ? tpl.slice(0, dot) : tpl;
|
|
209
|
+
const ext = dot > 0 ? tpl.slice(dot) : '';
|
|
210
|
+
return node_path_1.default.resolve(base, `${baseName}_${groupId}${ext}`);
|
|
211
|
+
}
|
|
212
|
+
async readBlacklistFile(session) {
|
|
213
|
+
try {
|
|
214
|
+
return await node_fs_1.default.promises.readFile(this.getBlacklistFilePath(session), 'utf8');
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return '';
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async writeBlacklistFile(session, content) {
|
|
221
|
+
await node_fs_1.default.promises.writeFile(this.getBlacklistFilePath(session), String(content), 'utf8');
|
|
222
|
+
}
|
|
223
|
+
/** 解析 banMember.md -> [{qq, name, at}],按 QQ 去重 */
|
|
224
|
+
parseBlacklist(content) {
|
|
225
|
+
const out = [];
|
|
226
|
+
const seen = new Set();
|
|
227
|
+
const lines = String(content || '').split(/\r?\n/);
|
|
228
|
+
let cur = null;
|
|
229
|
+
const flush = () => {
|
|
230
|
+
if (cur && cur.qq && !seen.has(cur.qq)) {
|
|
231
|
+
seen.add(cur.qq);
|
|
232
|
+
out.push(cur);
|
|
233
|
+
}
|
|
234
|
+
cur = null;
|
|
235
|
+
};
|
|
236
|
+
for (const line of lines) {
|
|
237
|
+
const m = line.match(/^##\s*(\d{5,12})\s*(?:·\s*(.*))?\s*$/);
|
|
238
|
+
if (m) {
|
|
239
|
+
flush();
|
|
240
|
+
cur = { qq: m[1], name: (m[2] || '').trim(), at: '' };
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (!cur)
|
|
244
|
+
continue;
|
|
245
|
+
const t = line.match(/^-\s*加入时间\s*[::]\s*(.*)$/);
|
|
246
|
+
if (t)
|
|
247
|
+
cur.at = t[1].trim();
|
|
248
|
+
}
|
|
249
|
+
flush();
|
|
250
|
+
return out;
|
|
251
|
+
}
|
|
252
|
+
/** 序列化(保持人类可读,便于在 Explorer 里直接改) */
|
|
253
|
+
serializeBlacklist(entries, groupId) {
|
|
254
|
+
const lines = [
|
|
255
|
+
`# 黑名单成员(群 ${groupId || '未知'})`,
|
|
256
|
+
'',
|
|
257
|
+
'> 每个条目以 `---` 分隔。格式:`## QQ号 · 备注`,`- 加入时间:` 记录时间。',
|
|
258
|
+
'> 本文件仅对应该群,可直接用控制台左侧「探索器 Explorer」编辑。',
|
|
259
|
+
'',
|
|
260
|
+
];
|
|
261
|
+
for (const e of entries) {
|
|
262
|
+
lines.push('---', '', `## ${e.qq}${e.name ? ' · ' + e.name : ''}`, `- 加入时间: ${e.at || ''}`, '');
|
|
263
|
+
}
|
|
264
|
+
return lines.join('\n');
|
|
265
|
+
}
|
|
266
|
+
async getBlacklist(session) {
|
|
267
|
+
return this.parseBlacklist(await this.readBlacklistFile(session));
|
|
268
|
+
}
|
|
269
|
+
async isBlacklisted(session, qq) {
|
|
270
|
+
const id = String(qq ?? '').trim();
|
|
271
|
+
if (!id)
|
|
272
|
+
return false;
|
|
273
|
+
return (await this.getBlacklist(session)).some((e) => e.qq === id);
|
|
274
|
+
}
|
|
275
|
+
/** 加入本群黑名单。返回 { ok, message } */
|
|
276
|
+
async addToBlacklist(session, qq, name) {
|
|
277
|
+
const id = String(qq ?? '').trim();
|
|
278
|
+
if (!/^\d{5,12}$/.test(id))
|
|
279
|
+
return { ok: false, message: 'QQ 号格式不正确。' };
|
|
280
|
+
const list = await this.getBlacklist(session);
|
|
281
|
+
if (list.some((e) => e.qq === id))
|
|
282
|
+
return { ok: false, message: '该成员已在黑名单中。' };
|
|
283
|
+
const stamp = new Date().toLocaleString('zh-CN', { hour12: false });
|
|
284
|
+
list.push({ qq: id, name: String(name ?? '').trim(), at: stamp });
|
|
285
|
+
await this.writeBlacklistFile(session, this.serializeBlacklist(list, this.normalizeGuildId(session && session.guildId)));
|
|
286
|
+
return { ok: true, message: `已将 ${id} 加入黑名单` };
|
|
287
|
+
}
|
|
288
|
+
/** 从本群黑名单移除。返回 { ok, message } */
|
|
289
|
+
async removeFromBlacklist(session, qq) {
|
|
290
|
+
const id = String(qq ?? '').trim();
|
|
291
|
+
const list = await this.getBlacklist(session);
|
|
292
|
+
const next = list.filter((e) => e.qq !== id);
|
|
293
|
+
if (next.length === list.length)
|
|
294
|
+
return { ok: false, message: `删除失败,未找到人员 ${id}` };
|
|
295
|
+
await this.writeBlacklistFile(session, this.serializeBlacklist(next, this.normalizeGuildId(session && session.guildId)));
|
|
296
|
+
return { ok: true, message: `已将 ${id} 移出黑名单` };
|
|
297
|
+
}
|
|
298
|
+
/** 该群是否启用黑名单(单群设置优先,未设置跟随全局) */
|
|
299
|
+
resolveBlacklistEnabled(session) {
|
|
300
|
+
const currentGuild = this.normalizeGuildId(session && session.guildId);
|
|
301
|
+
const rule = this.config.groupRules.find((item) => this.normalizeGuildId(item.guildId) === currentGuild);
|
|
302
|
+
return this.resolveSwitch(rule, 'blacklistEnabled', 'enableBlacklist');
|
|
303
|
+
}
|
|
304
|
+
/** 取群成员信息(用于校验"必须是群内人员"并拿到昵称) */
|
|
305
|
+
/**
|
|
306
|
+
* 提取本条消息中 @ 到的目标 QQ 号(@ 可代替 QQ 号作为指令目标)。
|
|
307
|
+
* 支持三种来源:CQ 码 [CQ:at,qq=xxx]、Koishi 的 at 元素、content 里的 <at id="xxx"/>。
|
|
308
|
+
* 排除 @全体成员 与 @机器人自身。
|
|
309
|
+
*/
|
|
310
|
+
extractMentionedTargets(session) {
|
|
311
|
+
const out = [];
|
|
312
|
+
const push = (v) => {
|
|
313
|
+
const s = String(v == null ? '' : v).trim();
|
|
314
|
+
if (!s || s === 'all' || s === '0')
|
|
315
|
+
return;
|
|
316
|
+
const self = String(session?.bot?.selfId ?? '');
|
|
317
|
+
if (self && s === self)
|
|
318
|
+
return;
|
|
319
|
+
if (!out.includes(s))
|
|
320
|
+
out.push(s);
|
|
321
|
+
};
|
|
322
|
+
const content = session?.content || '';
|
|
323
|
+
// CQ 码
|
|
324
|
+
for (const chunk of content.match(/\[CQ:at,[^\]]*\]/gi) || []) {
|
|
325
|
+
const m = chunk.match(/(?:qq|id)=([^,\]]+)/i);
|
|
326
|
+
if (m)
|
|
327
|
+
push(decodeURIComponent(m[1]));
|
|
328
|
+
}
|
|
329
|
+
// Koishi at 元素
|
|
330
|
+
for (const el of session?.elements || []) {
|
|
331
|
+
if (String(el?.type || '').toLowerCase() !== 'at')
|
|
332
|
+
continue;
|
|
333
|
+
push(el.attrs?.qq ?? el.attrs?.id ?? el.qq ?? el.id);
|
|
334
|
+
}
|
|
335
|
+
// HTML 形式
|
|
336
|
+
for (const tag of content.match(/<at\b[^>]*\/?>/gi) || []) {
|
|
337
|
+
const m = tag.match(/(?:id|qq)\s*=\s*"([^"]*)"/i) || tag.match(/(?:id|qq)\s*=\s*'([^']*)'/i);
|
|
338
|
+
if (m)
|
|
339
|
+
push(m[1]);
|
|
340
|
+
}
|
|
341
|
+
return out;
|
|
342
|
+
}
|
|
343
|
+
async fetchGroupMember(session, qq) {
|
|
344
|
+
const onebot = this.getOneBotApi(session);
|
|
345
|
+
const groupId = this.toGroupId(session);
|
|
346
|
+
const uid = Number(qq);
|
|
347
|
+
if (!onebot?.getGroupMemberInfo || groupId == null || !Number.isFinite(uid))
|
|
348
|
+
return null;
|
|
349
|
+
try {
|
|
350
|
+
const info = await onebot.getGroupMemberInfo(groupId, uid, true);
|
|
351
|
+
if (!info)
|
|
352
|
+
return null;
|
|
353
|
+
return {
|
|
354
|
+
qq: String(uid),
|
|
355
|
+
name: String(info.card || info.nickname || info.nick || '').trim(),
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
catch {
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
// ============ 记忆库 ============
|
|
209
363
|
getMemoryFilePath() {
|
|
210
364
|
const base = (this.ctx && this.ctx.baseDir) || process.cwd();
|
|
211
365
|
const name = (this.config.memoryFileName || 'Memory.md').trim();
|
|
@@ -230,14 +384,27 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
230
384
|
.map((b) => b.trim())
|
|
231
385
|
.filter(Boolean);
|
|
232
386
|
}
|
|
387
|
+
/**
|
|
388
|
+
* 记忆库写互斥:把「读整档 → 改 → 整写」串行化。
|
|
389
|
+
* 并发保存时后一次读到的才是前一次写完的内容,不会互相覆盖丢条目。
|
|
390
|
+
* 记忆属于低频写,一把 promise 队列足够,无需文件锁。
|
|
391
|
+
*/
|
|
392
|
+
runMemoryWriteLocked(task) {
|
|
393
|
+
const run = this._memoryWriteLock.then(() => task());
|
|
394
|
+
// 锁链本身永不 reject,失败只回传给调用方,避免一次失败卡死后续写入
|
|
395
|
+
this._memoryWriteLock = run.then(() => undefined, () => undefined);
|
|
396
|
+
return run;
|
|
397
|
+
}
|
|
233
398
|
async saveMemoryToFile(userId, content) {
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
399
|
+
return this.runMemoryWriteLocked(async () => {
|
|
400
|
+
const now = new Date();
|
|
401
|
+
const stamp = now.toLocaleString('zh-CN', { hour12: false });
|
|
402
|
+
const block = `## ${stamp} · 用户 ${userId || 'unknown'}\n${String(content).trim()}`;
|
|
403
|
+
const existing = (await this.readMemoryFile()).trim();
|
|
404
|
+
const next = existing ? `${existing}\n\n---\n\n${block}\n` : `${block}\n`;
|
|
405
|
+
await this.writeMemoryFile(next);
|
|
406
|
+
return block;
|
|
407
|
+
});
|
|
241
408
|
}
|
|
242
409
|
async searchMemory(keyword, limit = 8) {
|
|
243
410
|
const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
|
|
@@ -259,68 +426,24 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
259
426
|
const memoryLines = results.map((b, i) => `${i + 1}. ${b.replace(/\n+/g, ' ').trim().slice(0, 140)}`).join('\n');
|
|
260
427
|
return `${prompt}\n\n【记忆库参考】(若与当前话题相关可引用;不相关请忽略,不要编造,不要暴露"系统记忆"字样):\n${memoryLines}\n`;
|
|
261
428
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
if (!
|
|
266
|
-
return false;
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
catch (error) {
|
|
281
|
-
await session.send(this.styleText(`记忆保存失败: ${String(error)}`));
|
|
282
|
-
this.logCommandResult('memory-save', { ok: false, message: String(error) }, session, { content });
|
|
283
|
-
}
|
|
284
|
-
return true;
|
|
285
|
-
}
|
|
286
|
-
const queryMatch = text.match(/^\[记忆查询\]\s*[::]?\s*([\s\S]*)$/);
|
|
287
|
-
if (queryMatch) {
|
|
288
|
-
const keyword = queryMatch[1].trim();
|
|
289
|
-
const results = await this.searchMemory(keyword, 8);
|
|
290
|
-
if (!results.length) {
|
|
291
|
-
await session.send(this.styleText(keyword ? `没有找到包含「${keyword}」的记忆。` : '记忆库为空或没有可显示的记录。'));
|
|
292
|
-
return true;
|
|
293
|
-
}
|
|
294
|
-
const reply = results.map((b, i) => `${i + 1}. ${b.replace(/\n+/g, ' ').trim()}`).join('\n');
|
|
295
|
-
await session.send(this.styleText(`记忆内容:\n${reply}`));
|
|
296
|
-
return true;
|
|
297
|
-
}
|
|
298
|
-
const listMatch = text.match(/^\[记忆(?:列表|全部|看)\]$/);
|
|
299
|
-
if (listMatch) {
|
|
300
|
-
const results = await this.searchMemory('', 8);
|
|
301
|
-
if (!results.length) {
|
|
302
|
-
await session.send(this.styleText('记忆库为空。'));
|
|
303
|
-
return true;
|
|
304
|
-
}
|
|
305
|
-
const reply = results.map((b, i) => `${i + 1}. ${b.replace(/\n+/g, ' ').trim()}`).join('\n');
|
|
306
|
-
await session.send(this.styleText(`最近的记忆:\n${reply}`));
|
|
307
|
-
return true;
|
|
308
|
-
}
|
|
309
|
-
const deleteMatch = text.match(/^\[记忆删除\]\s*[::]?\s*([\s\S]+)$/);
|
|
310
|
-
if (deleteMatch) {
|
|
311
|
-
const keyword = deleteMatch[1].trim();
|
|
312
|
-
const existing = await this.readMemoryFile();
|
|
313
|
-
const blocks = this.extractMemoryBlocks(existing);
|
|
314
|
-
const kept = blocks.filter((b) => !b.includes(keyword));
|
|
315
|
-
if (kept.length === blocks.length) {
|
|
316
|
-
await session.send(this.styleText(`没有找到包含「${keyword}」的记忆可删除。`));
|
|
317
|
-
return true;
|
|
318
|
-
}
|
|
319
|
-
await this.writeMemoryFile(kept.length ? `${kept.join('\n\n---\n\n')}\n` : '');
|
|
320
|
-
await session.send(this.styleText(`已删除包含「${keyword}」的记忆(${blocks.length - kept.length} 条)。`));
|
|
321
|
-
return true;
|
|
322
|
-
}
|
|
323
|
-
return false;
|
|
429
|
+
/** 按关键词删除记忆条目(含该关键词的整条记忆块)。返回 { ok, removed, message } */
|
|
430
|
+
async deleteMemoryByKeyword(keyword) {
|
|
431
|
+
const kw = String(keyword ?? '').trim();
|
|
432
|
+
if (!kw)
|
|
433
|
+
return { ok: false, removed: 0, message: '关键词为空。' };
|
|
434
|
+
// 同样走写锁:删除与保存并发时不会互相覆盖
|
|
435
|
+
return this.runMemoryWriteLocked(async () => {
|
|
436
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
|
|
437
|
+
if (!blocks.length)
|
|
438
|
+
return { ok: false, removed: 0, message: '记忆库为空。' };
|
|
439
|
+
const kept = blocks.filter((b) => !b.includes(kw));
|
|
440
|
+
const removed = blocks.length - kept.length;
|
|
441
|
+
if (!removed)
|
|
442
|
+
return { ok: false, removed: 0, message: `未找到包含「${kw}」的记忆` };
|
|
443
|
+
const content = kept.length ? kept.join('\n\n---\n\n') + '\n' : '';
|
|
444
|
+
await this.writeMemoryFile(content);
|
|
445
|
+
return { ok: true, removed, message: `已删除 ${removed} 条` };
|
|
446
|
+
});
|
|
324
447
|
}
|
|
325
448
|
getDisplayName(session) {
|
|
326
449
|
return session.username?.trim()
|
|
@@ -2199,448 +2322,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2199
2322
|
this.aiInFlight.delete(groupKey);
|
|
2200
2323
|
}
|
|
2201
2324
|
}
|
|
2202
|
-
async fetchOneBotStatus(session) {
|
|
2203
|
-
if (!session || session.platform !== 'onebot')
|
|
2204
|
-
return null;
|
|
2205
|
-
const onebot = this.getOneBotApi(session);
|
|
2206
|
-
if (!onebot?.getStatus)
|
|
2207
|
-
return null;
|
|
2208
|
-
try {
|
|
2209
|
-
return await onebot.getStatus();
|
|
2210
|
-
}
|
|
2211
|
-
catch (error) {
|
|
2212
|
-
this._logger.warn(`[status] 获取 OneBot 状态失败: ${String(error)}`);
|
|
2213
|
-
return null;
|
|
2214
|
-
}
|
|
2215
|
-
}
|
|
2216
|
-
async fetchOnlineClientsCount(session) {
|
|
2217
|
-
if (!session || session.platform !== 'onebot')
|
|
2218
|
-
return null;
|
|
2219
|
-
const onebot = this.getOneBotApi(session);
|
|
2220
|
-
if (!onebot?.getOnlineClients)
|
|
2221
|
-
return null;
|
|
2222
|
-
try {
|
|
2223
|
-
const data = await onebot.getOnlineClients(true);
|
|
2224
|
-
return Array.isArray(data) ? data.length : null;
|
|
2225
|
-
}
|
|
2226
|
-
catch {
|
|
2227
|
-
return null;
|
|
2228
|
-
}
|
|
2229
|
-
}
|
|
2230
|
-
formatRssKbToMb(rssKb) {
|
|
2231
|
-
if (!Number.isFinite(rssKb) || rssKb <= 0)
|
|
2232
|
-
return '-';
|
|
2233
|
-
return `${(rssKb / 1024).toFixed(1)} MB`;
|
|
2234
|
-
}
|
|
2235
|
-
async fetchProcessUsageByHints(hints) {
|
|
2236
|
-
try {
|
|
2237
|
-
const { stdout } = await execFile('ps', ['-eo', 'comm=,%cpu=,rss=,args='], { timeout: 1800, maxBuffer: 1024 * 1024 });
|
|
2238
|
-
const loweredHints = hints.map((item) => item.toLowerCase());
|
|
2239
|
-
const lines = stdout.split('\n').map((line) => line.trim()).filter(Boolean);
|
|
2240
|
-
let best = null;
|
|
2241
|
-
for (const line of lines) {
|
|
2242
|
-
const matched = line.match(/^(\S+)\s+(\S+)\s+(\S+)\s+(.+)$/);
|
|
2243
|
-
if (!matched)
|
|
2244
|
-
continue;
|
|
2245
|
-
const comm = matched[1];
|
|
2246
|
-
const cpu = Number(matched[2]);
|
|
2247
|
-
const rssKb = Number(matched[3]);
|
|
2248
|
-
const args = matched[4];
|
|
2249
|
-
const haystack = `${comm} ${args}`.toLowerCase();
|
|
2250
|
-
if (!loweredHints.some((hint) => haystack.includes(hint)))
|
|
2251
|
-
continue;
|
|
2252
|
-
if (!best || cpu > best.cpu) {
|
|
2253
|
-
best = { name: comm, cpu: Number.isFinite(cpu) ? cpu : 0, rssKb: Number.isFinite(rssKb) ? rssKb : 0 };
|
|
2254
|
-
}
|
|
2255
|
-
}
|
|
2256
|
-
if (!best)
|
|
2257
|
-
return null;
|
|
2258
|
-
return {
|
|
2259
|
-
source: 'process',
|
|
2260
|
-
name: best.name,
|
|
2261
|
-
cpuText: `${best.cpu.toFixed(1)}%`,
|
|
2262
|
-
memText: this.formatRssKbToMb(best.rssKb),
|
|
2263
|
-
};
|
|
2264
|
-
}
|
|
2265
|
-
catch {
|
|
2266
|
-
return null;
|
|
2267
|
-
}
|
|
2268
|
-
}
|
|
2269
|
-
async fetchDockerUsageByHints(hints) {
|
|
2270
|
-
try {
|
|
2271
|
-
const { stdout: namesStdout } = await execFile('docker', ['ps', '--format', '{{.Names}}'], { timeout: 1800, maxBuffer: 1024 * 1024 });
|
|
2272
|
-
const names = namesStdout.split('\n').map((line) => line.trim()).filter(Boolean);
|
|
2273
|
-
if (!names.length)
|
|
2274
|
-
return null;
|
|
2275
|
-
const loweredHints = hints.map((item) => item.toLowerCase());
|
|
2276
|
-
const target = names.find((name) => loweredHints.some((hint) => name.toLowerCase().includes(hint)));
|
|
2277
|
-
if (!target)
|
|
2278
|
-
return null;
|
|
2279
|
-
const { stdout: statsStdout } = await execFile('docker', ['stats', '--no-stream', '--format', '{{.Name}}|{{.CPUPerc}}|{{.MemUsage}}'], { timeout: 2200, maxBuffer: 1024 * 1024 });
|
|
2280
|
-
const line = statsStdout
|
|
2281
|
-
.split('\n')
|
|
2282
|
-
.map((item) => item.trim())
|
|
2283
|
-
.find((item) => item.startsWith(`${target}|`));
|
|
2284
|
-
if (!line)
|
|
2285
|
-
return null;
|
|
2286
|
-
const parts = line.split('|');
|
|
2287
|
-
if (parts.length < 3)
|
|
2288
|
-
return null;
|
|
2289
|
-
const memUsage = parts[2].split('/')[0].trim();
|
|
2290
|
-
return {
|
|
2291
|
-
source: 'docker',
|
|
2292
|
-
name: parts[0],
|
|
2293
|
-
cpuText: parts[1].trim() || '-',
|
|
2294
|
-
memText: memUsage || '-',
|
|
2295
|
-
};
|
|
2296
|
-
}
|
|
2297
|
-
catch {
|
|
2298
|
-
return null;
|
|
2299
|
-
}
|
|
2300
|
-
}
|
|
2301
|
-
async fetchLlbotClientUsage() {
|
|
2302
|
-
const hints = ['llonebot', 'llbot', 'onebot', 'napcat', 'lagrange'];
|
|
2303
|
-
const dockerUsage = await this.fetchDockerUsageByHints(hints);
|
|
2304
|
-
if (dockerUsage)
|
|
2305
|
-
return dockerUsage;
|
|
2306
|
-
return this.fetchProcessUsageByHints(hints);
|
|
2307
|
-
}
|
|
2308
|
-
async fetchQqClientUsage() {
|
|
2309
|
-
const hints = ['ntqq', 'qq', 'qqnt'];
|
|
2310
|
-
return this.fetchProcessUsageByHints(hints);
|
|
2311
|
-
}
|
|
2312
|
-
async handleMenuPairing(session) {
|
|
2313
|
-
const key = this.pairingKey(session);
|
|
2314
|
-
if (!key)
|
|
2315
|
-
return false;
|
|
2316
|
-
const expiresAt = this.menuPairings.get(key);
|
|
2317
|
-
if (!expiresAt)
|
|
2318
|
-
return false;
|
|
2319
|
-
if (Date.now() > expiresAt) {
|
|
2320
|
-
this.menuPairings.delete(key);
|
|
2321
|
-
return false;
|
|
2322
|
-
}
|
|
2323
|
-
const keyword = this.getMessageText(session);
|
|
2324
|
-
if (!keyword)
|
|
2325
|
-
return false;
|
|
2326
|
-
this.menuPairings.delete(key);
|
|
2327
|
-
const hit = this.resolveMenuCategory(keyword, session);
|
|
2328
|
-
if (!hit) {
|
|
2329
|
-
this.logCommandResult('menu-pairing', { ok: true, message: 'paired menu ignored: no match' }, session, { keyword });
|
|
2330
|
-
return false;
|
|
2331
|
-
}
|
|
2332
|
-
const output = await this.renderMenu(keyword, session);
|
|
2333
|
-
try {
|
|
2334
|
-
await session.send(output);
|
|
2335
|
-
this.logCommandResult('menu-pairing', { ok: true, message: 'paired menu rendered' }, session, { keyword });
|
|
2336
|
-
}
|
|
2337
|
-
catch (error) {
|
|
2338
|
-
this.logCommandResult('menu-pairing', { ok: false, message: `paired menu send failed: ${String(error)}` }, session, { keyword });
|
|
2339
|
-
}
|
|
2340
|
-
return true;
|
|
2341
|
-
}
|
|
2342
|
-
getPuppeteer() {
|
|
2343
|
-
return this.ctx.puppeteer;
|
|
2344
|
-
}
|
|
2345
|
-
formatBytes(bytes) {
|
|
2346
|
-
const mb = bytes / 1024 / 1024;
|
|
2347
|
-
if (mb < 1024)
|
|
2348
|
-
return `${mb.toFixed(1)} MB`;
|
|
2349
|
-
return `${(mb / 1024).toFixed(2)} GB`;
|
|
2350
|
-
}
|
|
2351
|
-
async sampleCpuUsage(intervalMs = 160) {
|
|
2352
|
-
const snapshot = () => {
|
|
2353
|
-
const cpus = node_os_1.default.cpus();
|
|
2354
|
-
let idle = 0;
|
|
2355
|
-
let total = 0;
|
|
2356
|
-
for (const cpu of cpus) {
|
|
2357
|
-
const t = cpu.times;
|
|
2358
|
-
idle += t.idle;
|
|
2359
|
-
total += t.user + t.nice + t.sys + t.irq + t.idle;
|
|
2360
|
-
}
|
|
2361
|
-
return { idle, total };
|
|
2362
|
-
};
|
|
2363
|
-
const a = snapshot();
|
|
2364
|
-
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
2365
|
-
const b = snapshot();
|
|
2366
|
-
const idle = b.idle - a.idle;
|
|
2367
|
-
const total = b.total - a.total;
|
|
2368
|
-
if (total <= 0)
|
|
2369
|
-
return 0;
|
|
2370
|
-
const used = 1 - idle / total;
|
|
2371
|
-
return Math.max(0, Math.min(100, used * 100));
|
|
2372
|
-
}
|
|
2373
|
-
async renderStatusCard(session) {
|
|
2374
|
-
const cpuPercent = await this.sampleCpuUsage();
|
|
2375
|
-
const onebotStatus = await this.fetchOneBotStatus(session);
|
|
2376
|
-
const onlineClientsCount = await this.fetchOnlineClientsCount(session);
|
|
2377
|
-
const [llbotUsage, qqUsage] = await Promise.all([
|
|
2378
|
-
this.fetchLlbotClientUsage(),
|
|
2379
|
-
this.fetchQqClientUsage(),
|
|
2380
|
-
]);
|
|
2381
|
-
const totalMem = node_os_1.default.totalmem();
|
|
2382
|
-
const freeMem = node_os_1.default.freemem();
|
|
2383
|
-
const usedMem = totalMem - freeMem;
|
|
2384
|
-
const usedPercent = totalMem > 0 ? (usedMem / totalMem) * 100 : 0;
|
|
2385
|
-
const processMem = process.memoryUsage();
|
|
2386
|
-
const uptimeSec = Math.floor(process.uptime());
|
|
2387
|
-
const h = Math.floor(uptimeSec / 3600);
|
|
2388
|
-
const m = Math.floor((uptimeSec % 3600) / 60);
|
|
2389
|
-
const s = uptimeSec % 60;
|
|
2390
|
-
const uptime = `${h}h ${m}m ${s}s`;
|
|
2391
|
-
const fallback = this.styleText(`状态:CPU ${cpuPercent.toFixed(1)}% | 内存 ${usedPercent.toFixed(1)}% | 进程RSS ${this.formatBytes(processMem.rss)}`
|
|
2392
|
-
+ (onebotStatus ? ` | OneBot ${onebotStatus.online ? '在线' : '离线'}` : '')
|
|
2393
|
-
+ (llbotUsage ? ` | LLBot ${llbotUsage.cpuText}/${llbotUsage.memText}` : ''));
|
|
2394
|
-
const puppeteer = this.getPuppeteer();
|
|
2395
|
-
if (!puppeteer)
|
|
2396
|
-
return fallback;
|
|
2397
|
-
const bar = (v) => Math.max(0, Math.min(100, v)).toFixed(1);
|
|
2398
|
-
const onlineText = onebotStatus?.online ? '在线' : '离线';
|
|
2399
|
-
const healthText = onebotStatus?.good ? '正常' : '异常';
|
|
2400
|
-
const onebotSection = onebotStatus
|
|
2401
|
-
? `
|
|
2402
|
-
<div class="item">
|
|
2403
|
-
<div class="line"><span>LLOneBot 状态</span><span class="${onebotStatus.online ? 'ok' : 'bad'}">${onlineText}</span></div>
|
|
2404
|
-
<div class="meta">连接状态:<span class="${onebotStatus.online ? 'ok' : 'bad'}">${onlineText}</span></div>
|
|
2405
|
-
<div class="meta">运行状态:<span class="${onebotStatus.good ? 'ok' : 'bad'}">${healthText}</span></div>
|
|
2406
|
-
<div class="meta">收到消息数 / 发送消息数:${onebotStatus.stat?.message_received ?? '-'} / ${onebotStatus.stat?.message_sent ?? '-'}</div>
|
|
2407
|
-
<div class="meta">在线客户端数:${onlineClientsCount ?? '-'}</div>
|
|
2408
|
-
<div class="meta">LLBot 客户端占用:${llbotUsage ? `${llbotUsage.cpuText} / ${llbotUsage.memText} (${llbotUsage.source}:${llbotUsage.name})` : '未获取到'}</div>
|
|
2409
|
-
<div class="meta">QQ 客户端占用:${qqUsage ? `${qqUsage.cpuText} / ${qqUsage.memText} (${qqUsage.name})` : '未获取到'}</div>
|
|
2410
|
-
</div>`
|
|
2411
|
-
: '';
|
|
2412
|
-
const html = `
|
|
2413
|
-
<!doctype html>
|
|
2414
|
-
<html>
|
|
2415
|
-
<head>
|
|
2416
|
-
<meta charset="utf-8" />
|
|
2417
|
-
<style>
|
|
2418
|
-
html { background: transparent; }
|
|
2419
|
-
body { margin: 0; display: inline-block; font-family: "LXGW WenKai", "Noto Sans SC", sans-serif; color: #2b1d2a; background: #f8f3f8; }
|
|
2420
|
-
.bg { position: relative; padding: 22px; background: linear-gradient(165deg, #fff4fb 0%, #ffe9f4 42%, #f8f3f8 100%); }
|
|
2421
|
-
.bg::before { content: ""; position: absolute; inset: 0; opacity: .08; pointer-events: none;
|
|
2422
|
-
background-image: url("data:image/svg+xml;utf8,%3Csvg width='120' height='120' viewBox='0 0 120 120' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23bca6d9'%3E%3Ccircle cx='24' cy='24' r='6'/%3E%3Ccircle cx='44' cy='18' r='6'/%3E%3Ccircle cx='64' cy='24' r='6'/%3E%3Ccircle cx='32' cy='48' r='12'/%3E%3C/g%3E%3C/svg%3E");
|
|
2423
|
-
background-size: 140px 140px; }
|
|
2424
|
-
.card { position: relative; width: 620px; border-radius: 18px; padding: 16px 18px 14px;
|
|
2425
|
-
background: rgba(255,255,255,.74); border: 1px solid rgba(233,217,234,.92); box-shadow: 0 12px 28px rgba(47,20,47,.12); }
|
|
2426
|
-
.bar { display: flex; align-items: center; gap: 12px; padding: 2px 2px 10px; font-size: 12px; letter-spacing: 1.5px; text-transform: uppercase; }
|
|
2427
|
-
.dots { width: 10px; height: 10px; border-radius: 50%; background: #f0b1c9; box-shadow: 16px 0 0 #f6d48f, 32px 0 0 #b9efdf; }
|
|
2428
|
-
.bar-title { margin-left: 28px; font-weight: 700; opacity: .88; }
|
|
2429
|
-
.title { font-size: 28px; font-weight: 800; margin: 0 0 4px; }
|
|
2430
|
-
.sub { font-size: 15px; opacity: .76; margin: 0 0 12px; }
|
|
2431
|
-
.item { margin-bottom: 10px; background: rgba(255,255,255,.78); border: 1px solid rgba(233,217,234,.9); border-radius: 14px; padding: 10px 12px; }
|
|
2432
|
-
.line { display: flex; justify-content: space-between; font-size: 16px; font-weight: 700; margin-bottom: 6px; }
|
|
2433
|
-
.meter { height: 10px; border-radius: 999px; background: rgba(221, 195, 221, .45); overflow: hidden; }
|
|
2434
|
-
.fill { height: 100%; background: linear-gradient(90deg, #f0b1c9, #b9efdf); }
|
|
2435
|
-
.meta { font-size: 14px; opacity: .78; line-height: 1.45; margin-top: 4px; }
|
|
2436
|
-
.ok { color: #1f8f49; font-weight: 700; }
|
|
2437
|
-
.bad { color: #cf3f48; font-weight: 700; }
|
|
2438
|
-
</style>
|
|
2439
|
-
</head>
|
|
2440
|
-
<body>
|
|
2441
|
-
<div class="bg">
|
|
2442
|
-
<div class="card">
|
|
2443
|
-
<div class="bar"><span class="dots"></span><span class="bar-title">MEOW STATUS</span></div>
|
|
2444
|
-
<div class="title">系统状态</div>
|
|
2445
|
-
<div class="sub">喵~ 实时资源占用</div>
|
|
2446
|
-
|
|
2447
|
-
<div class="item">
|
|
2448
|
-
<div class="line"><span>CPU 占用</span><span>${cpuPercent.toFixed(1)}%</span></div>
|
|
2449
|
-
<div class="meter"><div class="fill" style="width:${bar(cpuPercent)}%"></div></div>
|
|
2450
|
-
</div>
|
|
2451
|
-
|
|
2452
|
-
<div class="item">
|
|
2453
|
-
<div class="line"><span>内存占用</span><span>${usedPercent.toFixed(1)}%</span></div>
|
|
2454
|
-
<div class="meter"><div class="fill" style="width:${bar(usedPercent)}%"></div></div>
|
|
2455
|
-
<div class="meta">系统内存:${this.formatBytes(usedMem)} / ${this.formatBytes(totalMem)}</div>
|
|
2456
|
-
<div class="meta">进程 RSS:${this.formatBytes(processMem.rss)},Heap:${this.formatBytes(processMem.heapUsed)} / ${this.formatBytes(processMem.heapTotal)}</div>
|
|
2457
|
-
<div class="meta">进程运行时长:${uptime}</div>
|
|
2458
|
-
</div>
|
|
2459
|
-
${onebotSection}
|
|
2460
|
-
</div>
|
|
2461
|
-
</div>
|
|
2462
|
-
</body>
|
|
2463
|
-
</html>`;
|
|
2464
|
-
try {
|
|
2465
|
-
return await puppeteer.render(html);
|
|
2466
|
-
}
|
|
2467
|
-
catch (error) {
|
|
2468
|
-
this._logger.warn(`[status] 图片渲染失败: ${String(error)}`);
|
|
2469
|
-
return fallback;
|
|
2470
|
-
}
|
|
2471
|
-
}
|
|
2472
|
-
renderCategoryHtml(title, subTitle, entries, options, narrow = true) {
|
|
2473
|
-
const showUsageLabel = options?.showUsageLabel ?? false;
|
|
2474
|
-
const lines = entries.map((item) => {
|
|
2475
|
-
const desc = item.desc
|
|
2476
|
-
? `<span class="desc">${showUsageLabel ? '用途:' : ''}${this.escapeHtml(item.desc)}</span>`
|
|
2477
|
-
: '';
|
|
2478
|
-
return `<li><span class="name">${this.escapeHtml(item.name)}</span>${desc}</li>`;
|
|
2479
|
-
}).join('');
|
|
2480
|
-
const width = narrow ? 620 : 680;
|
|
2481
|
-
return `
|
|
2482
|
-
<!doctype html>
|
|
2483
|
-
<html>
|
|
2484
|
-
<head>
|
|
2485
|
-
<meta charset="utf-8" />
|
|
2486
|
-
<style>
|
|
2487
|
-
html { background: transparent; }
|
|
2488
|
-
body { margin: 0; display: inline-block; font-family: "LXGW WenKai", "Noto Sans SC", sans-serif; color: #2b1d2a; background: #f8f3f8; }
|
|
2489
|
-
.bg { position: relative; padding: 22px; background: linear-gradient(165deg, #fff4fb 0%, #ffe9f4 42%, #f8f3f8 100%); }
|
|
2490
|
-
.bg::before { content: ""; position: absolute; inset: 0; opacity: 0.08; pointer-events: none;
|
|
2491
|
-
background-image: url("data:image/svg+xml;utf8,%3Csvg width='120' height='120' viewBox='0 0 120 120' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23bca6d9'%3E%3Ccircle cx='24' cy='24' r='6'/%3E%3Ccircle cx='44' cy='18' r='6'/%3E%3Ccircle cx='64' cy='24' r='6'/%3E%3Ccircle cx='32' cy='48' r='12'/%3E%3C/g%3E%3C/svg%3E");
|
|
2492
|
-
background-size: 140px 140px; }
|
|
2493
|
-
.card { position: relative; width: ${width}px; border-radius: 18px; padding: 16px 18px 14px;
|
|
2494
|
-
background: rgba(255, 255, 255, 0.74); border: 1px solid rgba(233, 217, 234, 0.92); box-shadow: 0 12px 28px rgba(47, 20, 47, 0.12); }
|
|
2495
|
-
.bar { display: flex; align-items: center; gap: 12px; padding: 2px 2px 10px; font-size: 12px; letter-spacing: 1.5px; text-transform: uppercase; }
|
|
2496
|
-
.dots { width: 10px; height: 10px; border-radius: 50%; background: #f0b1c9; box-shadow: 16px 0 0 #f6d48f, 32px 0 0 #b9efdf; }
|
|
2497
|
-
.bar-title { margin-left: 28px; font-weight: 700; opacity: .88; }
|
|
2498
|
-
.title { font-size: 28px; font-weight: 800; margin: 0 0 4px; }
|
|
2499
|
-
.sub { font-size: 15px; opacity: .76; margin: 0 0 12px; }
|
|
2500
|
-
ul { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: 1fr; gap: 8px; }
|
|
2501
|
-
li { border-radius: 14px; padding: 10px 12px; background: rgba(255,255,255,.78); border: 1px solid rgba(233, 217, 234, 0.9); }
|
|
2502
|
-
.name { font-size: 18px; font-weight: 700; display: block; }
|
|
2503
|
-
.desc { font-size: 13px; opacity: .75; display: block; margin-top: 2px; line-height: 1.35; }
|
|
2504
|
-
.foot { margin-top: 10px; font-size: 13px; opacity: .72; }
|
|
2505
|
-
</style>
|
|
2506
|
-
</head>
|
|
2507
|
-
<body>
|
|
2508
|
-
<div class="bg">
|
|
2509
|
-
<div class="card">
|
|
2510
|
-
<div class="bar"><span class="dots"></span><span class="bar-title">MEOW MENU</span></div>
|
|
2511
|
-
<div class="title">${this.escapeHtml(title)}</div>
|
|
2512
|
-
<div class="sub">${this.escapeHtml(subTitle)}</div>
|
|
2513
|
-
<ul>${lines}</ul>
|
|
2514
|
-
<div class="foot">喵~ 发送 help <父指令菜单> 查看子指令</div>
|
|
2515
|
-
</div>
|
|
2516
|
-
</div>
|
|
2517
|
-
</body>
|
|
2518
|
-
</html>`;
|
|
2519
|
-
}
|
|
2520
|
-
async renderMenu(keyword, session) {
|
|
2521
|
-
const categories = this.collectCategories(session);
|
|
2522
|
-
if (!categories.length)
|
|
2523
|
-
return this.styleText('没有匹配到可用指令。');
|
|
2524
|
-
const puppeteer = this.getPuppeteer();
|
|
2525
|
-
if (!puppeteer) {
|
|
2526
|
-
return this.styleText('未启用 puppeteer,无法生成图片菜单。');
|
|
2527
|
-
}
|
|
2528
|
-
const hit = this.resolveMenuCategory(keyword, session);
|
|
2529
|
-
const html = hit
|
|
2530
|
-
? this.renderCategoryHtml(`Meow 菜单 · ${hit.title}`, `分类 ${hit.key},共 ${hit.children.length} 条子指令`, hit.children, { showUsageLabel: true })
|
|
2531
|
-
: this.renderCategoryHtml('Meow 菜单', `共 ${categories.length} 个大分类`, categories.map((cat) => ({
|
|
2532
|
-
name: `${cat.title}菜单`,
|
|
2533
|
-
desc: cat.desc
|
|
2534
|
-
? `${cat.children.length} 条子指令 · ${cat.desc}`
|
|
2535
|
-
: `${cat.children.length} 条子指令`,
|
|
2536
|
-
})), { showUsageLabel: false }, false);
|
|
2537
|
-
try {
|
|
2538
|
-
return await puppeteer.render(html);
|
|
2539
|
-
}
|
|
2540
|
-
catch (error) {
|
|
2541
|
-
this._logger.warn(`[menu] 图片渲染失败: ${String(error)}`);
|
|
2542
|
-
return this.styleText('图片菜单生成失败,请检查 puppeteer。');
|
|
2543
|
-
}
|
|
2544
|
-
}
|
|
2545
|
-
logAuth(stage, result, session) {
|
|
2546
|
-
if (!this.config.logAuthCheck)
|
|
2547
|
-
return;
|
|
2548
|
-
const level = result.ok ? 'info' : 'warn';
|
|
2549
|
-
this._logger[level](`[auth:${stage}] ${result.message} | ${this.sessionTag(session)}`);
|
|
2550
|
-
}
|
|
2551
|
-
logCommandResult(command, result, session, extra) {
|
|
2552
|
-
if (!this.config.logCommandResult)
|
|
2553
|
-
return;
|
|
2554
|
-
const level = result.ok ? 'info' : 'warn';
|
|
2555
|
-
const plan = result.plan ? JSON.stringify(result.plan) : '-';
|
|
2556
|
-
const payload = extra ? ` extra=${JSON.stringify(extra)}` : '';
|
|
2557
|
-
this._logger[level](`[cmd:${command}] ok=${result.ok} message="${result.message}" plan=${plan}${payload} | ${this.sessionTag(session)}`);
|
|
2558
|
-
}
|
|
2559
|
-
async authorizeCommand(command, session) {
|
|
2560
|
-
const result = await this.authorize(session);
|
|
2561
|
-
this.logAuth(command, result, session);
|
|
2562
|
-
return result;
|
|
2563
|
-
}
|
|
2564
|
-
async authorize(session) {
|
|
2565
|
-
if (!session) {
|
|
2566
|
-
return { ok: false, message: '缺少会话上下文。', userMessage: '权限不足或上下文不符合要求。' };
|
|
2567
|
-
}
|
|
2568
|
-
const platform = session.platform;
|
|
2569
|
-
if (!this.isPlatformAllowed(platform)) {
|
|
2570
|
-
return {
|
|
2571
|
-
ok: false,
|
|
2572
|
-
message: `当前平台 ${platform ?? 'unknown'} 未启用群管理。`,
|
|
2573
|
-
userMessage: '当前平台未启用群管理。',
|
|
2574
|
-
};
|
|
2575
|
-
}
|
|
2576
|
-
const userId = session.userId;
|
|
2577
|
-
if (!userId) {
|
|
2578
|
-
return { ok: false, message: '无法识别当前账号。', userMessage: '权限不足或上下文不符合要求。' };
|
|
2579
|
-
}
|
|
2580
|
-
if (this.config.allowedUserIds.includes(userId)) {
|
|
2581
|
-
return { ok: true, message: '账号白名单通过。' };
|
|
2582
|
-
}
|
|
2583
|
-
if (!session.guildId) {
|
|
2584
|
-
return {
|
|
2585
|
-
ok: false,
|
|
2586
|
-
message: '当前账号不在白名单,且仅支持在群聊中按管理员权限使用。',
|
|
2587
|
-
userMessage: '仅支持群聊中按管理员权限使用。',
|
|
2588
|
-
};
|
|
2589
|
-
}
|
|
2590
|
-
const role = await this.resolveMemberRole(session);
|
|
2591
|
-
if (!role) {
|
|
2592
|
-
return { ok: false, message: '无法获取群成员角色,权限校验失败。', userMessage: '权限校验失败。' };
|
|
2593
|
-
}
|
|
2594
|
-
if (role === 'owner' && this.config.allowGroupOwner) {
|
|
2595
|
-
return { ok: true, message: '群主权限通过。' };
|
|
2596
|
-
}
|
|
2597
|
-
if (role === 'admin' && this.config.allowGroupAdmin) {
|
|
2598
|
-
return { ok: true, message: '群管理员权限通过。' };
|
|
2599
|
-
}
|
|
2600
|
-
return {
|
|
2601
|
-
ok: false,
|
|
2602
|
-
message: '权限不足:仅账号白名单、群主或群管理员可执行。',
|
|
2603
|
-
userMessage: '权限不足:仅白名单、群主或群管理员可执行。',
|
|
2604
|
-
};
|
|
2605
|
-
}
|
|
2606
|
-
async canUseAdminCommand(session) {
|
|
2607
|
-
if (!this.config.requireBotOwnerForAdmin) {
|
|
2608
|
-
const allowed = { ok: true, message: '已关闭 bot 群主限制,admin 子命令可用。' };
|
|
2609
|
-
this.logAuth('admin-visibility', allowed, session);
|
|
2610
|
-
return allowed;
|
|
2611
|
-
}
|
|
2612
|
-
if (!session) {
|
|
2613
|
-
const denied = { ok: false, message: '缺少会话上下文,admin 子命令不可用。', userMessage: '当前场景不可用该子命令。' };
|
|
2614
|
-
this.logAuth('admin-visibility', denied, session);
|
|
2615
|
-
return denied;
|
|
2616
|
-
}
|
|
2617
|
-
if (!session.guildId) {
|
|
2618
|
-
const denied = { ok: false, message: '当前不是群聊上下文,admin 子命令不可用。', userMessage: '请在群聊中使用该子命令。' };
|
|
2619
|
-
this.logAuth('admin-visibility', denied, session);
|
|
2620
|
-
return denied;
|
|
2621
|
-
}
|
|
2622
|
-
const botId = Number(session.bot?.selfId);
|
|
2623
|
-
if (!Number.isFinite(botId)) {
|
|
2624
|
-
const denied = { ok: false, message: `bot selfId 无法解析为数字: ${session.bot?.selfId ?? 'unknown'}`, userMessage: '当前场景不可用该子命令。' };
|
|
2625
|
-
this.logAuth('admin-visibility', denied, session);
|
|
2626
|
-
return denied;
|
|
2627
|
-
}
|
|
2628
|
-
const botRole = await this.getTargetRole(session, botId);
|
|
2629
|
-
if (botRole === 'owner') {
|
|
2630
|
-
const allowed = { ok: true, message: `bot(${botId}) 在当前群是 owner,admin 子命令可用。` };
|
|
2631
|
-
this.logAuth('admin-visibility', allowed, session);
|
|
2632
|
-
return allowed;
|
|
2633
|
-
}
|
|
2634
|
-
const denied = {
|
|
2635
|
-
ok: false,
|
|
2636
|
-
message: `bot(${botId}) 在当前群角色=${botRole ?? 'unknown'},未达到 owner,admin 子命令不可用。`,
|
|
2637
|
-
userMessage: '当前群中 bot 不是群主,admin 子命令不可用。',
|
|
2638
|
-
};
|
|
2639
|
-
this.logAuth('admin-visibility', denied, session);
|
|
2640
|
-
return denied;
|
|
2641
|
-
}
|
|
2642
2325
|
async isBotOwnerInGroup(session) {
|
|
2643
|
-
if (!session?.
|
|
2326
|
+
if (!session?.guildId || session.platform !== 'onebot')
|
|
2644
2327
|
return false;
|
|
2645
2328
|
const botId = Number(session.bot.selfId);
|
|
2646
2329
|
if (!Number.isFinite(botId))
|
|
@@ -2730,7 +2413,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2730
2413
|
parseDurationToken(token) {
|
|
2731
2414
|
if (typeof token !== 'string')
|
|
2732
2415
|
return null;
|
|
2733
|
-
|
|
2416
|
+
// 只接受英文/数字单位([记忆] 新规:指令除自定义外不含汉字)
|
|
2417
|
+
const matched = String(token).trim().match(/^(\d+(?:\.\d+)?)\s*(min|mins|minute|minutes|m|hour|hours|h|day|days|d|week|weeks|w)?$/i);
|
|
2734
2418
|
if (!matched)
|
|
2735
2419
|
return null;
|
|
2736
2420
|
const value = parseFloat(matched[1]);
|
|
@@ -2738,13 +2422,13 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2738
2422
|
return null;
|
|
2739
2423
|
const unit = (matched[2] || '').toLowerCase();
|
|
2740
2424
|
let factor = 1;
|
|
2741
|
-
if (unit === '
|
|
2425
|
+
if (unit === 'hour' || unit === 'hours' || unit === 'h') {
|
|
2742
2426
|
factor = 60;
|
|
2743
2427
|
}
|
|
2744
|
-
else if (unit === '
|
|
2428
|
+
else if (unit === 'day' || unit === 'days' || unit === 'd') {
|
|
2745
2429
|
factor = 24 * 60;
|
|
2746
2430
|
}
|
|
2747
|
-
else if (unit === '
|
|
2431
|
+
else if (unit === 'week' || unit === 'weeks' || unit === 'w') {
|
|
2748
2432
|
factor = 7 * 24 * 60;
|
|
2749
2433
|
}
|
|
2750
2434
|
return { raw: String(token).trim(), value, hasUnit: !!unit, minutes: Math.ceil(value * factor) };
|
|
@@ -3028,6 +2712,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3028
2712
|
if (!rule) {
|
|
3029
2713
|
return {
|
|
3030
2714
|
bannedWords: this.config.bannedWords,
|
|
2715
|
+
whitelistKeywords: [],
|
|
2716
|
+
whitelistOnlyOwners: false,
|
|
3031
2717
|
blockCardMessage: this.config.blockCardMessage,
|
|
3032
2718
|
blockForwardMessage: this.config.blockForwardMessage,
|
|
3033
2719
|
autoDeleteViolation: this.config.autoDeleteViolation,
|
|
@@ -3042,6 +2728,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3042
2728
|
}
|
|
3043
2729
|
return {
|
|
3044
2730
|
bannedWords: rule.bannedWords,
|
|
2731
|
+
whitelistKeywords: rule.whitelistKeywords || [],
|
|
2732
|
+
whitelistOnlyOwners: rule.whitelistOnlyOwners === true,
|
|
3045
2733
|
blockCardMessage: rule.blockCardMessage,
|
|
3046
2734
|
blockForwardMessage: rule.blockForwardMessage,
|
|
3047
2735
|
autoDeleteViolation: rule.autoDeleteViolation,
|
|
@@ -3213,7 +2901,34 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3213
2901
|
evaluations.sort((a, b) => b.gained - a.gained);
|
|
3214
2902
|
return { total: Math.round(total * 100) / 100, evaluations };
|
|
3215
2903
|
}
|
|
3216
|
-
|
|
2904
|
+
/**
|
|
2905
|
+
* 违禁词白名单豁免检查。
|
|
2906
|
+
*
|
|
2907
|
+
* 用于「校学生会招新」这类特殊场景:招新文案本身会包含“加群”“群号”等
|
|
2908
|
+
* 违禁词,但只要命中白名单关键词(如“宣传部”“纪检部”),就整条跳过违禁词评分。
|
|
2909
|
+
*
|
|
2910
|
+
* 返回 { keyword, reason } 表示命中并豁免;返回 null 表示未命中。
|
|
2911
|
+
*/
|
|
2912
|
+
async checkWhitelistBypass(session, policy, text) {
|
|
2913
|
+
const keywords = (policy?.whitelistKeywords ?? [])
|
|
2914
|
+
.map((w) => String(w ?? '').trim())
|
|
2915
|
+
.filter(Boolean);
|
|
2916
|
+
if (!keywords.length || !text)
|
|
2917
|
+
return null;
|
|
2918
|
+
const hit = keywords.find((kw) => text.includes(kw));
|
|
2919
|
+
if (!hit)
|
|
2920
|
+
return null;
|
|
2921
|
+
// 可选的权限收紧:仅群主/管理员可用白名单
|
|
2922
|
+
if (policy.whitelistOnlyOwners) {
|
|
2923
|
+
const role = await this.resolveMemberRole(session);
|
|
2924
|
+
if (role !== 'owner' && role !== 'admin') {
|
|
2925
|
+
this._logger.info(`[whitelist] 命中「${hit}」但发送者非群主/管理员(role=${role}),不豁免 | ${this.sessionTag(session)}`);
|
|
2926
|
+
return null;
|
|
2927
|
+
}
|
|
2928
|
+
}
|
|
2929
|
+
return { keyword: hit, reason: 'whitelist' };
|
|
2930
|
+
}
|
|
2931
|
+
async detectViolation(session, policy, type = 'message') {
|
|
3217
2932
|
// 纯图片/表情/贴纸(无实际文字内容)的消息不作为违规处理,避免表情包被当成违禁词
|
|
3218
2933
|
if (type === 'message' && this.hasImageOrFace(session) && !this.hasTextContent(session)) {
|
|
3219
2934
|
return null;
|
|
@@ -3227,6 +2942,13 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3227
2942
|
const text = this.extractTextForFilter(session);
|
|
3228
2943
|
if (!text)
|
|
3229
2944
|
return null;
|
|
2945
|
+
// 白名单豁免:命中白名单关键词则跳过违禁词评分(招新等允许的宣传场景)。
|
|
2946
|
+
// 注意:卡片/合并转发的拦截在上面已判定,白名单只豁免「违禁词」,不放过卡片类消息。
|
|
2947
|
+
const bypass = await this.checkWhitelistBypass(session, policy, text);
|
|
2948
|
+
if (bypass) {
|
|
2949
|
+
this._logger.info(`[whitelist] 命中「${bypass.keyword}」,跳过违禁词管控 | ${this.sessionTag(session)}`);
|
|
2950
|
+
return null;
|
|
2951
|
+
}
|
|
3230
2952
|
const assessment = this.evaluateBannedWords(text, policy);
|
|
3231
2953
|
const threshold = Math.max(1, Math.min(100, Number(this.config.bannedWordScoreThreshold ?? 70)));
|
|
3232
2954
|
if (assessment.total >= threshold) {
|
|
@@ -3298,6 +3020,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3298
3020
|
try {
|
|
3299
3021
|
await onebot.setGroupKick(groupId, userId, false);
|
|
3300
3022
|
this.clearViolationRecord(session);
|
|
3023
|
+
// 触发踢出 → 加入本群黑名单
|
|
3024
|
+
await this.recordKickToBlacklist(session, String(userId));
|
|
3301
3025
|
return { ok: true, action: 'auto-kick', count, message: `累计违规 ${count} 次,已自动移出群聊。` };
|
|
3302
3026
|
}
|
|
3303
3027
|
catch (error) {
|
|
@@ -3318,12 +3042,532 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3318
3042
|
}
|
|
3319
3043
|
return { ok: true, action: 'none', count, message: `累计违规 ${count} 次(自动禁言线 ${muteThreshold} 次 / 自动踢人线 ${kickThreshold} 次)。` };
|
|
3320
3044
|
}
|
|
3045
|
+
/**
|
|
3046
|
+
* 自定义命令处理器:整条消息与触发词完全一致(忽略首尾空白)即回复预设内容。
|
|
3047
|
+
* 触发词约定用方括号包裹(如 [签到])。命中后返回 true,调用方据此跳过后续
|
|
3048
|
+
* 违禁词管控与 AI 回复(自定义命令完全不走 AI)。
|
|
3049
|
+
*/
|
|
3050
|
+
async handleCustomCommand(session) {
|
|
3051
|
+
const list = Array.isArray(this.config.customCommands) ? this.config.customCommands : [];
|
|
3052
|
+
if (!list.length)
|
|
3053
|
+
return false;
|
|
3054
|
+
const text = this.getMessageText(session).trim();
|
|
3055
|
+
if (!text)
|
|
3056
|
+
return false;
|
|
3057
|
+
|
|
3058
|
+
const guildId = this.normalizeGuildId(session.guildId);
|
|
3059
|
+
const cmd = list.find((c) => {
|
|
3060
|
+
if (!c || c.enabled === false)
|
|
3061
|
+
return false;
|
|
3062
|
+
const trigger = String(c.trigger ?? '').trim();
|
|
3063
|
+
if (!trigger || trigger !== text)
|
|
3064
|
+
return false;
|
|
3065
|
+
const groups = (c.groups ?? []).map((g) => this.normalizeGuildId(g)).filter(Boolean);
|
|
3066
|
+
return !groups.length || groups.includes(guildId);
|
|
3067
|
+
});
|
|
3068
|
+
if (!cmd)
|
|
3069
|
+
return false;
|
|
3070
|
+
|
|
3071
|
+
// 冷却
|
|
3072
|
+
const cd = Number(cmd.cooldownSeconds || 0);
|
|
3073
|
+
if (cd > 0) {
|
|
3074
|
+
const key = `${guildId}:${cmd.trigger}`;
|
|
3075
|
+
if (!this._customCmdAt)
|
|
3076
|
+
this._customCmdAt = new Map();
|
|
3077
|
+
const last = this._customCmdAt.get(key) ?? 0;
|
|
3078
|
+
const left = Math.ceil((cd * 1000 - (Date.now() - last)) / 1000);
|
|
3079
|
+
if (left > 0) {
|
|
3080
|
+
if (cmd.logHit !== false)
|
|
3081
|
+
this._logger.info(`[custom-cmd] 「${cmd.trigger}」冷却中(剩余 ${left}s) | ${this.sessionTag(session)}`);
|
|
3082
|
+
return true; // 命中但冷却中,同样不交给 AI
|
|
3083
|
+
}
|
|
3084
|
+
this._customCmdAt.set(key, Date.now());
|
|
3085
|
+
}
|
|
3086
|
+
|
|
3087
|
+
const replies = (cmd.replies ?? []).map((r) => String(r ?? '')).filter(Boolean);
|
|
3088
|
+
if (!replies.length) {
|
|
3089
|
+
this._logger.warn(`[custom-cmd] 「${cmd.trigger}」未配置回复内容 | ${this.sessionTag(session)}`);
|
|
3090
|
+
return true;
|
|
3091
|
+
}
|
|
3092
|
+
|
|
3093
|
+
// 多回复:随机 或 轮换
|
|
3094
|
+
let raw;
|
|
3095
|
+
if (replies.length === 1) {
|
|
3096
|
+
raw = replies[0];
|
|
3097
|
+
}
|
|
3098
|
+
else if (cmd.randomReply === true) {
|
|
3099
|
+
raw = replies[Math.floor(Math.random() * replies.length)];
|
|
3100
|
+
}
|
|
3101
|
+
else {
|
|
3102
|
+
const key = `${guildId}:${cmd.trigger}`;
|
|
3103
|
+
if (!this._customCmdIdx)
|
|
3104
|
+
this._customCmdIdx = new Map();
|
|
3105
|
+
const i = (this._customCmdIdx.get(key) ?? 0) % replies.length;
|
|
3106
|
+
this._customCmdIdx.set(key, i + 1);
|
|
3107
|
+
raw = replies[i];
|
|
3108
|
+
}
|
|
3109
|
+
|
|
3110
|
+
try {
|
|
3111
|
+
const parts = [];
|
|
3112
|
+
if (cmd.quote && session.messageId)
|
|
3113
|
+
parts.push(koishi_1.h.quote(session.messageId));
|
|
3114
|
+
// 变量占位符:{user} 昵称 / {at} @发送者 / {group} 群号
|
|
3115
|
+
const name = this.getDisplayName(session);
|
|
3116
|
+
let seg = raw;
|
|
3117
|
+
let guard = 0;
|
|
3118
|
+
while (guard++ < 20) {
|
|
3119
|
+
const atIdx = seg.indexOf('{at}');
|
|
3120
|
+
const userIdx = seg.indexOf('{user}');
|
|
3121
|
+
const groupIdx = seg.indexOf('{group}');
|
|
3122
|
+
const cands = [
|
|
3123
|
+
atIdx >= 0 ? { i: atIdx, k: 'at' } : null,
|
|
3124
|
+
userIdx >= 0 ? { i: userIdx, k: 'user' } : null,
|
|
3125
|
+
groupIdx >= 0 ? { i: groupIdx, k: 'group' } : null,
|
|
3126
|
+
].filter(Boolean).sort((a, b) => a.i - b.i);
|
|
3127
|
+
if (!cands.length)
|
|
3128
|
+
break;
|
|
3129
|
+
const first = cands[0];
|
|
3130
|
+
if (first.k === 'at') {
|
|
3131
|
+
if (seg.slice(0, first.i))
|
|
3132
|
+
parts.push(koishi_1.h.text(seg.slice(0, first.i)));
|
|
3133
|
+
parts.push(koishi_1.h.at(session.userId));
|
|
3134
|
+
seg = seg.slice(first.i + 4);
|
|
3135
|
+
}
|
|
3136
|
+
else if (first.k === 'user') {
|
|
3137
|
+
if (seg.slice(0, first.i))
|
|
3138
|
+
parts.push(koishi_1.h.text(seg.slice(0, first.i)));
|
|
3139
|
+
parts.push(koishi_1.h.text(name));
|
|
3140
|
+
seg = seg.slice(first.i + 6);
|
|
3141
|
+
}
|
|
3142
|
+
else {
|
|
3143
|
+
if (seg.slice(0, first.i))
|
|
3144
|
+
parts.push(koishi_1.h.text(seg.slice(0, first.i)));
|
|
3145
|
+
parts.push(koishi_1.h.text(String(session.guildId ?? '')));
|
|
3146
|
+
seg = seg.slice(first.i + 7);
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
3149
|
+
if (seg)
|
|
3150
|
+
parts.push(koishi_1.h.text(seg));
|
|
3151
|
+
if (!parts.length)
|
|
3152
|
+
parts.push(koishi_1.h.text(raw));
|
|
3153
|
+
|
|
3154
|
+
await session.send(parts);
|
|
3155
|
+
if (cmd.logHit !== false)
|
|
3156
|
+
this._logger.info(`[custom-cmd] 命中「${cmd.trigger}」已回复 | ${this.sessionTag(session)}`);
|
|
3157
|
+
}
|
|
3158
|
+
catch (error) {
|
|
3159
|
+
this._logger.warn(`[custom-cmd] 「${cmd.trigger}」回复失败: ${String(error)} | ${this.sessionTag(session)}`);
|
|
3160
|
+
}
|
|
3161
|
+
return true;
|
|
3162
|
+
}
|
|
3163
|
+
/**
|
|
3164
|
+
* 读取指令前缀配置(带默认值)。
|
|
3165
|
+
*/
|
|
3166
|
+
cmdPrefix(key, def) {
|
|
3167
|
+
const v = this.config ? this.config[key] : undefined;
|
|
3168
|
+
return (typeof v === 'string' && v.trim()) ? v.trim() : def;
|
|
3169
|
+
}
|
|
3170
|
+
/**
|
|
3171
|
+
* 统一指令路由器:所有指令均为「方括号直连」语法,如 [mute] 12345 10 广告。
|
|
3172
|
+
* 命中并处理返回 true(不再走后续管控与 AI)。
|
|
3173
|
+
*/
|
|
3174
|
+
async routeBracketCommand(session) {
|
|
3175
|
+
const raw = (session.content || '').replace(/<at\b[^>]*\/?>/gi, ' ').trim();
|
|
3176
|
+
if (!raw.startsWith('['))
|
|
3177
|
+
return false;
|
|
3178
|
+
const m = raw.match(/^\[([^\]\s]+)\]\s*([\s\S]*)$/);
|
|
3179
|
+
if (!m)
|
|
3180
|
+
return false;
|
|
3181
|
+
const name = `[${m[1]}]`;
|
|
3182
|
+
const rest = (m[2] || '').trim();
|
|
3183
|
+
// @ 到的目标(可代替 QQ 号)
|
|
3184
|
+
const mentions = this.extractMentionedTargets(session);
|
|
3185
|
+
|
|
3186
|
+
// 菜单:单独发送 [bot]
|
|
3187
|
+
if (name === this.cmdPrefix('command', '[bot]')) {
|
|
3188
|
+
if (!rest) {
|
|
3189
|
+
await this.sendCommandMenu(session);
|
|
3190
|
+
return true;
|
|
3191
|
+
}
|
|
3192
|
+
return false;
|
|
3193
|
+
}
|
|
3194
|
+
if (name === this.cmdPrefix('cmdMute', '[mute]'))
|
|
3195
|
+
return this.execMute(session, rest, mentions);
|
|
3196
|
+
if (name === this.cmdPrefix('cmdUnmute', '[unmute]'))
|
|
3197
|
+
return this.execUnmute(session, rest, mentions);
|
|
3198
|
+
if (name === this.cmdPrefix('cmdKick', '[kick]'))
|
|
3199
|
+
return this.execKick(session, rest, mentions);
|
|
3200
|
+
// 记忆:统一使用 [memory](旧 [记忆] 写法已废弃)
|
|
3201
|
+
if (name === this.cmdPrefix('cmdMemory', '[memory]'))
|
|
3202
|
+
return this.execMemory(session, rest);
|
|
3203
|
+
if (name === this.cmdPrefix('cmdBan', '[ban]'))
|
|
3204
|
+
return this.execBanAdd(session, rest, mentions);
|
|
3205
|
+
if (name === this.cmdPrefix('cmdUnban', '[unban]'))
|
|
3206
|
+
return this.execUnban(session, rest, mentions);
|
|
3207
|
+
if (name === this.cmdPrefix('cmdBanList', '[banlist]')) {
|
|
3208
|
+
await this.execBanList(session);
|
|
3209
|
+
return true;
|
|
3210
|
+
}
|
|
3211
|
+
if (name === this.cmdPrefix('cmdCustom', '[custom]')) {
|
|
3212
|
+
await this.sendCustomCommandList(session);
|
|
3213
|
+
return true;
|
|
3214
|
+
}
|
|
3215
|
+
return false;
|
|
3216
|
+
}
|
|
3217
|
+
/**
|
|
3218
|
+
* 指令菜单:仅英文与数字([记忆] 新规),记忆查询紧跟在记忆保存之后。
|
|
3219
|
+
* 冒号后留一个空行,避免标题与条目挤在一起。
|
|
3220
|
+
*/
|
|
3221
|
+
async sendCommandMenu(session) {
|
|
3222
|
+
const P = (k, d) => this.cmdPrefix(k, d);
|
|
3223
|
+
const lines = [
|
|
3224
|
+
'mute ' + P('cmdMute', '[mute]') + ' qq time reason',
|
|
3225
|
+
'unmute ' + P('cmdUnmute', '[unmute]') + ' qq reason',
|
|
3226
|
+
'memory ' + P('cmdMemory', '[memory]') + ' content',
|
|
3227
|
+
'memory search ' + P('cmdMemory', '[memory]') + ' search keyword',
|
|
3228
|
+
'ban ' + P('cmdBan', '[ban]') + ' qq reason',
|
|
3229
|
+
'unban ' + P('cmdUnban', '[unban]') + ' qq reason',
|
|
3230
|
+
'banlist ' + P('cmdBanList', '[banlist]'),
|
|
3231
|
+
'custom ' + P('cmdCustom', '[custom]'),
|
|
3232
|
+
'kick ' + P('cmdKick', '[kick]') + ' qq reason',
|
|
3233
|
+
];
|
|
3234
|
+
await session.send(this.styleText(
|
|
3235
|
+
'available commands:\n\n' + lines.join('\n')
|
|
3236
|
+
));
|
|
3237
|
+
}
|
|
3238
|
+
/** 自定义指令集:列出当前生效的自定义命令;没有配置时明确提示暂无指令 */
|
|
3239
|
+
async sendCustomCommandList(session) {
|
|
3240
|
+
const list = (Array.isArray(this.config.customCommands) ? this.config.customCommands : [])
|
|
3241
|
+
.filter((c) => c && c.enabled !== false && String(c.trigger || '').trim());
|
|
3242
|
+
if (!list.length) {
|
|
3243
|
+
await session.send(this.styleText('目前还没有指令。'));
|
|
3244
|
+
return;
|
|
3245
|
+
}
|
|
3246
|
+
const lines = list.map((c) => `${String(c.trigger).trim()} → ${(c.replies || []).length} 条回复`);
|
|
3247
|
+
await session.send(this.styleText(`自定义指令集(共 ${list.length} 条):\n${lines.join('\n')}`));
|
|
3248
|
+
}
|
|
3249
|
+
/** 权限不足提示 */
|
|
3250
|
+
async denyAdmin(session) {
|
|
3251
|
+
await session.send(this.styleText('你没有权限执行该操作。'));
|
|
3252
|
+
return true;
|
|
3253
|
+
}
|
|
3254
|
+
/** [mute] qq号|@某人 时长 [原因] */
|
|
3255
|
+
async execMute(session, rest, mentions = []) {
|
|
3256
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
3257
|
+
// 目标:优先取显式 qq号(纯数字),否则用 @ 到的第一个人
|
|
3258
|
+
let target = '';
|
|
3259
|
+
let consumed = 0;
|
|
3260
|
+
if (tokens[0] && /^\d{5,12}$/.test(tokens[0])) {
|
|
3261
|
+
target = tokens[0];
|
|
3262
|
+
consumed = 1;
|
|
3263
|
+
}
|
|
3264
|
+
else if (mentions.length) {
|
|
3265
|
+
target = mentions[0];
|
|
3266
|
+
consumed = 0; // @ 不在 tokens 里(已从 content 剥离)
|
|
3267
|
+
}
|
|
3268
|
+
if (!target) {
|
|
3269
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdMute', '[mute]')} qq|@user duration [reason](时长如 10 / 10m / 1h / 1d)`));
|
|
3270
|
+
return true;
|
|
3271
|
+
}
|
|
3272
|
+
const remaining = tokens.slice(consumed);
|
|
3273
|
+
let minutes = null;
|
|
3274
|
+
let reason = '';
|
|
3275
|
+
if (remaining[0]) {
|
|
3276
|
+
const d = this.parseDurationToken(remaining[0]);
|
|
3277
|
+
if (d) {
|
|
3278
|
+
minutes = d.minutes;
|
|
3279
|
+
reason = remaining.slice(1).join(' ');
|
|
3280
|
+
}
|
|
3281
|
+
else {
|
|
3282
|
+
reason = remaining.join(' ');
|
|
3283
|
+
}
|
|
3284
|
+
}
|
|
3285
|
+
if (minutes == null) {
|
|
3286
|
+
await session.send(this.styleText('请给出有效的禁言时长,例如:10 / 10m / 1h / 1d。'));
|
|
3287
|
+
return true;
|
|
3288
|
+
}
|
|
3289
|
+
if (!(await this.canUseAdminCommand(session)).ok)
|
|
3290
|
+
return this.denyAdmin(session);
|
|
3291
|
+
const r = await this.mute(session, target, minutes, reason);
|
|
3292
|
+
await session.send(this.styleText(r.message));
|
|
3293
|
+
this._logger.info(`[cmd:mute] target=${target} minutes=${minutes} byMention=${consumed === 0 && !!mentions.length} | ${this.sessionTag(session)}`);
|
|
3294
|
+
return true;
|
|
3295
|
+
}
|
|
3296
|
+
/** [unmute] qq号|@某人 [原因] */
|
|
3297
|
+
async execUnmute(session, rest, mentions = []) {
|
|
3298
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
3299
|
+
let target = '';
|
|
3300
|
+
let consumed = 0;
|
|
3301
|
+
if (tokens[0] && /^\d{5,12}$/.test(tokens[0])) {
|
|
3302
|
+
target = tokens[0];
|
|
3303
|
+
consumed = 1;
|
|
3304
|
+
}
|
|
3305
|
+
else if (mentions.length) {
|
|
3306
|
+
target = mentions[0];
|
|
3307
|
+
}
|
|
3308
|
+
if (!target) {
|
|
3309
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdUnmute', '[unmute]')} qq号|@某人 原因(原因选填)`));
|
|
3310
|
+
return true;
|
|
3311
|
+
}
|
|
3312
|
+
if (!(await this.canUseAdminCommand(session)).ok)
|
|
3313
|
+
return this.denyAdmin(session);
|
|
3314
|
+
const r = await this.unmute(session, target, tokens.slice(consumed).join(' '));
|
|
3315
|
+
await session.send(this.styleText(r.message));
|
|
3316
|
+
this._logger.info(`[cmd:unmute] target=${target} | ${this.sessionTag(session)}`);
|
|
3317
|
+
return true;
|
|
3318
|
+
}
|
|
3319
|
+
/** [kick] qq号|@某人 [原因] */
|
|
3320
|
+
async execKick(session, rest, mentions = []) {
|
|
3321
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
3322
|
+
let target = '';
|
|
3323
|
+
let consumed = 0;
|
|
3324
|
+
if (tokens[0] && /^\d{5,12}$/.test(tokens[0])) {
|
|
3325
|
+
target = tokens[0];
|
|
3326
|
+
consumed = 1;
|
|
3327
|
+
}
|
|
3328
|
+
else if (mentions.length) {
|
|
3329
|
+
target = mentions[0];
|
|
3330
|
+
}
|
|
3331
|
+
if (!target) {
|
|
3332
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdKick', '[kick]')} qq号|@某人 原因(原因选填)`));
|
|
3333
|
+
return true;
|
|
3334
|
+
}
|
|
3335
|
+
if (!(await this.canUseAdminCommand(session)).ok)
|
|
3336
|
+
return this.denyAdmin(session);
|
|
3337
|
+
const r = await this.kick(session, target, false, tokens.slice(consumed).join(' '));
|
|
3338
|
+
await session.send(this.styleText(r.message));
|
|
3339
|
+
this._logger.info(`[cmd:kick] target=${target} | ${this.sessionTag(session)}`);
|
|
3340
|
+
return true;
|
|
3341
|
+
}
|
|
3342
|
+
/** [memory] content / [memory] list / [memory] search keyword / [memory] delete keyword */
|
|
3343
|
+
async execMemory(session, rest) {
|
|
3344
|
+
if (!this.config.enableMemory) {
|
|
3345
|
+
await session.send(this.styleText('记忆库未启用。'));
|
|
3346
|
+
return true;
|
|
3347
|
+
}
|
|
3348
|
+
const sub = rest.trim();
|
|
3349
|
+
if (!sub) {
|
|
3350
|
+
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 删除`));
|
|
3351
|
+
return true;
|
|
3352
|
+
}
|
|
3353
|
+
const delMatch = sub.match(/^(?:delete|del)\s*([\s\S]*)$/i);
|
|
3354
|
+
if (delMatch) {
|
|
3355
|
+
const keyword = delMatch[1].trim();
|
|
3356
|
+
if (!keyword) {
|
|
3357
|
+
await session.send(this.styleText('请给出要删除的关键词。'));
|
|
3358
|
+
return true;
|
|
3359
|
+
}
|
|
3360
|
+
const results = await this.searchMemory(keyword, 8);
|
|
3361
|
+
if (!results.length) {
|
|
3362
|
+
await session.send(this.styleText(`删除失败,未找到包含「${keyword}」的记忆。`));
|
|
3363
|
+
return true;
|
|
3364
|
+
}
|
|
3365
|
+
const r = await this.deleteMemoryByKeyword(keyword);
|
|
3366
|
+
await session.send(this.styleText(r.ok ? `已删除 ${r.removed} 条记忆。` : `删除失败:${r.message}`));
|
|
3367
|
+
return true;
|
|
3368
|
+
}
|
|
3369
|
+
if (/^(?:list|all)$/i.test(sub)) {
|
|
3370
|
+
const blocks = this.extractMemoryBlocks(await this.readMemoryFile());
|
|
3371
|
+
if (!blocks.length) {
|
|
3372
|
+
await session.send(this.styleText('记忆库为空。'));
|
|
3373
|
+
return true;
|
|
3374
|
+
}
|
|
3375
|
+
const show = blocks.slice(-10).map((b, i) => `${i + 1}. ${b.replace(/\n+/g, ' ').trim()}`).join('\n');
|
|
3376
|
+
await session.send(this.styleText(`记忆库共 ${blocks.length} 条(显示最近 10 条):\n${show}`));
|
|
3377
|
+
return true;
|
|
3378
|
+
}
|
|
3379
|
+
// 查询:[memory] search 关键词 / [memory] query 关键词 / [memory] find 关键词
|
|
3380
|
+
const queryMatch = sub.match(/^(?:search|query|find)\s*[::]?\s*([\s\S]*)$/i);
|
|
3381
|
+
if (queryMatch) {
|
|
3382
|
+
const keyword = queryMatch[1].trim();
|
|
3383
|
+
const results = await this.searchMemory(keyword, 8);
|
|
3384
|
+
if (!results.length) {
|
|
3385
|
+
await session.send(this.styleText(keyword ? `没有找到包含「${keyword}」的记忆。` : '记忆库为空或没有可显示的记录。'));
|
|
3386
|
+
return true;
|
|
3387
|
+
}
|
|
3388
|
+
const reply = results.map((b, i) => `${i + 1}. ${b.replace(/\n+/g, ' ').trim()}`).join('\n');
|
|
3389
|
+
await session.send(this.styleText(keyword ? `包含「${keyword}」的记忆:\n${reply}` : `最近的记忆:\n${reply}`));
|
|
3390
|
+
this._logger.info(`[cmd:memory] 查询 keyword=${keyword || '-'} 命中=${results.length} | ${this.sessionTag(session)}`);
|
|
3391
|
+
return true;
|
|
3392
|
+
}
|
|
3393
|
+
// 保存
|
|
3394
|
+
try {
|
|
3395
|
+
await this.saveMemoryToFile(session.userId, sub);
|
|
3396
|
+
await session.send(this.styleText('已记住。'));
|
|
3397
|
+
this.logCommandResult('memory-save', { ok: true, message: 'memory saved' }, session, { content: sub });
|
|
3398
|
+
}
|
|
3399
|
+
catch (error) {
|
|
3400
|
+
await session.send(this.styleText(`记忆保存失败: ${String(error)}`));
|
|
3401
|
+
}
|
|
3402
|
+
return true;
|
|
3403
|
+
}
|
|
3404
|
+
/** [ban] qq号|@某人 [原因](兼容旧的 [ban] add qq号) */
|
|
3405
|
+
async execBanAdd(session, rest, mentions = []) {
|
|
3406
|
+
if (!this.resolveBlacklistEnabled(session)) {
|
|
3407
|
+
await session.send(this.styleText('本群未启用黑名单系统。'));
|
|
3408
|
+
return true;
|
|
3409
|
+
}
|
|
3410
|
+
if (!(await this.canUseAdminCommand(session)).ok)
|
|
3411
|
+
return this.denyAdmin(session);
|
|
3412
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
3413
|
+
let qq = '';
|
|
3414
|
+
let reason = '';
|
|
3415
|
+
if (/^(?:add)$/i.test(tokens[0] || '')) {
|
|
3416
|
+
qq = tokens[1] || '';
|
|
3417
|
+
reason = tokens.slice(2).join(' ');
|
|
3418
|
+
}
|
|
3419
|
+
else if (tokens[0] && /^\d{5,12}$/.test(tokens[0])) {
|
|
3420
|
+
qq = tokens[0];
|
|
3421
|
+
reason = tokens.slice(1).join(' ');
|
|
3422
|
+
}
|
|
3423
|
+
else if (mentions.length) {
|
|
3424
|
+
qq = mentions[0];
|
|
3425
|
+
reason = tokens.join(' '); // @ 已从 content 剥离,剩余全是原因
|
|
3426
|
+
}
|
|
3427
|
+
if (!/^\d{5,12}$/.test(qq)) {
|
|
3428
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdBan', '[ban]')} qq号|@某人 原因(原因选填)`));
|
|
3429
|
+
return true;
|
|
3430
|
+
}
|
|
3431
|
+
const member = await this.fetchGroupMember(session, qq);
|
|
3432
|
+
if (!member) {
|
|
3433
|
+
await session.send(this.styleText('增加失败,未找到群内人员。'));
|
|
3434
|
+
return true;
|
|
3435
|
+
}
|
|
3436
|
+
const r = await this.addToBlacklist(session, member.qq, member.name);
|
|
3437
|
+
await session.send(this.styleText(r.ok
|
|
3438
|
+
? `已将 ${member.qq}${member.name ? ' · ' + member.name : ''} 加入黑名单${reason ? `(原因:${reason})` : ''}`
|
|
3439
|
+
: `增加失败:${r.message}`));
|
|
3440
|
+
this._logger.info(`[cmd:ban] qq=${member.qq} reason=${reason || '-'} ok=${r.ok} | ${this.sessionTag(session)}`);
|
|
3441
|
+
return true;
|
|
3442
|
+
}
|
|
3443
|
+
/** [unban] qq号|@某人 [原因] */
|
|
3444
|
+
async execUnban(session, rest, mentions = []) {
|
|
3445
|
+
if (!this.resolveBlacklistEnabled(session)) {
|
|
3446
|
+
await session.send(this.styleText('本群未启用黑名单系统。'));
|
|
3447
|
+
return true;
|
|
3448
|
+
}
|
|
3449
|
+
if (!(await this.canUseAdminCommand(session)).ok)
|
|
3450
|
+
return this.denyAdmin(session);
|
|
3451
|
+
const tokens = rest.split(/\s+/).filter(Boolean);
|
|
3452
|
+
let qq = '';
|
|
3453
|
+
let reason = '';
|
|
3454
|
+
if (tokens[0] && /^\d{5,12}$/.test(tokens[0])) {
|
|
3455
|
+
qq = tokens[0];
|
|
3456
|
+
reason = tokens.slice(1).join(' ');
|
|
3457
|
+
}
|
|
3458
|
+
else if (mentions.length) {
|
|
3459
|
+
qq = mentions[0];
|
|
3460
|
+
reason = tokens.join(' ');
|
|
3461
|
+
}
|
|
3462
|
+
if (!/^\d{5,12}$/.test(qq)) {
|
|
3463
|
+
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdUnban', '[unban]')} qq号|@某人 原因(原因选填)`));
|
|
3464
|
+
return true;
|
|
3465
|
+
}
|
|
3466
|
+
const r = await this.removeFromBlacklist(session, qq);
|
|
3467
|
+
await session.send(this.styleText(r.ok && reason ? `${r.message}(原因:${reason})` : r.message));
|
|
3468
|
+
this._logger.info(`[cmd:unban] qq=${qq} reason=${reason || '-'} ok=${r.ok} | ${this.sessionTag(session)}`);
|
|
3469
|
+
return true;
|
|
3470
|
+
}
|
|
3471
|
+
/** [banlist] */
|
|
3472
|
+
async execBanList(session) {
|
|
3473
|
+
if (!this.resolveBlacklistEnabled(session)) {
|
|
3474
|
+
await session.send(this.styleText('本群未启用黑名单系统。'));
|
|
3475
|
+
return;
|
|
3476
|
+
}
|
|
3477
|
+
const list = await this.getBlacklist(session);
|
|
3478
|
+
if (!list.length) {
|
|
3479
|
+
await session.send(this.styleText('本群黑名单为空。'));
|
|
3480
|
+
return;
|
|
3481
|
+
}
|
|
3482
|
+
const lines = list.map((e, i) => `${i + 1}. ${e.qq}${e.name ? ' · ' + e.name : ''}${e.at ? `(${e.at})` : ''}`);
|
|
3483
|
+
await session.send(this.styleText(`本群黑名单共 ${list.length} 人:\n${lines.join('\n')}`));
|
|
3484
|
+
}
|
|
3485
|
+
/**
|
|
3486
|
+
* 黑名单指令(旧式 [ban] list / add / delete 兼容入口)。
|
|
3487
|
+
*/
|
|
3488
|
+
async handleBanCommand(session) {
|
|
3489
|
+
const prefix = String(this.config.banCommand || '[ban]').trim();
|
|
3490
|
+
if (!prefix)
|
|
3491
|
+
return false;
|
|
3492
|
+
const raw = (session.content || '').replace(/<at\b[^>]*\/?>/gi, ' ').trim();
|
|
3493
|
+
if (!raw.startsWith(prefix))
|
|
3494
|
+
return false;
|
|
3495
|
+
|
|
3496
|
+
const rest = raw.slice(prefix.length).trim();
|
|
3497
|
+
const parts = rest.split(/\s+/).filter(Boolean);
|
|
3498
|
+
const sub = (parts[0] || '').toLowerCase();
|
|
3499
|
+
const arg = parts[1] || '';
|
|
3500
|
+
|
|
3501
|
+
// 是否启用(单群设置优先,未设置跟随全局)
|
|
3502
|
+
if (!this.resolveBlacklistEnabled(session)) {
|
|
3503
|
+
await session.send(this.styleText('本群未启用黑名单系统。'));
|
|
3504
|
+
return true;
|
|
3505
|
+
}
|
|
3506
|
+
|
|
3507
|
+
const isAdmin = await this.canUseAdminCommand(session).then((r) => r && r.ok).catch(() => false);
|
|
3508
|
+
|
|
3509
|
+
if (sub === 'list') {
|
|
3510
|
+
const list = await this.getBlacklist(session);
|
|
3511
|
+
if (!list.length) {
|
|
3512
|
+
await session.send(this.styleText('本群黑名单为空。'));
|
|
3513
|
+
return true;
|
|
3514
|
+
}
|
|
3515
|
+
const lines = list.map((e, i) => `${i + 1}. ${e.qq}${e.name ? ' · ' + e.name : ''}${e.at ? `(${e.at})` : ''}`);
|
|
3516
|
+
await session.send(this.styleText(`本群黑名单共 ${list.length} 人:\n${lines.join('\n')}`));
|
|
3517
|
+
return true;
|
|
3518
|
+
}
|
|
3519
|
+
|
|
3520
|
+
if (sub === 'add') {
|
|
3521
|
+
if (!isAdmin) {
|
|
3522
|
+
await session.send(this.styleText('你没有权限操作黑名单。'));
|
|
3523
|
+
return true;
|
|
3524
|
+
}
|
|
3525
|
+
if (!/^\d{5,12}$/.test(arg)) {
|
|
3526
|
+
await session.send(this.styleText(`用法:${prefix} add QQ号`));
|
|
3527
|
+
return true;
|
|
3528
|
+
}
|
|
3529
|
+
// 必须是群内人员
|
|
3530
|
+
const member = await this.fetchGroupMember(session, arg);
|
|
3531
|
+
if (!member) {
|
|
3532
|
+
await session.send(this.styleText('增加失败,未找到群内人员。'));
|
|
3533
|
+
return true;
|
|
3534
|
+
}
|
|
3535
|
+
const r = await this.addToBlacklist(session, member.qq, member.name);
|
|
3536
|
+
await session.send(this.styleText(r.ok ? `已将 ${member.qq} 加入黑名单` : `增加失败:${r.message}`));
|
|
3537
|
+
this._logger.info(`[ban] add qq=${member.qq} ok=${r.ok} | ${this.sessionTag(session)}`);
|
|
3538
|
+
return true;
|
|
3539
|
+
}
|
|
3540
|
+
|
|
3541
|
+
if (sub === 'delete' || sub === 'del') {
|
|
3542
|
+
if (!isAdmin) {
|
|
3543
|
+
await session.send(this.styleText('你没有权限操作黑名单。'));
|
|
3544
|
+
return true;
|
|
3545
|
+
}
|
|
3546
|
+
if (!/^\d{5,12}$/.test(arg)) {
|
|
3547
|
+
await session.send(this.styleText(`用法:${prefix} delete QQ号`));
|
|
3548
|
+
return true;
|
|
3549
|
+
}
|
|
3550
|
+
const r = await this.removeFromBlacklist(session, arg);
|
|
3551
|
+
await session.send(this.styleText(r.message));
|
|
3552
|
+
this._logger.info(`[ban] delete qq=${arg} ok=${r.ok} | ${this.sessionTag(session)}`);
|
|
3553
|
+
return true;
|
|
3554
|
+
}
|
|
3555
|
+
|
|
3556
|
+
await session.send(this.styleText(`用法:${prefix} list | ${prefix} add QQ号 | ${prefix} delete QQ号`));
|
|
3557
|
+
return true;
|
|
3558
|
+
}
|
|
3321
3559
|
async handleGroupModeration(session) {
|
|
3322
3560
|
if (!this.isPlatformAllowed(session.platform))
|
|
3323
3561
|
return;
|
|
3324
|
-
|
|
3562
|
+
// 注:旧的 [记忆] 文本入口已停用,记忆功能统一由 routeBracketCommand 处理,只认 [memory]
|
|
3563
|
+
// 统一方括号指令路由([mute]/[unmute]/[kick]/[memory]/[ban]/[unban]/[banlist]/[custom]/[bot])
|
|
3564
|
+
if (await this.routeBracketCommand(session))
|
|
3565
|
+
return;
|
|
3566
|
+
// 兼容旧入口
|
|
3567
|
+
if (await this.handleBanCommand(session))
|
|
3325
3568
|
return;
|
|
3326
|
-
|
|
3569
|
+
// 自定义命令优先于违禁词管控与 AI:命中后直接结束本轮处理
|
|
3570
|
+
if (await this.handleCustomCommand(session))
|
|
3327
3571
|
return;
|
|
3328
3572
|
if (!session.guildId)
|
|
3329
3573
|
return;
|
|
@@ -3333,7 +3577,7 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3333
3577
|
return;
|
|
3334
3578
|
if (session.platform === 'onebot') {
|
|
3335
3579
|
const policy = this.resolveModerationPolicy(session);
|
|
3336
|
-
const violation = this.detectViolation(session, policy);
|
|
3580
|
+
const violation = await this.detectViolation(session, policy);
|
|
3337
3581
|
if (violation) {
|
|
3338
3582
|
let deleted = false;
|
|
3339
3583
|
if (policy.autoDeleteViolation) {
|
|
@@ -3392,6 +3636,141 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3392
3636
|
}
|
|
3393
3637
|
await this.maybeReplyWithAi(session);
|
|
3394
3638
|
}
|
|
3639
|
+
/**
|
|
3640
|
+
* 待审入群申请的落盘文件路径。
|
|
3641
|
+
* 与 Memory.md 同目录(ctx.baseDir),可用 Koishi 控制台「探索器 Explorer」直接查看。
|
|
3642
|
+
*/
|
|
3643
|
+
getPendingJoinFilePath() {
|
|
3644
|
+
const base = (this.ctx && this.ctx.baseDir) || process.cwd();
|
|
3645
|
+
const name = (this.config.pendingJoinFileName || 'JoinRequests.md').trim();
|
|
3646
|
+
return node_path_1.default.resolve(base, name);
|
|
3647
|
+
}
|
|
3648
|
+
buildPendingJoinFileContent() {
|
|
3649
|
+
const now = new Date().toLocaleString('zh-CN', { hour12: false });
|
|
3650
|
+
const items = [...this.pendingJoinRequests.values()];
|
|
3651
|
+
const lines = [
|
|
3652
|
+
'# 待审入群申请(插件自动维护,可删除本文件重置)',
|
|
3653
|
+
'',
|
|
3654
|
+
`更新时间:${now}`,
|
|
3655
|
+
`待审数量:${items.length}`,
|
|
3656
|
+
`有效期:${Math.max(1, this.config.joinRequestReviewTtlMinutes || 30)} 分钟`,
|
|
3657
|
+
'',
|
|
3658
|
+
];
|
|
3659
|
+
if (items.length) {
|
|
3660
|
+
lines.push('| 编号 | 群号 | 申请人 | 验证信息 | 申请时间 |', '| --- | --- | --- | --- | --- |');
|
|
3661
|
+
for (const item of items) {
|
|
3662
|
+
const comment = String(item.comment || '').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
|
|
3663
|
+
const created = new Date(item.createdAt).toLocaleString('zh-CN', { hour12: false });
|
|
3664
|
+
lines.push(`| ${item.code} | ${item.guildId} | ${item.userId} | ${comment} | ${created} |`);
|
|
3665
|
+
}
|
|
3666
|
+
}
|
|
3667
|
+
else {
|
|
3668
|
+
lines.push('(当前没有待审核的入群申请)');
|
|
3669
|
+
}
|
|
3670
|
+
// 机器可读区段:启动时据此恢复内存 Map
|
|
3671
|
+
lines.push('', '<!-- PENDING-JOIN-REQUESTS:JSON -->', '```json', JSON.stringify(items), '```');
|
|
3672
|
+
return lines.join('\n') + '\n';
|
|
3673
|
+
}
|
|
3674
|
+
/** 立即把待审单写入 MD(供 dispose / 去抖到期调用) */
|
|
3675
|
+
async persistPendingJoinRequestsNow() {
|
|
3676
|
+
const p = this.getPendingJoinFilePath();
|
|
3677
|
+
try {
|
|
3678
|
+
await this.runPendingJoinWriteLocked(async () => {
|
|
3679
|
+
await node_fs_1.default.promises.writeFile(p, this.buildPendingJoinFileContent(), 'utf8');
|
|
3680
|
+
});
|
|
3681
|
+
}
|
|
3682
|
+
catch (error) {
|
|
3683
|
+
this._logger.warn(`[join-review] 待审单落盘失败: ${String(error)}`);
|
|
3684
|
+
}
|
|
3685
|
+
}
|
|
3686
|
+
/** 去抖落盘:入群申请是低频事件,合并多次写入避免频繁 I/O */
|
|
3687
|
+
schedulePendingJoinPersist(delayMs = 500) {
|
|
3688
|
+
if (this._pendingJoinSaveTimer)
|
|
3689
|
+
clearTimeout(this._pendingJoinSaveTimer);
|
|
3690
|
+
this._pendingJoinSaveTimer = setTimeout(() => {
|
|
3691
|
+
this._pendingJoinSaveTimer = null;
|
|
3692
|
+
this.persistPendingJoinRequestsNow().catch(() => { /* 已内部记录日志 */ });
|
|
3693
|
+
}, delayMs);
|
|
3694
|
+
if (typeof this._pendingJoinSaveTimer.unref === 'function')
|
|
3695
|
+
this._pendingJoinSaveTimer.unref();
|
|
3696
|
+
}
|
|
3697
|
+
/** 卸载/重启前的同步兜底:写失败只记日志,不阻塞退出 */
|
|
3698
|
+
flushPendingJoinRequests() {
|
|
3699
|
+
if (this._pendingJoinSaveTimer) {
|
|
3700
|
+
clearTimeout(this._pendingJoinSaveTimer);
|
|
3701
|
+
this._pendingJoinSaveTimer = null;
|
|
3702
|
+
}
|
|
3703
|
+
try {
|
|
3704
|
+
node_fs_1.default.writeFileSync(this.getPendingJoinFilePath(), this.buildPendingJoinFileContent(), 'utf8');
|
|
3705
|
+
}
|
|
3706
|
+
catch (error) {
|
|
3707
|
+
this._logger.warn(`[join-review] 退出前落盘待审单失败: ${String(error)}`);
|
|
3708
|
+
}
|
|
3709
|
+
}
|
|
3710
|
+
/**
|
|
3711
|
+
* 启动时从 MD 恢复待审单,并顺手清掉已过期的编号。
|
|
3712
|
+
* 这样重启不再丢审核单;超过 TTL 的自然失效。
|
|
3713
|
+
*/
|
|
3714
|
+
loadPendingJoinRequests() {
|
|
3715
|
+
const p = this.getPendingJoinFilePath();
|
|
3716
|
+
let raw;
|
|
3717
|
+
try {
|
|
3718
|
+
if (!node_fs_1.default.existsSync(p))
|
|
3719
|
+
return;
|
|
3720
|
+
raw = node_fs_1.default.readFileSync(p, 'utf8');
|
|
3721
|
+
}
|
|
3722
|
+
catch (error) {
|
|
3723
|
+
this._logger.warn(`[join-review] 读取待审单文件失败: ${String(error)}`);
|
|
3724
|
+
return;
|
|
3725
|
+
}
|
|
3726
|
+
const match = raw.match(/<!-- PENDING-JOIN-REQUESTS:JSON -->\s*```json\s*([\s\S]*?)```/);
|
|
3727
|
+
if (!match) {
|
|
3728
|
+
this._logger.warn(`[join-review] 待审单文件缺少数据区段,已忽略: ${p}`);
|
|
3729
|
+
return;
|
|
3730
|
+
}
|
|
3731
|
+
let records = [];
|
|
3732
|
+
try {
|
|
3733
|
+
const parsed = JSON.parse(match[1].trim());
|
|
3734
|
+
if (Array.isArray(parsed))
|
|
3735
|
+
records = parsed;
|
|
3736
|
+
}
|
|
3737
|
+
catch (error) {
|
|
3738
|
+
this._logger.warn(`[join-review] 待审单数据区段解析失败: ${String(error)}`);
|
|
3739
|
+
return;
|
|
3740
|
+
}
|
|
3741
|
+
let restored = 0;
|
|
3742
|
+
let dropped = 0;
|
|
3743
|
+
for (const item of records) {
|
|
3744
|
+
const code = String(item?.code || '').trim().toUpperCase();
|
|
3745
|
+
const flag = String(item?.flag || '').trim();
|
|
3746
|
+
const guildId = String(item?.guildId || '').trim();
|
|
3747
|
+
const userId = String(item?.userId || '').trim();
|
|
3748
|
+
const createdAt = Number(item?.createdAt);
|
|
3749
|
+
if (!code || !flag || !guildId || !userId || !Number.isFinite(createdAt)) {
|
|
3750
|
+
dropped += 1;
|
|
3751
|
+
continue;
|
|
3752
|
+
}
|
|
3753
|
+
this.pendingJoinRequests.set(code, {
|
|
3754
|
+
code,
|
|
3755
|
+
flag,
|
|
3756
|
+
guildId,
|
|
3757
|
+
userId,
|
|
3758
|
+
comment: String(item?.comment || ''),
|
|
3759
|
+
createdAt,
|
|
3760
|
+
});
|
|
3761
|
+
this.pendingJoinRequestFlags.set(flag, code);
|
|
3762
|
+
restored += 1;
|
|
3763
|
+
}
|
|
3764
|
+
// 清理过期项(沿用 TTL 配置)
|
|
3765
|
+
this.cleanupPendingJoinRequests();
|
|
3766
|
+
const alive = this.pendingJoinRequests.size;
|
|
3767
|
+
dropped += restored - alive;
|
|
3768
|
+
if (records.length) {
|
|
3769
|
+
this._logger.info(`[join-review] 已恢复待审入群申请 ${alive} 条(读取 ${records.length} 条,过期/无效 ${Math.max(0, dropped)} 条)`);
|
|
3770
|
+
}
|
|
3771
|
+
if (alive !== records.length)
|
|
3772
|
+
this.schedulePendingJoinPersist();
|
|
3773
|
+
}
|
|
3395
3774
|
cleanupPendingJoinRequests() {
|
|
3396
3775
|
const ttlMs = Math.max(1, this.config.joinRequestReviewTtlMinutes || 30) * 60 * 1000;
|
|
3397
3776
|
const now = Date.now();
|
|
@@ -3420,12 +3799,12 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3420
3799
|
return null;
|
|
3421
3800
|
// 去掉可能的命令前缀(如 [bot])
|
|
3422
3801
|
source = source.replace(/^\[[^\]]+\]\s*/, '').trim();
|
|
3423
|
-
//
|
|
3424
|
-
const approveMatch = source.match(/^(
|
|
3802
|
+
// 只接受英文触发词([记忆] 新规):approve [编号] [理由] / reject [编号] [理由],编号可省略
|
|
3803
|
+
const approveMatch = source.match(/^(approve|ok|yes|accept|pass)\s*(?:join|request)?\s*#?([A-Za-z0-9]{4,12})?\s*([\s\S]*)$/i);
|
|
3425
3804
|
if (approveMatch) {
|
|
3426
3805
|
return { approve: true, code: approveMatch[2] ? approveMatch[2].toUpperCase() : '', reason: (approveMatch[3] || '').trim() };
|
|
3427
3806
|
}
|
|
3428
|
-
const rejectMatch = source.match(/^(
|
|
3807
|
+
const rejectMatch = source.match(/^(reject|deny|no|refuse)\s*(?:join|request)?\s*#?([A-Za-z0-9]{4,12})?\s*([\s\S]*)$/i);
|
|
3429
3808
|
if (rejectMatch) {
|
|
3430
3809
|
return { approve: false, code: rejectMatch[2] ? rejectMatch[2].toUpperCase() : '', reason: (rejectMatch[3] || '').trim() };
|
|
3431
3810
|
}
|
|
@@ -3484,8 +3863,7 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3484
3863
|
if (extra?.level)
|
|
3485
3864
|
lines.push(`QQ等级:${extra.level}`);
|
|
3486
3865
|
lines.push(`验证信息:${applicant.comment || '(无)'}`);
|
|
3487
|
-
lines.push(
|
|
3488
|
-
lines.push(`拒绝:${this.config.command} 拒绝 [理由]`);
|
|
3866
|
+
lines.push(`approve: approve [reason] | reject: reject [reason]`);
|
|
3489
3867
|
return lines.join('\n');
|
|
3490
3868
|
}
|
|
3491
3869
|
async handleGuildMemberRequest(session) {
|
|
@@ -3511,6 +3889,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3511
3889
|
};
|
|
3512
3890
|
this.pendingJoinRequests.set(code, item);
|
|
3513
3891
|
this.pendingJoinRequestFlags.set(item.flag, code);
|
|
3892
|
+
// 落盘待审单:重启后仍可审核
|
|
3893
|
+
this.schedulePendingJoinPersist();
|
|
3514
3894
|
// 尽力获取申请者信息(昵称/性别/年龄/等级/头像)
|
|
3515
3895
|
let extra = {};
|
|
3516
3896
|
const bot = this.getOneBotApi(session);
|
|
@@ -3582,6 +3962,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3582
3962
|
await bot.handleGuildMemberRequest(item.flag, approve, reason || '');
|
|
3583
3963
|
this.pendingJoinRequests.delete(item.code);
|
|
3584
3964
|
this.pendingJoinRequestFlags.delete(item.flag);
|
|
3965
|
+
// 处理完立即更新落盘,避免重启后又被当成待审
|
|
3966
|
+
this.schedulePendingJoinPersist();
|
|
3585
3967
|
return {
|
|
3586
3968
|
ok: true,
|
|
3587
3969
|
message: approve
|
|
@@ -3678,6 +4060,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3678
4060
|
}
|
|
3679
4061
|
try {
|
|
3680
4062
|
await onebot.setGroupKick(groupId, targetId, rejectAddRequest);
|
|
4063
|
+
// 手动踢出 → 加入本群黑名单
|
|
4064
|
+
await this.recordKickToBlacklist(session, targetIdRaw);
|
|
3681
4065
|
return { ok: true, message: `已执行踢人: ${targetIdRaw}`, plan };
|
|
3682
4066
|
}
|
|
3683
4067
|
catch (error) {
|