@napuketto/adapter 0.16.4 → 0.17.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/dist/{essence-CU3kvItK.mjs → buddy-req-BvAxJo6d.mjs} +84 -84
- package/dist/buddy-req-BvAxJo6d.mjs.map +1 -0
- package/dist/core/index.d.mts +5 -2
- package/dist/core/index.mjs +1 -1
- package/dist/{core-l7TM-aKF.mjs → core-D8sq68iP.mjs} +44 -5
- package/dist/core-D8sq68iP.mjs.map +1 -0
- package/dist/{log-AtQxAmbQ.mjs → gray-tip-DmZmdtjP.mjs} +46 -46
- package/dist/gray-tip-DmZmdtjP.mjs.map +1 -0
- package/dist/index-B-HpCes-.d.mts +820 -0
- package/dist/index-B-HpCes-.d.mts.map +1 -0
- package/dist/index-CepyMhuM.d.mts +701 -0
- package/dist/index-CepyMhuM.d.mts.map +1 -0
- package/dist/index-DBD-IZKn.d.mts +808 -0
- package/dist/index-DBD-IZKn.d.mts.map +1 -0
- package/dist/{index-jdSniAj1.d.mts → index-DBjlR2dn.d.mts} +26 -6
- package/dist/index-DBjlR2dn.d.mts.map +1 -0
- package/dist/index-dsurF2t_.d.mts +435 -0
- package/dist/index-dsurF2t_.d.mts.map +1 -0
- package/dist/index.d.mts +23 -1
- package/dist/index.mjs +6 -1
- package/dist/kurobot/index.d.mts +2 -819
- package/dist/kurobot/index.mjs +1 -1125
- package/dist/kurobot-cMBAVX3L.mjs +1126 -0
- package/dist/kurobot-cMBAVX3L.mjs.map +1 -0
- package/dist/milky/index.d.mts +5 -206
- package/dist/milky/index.mjs +1 -3321
- package/dist/milky-CYAOJLv_.mjs +3323 -0
- package/dist/milky-CYAOJLv_.mjs.map +1 -0
- package/dist/onebot11/index.d.mts +2 -805
- package/dist/onebot11/index.mjs +1 -3899
- package/dist/onebot11-BikYDo3k.mjs +3900 -0
- package/dist/onebot11-BikYDo3k.mjs.map +1 -0
- package/dist/satori/index.d.mts +2 -433
- package/dist/satori/index.mjs +1 -1743
- package/dist/satori-Cb2uM3PY.mjs +1754 -0
- package/dist/satori-Cb2uM3PY.mjs.map +1 -0
- package/package.json +4 -4
- package/dist/core-l7TM-aKF.mjs.map +0 -1
- package/dist/essence-CU3kvItK.mjs.map +0 -1
- package/dist/index-jdSniAj1.d.mts.map +0 -1
- package/dist/kurobot/index.d.mts.map +0 -1
- package/dist/kurobot/index.mjs.map +0 -1
- package/dist/log-AtQxAmbQ.mjs.map +0 -1
- package/dist/milky/index.d.mts.map +0 -1
- package/dist/milky/index.mjs.map +0 -1
- package/dist/onebot11/index.d.mts.map +0 -1
- package/dist/onebot11/index.mjs.map +0 -1
- package/dist/satori/index.d.mts.map +0 -1
- package/dist/satori/index.mjs.map +0 -1
package/dist/onebot11/index.mjs
CHANGED
|
@@ -1,3899 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { a as firstNonEmptyString, c as MS_TO_SEC, f as toUin, i as toUnixSeconds, l as NUMERIC_RE, n as senderNickname, o as stringOrUndefined, r as subscribeRawMessages, s as startupBaselineSec, u as numericUin } from "../raw-message-D5nMIebz.mjs";
|
|
3
|
-
import { a as ensureSilk, c as collectGrayTipUids, d as hasGrayTip, i as downloadBufferToFile, n as sliceRaw, o as fileUriToPath, r as truncRaw, s as prepareVideoElements, t as logEventFailure, u as firstUntranslatedGrayTip } from "../log-AtQxAmbQ.mjs";
|
|
4
|
-
import { a as narrowSysMsgBlobs, c as recognizeSysMsg, f as BuddyReqDedup, h as narrowBuddyReqs, i as OBSERVED_UNNAMED_SYSMSG_KEYS, m as filterBuddyReqs, n as extractEssenceSetSysMsg, p as batchUnreadNums, r as narrowEssenceGroupArg, s as processSysMsgBlob, t as EssenceListSync } from "../essence-CU3kvItK.mjs";
|
|
5
|
-
import { ChatType, GrayTipSubType, GroupApi, GroupNotifyMsgStatus, GroupNotifyMsgType, NTGroupMemberRole, NTGroupRequestOperateTypes, TicketApi, TipGroupElementType, WebHonorType, errorMessage, kernelError, toCanonicalElements } from "@napuketto/kernel";
|
|
6
|
-
import { z } from "zod";
|
|
7
|
-
import { randomUUID } from "node:crypto";
|
|
8
|
-
import { existsSync } from "node:fs";
|
|
9
|
-
import { mkdir } from "node:fs/promises";
|
|
10
|
-
import { basename, join } from "node:path";
|
|
11
|
-
import { downloadUrl, inferExtension } from "@napuketto/media";
|
|
12
|
-
import { HttpClient, HttpServer, WsClient, WsServer } from "@napuketto/network";
|
|
13
|
-
// src/onebot11/helper/message-unique.ts
|
|
14
|
-
/** OB11 message_id 上限(int32 max = 0x7FFF_FFFF)。 */
|
|
15
|
-
const INT32_MAX = 2147483647;
|
|
16
|
-
/** int32 下限。 */
|
|
17
|
-
const INT32_MIN = 1;
|
|
18
|
-
var MessageUnique = class {
|
|
19
|
-
/** NT msgId → OB11 message_id。 */
|
|
20
|
-
msgIdToInt = /* @__PURE__ */ new Map();
|
|
21
|
-
/** OB11 message_id → NT msgId。 */
|
|
22
|
-
intToMsgId = /* @__PURE__ */ new Map();
|
|
23
|
-
/** NT msgId → Peer(delete_msg / get_msg 等只有 message_id 时反查用)。 */
|
|
24
|
-
msgIdToPeer = /* @__PURE__ */ new Map();
|
|
25
|
-
/** 递增计数器。 */
|
|
26
|
-
cursor = 1;
|
|
27
|
-
/** 已释放的槽位(可复用)。 */
|
|
28
|
-
freed = /* @__PURE__ */ new Set();
|
|
29
|
-
/**
|
|
30
|
-
* 为新 NT 消息分配 OB11 message_id(幂等:同一 msgId 返回同一 id)。
|
|
31
|
-
* peer 可选:传入则记录,供 message_id → peer 反查。
|
|
32
|
-
*/
|
|
33
|
-
alloc(msgId, peer) {
|
|
34
|
-
const existing = this.msgIdToInt.get(msgId);
|
|
35
|
-
if (existing !== void 0) {
|
|
36
|
-
if (peer !== void 0) this.msgIdToPeer.set(msgId, peer);
|
|
37
|
-
return existing;
|
|
38
|
-
}
|
|
39
|
-
const id = this.nextFreeId();
|
|
40
|
-
this.msgIdToInt.set(msgId, id);
|
|
41
|
-
this.intToMsgId.set(id, msgId);
|
|
42
|
-
if (peer !== void 0) this.msgIdToPeer.set(msgId, peer);
|
|
43
|
-
this.freed.delete(id);
|
|
44
|
-
return id;
|
|
45
|
-
}
|
|
46
|
-
/** OB11 message_id → NT msgId。 */
|
|
47
|
-
getMsgId(messageId) {
|
|
48
|
-
return this.intToMsgId.get(messageId);
|
|
49
|
-
}
|
|
50
|
-
/** NT msgId → OB11 message_id(未分配返回 undefined)。 */
|
|
51
|
-
getMessageId(msgId) {
|
|
52
|
-
return this.msgIdToInt.get(msgId);
|
|
53
|
-
}
|
|
54
|
-
/** NT msgId → Peer(alloc 时未记录返回 undefined)。 */
|
|
55
|
-
getPeer(msgId) {
|
|
56
|
-
return this.msgIdToPeer.get(msgId);
|
|
57
|
-
}
|
|
58
|
-
/** 释放 NT msgId 占用的槽位(消息过期/删除时调用,可选)。 */
|
|
59
|
-
release(msgId) {
|
|
60
|
-
const id = this.msgIdToInt.get(msgId);
|
|
61
|
-
if (id === void 0) return;
|
|
62
|
-
this.msgIdToInt.delete(msgId);
|
|
63
|
-
this.intToMsgId.delete(id);
|
|
64
|
-
this.msgIdToPeer.delete(msgId);
|
|
65
|
-
this.freed.add(id);
|
|
66
|
-
}
|
|
67
|
-
/** 取下一个可用 id:优先释放池,否则递增(溢出后线性扫描空洞)。 */
|
|
68
|
-
nextFreeId() {
|
|
69
|
-
for (const id of this.freed) return id;
|
|
70
|
-
if (this.cursor > INT32_MAX) {
|
|
71
|
-
for (let i = INT32_MIN; i <= INT32_MAX; i += 1) if (!this.intToMsgId.has(i)) {
|
|
72
|
-
this.cursor = i + 1;
|
|
73
|
-
return i;
|
|
74
|
-
}
|
|
75
|
-
throw kernelError("MessageUnique 槽位耗尽(>2^31 条消息)", "INVALID_STATE");
|
|
76
|
-
}
|
|
77
|
-
const id = this.cursor;
|
|
78
|
-
this.cursor += 1;
|
|
79
|
-
return id;
|
|
80
|
-
}
|
|
81
|
-
};
|
|
82
|
-
/**
|
|
83
|
-
* 从 OB11 message_id 反查 NT msgId + Peer。
|
|
84
|
-
* delete_msg / get_msg / set_msg_emoji_like / fetch_ptt_text / 精华消息等
|
|
85
|
-
* 只有 message_id 参数的动作共用(消息不存在抛 KernelError NOT_FOUND)。
|
|
86
|
-
*/
|
|
87
|
-
function resolveMsgIdAndPeer(messageId, unique) {
|
|
88
|
-
let shortId;
|
|
89
|
-
if (typeof messageId === "number") shortId = messageId;
|
|
90
|
-
else shortId = Number(messageId);
|
|
91
|
-
const msgId = unique.getMsgId(shortId);
|
|
92
|
-
if (msgId === void 0) throw kernelError(`消息 ${messageId} 不存在`, "NOT_FOUND");
|
|
93
|
-
const peer = unique.getPeer(msgId);
|
|
94
|
-
if (peer === void 0) throw kernelError(`消息 ${messageId} 无会话记录`, "NOT_FOUND");
|
|
95
|
-
return {
|
|
96
|
-
msgId,
|
|
97
|
-
peer
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
// src/onebot11/action/base-action.ts
|
|
101
|
-
/**
|
|
102
|
-
* OB11 动作运行时:声明式动作工厂 + 响应信封 + 错误码映射 + 共享解析助手。
|
|
103
|
-
*
|
|
104
|
-
* 动作 = `{ name, schema, handle }` 声明对象,经 defineOb11Action 组装出
|
|
105
|
-
* HTTP `handle`(校验失败 retcode=400)与 WS `websocketHandle`(1400 +
|
|
106
|
-
* echo 透传)两个入口;执行骨架走 core runAction(zod safeParse → 执行 →
|
|
107
|
-
* isKernelError 统一映射,映射表收拢为本文件 ob11ErrorCodeMap)。
|
|
108
|
-
*/
|
|
109
|
-
/** 校验失败 retcode:HTTP 入口。 */
|
|
110
|
-
const INVALID_RETCODE_HTTP = 400;
|
|
111
|
-
/** 校验失败 retcode:WS 入口。 */
|
|
112
|
-
const INVALID_RETCODE_WS = 1400;
|
|
113
|
-
/** OB11 错误码映射表(kernel KernelErrorCode → retcode;全部 OB11 动作共用)。 */
|
|
114
|
-
const ob11ErrorCodeMap = {
|
|
115
|
-
SEND_FAILED: 100,
|
|
116
|
-
PERMISSION_DENIED: 101,
|
|
117
|
-
NOT_FOUND: 102,
|
|
118
|
-
TIMEOUT: 103,
|
|
119
|
-
NOT_LOGIN: 104,
|
|
120
|
-
INVALID_PARAM: 105,
|
|
121
|
-
INVALID_STATE: 106,
|
|
122
|
-
UNKNOWN: 999
|
|
123
|
-
};
|
|
124
|
-
/** 声明式动作工厂:闭包依赖 + 统一信封与错误映射。 */
|
|
125
|
-
function defineOb11Action(spec) {
|
|
126
|
-
const run = async (payload, invalidRetcode, echo) => {
|
|
127
|
-
const outcome = await runAction({
|
|
128
|
-
schema: spec.schema,
|
|
129
|
-
handle: spec.handle,
|
|
130
|
-
errorCodeMap: ob11ErrorCodeMap,
|
|
131
|
-
invalidRetcode
|
|
132
|
-
}, payload);
|
|
133
|
-
const result = outcome.ok ? {
|
|
134
|
-
retcode: 0,
|
|
135
|
-
status: "ok",
|
|
136
|
-
data: outcome.data,
|
|
137
|
-
message: ""
|
|
138
|
-
} : {
|
|
139
|
-
retcode: outcome.retcode,
|
|
140
|
-
status: "failed",
|
|
141
|
-
data: null,
|
|
142
|
-
message: outcome.message
|
|
143
|
-
};
|
|
144
|
-
if (echo !== void 0) result.echo = echo;
|
|
145
|
-
return result;
|
|
146
|
-
};
|
|
147
|
-
return {
|
|
148
|
-
name: spec.name,
|
|
149
|
-
schema: spec.schema,
|
|
150
|
-
handle: (payload) => run(payload, INVALID_RETCODE_HTTP),
|
|
151
|
-
websocketHandle: (payload, echo) => run(payload, INVALID_RETCODE_WS, echo)
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
/** 解析单个 uin → uid(失败抛 KernelError INVALID_PARAM;多动作共用)。 */
|
|
155
|
-
async function resolveUid(uin, uinToUid) {
|
|
156
|
-
const uid = (await uinToUid([uin])).get(uin);
|
|
157
|
-
if (uid === void 0) throw kernelError(`用户 ${uin} 的 uid 解析失败`, "INVALID_PARAM");
|
|
158
|
-
return uid;
|
|
159
|
-
}
|
|
160
|
-
/** 解析目标 Peer(group_id 直通;user_id 经 uin→uid)。 */
|
|
161
|
-
async function resolveTargetPeer(payload, deps, missingHint) {
|
|
162
|
-
if (payload.group_id !== void 0) return {
|
|
163
|
-
chatType: ChatType.GROUP,
|
|
164
|
-
peerUid: String(payload.group_id)
|
|
165
|
-
};
|
|
166
|
-
if (payload.user_id !== void 0) return {
|
|
167
|
-
chatType: ChatType.C2C,
|
|
168
|
-
peerUid: await resolveUid(String(payload.user_id), deps.uinToUid)
|
|
169
|
-
};
|
|
170
|
-
throw kernelError(missingHint, "INVALID_PARAM");
|
|
171
|
-
}
|
|
172
|
-
/**
|
|
173
|
-
* 按 message_id(OB11 int32 或 NT msgId)拉取单条消息。
|
|
174
|
-
* 消息不存在/已被撤回 → 抛 KernelError NOT_FOUND。
|
|
175
|
-
*/
|
|
176
|
-
async function fetchMsgById(messageId, messageUnique, msgApi) {
|
|
177
|
-
const { msgId, peer } = resolveMsgIdAndPeer(messageId, messageUnique);
|
|
178
|
-
const [msg] = await msgApi.fetchMsgsByMsgId(peer, [msgId]);
|
|
179
|
-
if (msg === void 0) throw kernelError(`消息 ${messageId} 不存在或已被撤回`, "NOT_FOUND");
|
|
180
|
-
return {
|
|
181
|
-
msg,
|
|
182
|
-
peer,
|
|
183
|
-
msgId
|
|
184
|
-
};
|
|
185
|
-
}
|
|
186
|
-
// src/onebot11/action/friend/manage.ts
|
|
187
|
-
/**
|
|
188
|
-
* 好友管理域动作
|
|
189
|
-
*
|
|
190
|
-
* - set_friend_add_request:flag=reqTime(NapCat 约定,需从好友请求事件上报中
|
|
191
|
-
* 获取)→ getBuddyReqList 匹配 → handleFriendRequest + optional remark
|
|
192
|
-
* - set_friend_remark / delete_friend:user_id 经 uin→uid
|
|
193
|
-
* - set_doubt_friends_add_request(可疑好友申请处理,NapCat 扩展;approve 字段
|
|
194
|
-
* NapCat 强制为 true,该接口无语义仅保留)
|
|
195
|
-
* - send_like:ProfileLikeApi.sendLike
|
|
196
|
-
*/
|
|
197
|
-
/** 好友管理域动作工厂(friend_add_request / friend_remark / delete_friend /
|
|
198
|
-
* doubt 申请处理 / send_like)。 */
|
|
199
|
-
function createFriendManageActions(api) {
|
|
200
|
-
return [
|
|
201
|
-
defineOb11Action({
|
|
202
|
-
name: "set_friend_add_request",
|
|
203
|
-
schema: z.object({
|
|
204
|
-
flag: z.string(),
|
|
205
|
-
approve: z.boolean().optional(),
|
|
206
|
-
remark: z.string().optional()
|
|
207
|
-
}),
|
|
208
|
-
handle: async (payload) => {
|
|
209
|
-
const notify = (await api.friendApi.getBuddyReqList()).find((req) => req.reqTime === payload.flag);
|
|
210
|
-
if (notify === void 0) throw kernelError("未找到对应的好友请求(flag 无效或已过期)", "NOT_FOUND");
|
|
211
|
-
await api.friendApi.handleFriendRequest(notify, payload.approve !== false);
|
|
212
|
-
if (payload.remark !== void 0) api.friendApi.setFriendRemark(notify.friendUid, payload.remark);
|
|
213
|
-
return null;
|
|
214
|
-
}
|
|
215
|
-
}),
|
|
216
|
-
defineOb11Action({
|
|
217
|
-
name: "set_friend_remark",
|
|
218
|
-
schema: z.object({
|
|
219
|
-
user_id: z.number(),
|
|
220
|
-
remark: z.string()
|
|
221
|
-
}),
|
|
222
|
-
handle: async (payload) => {
|
|
223
|
-
const uid = await resolveUid(String(payload.user_id), api.uinToUid);
|
|
224
|
-
api.friendApi.setFriendRemark(uid, payload.remark);
|
|
225
|
-
return null;
|
|
226
|
-
}
|
|
227
|
-
}),
|
|
228
|
-
defineOb11Action({
|
|
229
|
-
name: "delete_friend",
|
|
230
|
-
schema: z.object({ user_id: z.number() }),
|
|
231
|
-
handle: async (payload) => {
|
|
232
|
-
const uid = await resolveUid(String(payload.user_id), api.uinToUid);
|
|
233
|
-
await api.friendApi.deleteFriend(uid);
|
|
234
|
-
return null;
|
|
235
|
-
}
|
|
236
|
-
}),
|
|
237
|
-
defineOb11Action({
|
|
238
|
-
name: "set_doubt_friends_add_request",
|
|
239
|
-
schema: z.object({
|
|
240
|
-
flag: z.string(),
|
|
241
|
-
approve: z.boolean().optional()
|
|
242
|
-
}),
|
|
243
|
-
handle: async (payload) => {
|
|
244
|
-
api.friendApi.handleDoubtFriendRequest(payload.flag);
|
|
245
|
-
return null;
|
|
246
|
-
}
|
|
247
|
-
}),
|
|
248
|
-
defineOb11Action({
|
|
249
|
-
name: "send_like",
|
|
250
|
-
schema: z.object({
|
|
251
|
-
user_id: z.number(),
|
|
252
|
-
times: z.number().optional()
|
|
253
|
-
}),
|
|
254
|
-
handle: async (payload) => {
|
|
255
|
-
const uid = await resolveUid(String(payload.user_id), api.uinToUid);
|
|
256
|
-
await api.profileLikeApi.sendLike(uid, payload.times ?? 1);
|
|
257
|
-
return null;
|
|
258
|
-
}
|
|
259
|
-
})
|
|
260
|
-
];
|
|
261
|
-
}
|
|
262
|
-
// src/onebot11/action/friend/query.ts
|
|
263
|
-
/** 可疑好友申请默认获取数量。 */
|
|
264
|
-
const DEFAULT_DOUBT_COUNT = 50;
|
|
265
|
-
/** 好友查询域动作工厂(friend_list / friends_with_category / stranger_info /
|
|
266
|
-
* doubt_friends_add_request)。 */
|
|
267
|
-
function createFriendQueryActions(api) {
|
|
268
|
-
return [
|
|
269
|
-
defineOb11Action({
|
|
270
|
-
name: "get_friend_list",
|
|
271
|
-
schema: z.object({
|
|
272
|
-
/** 是否忽略缓存(go-cqhttp 扩展)。 */
|
|
273
|
-
no_cache: z.boolean().optional() }),
|
|
274
|
-
handle: async () => {
|
|
275
|
-
return (await api.friendApi.getFriendList()).map((f) => {
|
|
276
|
-
const info = {
|
|
277
|
-
user_id: Number(f.uin),
|
|
278
|
-
nickname: f.nickname
|
|
279
|
-
};
|
|
280
|
-
if (f.remark !== "") info.remark = f.remark;
|
|
281
|
-
return info;
|
|
282
|
-
});
|
|
283
|
-
}
|
|
284
|
-
}),
|
|
285
|
-
defineOb11Action({
|
|
286
|
-
name: "get_friends_with_category",
|
|
287
|
-
schema: z.object({}),
|
|
288
|
-
handle: () => api.friendApi.getFriendCategories()
|
|
289
|
-
}),
|
|
290
|
-
defineOb11Action({
|
|
291
|
-
name: "get_stranger_info",
|
|
292
|
-
schema: z.object({
|
|
293
|
-
user_id: z.number(),
|
|
294
|
-
no_cache: z.boolean().optional()
|
|
295
|
-
}),
|
|
296
|
-
handle: async (payload) => {
|
|
297
|
-
return {
|
|
298
|
-
...await api.profileApi.getStrangerInfo(String(payload.user_id)),
|
|
299
|
-
user_id: payload.user_id
|
|
300
|
-
};
|
|
301
|
-
}
|
|
302
|
-
}),
|
|
303
|
-
defineOb11Action({
|
|
304
|
-
name: "get_doubt_friends_add_request",
|
|
305
|
-
schema: z.object({ count: z.number().optional() }),
|
|
306
|
-
handle: (payload) => api.friendApi.getDoubtFriendRequest(payload.count ?? DEFAULT_DOUBT_COUNT)
|
|
307
|
-
})
|
|
308
|
-
];
|
|
309
|
-
}
|
|
310
|
-
// src/onebot11/action/group/essence.ts
|
|
311
|
-
/**
|
|
312
|
-
* 群精华/荣誉域动作
|
|
313
|
-
*
|
|
314
|
-
* - set/delete_essence_msg:message_id → msgId + peer(MessageUnique 反查,
|
|
315
|
-
* 需群消息)→ GroupApi.addGroupEssence / removeGroupEssence(共用实现)
|
|
316
|
-
* - get_essence_msg_list:qun.qq.com digest_list web 接口 → msg_list,
|
|
317
|
-
* msg_content 映射 text/image 段
|
|
318
|
-
* - get_group_honor_info:qun.qq.com honorlist web 接口;type 缺省 all
|
|
319
|
-
*/
|
|
320
|
-
/** 文本段类型(msg_content.msg_type)。 */
|
|
321
|
-
const MSG_TYPE_TEXT = 1;
|
|
322
|
-
/** 图片段类型(msg_content.msg_type)。 */
|
|
323
|
-
const MSG_TYPE_IMAGE = 3;
|
|
324
|
-
/** set/delete 精华共用实现:message_id 反查 + 群聊校验 + 具体精华操作。 */
|
|
325
|
-
async function operateEssence(api, messageId, operate) {
|
|
326
|
-
const { msgId, peer } = resolveMsgIdAndPeer(messageId, api.messageUnique);
|
|
327
|
-
if (peer.chatType !== ChatType.GROUP) throw kernelError("精华消息仅支持群聊消息", "INVALID_PARAM");
|
|
328
|
-
await operate(peer.peerUid, msgId);
|
|
329
|
-
return null;
|
|
330
|
-
}
|
|
331
|
-
/** msg_content 项 → OB11 段(1=text 3=image,纯函数)。 */
|
|
332
|
-
function toSegment(part) {
|
|
333
|
-
if (part.msg_type === MSG_TYPE_TEXT) return {
|
|
334
|
-
type: "text",
|
|
335
|
-
data: { text: part.text ?? "" }
|
|
336
|
-
};
|
|
337
|
-
if (part.msg_type === MSG_TYPE_IMAGE) return {
|
|
338
|
-
type: "image",
|
|
339
|
-
data: { file: part.image_url ?? "" }
|
|
340
|
-
};
|
|
341
|
-
return null;
|
|
342
|
-
}
|
|
343
|
-
/** type 字符串 → WebHonorType(talkative/performer/legend/emotion/all,纯函数)。 */
|
|
344
|
-
function mapHonorType(raw) {
|
|
345
|
-
if (raw === "talkative") return WebHonorType.TALKATIVE;
|
|
346
|
-
if (raw === "performer") return WebHonorType.PERFORMER;
|
|
347
|
-
if (raw === "legend") return WebHonorType.LEGEND;
|
|
348
|
-
if (raw === "emotion") return WebHonorType.EMOTION;
|
|
349
|
-
return WebHonorType.ALL;
|
|
350
|
-
}
|
|
351
|
-
/** 群精华/荣誉域动作工厂(set/delete_essence_msg / essence_msg_list / honor_info)。 */
|
|
352
|
-
function createGroupEssenceActions(api) {
|
|
353
|
-
return [
|
|
354
|
-
defineOb11Action({
|
|
355
|
-
name: "set_essence_msg",
|
|
356
|
-
schema: z.object({ message_id: z.union([z.number(), z.string()]) }),
|
|
357
|
-
handle: (payload) => operateEssence(api, payload.message_id, (groupCode, msgId) => api.groupApi.addGroupEssence(groupCode, msgId))
|
|
358
|
-
}),
|
|
359
|
-
defineOb11Action({
|
|
360
|
-
name: "delete_essence_msg",
|
|
361
|
-
schema: z.object({ message_id: z.union([z.number(), z.string()]) }),
|
|
362
|
-
handle: (payload) => operateEssence(api, payload.message_id, (groupCode, msgId) => api.groupApi.removeGroupEssence(groupCode, msgId))
|
|
363
|
-
}),
|
|
364
|
-
defineOb11Action({
|
|
365
|
-
name: "get_essence_msg_list",
|
|
366
|
-
schema: z.object({ group_id: z.number() }),
|
|
367
|
-
handle: async (payload) => {
|
|
368
|
-
const list = await api.webApi.getEssenceMsgList(String(payload.group_id));
|
|
369
|
-
const out = [];
|
|
370
|
-
for (const item of list) {
|
|
371
|
-
const content = [];
|
|
372
|
-
for (const part of item.msg_content ?? []) {
|
|
373
|
-
const seg = toSegment(part);
|
|
374
|
-
if (seg !== null) content.push(seg);
|
|
375
|
-
}
|
|
376
|
-
out.push({
|
|
377
|
-
msg_seq: item.msg_seq,
|
|
378
|
-
msg_random: item.msg_random,
|
|
379
|
-
sender_id: Number(item.sender_uin),
|
|
380
|
-
sender_nick: item.sender_nick,
|
|
381
|
-
operator_id: Number(item.add_digest_uin),
|
|
382
|
-
operator_nick: item.add_digest_nick,
|
|
383
|
-
operator_time: item.add_digest_time,
|
|
384
|
-
message_id: 0,
|
|
385
|
-
content
|
|
386
|
-
});
|
|
387
|
-
}
|
|
388
|
-
return out;
|
|
389
|
-
}
|
|
390
|
-
}),
|
|
391
|
-
defineOb11Action({
|
|
392
|
-
name: "get_group_honor_info",
|
|
393
|
-
schema: z.object({
|
|
394
|
-
group_id: z.number(),
|
|
395
|
-
type: z.string().optional()
|
|
396
|
-
}),
|
|
397
|
-
handle: (payload) => api.webApi.getGroupHonorInfo(String(payload.group_id), mapHonorType(payload.type))
|
|
398
|
-
})
|
|
399
|
-
];
|
|
400
|
-
}
|
|
401
|
-
// src/onebot11/action/limits.ts
|
|
402
|
-
/** 批量翻译的词条上限(translate_en2zh)。 */
|
|
403
|
-
const MAX_TRANSLATE_WORDS = 2e3;
|
|
404
|
-
// src/onebot11/action/group/files-op.ts
|
|
405
|
-
/**
|
|
406
|
-
* 群文件操作动作:create_group_file_folder / delete_group_file /
|
|
407
|
-
* delete_group_folder / rename_group_file / move_group_file / trans_group_file
|
|
408
|
-
*/
|
|
409
|
-
/** 群文件操作域动作工厂(create/delete folder、delete/rename/move/trans file)。 */
|
|
410
|
-
function createGroupFileOpActions(api) {
|
|
411
|
-
return [
|
|
412
|
-
defineOb11Action({
|
|
413
|
-
name: "create_group_file_folder",
|
|
414
|
-
schema: z.object({
|
|
415
|
-
group_id: z.number(),
|
|
416
|
-
folder_name: z.string()
|
|
417
|
-
}),
|
|
418
|
-
handle: async (payload) => {
|
|
419
|
-
return { folder_id: await api.richMediaApi.createGroupFolder(String(payload.group_id), payload.folder_name) };
|
|
420
|
-
}
|
|
421
|
-
}),
|
|
422
|
-
defineOb11Action({
|
|
423
|
-
name: "delete_group_file",
|
|
424
|
-
schema: z.object({
|
|
425
|
-
group_id: z.number(),
|
|
426
|
-
file_id: z.string(),
|
|
427
|
-
/** 兼容 go-cqhttp 的 file_ids 数组(取第一个)。 */
|
|
428
|
-
file_ids: z.array(z.string()).max(100).optional()
|
|
429
|
-
}),
|
|
430
|
-
handle: async (payload) => {
|
|
431
|
-
const ids = payload.file_ids ?? [payload.file_id];
|
|
432
|
-
await api.richMediaApi.deleteGroupFile(String(payload.group_id), ids);
|
|
433
|
-
return null;
|
|
434
|
-
}
|
|
435
|
-
}),
|
|
436
|
-
defineOb11Action({
|
|
437
|
-
name: "delete_group_folder",
|
|
438
|
-
schema: z.object({
|
|
439
|
-
group_id: z.number(),
|
|
440
|
-
folder_id: z.string()
|
|
441
|
-
}),
|
|
442
|
-
handle: async (payload) => {
|
|
443
|
-
await api.richMediaApi.deleteGroupFolder(String(payload.group_id), payload.folder_id);
|
|
444
|
-
return null;
|
|
445
|
-
}
|
|
446
|
-
}),
|
|
447
|
-
defineOb11Action({
|
|
448
|
-
name: "rename_group_file",
|
|
449
|
-
schema: z.object({
|
|
450
|
-
group_id: z.number(),
|
|
451
|
-
file_id: z.string(),
|
|
452
|
-
new_name: z.string()
|
|
453
|
-
}),
|
|
454
|
-
handle: async (payload) => {
|
|
455
|
-
await api.richMediaApi.renameGroupFile(String(payload.group_id), payload.file_id, payload.new_name);
|
|
456
|
-
return null;
|
|
457
|
-
}
|
|
458
|
-
}),
|
|
459
|
-
defineOb11Action({
|
|
460
|
-
name: "move_group_file",
|
|
461
|
-
schema: z.object({
|
|
462
|
-
group_id: z.number(),
|
|
463
|
-
file_id: z.string(),
|
|
464
|
-
file_ids: z.array(z.string()).max(100).optional(),
|
|
465
|
-
/** 目标文件夹 ID(空为根目录)。 */
|
|
466
|
-
folder_id: z.string().optional()
|
|
467
|
-
}),
|
|
468
|
-
handle: async (payload) => {
|
|
469
|
-
const ids = payload.file_ids ?? [payload.file_id];
|
|
470
|
-
await api.richMediaApi.moveGroupFile(String(payload.group_id), ids, payload.folder_id ?? "");
|
|
471
|
-
return null;
|
|
472
|
-
}
|
|
473
|
-
}),
|
|
474
|
-
defineOb11Action({
|
|
475
|
-
name: "trans_group_file",
|
|
476
|
-
schema: z.object({
|
|
477
|
-
group_id: z.number(),
|
|
478
|
-
file_id: z.string()
|
|
479
|
-
}),
|
|
480
|
-
handle: async (payload) => {
|
|
481
|
-
await api.richMediaApi.transGroupFile(String(payload.group_id), payload.file_id);
|
|
482
|
-
return null;
|
|
483
|
-
}
|
|
484
|
-
})
|
|
485
|
-
];
|
|
486
|
-
}
|
|
487
|
-
// src/onebot11/action/group/files-query.ts
|
|
488
|
-
/** 默认文件数量。 */
|
|
489
|
-
const DEFAULT_FILE_COUNT = 50;
|
|
490
|
-
/** 列表拆分 files/folders(fileInfo/folderInfo 取其一,纯函数)。 */
|
|
491
|
-
function splitFilesAndFolders(list) {
|
|
492
|
-
const files = [];
|
|
493
|
-
const folders = [];
|
|
494
|
-
for (const item of list) {
|
|
495
|
-
const file = item.fileInfo;
|
|
496
|
-
if (file === void 0) {
|
|
497
|
-
const folder = item.folderInfo;
|
|
498
|
-
if (folder !== void 0) folders.push(toGroupFolderInfo(folder));
|
|
499
|
-
} else {
|
|
500
|
-
const out = toGroupFileInfo(file);
|
|
501
|
-
files.push(out);
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
return {
|
|
505
|
-
files,
|
|
506
|
-
folders
|
|
507
|
-
};
|
|
508
|
-
}
|
|
509
|
-
/** GroupFileItemInfo → OB11 文件结构(纯函数)。 */
|
|
510
|
-
function toGroupFileInfo(file) {
|
|
511
|
-
const out = {
|
|
512
|
-
file_id: file.fileId,
|
|
513
|
-
file_name: file.fileName,
|
|
514
|
-
file_size: file.fileSize
|
|
515
|
-
};
|
|
516
|
-
if (file.uploaderUin !== void 0) out.uploader = Number(file.uploaderUin);
|
|
517
|
-
if (file.uploadTime !== void 0) out.upload_time = file.uploadTime;
|
|
518
|
-
if (file.modifyTime !== void 0) out.modify_time = file.modifyTime;
|
|
519
|
-
return out;
|
|
520
|
-
}
|
|
521
|
-
/** GroupFolderInfo → OB11 文件夹结构(纯函数)。 */
|
|
522
|
-
function toGroupFolderInfo(folder) {
|
|
523
|
-
return {
|
|
524
|
-
folder_id: folder.folderId,
|
|
525
|
-
folder_name: folder.folderName
|
|
526
|
-
};
|
|
527
|
-
}
|
|
528
|
-
/** 群文件查询域动作工厂(root files / by folder / system info)。 */
|
|
529
|
-
function createGroupFileQueryActions(api) {
|
|
530
|
-
return [
|
|
531
|
-
defineOb11Action({
|
|
532
|
-
name: "get_group_root_files",
|
|
533
|
-
schema: z.object({
|
|
534
|
-
group_id: z.number(),
|
|
535
|
-
file_count: z.number().optional()
|
|
536
|
-
}),
|
|
537
|
-
handle: async (payload) => {
|
|
538
|
-
return splitFilesAndFolders(await api.richMediaApi.getGroupFileList(String(payload.group_id), "", payload.file_count ?? DEFAULT_FILE_COUNT));
|
|
539
|
-
}
|
|
540
|
-
}),
|
|
541
|
-
defineOb11Action({
|
|
542
|
-
name: "get_group_files_by_folder",
|
|
543
|
-
schema: z.object({
|
|
544
|
-
group_id: z.number(),
|
|
545
|
-
folder_id: z.string(),
|
|
546
|
-
file_count: z.number().optional()
|
|
547
|
-
}),
|
|
548
|
-
handle: async (payload) => {
|
|
549
|
-
return splitFilesAndFolders(await api.richMediaApi.getGroupFileList(String(payload.group_id), payload.folder_id, payload.file_count ?? DEFAULT_FILE_COUNT));
|
|
550
|
-
}
|
|
551
|
-
}),
|
|
552
|
-
defineOb11Action({
|
|
553
|
-
name: "get_group_file_system_info",
|
|
554
|
-
schema: z.object({ group_id: z.number() }),
|
|
555
|
-
handle: async (payload) => {
|
|
556
|
-
const info = await api.richMediaApi.getGroupFileSystemInfo(String(payload.group_id));
|
|
557
|
-
return {
|
|
558
|
-
file_count: info.fileCount,
|
|
559
|
-
limit_count: info.limitCount,
|
|
560
|
-
used_space: info.usedSpace,
|
|
561
|
-
total_space: info.totalSpace
|
|
562
|
-
};
|
|
563
|
-
}
|
|
564
|
-
})
|
|
565
|
-
];
|
|
566
|
-
}
|
|
567
|
-
// src/onebot11/action/group/manage.ts
|
|
568
|
-
/**
|
|
569
|
-
* 群管理域动作
|
|
570
|
-
*
|
|
571
|
-
* 踢人 / 单人与全员禁言 / 管理员 / 名片 / 群名 / 退群,均接 kernel GroupApi;
|
|
572
|
-
* user_id(uin)→ uid 经 resolveUid。
|
|
573
|
-
*/
|
|
574
|
-
/** 默认禁言时长(秒)。 */
|
|
575
|
-
const DEFAULT_BAN_DURATION = 30;
|
|
576
|
-
/** 群管理域动作工厂(kick / ban / whole_ban / admin / card / name / leave)。 */
|
|
577
|
-
/** uin → uid(groupApi.uinToUid 绑定视图;kernel 方法非箭头绑定)。 */
|
|
578
|
-
function memberUidOf(api, uin) {
|
|
579
|
-
return resolveUid(String(uin), (uins) => api.groupApi.uinToUid(uins));
|
|
580
|
-
}
|
|
581
|
-
function createGroupManageActions(api) {
|
|
582
|
-
return [
|
|
583
|
-
defineOb11Action({
|
|
584
|
-
name: "set_group_kick",
|
|
585
|
-
schema: z.object({
|
|
586
|
-
group_id: z.number(),
|
|
587
|
-
user_id: z.number(),
|
|
588
|
-
/** 是否拒绝加群请求(拉黑)。 */
|
|
589
|
-
reject_add_request: z.boolean().optional(),
|
|
590
|
-
/** 踢人理由。 */
|
|
591
|
-
kick_reason: z.string().optional()
|
|
592
|
-
}),
|
|
593
|
-
handle: async (payload) => {
|
|
594
|
-
const uid = await memberUidOf(api, payload.user_id);
|
|
595
|
-
await api.groupApi.kickMember(String(payload.group_id), [uid], payload.reject_add_request === true, payload.kick_reason ?? "");
|
|
596
|
-
return null;
|
|
597
|
-
}
|
|
598
|
-
}),
|
|
599
|
-
defineOb11Action({
|
|
600
|
-
name: "set_group_ban",
|
|
601
|
-
schema: z.object({
|
|
602
|
-
group_id: z.number(),
|
|
603
|
-
user_id: z.number(),
|
|
604
|
-
/** 禁言时长(秒),0 解除。 */
|
|
605
|
-
duration: z.number().default(DEFAULT_BAN_DURATION)
|
|
606
|
-
}),
|
|
607
|
-
handle: async (payload) => {
|
|
608
|
-
const uid = await memberUidOf(api, payload.user_id);
|
|
609
|
-
await api.groupApi.setMemberShutUp(String(payload.group_id), [{
|
|
610
|
-
uid,
|
|
611
|
-
duration: payload.duration
|
|
612
|
-
}]);
|
|
613
|
-
return null;
|
|
614
|
-
}
|
|
615
|
-
}),
|
|
616
|
-
defineOb11Action({
|
|
617
|
-
name: "set_group_whole_ban",
|
|
618
|
-
schema: z.object({
|
|
619
|
-
group_id: z.number(),
|
|
620
|
-
/** 是否开启全员禁言。 */
|
|
621
|
-
enable: z.boolean().default(true)
|
|
622
|
-
}),
|
|
623
|
-
handle: async (payload) => {
|
|
624
|
-
await api.groupApi.setGroupShutUp(String(payload.group_id), payload.enable);
|
|
625
|
-
return null;
|
|
626
|
-
}
|
|
627
|
-
}),
|
|
628
|
-
defineOb11Action({
|
|
629
|
-
name: "set_group_admin",
|
|
630
|
-
schema: z.object({
|
|
631
|
-
group_id: z.number(),
|
|
632
|
-
user_id: z.number(),
|
|
633
|
-
/** 是否设为管理员。 */
|
|
634
|
-
enable: z.boolean().default(true)
|
|
635
|
-
}),
|
|
636
|
-
handle: async (payload) => {
|
|
637
|
-
const uid = await memberUidOf(api, payload.user_id);
|
|
638
|
-
let role = NTGroupMemberRole.MEMBER;
|
|
639
|
-
if (payload.enable) role = NTGroupMemberRole.ADMIN;
|
|
640
|
-
api.groupApi.setMemberRole(String(payload.group_id), uid, role);
|
|
641
|
-
return null;
|
|
642
|
-
}
|
|
643
|
-
}),
|
|
644
|
-
defineOb11Action({
|
|
645
|
-
name: "set_group_card",
|
|
646
|
-
schema: z.object({
|
|
647
|
-
group_id: z.number(),
|
|
648
|
-
user_id: z.number(),
|
|
649
|
-
/** 群名片(空串清除)。 */
|
|
650
|
-
card: z.string().optional().default("")
|
|
651
|
-
}),
|
|
652
|
-
handle: async (payload) => {
|
|
653
|
-
const uid = await memberUidOf(api, payload.user_id);
|
|
654
|
-
api.groupApi.setMemberCardName(String(payload.group_id), uid, payload.card);
|
|
655
|
-
return null;
|
|
656
|
-
}
|
|
657
|
-
}),
|
|
658
|
-
defineOb11Action({
|
|
659
|
-
name: "set_group_name",
|
|
660
|
-
schema: z.object({
|
|
661
|
-
group_id: z.number(),
|
|
662
|
-
group_name: z.string()
|
|
663
|
-
}),
|
|
664
|
-
handle: async (payload) => {
|
|
665
|
-
await api.groupApi.modifyGroupName(String(payload.group_id), payload.group_name);
|
|
666
|
-
return null;
|
|
667
|
-
}
|
|
668
|
-
}),
|
|
669
|
-
defineOb11Action({
|
|
670
|
-
name: "set_group_leave",
|
|
671
|
-
schema: z.object({
|
|
672
|
-
group_id: z.number(),
|
|
673
|
-
/** 是否解散群(仅群主可用)。 */
|
|
674
|
-
is_dismiss: z.boolean().optional().default(false)
|
|
675
|
-
}),
|
|
676
|
-
handle: async (payload) => {
|
|
677
|
-
await api.groupApi.quitGroup(String(payload.group_id), payload.is_dismiss);
|
|
678
|
-
return null;
|
|
679
|
-
}
|
|
680
|
-
})
|
|
681
|
-
];
|
|
682
|
-
}
|
|
683
|
-
// src/onebot11/action/group/notify.ts
|
|
684
|
-
/**
|
|
685
|
-
* 群通知域动作(均接 kernel GroupNotifyApi)
|
|
686
|
-
*
|
|
687
|
-
* - get_group_add_request / get_group_ignored_notifies:未处理申请列表 /
|
|
688
|
-
* 可疑忽略列表(getSingleScreenNotifies(false|true));flag=seq 用于应答
|
|
689
|
-
* - set_group_add_request:flag=seq 匹配 → handleGroupRequest
|
|
690
|
-
* (approve=true→同意 / false→拒绝,reason 默认空格)
|
|
691
|
-
* - get_group_shut_list:getGroupShutUpMemberList → 禁言成员列表
|
|
692
|
-
* (uin 经 uidToUin 批量转换)
|
|
693
|
-
*/
|
|
694
|
-
const getGroupAddRequestSchema = z.object({ count: z.number().optional() });
|
|
695
|
-
/** 默认获取数量。 */
|
|
696
|
-
const DEFAULT_COUNT$1 = 100;
|
|
697
|
-
/** GroupNotify → OB11 群请求项(纯函数)。 */
|
|
698
|
-
function toGroupAddRequestItem(notify) {
|
|
699
|
-
const { seq, type, status, postscript, user1, group } = notify;
|
|
700
|
-
let groupCode = 0;
|
|
701
|
-
let groupName = "";
|
|
702
|
-
if (group !== void 0) {
|
|
703
|
-
const { groupCode: code, groupName: name } = group;
|
|
704
|
-
groupCode = Number(code);
|
|
705
|
-
groupName = name;
|
|
706
|
-
}
|
|
707
|
-
let userId = 0;
|
|
708
|
-
let userNick = "";
|
|
709
|
-
if (user1 !== void 0) {
|
|
710
|
-
const { uid, nickName } = user1;
|
|
711
|
-
userId = Number(uid);
|
|
712
|
-
userNick = nickName;
|
|
713
|
-
}
|
|
714
|
-
return {
|
|
715
|
-
flag: seq,
|
|
716
|
-
group_id: groupCode,
|
|
717
|
-
group_name: groupName,
|
|
718
|
-
user_id: userId,
|
|
719
|
-
user_nick: userNick,
|
|
720
|
-
type,
|
|
721
|
-
checked: status !== 1,
|
|
722
|
-
postscript: postscript ?? ""
|
|
723
|
-
};
|
|
724
|
-
}
|
|
725
|
-
/** 按 seq 匹配通知(先非可疑,后可疑)。 */
|
|
726
|
-
async function findGroupNotify(groupNotifyApi, flag, count) {
|
|
727
|
-
const hit = (await groupNotifyApi.getSingleScreenNotifies(false, count)).find((item) => item.seq === flag);
|
|
728
|
-
if (hit !== void 0) return hit;
|
|
729
|
-
return (await groupNotifyApi.getSingleScreenNotifies(true, count)).find((item) => item.seq === flag) ?? null;
|
|
730
|
-
}
|
|
731
|
-
/** 群通知域动作工厂(get_group_add_request / get_group_ignored_notifies /
|
|
732
|
-
* set_group_add_request / get_group_shut_list)。 */
|
|
733
|
-
function createGroupNotifyActions(api) {
|
|
734
|
-
return [
|
|
735
|
-
defineOb11Action({
|
|
736
|
-
name: "get_group_add_request",
|
|
737
|
-
schema: getGroupAddRequestSchema,
|
|
738
|
-
handle: async (payload) => {
|
|
739
|
-
return (await api.groupNotifyApi.getSingleScreenNotifies(false, payload.count ?? DEFAULT_COUNT$1)).map(toGroupAddRequestItem);
|
|
740
|
-
}
|
|
741
|
-
}),
|
|
742
|
-
defineOb11Action({
|
|
743
|
-
name: "get_group_ignored_notifies",
|
|
744
|
-
schema: getGroupAddRequestSchema,
|
|
745
|
-
handle: async (payload) => {
|
|
746
|
-
return (await api.groupNotifyApi.getSingleScreenNotifies(true, payload.count ?? DEFAULT_COUNT$1)).map(toGroupAddRequestItem);
|
|
747
|
-
}
|
|
748
|
-
}),
|
|
749
|
-
defineOb11Action({
|
|
750
|
-
name: "set_group_add_request",
|
|
751
|
-
schema: z.object({
|
|
752
|
-
flag: z.string(),
|
|
753
|
-
approve: z.boolean().optional(),
|
|
754
|
-
reason: z.string().optional(),
|
|
755
|
-
count: z.number().optional()
|
|
756
|
-
}),
|
|
757
|
-
handle: async (payload) => {
|
|
758
|
-
const count = payload.count ?? DEFAULT_COUNT$1;
|
|
759
|
-
const notify = await findGroupNotify(api.groupNotifyApi, payload.flag, count);
|
|
760
|
-
if (notify === null) throw kernelError("未找到对应的群请求(flag 无效或已过期)", "NOT_FOUND");
|
|
761
|
-
let operateType = NTGroupRequestOperateTypes.KREFUSE;
|
|
762
|
-
if (payload.approve !== false) operateType = NTGroupRequestOperateTypes.KAGREE;
|
|
763
|
-
await api.groupNotifyApi.handleGroupRequest(false, notify, operateType, payload.reason ?? " ");
|
|
764
|
-
return null;
|
|
765
|
-
}
|
|
766
|
-
}),
|
|
767
|
-
defineOb11Action({
|
|
768
|
-
name: "get_group_shut_list",
|
|
769
|
-
schema: z.object({ group_id: z.number() }),
|
|
770
|
-
handle: async (payload) => {
|
|
771
|
-
const members = await api.groupNotifyApi.getGroupShutUpMemberList(String(payload.group_id));
|
|
772
|
-
const uids = members.map((m) => m.uid);
|
|
773
|
-
let uinMap = /* @__PURE__ */ new Map();
|
|
774
|
-
if (uids.length > 0) uinMap = await api.uidToUin(uids);
|
|
775
|
-
const out = [];
|
|
776
|
-
for (const member of members) out.push({
|
|
777
|
-
user_id: Number(uinMap.get(member.uid) ?? member.uin ?? member.uid),
|
|
778
|
-
nickname: member.nick,
|
|
779
|
-
shut_up_time: member.shutUpTime
|
|
780
|
-
});
|
|
781
|
-
return out;
|
|
782
|
-
}
|
|
783
|
-
})
|
|
784
|
-
];
|
|
785
|
-
}
|
|
786
|
-
// src/onebot11/helper/translate.ts
|
|
787
|
-
/**
|
|
788
|
-
* OB11 翻译辅助(NT 实体 → OB11 结构)
|
|
789
|
-
*
|
|
790
|
-
* 纯函数:只读入参,不调 API、不读缓存。
|
|
791
|
-
* 群成员/群信息等 NT 实体 → OB11 返回结构的薄映射。
|
|
792
|
-
*/
|
|
793
|
-
/** NT Group → OB11 GroupInfo。 */
|
|
794
|
-
function toOb11GroupInfo(group) {
|
|
795
|
-
const info = {
|
|
796
|
-
group_id: Number(group.groupCode),
|
|
797
|
-
group_name: group.groupName
|
|
798
|
-
};
|
|
799
|
-
if (typeof group.memberCount === "number") info.member_count = group.memberCount;
|
|
800
|
-
if (typeof group.maxMember === "number") info.max_member_count = group.maxMember;
|
|
801
|
-
return info;
|
|
802
|
-
}
|
|
803
|
-
/** NT GroupDetailInfo → OB11 GroupInfo(getGroupDetailInfo / GroupCache 用)。 */
|
|
804
|
-
function toOb11GroupInfoDetail(detail) {
|
|
805
|
-
const info = {
|
|
806
|
-
group_id: Number(detail.groupCode),
|
|
807
|
-
group_name: detail.groupName
|
|
808
|
-
};
|
|
809
|
-
if (typeof detail.memberNum === "number") info.member_count = detail.memberNum;
|
|
810
|
-
if (typeof detail.maxMemberNum === "number") info.max_member_count = detail.maxMemberNum;
|
|
811
|
-
return info;
|
|
812
|
-
}
|
|
813
|
-
/** 禁言秒 → 毫秒(shut_up_timestamp 单位)。 */
|
|
814
|
-
const SEC_TO_MS = 1e3;
|
|
815
|
-
/** NT GroupMember → OB11 GroupMemberInfo(uin 由 uidToUin 映射补全)。 */
|
|
816
|
-
function toOb11GroupMemberInfo(groupCode, member, uidToUin) {
|
|
817
|
-
let uinStr = member.uin;
|
|
818
|
-
if (uinStr === "") uinStr = uidToUin.get(member.uid) ?? member.uid;
|
|
819
|
-
const info = {
|
|
820
|
-
group_id: Number(groupCode),
|
|
821
|
-
user_id: Number(uinStr),
|
|
822
|
-
nickname: member.nick,
|
|
823
|
-
role: GroupApi.roleToString(member.role)
|
|
824
|
-
};
|
|
825
|
-
if (member.cardName !== "") info.card = member.cardName;
|
|
826
|
-
if (member.memberSpecialTitle !== void 0 && member.memberSpecialTitle !== "") {
|
|
827
|
-
info.title = member.memberSpecialTitle;
|
|
828
|
-
info.special_title = member.memberSpecialTitle;
|
|
829
|
-
}
|
|
830
|
-
if (member.shutUpTime > 0) info.shut_up_timestamp = member.shutUpTime * SEC_TO_MS;
|
|
831
|
-
if (member.joinTime !== "" && member.joinTime !== "0") info.join_time = Number(member.joinTime);
|
|
832
|
-
if (member.lastSpeakTime !== "" && member.lastSpeakTime !== "0") info.last_sent_time = Number(member.lastSpeakTime);
|
|
833
|
-
if (typeof member.age === "number") info.age = member.age;
|
|
834
|
-
return info;
|
|
835
|
-
}
|
|
836
|
-
// src/onebot11/action/group/query.ts
|
|
837
|
-
/**
|
|
838
|
-
* 群查询域动作
|
|
839
|
-
*
|
|
840
|
-
* 接 kernel GroupApi;群信息/成员动作优先读 GroupCache,no_cache=true
|
|
841
|
-
* 直查 api。get_group_list 有实测校准:原生 getGroupList 返回值无数据(仅
|
|
842
|
-
* { result, errMsg }),列表经 onGroupListUpdate 事件推送 → GroupCache 维护。
|
|
843
|
-
*/
|
|
844
|
-
/** 群查询域动作工厂(group_info / group_list / member_info / member_list / at_all_remain)。 */
|
|
845
|
-
function createGroupQueryActions(api) {
|
|
846
|
-
return [
|
|
847
|
-
defineOb11Action({
|
|
848
|
-
name: "get_group_info",
|
|
849
|
-
schema: z.object({
|
|
850
|
-
group_id: z.number(),
|
|
851
|
-
/** 是否忽略缓存(go-cqhttp 扩展)。 */
|
|
852
|
-
no_cache: z.boolean().optional()
|
|
853
|
-
}),
|
|
854
|
-
handle: async (payload) => {
|
|
855
|
-
const groupCode = String(payload.group_id);
|
|
856
|
-
if (payload.no_cache !== true && api.groupCache !== void 0) return toOb11GroupInfoDetail(await api.groupCache.getGroupDetail(groupCode));
|
|
857
|
-
return toOb11GroupInfoDetail(await api.groupApi.getGroupInfo(groupCode));
|
|
858
|
-
}
|
|
859
|
-
}),
|
|
860
|
-
defineOb11Action({
|
|
861
|
-
name: "get_group_list",
|
|
862
|
-
schema: z.object({
|
|
863
|
-
/** 是否忽略缓存(go-cqhttp 扩展)。 */
|
|
864
|
-
no_cache: z.boolean().optional() }),
|
|
865
|
-
handle: async (payload) => {
|
|
866
|
-
return (api.groupCache === void 0 ? await api.groupApi.getGroupList(true) : payload.no_cache === true ? await api.groupCache.listGroupsRefreshed() : api.groupCache.listGroups()).map(toOb11GroupInfo);
|
|
867
|
-
}
|
|
868
|
-
}),
|
|
869
|
-
defineOb11Action({
|
|
870
|
-
name: "get_group_member_info",
|
|
871
|
-
schema: z.object({
|
|
872
|
-
group_id: z.number(),
|
|
873
|
-
user_id: z.number(),
|
|
874
|
-
/** 是否忽略缓存(go-cqhttp 扩展)。 */
|
|
875
|
-
no_cache: z.boolean().optional()
|
|
876
|
-
}),
|
|
877
|
-
handle: async (payload) => {
|
|
878
|
-
const groupCode = String(payload.group_id);
|
|
879
|
-
const uid = (await api.groupApi.uinToUid([String(payload.user_id)])).get(String(payload.user_id));
|
|
880
|
-
if (uid === void 0) throw kernelError(`成员 ${payload.user_id} 不在群 ${payload.group_id}`, "NOT_FOUND");
|
|
881
|
-
let member;
|
|
882
|
-
if (payload.no_cache === true || api.groupCache === void 0) {
|
|
883
|
-
const [first] = await api.groupApi.getGroupMemberInfo(groupCode, [uid]);
|
|
884
|
-
member = first;
|
|
885
|
-
} else member = await api.groupCache.getMember(groupCode, uid);
|
|
886
|
-
if (member === void 0) throw kernelError(`成员 ${payload.user_id} 不在群 ${payload.group_id}`, "NOT_FOUND");
|
|
887
|
-
const uinMap = await api.groupApi.uidToUin([uid]);
|
|
888
|
-
return toOb11GroupMemberInfo(groupCode, member, uinMap);
|
|
889
|
-
}
|
|
890
|
-
}),
|
|
891
|
-
defineOb11Action({
|
|
892
|
-
name: "get_group_member_list",
|
|
893
|
-
schema: z.object({
|
|
894
|
-
group_id: z.number(),
|
|
895
|
-
/** 是否忽略缓存(go-cqhttp 扩展)。 */
|
|
896
|
-
no_cache: z.boolean().optional()
|
|
897
|
-
}),
|
|
898
|
-
handle: async (payload) => {
|
|
899
|
-
const groupCode = String(payload.group_id);
|
|
900
|
-
const noCache = payload.no_cache === true;
|
|
901
|
-
let members;
|
|
902
|
-
if (noCache || api.groupCache === void 0) members = await api.groupApi.getGroupMemberList(groupCode, noCache);
|
|
903
|
-
else members = await api.groupCache.getMembers(groupCode);
|
|
904
|
-
const uinMap = await api.groupApi.uidToUin(members.map((m) => m.uid));
|
|
905
|
-
return members.map((m) => toOb11GroupMemberInfo(groupCode, m, uinMap));
|
|
906
|
-
}
|
|
907
|
-
}),
|
|
908
|
-
defineOb11Action({
|
|
909
|
-
name: "get_group_at_all_remain",
|
|
910
|
-
schema: z.object({ group_id: z.number() }),
|
|
911
|
-
handle: async (payload) => {
|
|
912
|
-
const remain = await api.groupApi.getGroupRemainAtTimes(String(payload.group_id));
|
|
913
|
-
return {
|
|
914
|
-
can_at_all: remain.canAtAll,
|
|
915
|
-
remain_at_all_count_for_uin: remain.remainAtAllCountForUin,
|
|
916
|
-
remain_at_all_count_for_group: remain.remainAtAllCountForGroup
|
|
917
|
-
};
|
|
918
|
-
}
|
|
919
|
-
})
|
|
920
|
-
];
|
|
921
|
-
}
|
|
922
|
-
// src/onebot11/action/group/system-msg.ts
|
|
923
|
-
/** 默认获取数量。 */
|
|
924
|
-
const DEFAULT_COUNT = 50;
|
|
925
|
-
/** 收集全部涉及的 uid 批量转 uin(循环外一次请求)。 */
|
|
926
|
-
async function collectUinMap(api, notifies) {
|
|
927
|
-
const uids = [];
|
|
928
|
-
for (const notify of notifies) {
|
|
929
|
-
const { user1, user2 } = notify;
|
|
930
|
-
if (user1 !== void 0) {
|
|
931
|
-
const { uid } = user1;
|
|
932
|
-
if (uid !== "") uids.push(uid);
|
|
933
|
-
}
|
|
934
|
-
if (user2 !== void 0) {
|
|
935
|
-
const { uid } = user2;
|
|
936
|
-
if (uid !== "") uids.push(uid);
|
|
937
|
-
}
|
|
938
|
-
}
|
|
939
|
-
if (uids.length === 0) return /* @__PURE__ */ new Map();
|
|
940
|
-
return await api.uidToUin(uids);
|
|
941
|
-
}
|
|
942
|
-
/** GroupNotify → OB11 群系统消息结构(纯函数,uin 已批量转换)。 */
|
|
943
|
-
function toMessageInfo(notify, uinMap) {
|
|
944
|
-
const { seq, status, postscript, user1, user2, group } = notify;
|
|
945
|
-
let user1Uid = "";
|
|
946
|
-
if (user1 !== void 0) {
|
|
947
|
-
const { uid } = user1;
|
|
948
|
-
user1Uid = uid;
|
|
949
|
-
}
|
|
950
|
-
let user2Uid = "";
|
|
951
|
-
if (user2 !== void 0) {
|
|
952
|
-
const { uid } = user2;
|
|
953
|
-
user2Uid = uid;
|
|
954
|
-
}
|
|
955
|
-
let groupCode = 0;
|
|
956
|
-
let groupName = "";
|
|
957
|
-
if (group !== void 0) {
|
|
958
|
-
const { groupCode: code, groupName: name } = group;
|
|
959
|
-
groupCode = Number(code);
|
|
960
|
-
groupName = name;
|
|
961
|
-
}
|
|
962
|
-
let invitorUin = Number(user1Uid);
|
|
963
|
-
const mapped1 = uinMap.get(user1Uid);
|
|
964
|
-
if (mapped1 !== void 0) invitorUin = Number(mapped1);
|
|
965
|
-
let actor = Number(user2Uid);
|
|
966
|
-
const mapped2 = uinMap.get(user2Uid);
|
|
967
|
-
if (mapped2 !== void 0) actor = Number(mapped2);
|
|
968
|
-
let invitorNick = "";
|
|
969
|
-
if (user1 !== void 0) {
|
|
970
|
-
const { nickName } = user1;
|
|
971
|
-
invitorNick = nickName;
|
|
972
|
-
}
|
|
973
|
-
return {
|
|
974
|
-
request_id: Number(seq),
|
|
975
|
-
invitor_uin: invitorUin,
|
|
976
|
-
invitor_nick: invitorNick,
|
|
977
|
-
group_id: groupCode,
|
|
978
|
-
message: postscript ?? "",
|
|
979
|
-
group_name: groupName,
|
|
980
|
-
checked: status !== 1,
|
|
981
|
-
actor,
|
|
982
|
-
requester_nick: invitorNick
|
|
983
|
-
};
|
|
984
|
-
}
|
|
985
|
-
/** 群系统消息动作工厂(get_group_system_msg)。 */
|
|
986
|
-
function createGroupSystemMsgActions(api) {
|
|
987
|
-
return [defineOb11Action({
|
|
988
|
-
name: "get_group_system_msg",
|
|
989
|
-
schema: z.object({ count: z.number().optional() }),
|
|
990
|
-
handle: async (payload) => {
|
|
991
|
-
const count = payload.count ?? DEFAULT_COUNT;
|
|
992
|
-
const notifies = await api.groupNotifyApi.getSingleScreenNotifies(false, count);
|
|
993
|
-
const uinMap = await collectUinMap(api, notifies);
|
|
994
|
-
const invited = [];
|
|
995
|
-
const joined = [];
|
|
996
|
-
for (const notify of notifies) {
|
|
997
|
-
const info = toMessageInfo(notify, uinMap);
|
|
998
|
-
if (notify.type === GroupNotifyMsgType.INVITED_BY_MEMBER) invited.push(info);
|
|
999
|
-
else if (notify.type === GroupNotifyMsgType.REQUEST_JOIN_NEED_ADMINI_STRATOR_PASS) joined.push(info);
|
|
1000
|
-
}
|
|
1001
|
-
const result = {
|
|
1002
|
-
invited_requests: invited,
|
|
1003
|
-
join_requests: joined
|
|
1004
|
-
};
|
|
1005
|
-
result["InvitedRequest"] = invited;
|
|
1006
|
-
return result;
|
|
1007
|
-
}
|
|
1008
|
-
})];
|
|
1009
|
-
}
|
|
1010
|
-
// src/onebot11/helper/codec/cqcode.ts
|
|
1011
|
-
/**
|
|
1012
|
-
* CQ 码编解码(OneBot 11 消息段序列化格式)
|
|
1013
|
-
*
|
|
1014
|
-
* 纯函数、无 OB11 类型依赖:本文件只处理「文本 ↔ CQ 码片段」的通用编解码,
|
|
1015
|
-
* segment 级别的映射在 data.ts(OB11Constructor)。
|
|
1016
|
-
*
|
|
1017
|
-
* 转义规则(OneBot 11 规范):
|
|
1018
|
-
* - 纯文本:& → &,[ → [,] → ]
|
|
1019
|
-
* - 参数值:额外 , → ,
|
|
1020
|
-
*/
|
|
1021
|
-
/** 解析单个 CQ 码文本 → 结构化 CqCode。 */
|
|
1022
|
-
function parseCqCode(raw) {
|
|
1023
|
-
const body = raw.slice(4, -1);
|
|
1024
|
-
const firstComma = body.indexOf(",");
|
|
1025
|
-
let type = body;
|
|
1026
|
-
if (firstComma !== -1) type = body.slice(0, firstComma);
|
|
1027
|
-
const params = {};
|
|
1028
|
-
if (firstComma !== -1) for (const pair of body.slice(firstComma + 1).split(",")) {
|
|
1029
|
-
const eq = pair.indexOf("=");
|
|
1030
|
-
if (eq > 0) params[pair.slice(0, eq)] = unescapeCqText(pair.slice(eq + 1));
|
|
1031
|
-
}
|
|
1032
|
-
return {
|
|
1033
|
-
type,
|
|
1034
|
-
params
|
|
1035
|
-
};
|
|
1036
|
-
}
|
|
1037
|
-
/** 转义纯文本(& [ ];& 必须先转,避免二次转义)。 */
|
|
1038
|
-
function escapeCqText(text) {
|
|
1039
|
-
return text.replaceAll("&", "&").replaceAll("[", "[").replaceAll("]", "]");
|
|
1040
|
-
}
|
|
1041
|
-
/** 转义 CQ 码参数值(& [ ] ,)。 */
|
|
1042
|
-
function escapeCqParam(value) {
|
|
1043
|
-
return escapeCqText(value).replaceAll(",", ",");
|
|
1044
|
-
}
|
|
1045
|
-
/** 反转义(, ] [ &;& 必须最后解,避免二次转义误伤)。 */
|
|
1046
|
-
function unescapeCqText(text) {
|
|
1047
|
-
return text.replaceAll(",", ",").replaceAll("]", "]").replaceAll("[", "[").replaceAll("&", "&");
|
|
1048
|
-
}
|
|
1049
|
-
/** 编码单个 CQ 码(undefined 参数自动省略)。 */
|
|
1050
|
-
function encodeCqCode(type, params) {
|
|
1051
|
-
const pairs = [];
|
|
1052
|
-
for (const [key, value] of Object.entries(params)) if (value !== void 0) pairs.push(`${key}=${escapeCqParam(String(value))}`);
|
|
1053
|
-
if (pairs.length === 0) return `[CQ:${type}]`;
|
|
1054
|
-
return `[CQ:${type},${pairs.join(",")}]`;
|
|
1055
|
-
}
|
|
1056
|
-
/**
|
|
1057
|
-
* 解析一条消息文本 → 文本片段与 CQ 码片段的混合数组(文本已反转义)。
|
|
1058
|
-
*
|
|
1059
|
-
* 手工 indexOf 扫描而非全局正则(/\[CQ:[^\]]*\]/g):消息文本不可信,正则在
|
|
1060
|
-
* 「大量 [CQ: 前缀且无闭合 ]」的输入下每个起点都全量回扫,复杂度 O(n²)
|
|
1061
|
-
* (CodeQL polynomial-redos)。indexOf 语义等价:从 [CQ: 起到其后第一个 ]。
|
|
1062
|
-
*/
|
|
1063
|
-
function parseCqMessage(text) {
|
|
1064
|
-
const parts = [];
|
|
1065
|
-
let lastIndex = 0;
|
|
1066
|
-
let start = text.indexOf("[CQ:");
|
|
1067
|
-
while (start !== -1) {
|
|
1068
|
-
const end = text.indexOf("]", start);
|
|
1069
|
-
if (end === -1) break;
|
|
1070
|
-
if (start > lastIndex) parts.push(unescapeCqText(text.slice(lastIndex, start)));
|
|
1071
|
-
parts.push(parseCqCode(text.slice(start, end + 1)));
|
|
1072
|
-
lastIndex = end + 1;
|
|
1073
|
-
start = text.indexOf("[CQ:", lastIndex);
|
|
1074
|
-
}
|
|
1075
|
-
if (lastIndex < text.length) parts.push(unescapeCqText(text.slice(lastIndex)));
|
|
1076
|
-
return parts;
|
|
1077
|
-
}
|
|
1078
|
-
/** 将混合片段数组序列化回消息文本(parseCqMessage 的逆操作)。 */
|
|
1079
|
-
function serializeCqParts(parts) {
|
|
1080
|
-
let out = "";
|
|
1081
|
-
for (const part of parts) if (typeof part === "string") out += escapeCqText(part);
|
|
1082
|
-
else out += encodeCqCode(part.type, part.params);
|
|
1083
|
-
return out;
|
|
1084
|
-
}
|
|
1085
|
-
// src/onebot11/helper/codec/segment.ts
|
|
1086
|
-
/** OB11 媒体段 data(image/record/video 共用,url 可选)。 */
|
|
1087
|
-
function mediaData(file, url) {
|
|
1088
|
-
const data = { file };
|
|
1089
|
-
if (url !== void 0) data.url = url;
|
|
1090
|
-
return data;
|
|
1091
|
-
}
|
|
1092
|
-
/** OB11 at 段 data(name 可选)。 */
|
|
1093
|
-
function atData(qq, name) {
|
|
1094
|
-
const data = { qq };
|
|
1095
|
-
if (name !== void 0) data.name = name;
|
|
1096
|
-
return data;
|
|
1097
|
-
}
|
|
1098
|
-
/** canonical at 元素(display 可选)。 */
|
|
1099
|
-
function canonicalAt(target, display) {
|
|
1100
|
-
const el = {
|
|
1101
|
-
type: "at",
|
|
1102
|
-
target
|
|
1103
|
-
};
|
|
1104
|
-
if (display !== void 0) el.display = display;
|
|
1105
|
-
return el;
|
|
1106
|
-
}
|
|
1107
|
-
/** canonical 媒体元素(image/voice/video,url 可选;type 为联合需断言收窄)。 */
|
|
1108
|
-
function canonicalMedia(type, path, url) {
|
|
1109
|
-
const el = {
|
|
1110
|
-
type,
|
|
1111
|
-
path
|
|
1112
|
-
};
|
|
1113
|
-
if (url !== void 0) el.url = url;
|
|
1114
|
-
return el;
|
|
1115
|
-
}
|
|
1116
|
-
/** canonical json/xml 的 raw → OB11 data 字符串(字符串原样,对象序列化)。 */
|
|
1117
|
-
function rawToString(raw) {
|
|
1118
|
-
if (typeof raw === "string") return raw;
|
|
1119
|
-
return JSON.stringify(raw);
|
|
1120
|
-
}
|
|
1121
|
-
/** canonical 元素 → OB11 segment 转换器(键 = canonical type,判别字段收窄)。 */
|
|
1122
|
-
const CANONICAL_TO_SEGMENT = {
|
|
1123
|
-
text: (el) => ({
|
|
1124
|
-
type: "text",
|
|
1125
|
-
data: { text: el.text }
|
|
1126
|
-
}),
|
|
1127
|
-
at: (el) => ({
|
|
1128
|
-
type: "at",
|
|
1129
|
-
data: atData(el.target, el.display)
|
|
1130
|
-
}),
|
|
1131
|
-
image: (el) => ({
|
|
1132
|
-
type: "image",
|
|
1133
|
-
data: mediaData(el.path, el.url)
|
|
1134
|
-
}),
|
|
1135
|
-
face: (el) => ({
|
|
1136
|
-
type: "face",
|
|
1137
|
-
data: { id: el.id }
|
|
1138
|
-
}),
|
|
1139
|
-
voice: (el) => ({
|
|
1140
|
-
type: "record",
|
|
1141
|
-
data: mediaData(el.path, el.url)
|
|
1142
|
-
}),
|
|
1143
|
-
video: (el) => ({
|
|
1144
|
-
type: "video",
|
|
1145
|
-
data: mediaData(el.path, el.url)
|
|
1146
|
-
}),
|
|
1147
|
-
file: (el) => ({
|
|
1148
|
-
type: "file",
|
|
1149
|
-
data: { file: el.name ?? el.path }
|
|
1150
|
-
}),
|
|
1151
|
-
reply: (el) => ({
|
|
1152
|
-
type: "reply",
|
|
1153
|
-
data: { id: el.messageId }
|
|
1154
|
-
}),
|
|
1155
|
-
forward: (el) => ({
|
|
1156
|
-
type: "forward",
|
|
1157
|
-
data: { id: el.messageIds[0] ?? "" }
|
|
1158
|
-
}),
|
|
1159
|
-
json: (el) => ({
|
|
1160
|
-
type: "json",
|
|
1161
|
-
data: { data: rawToString(el.raw) }
|
|
1162
|
-
}),
|
|
1163
|
-
xml: (el) => ({
|
|
1164
|
-
type: "xml",
|
|
1165
|
-
data: { data: rawToString(el.raw) }
|
|
1166
|
-
})
|
|
1167
|
-
};
|
|
1168
|
-
/** canonical 元素 → OB11 segment(null = OB11 无法表达,跳过)。 */
|
|
1169
|
-
function canonicalToSegment(el) {
|
|
1170
|
-
const builder = CANONICAL_TO_SEGMENT[el.type];
|
|
1171
|
-
return builder === void 0 ? null : builder(el);
|
|
1172
|
-
}
|
|
1173
|
-
/** OB11 segment → canonical 元素转换器(键 = segment type)。 */
|
|
1174
|
-
const SEGMENT_TO_CANONICAL = {
|
|
1175
|
-
text: (seg) => ({
|
|
1176
|
-
type: "text",
|
|
1177
|
-
text: seg.data.text
|
|
1178
|
-
}),
|
|
1179
|
-
string: (seg) => ({
|
|
1180
|
-
type: "text",
|
|
1181
|
-
text: seg.data.text
|
|
1182
|
-
}),
|
|
1183
|
-
at: (seg) => canonicalAt(seg.data.qq, seg.data.name),
|
|
1184
|
-
face: (seg) => ({
|
|
1185
|
-
type: "face",
|
|
1186
|
-
id: seg.data.id
|
|
1187
|
-
}),
|
|
1188
|
-
image: (seg) => canonicalMedia("image", seg.data.file, seg.data.url),
|
|
1189
|
-
record: (seg) => canonicalMedia("voice", seg.data.file, seg.data.url),
|
|
1190
|
-
video: (seg) => canonicalMedia("video", seg.data.file, seg.data.url),
|
|
1191
|
-
reply: (seg) => ({
|
|
1192
|
-
type: "reply",
|
|
1193
|
-
messageId: seg.data.id
|
|
1194
|
-
}),
|
|
1195
|
-
forward: (seg) => ({
|
|
1196
|
-
type: "forward",
|
|
1197
|
-
messageIds: [seg.data.id]
|
|
1198
|
-
}),
|
|
1199
|
-
json: (seg) => ({
|
|
1200
|
-
type: "json",
|
|
1201
|
-
raw: seg.data.data
|
|
1202
|
-
}),
|
|
1203
|
-
xml: (seg) => ({
|
|
1204
|
-
type: "xml",
|
|
1205
|
-
raw: seg.data.data
|
|
1206
|
-
})
|
|
1207
|
-
};
|
|
1208
|
-
/** OB11 segment → canonical 元素(未知 type 兜底按 xml 处理,保持既有行为)。 */
|
|
1209
|
-
function segmentToCanonical(seg) {
|
|
1210
|
-
const builder = SEGMENT_TO_CANONICAL[seg.type];
|
|
1211
|
-
if (builder !== void 0) return builder(seg);
|
|
1212
|
-
const xmlBuilder = SEGMENT_TO_CANONICAL["xml"];
|
|
1213
|
-
return xmlBuilder === void 0 ? null : xmlBuilder(seg);
|
|
1214
|
-
}
|
|
1215
|
-
/** 已知 CQ 类型 → segment 构造器。 */
|
|
1216
|
-
const CQ_SEGMENT_BUILDERS = {
|
|
1217
|
-
text: (params) => ({
|
|
1218
|
-
type: "text",
|
|
1219
|
-
data: { text: params["text"] ?? "" }
|
|
1220
|
-
}),
|
|
1221
|
-
at: (params) => ({
|
|
1222
|
-
type: "at",
|
|
1223
|
-
data: atData(params["qq"] ?? "", params["name"])
|
|
1224
|
-
}),
|
|
1225
|
-
face: (params) => ({
|
|
1226
|
-
type: "face",
|
|
1227
|
-
data: { id: params["id"] ?? "" }
|
|
1228
|
-
}),
|
|
1229
|
-
image: (params) => ({
|
|
1230
|
-
type: "image",
|
|
1231
|
-
data: mediaData(params["file"] ?? "", params["url"])
|
|
1232
|
-
}),
|
|
1233
|
-
record: (params) => ({
|
|
1234
|
-
type: "record",
|
|
1235
|
-
data: mediaData(params["file"] ?? "", params["url"])
|
|
1236
|
-
}),
|
|
1237
|
-
video: (params) => ({
|
|
1238
|
-
type: "video",
|
|
1239
|
-
data: mediaData(params["file"] ?? "", params["url"])
|
|
1240
|
-
}),
|
|
1241
|
-
file: (params) => ({
|
|
1242
|
-
type: "file",
|
|
1243
|
-
data: { file: params["file"] ?? "" }
|
|
1244
|
-
}),
|
|
1245
|
-
reply: (params) => ({
|
|
1246
|
-
type: "reply",
|
|
1247
|
-
data: { id: params["id"] ?? "" }
|
|
1248
|
-
}),
|
|
1249
|
-
forward: (params) => ({
|
|
1250
|
-
type: "forward",
|
|
1251
|
-
data: { id: params["id"] ?? "" }
|
|
1252
|
-
}),
|
|
1253
|
-
json: (params) => ({
|
|
1254
|
-
type: "json",
|
|
1255
|
-
data: { data: params["data"] ?? "" }
|
|
1256
|
-
}),
|
|
1257
|
-
xml: (params) => ({
|
|
1258
|
-
type: "xml",
|
|
1259
|
-
data: { data: params["data"] ?? "" }
|
|
1260
|
-
})
|
|
1261
|
-
};
|
|
1262
|
-
/** CQ 码片段 → OB11 segment(未知类型保留原文为 text 段,往返不丢数据)。 */
|
|
1263
|
-
function cqCodeToSegment(code) {
|
|
1264
|
-
const builder = CQ_SEGMENT_BUILDERS[code.type];
|
|
1265
|
-
if (builder === void 0) return {
|
|
1266
|
-
type: "text",
|
|
1267
|
-
data: { text: encodeCqCode(code.type, code.params) }
|
|
1268
|
-
};
|
|
1269
|
-
return builder(code.params);
|
|
1270
|
-
}
|
|
1271
|
-
/** OB11 segment 数组 → CQ 码字符串(text 段转义拼接,特殊段编码)。 */
|
|
1272
|
-
function segmentsToCqMessage(segments) {
|
|
1273
|
-
let out = "";
|
|
1274
|
-
for (const seg of segments) if (seg.type === "text" || seg.type === "string") out += escapeCqText(seg.data.text);
|
|
1275
|
-
else out += encodeCqCode(seg.type, seg.data);
|
|
1276
|
-
return out;
|
|
1277
|
-
}
|
|
1278
|
-
// src/onebot11/helper/config.ts
|
|
1279
|
-
/**
|
|
1280
|
-
* OneBot 11 协议配置(zod schema,归属本包)
|
|
1281
|
-
* 协议配置 schema 在各自协议包,kernel 只提供 ConfigBase 基类。
|
|
1282
|
-
*
|
|
1283
|
-
* 多实例化:对齐 NapCat——httpServers / httpPostUrls / wsServers /
|
|
1284
|
-
* wsReverseUrls 四个数组实例(每实例可覆盖全局 token);旧单对象字段 http/httpPost/ws/
|
|
1285
|
-
* wsReverse 废弃(zod strip 静默忽略,不兼容迁移)。
|
|
1286
|
-
*/
|
|
1287
|
-
/** HTTP 反向服务器默认端口。 */
|
|
1288
|
-
const DEFAULT_HTTP_PORT = 3e3;
|
|
1289
|
-
/** 反向 WS server 默认端口。 */
|
|
1290
|
-
const DEFAULT_WS_PORT = 3001;
|
|
1291
|
-
/** 心跳 meta 事件默认间隔(毫秒)。 */
|
|
1292
|
-
const DEFAULT_HEARTBEAT_INTERVAL_MS = 3e3;
|
|
1293
|
-
/** WS 传输 ping 默认间隔(毫秒)。 */
|
|
1294
|
-
const DEFAULT_WS_HEARTBEAT_MS = 3e4;
|
|
1295
|
-
/** WS 反向断线重连默认延迟(毫秒)。 */
|
|
1296
|
-
const DEFAULT_RECONNECT_DELAY_MS = 5e3;
|
|
1297
|
-
/** 消息内容格式(NapCat messagePostFormat)。 */
|
|
1298
|
-
const MESSAGE_FORMATS = ["array", "string"];
|
|
1299
|
-
/** HTTP 反向服务器实例(第三方 POST 指令入口)。 */
|
|
1300
|
-
const httpServerSchema = createServerSchema(DEFAULT_HTTP_PORT);
|
|
1301
|
-
/** HTTP 正向上报实例(Webhook 事件推送)。 */
|
|
1302
|
-
const httpPostSchema = z.object({
|
|
1303
|
-
enabled: z.boolean().default(false),
|
|
1304
|
-
url: z.string().optional(),
|
|
1305
|
-
/** 实例级 token,覆盖全局 token(缺省继承全局)。 */
|
|
1306
|
-
token: z.string().optional(),
|
|
1307
|
-
/** 上报超时(毫秒),缺省不超时。 */
|
|
1308
|
-
timeoutMs: z.number().int().optional()
|
|
1309
|
-
});
|
|
1310
|
-
/** 反向 WS server 实例(第三方 WS 连入,带 WS ping 间隔扩展字段)。 */
|
|
1311
|
-
const wsServerSchema = createServerSchema(DEFAULT_WS_PORT).extend({
|
|
1312
|
-
/** WS ping 间隔(毫秒)。 */
|
|
1313
|
-
heartbeatInterval: z.number().int().default(DEFAULT_WS_HEARTBEAT_MS) });
|
|
1314
|
-
/** 正向 WS client 实例(主动连接第三方,双向)。 */
|
|
1315
|
-
const wsReverseSchema = z.object({
|
|
1316
|
-
enabled: z.boolean().default(false),
|
|
1317
|
-
url: z.string().optional(),
|
|
1318
|
-
/** 实例级 token,覆盖全局 token(缺省继承全局)。 */
|
|
1319
|
-
token: z.string().optional(),
|
|
1320
|
-
/** 断线重连延迟(毫秒)。 */
|
|
1321
|
-
reconnectDelayMs: z.number().int().default(DEFAULT_RECONNECT_DELAY_MS),
|
|
1322
|
-
/** 最大重连次数(缺省无限)。 */
|
|
1323
|
-
maxReconnectAttempts: z.number().int().optional(),
|
|
1324
|
-
/** wss:// 是否校验证书(自签证书场景设 false,对齐 NapCat enableSelfSigned)。 */
|
|
1325
|
-
rejectUnauthorized: z.boolean().default(true),
|
|
1326
|
-
/** WS ping 间隔(毫秒)。 */
|
|
1327
|
-
heartbeatInterval: z.number().int().default(DEFAULT_WS_HEARTBEAT_MS)
|
|
1328
|
-
});
|
|
1329
|
-
/** OB11 配置 schema。 */
|
|
1330
|
-
const ob11ConfigSchema = z.object({
|
|
1331
|
-
/** 鉴权 token(全局默认,实例未指定时继承)。 */
|
|
1332
|
-
token: z.string().optional(),
|
|
1333
|
-
/** 心跳 meta 事件间隔(毫秒),0 关闭心跳。 */
|
|
1334
|
-
heartbeatInterval: z.number().int().default(DEFAULT_HEARTBEAT_INTERVAL_MS),
|
|
1335
|
-
/** 是否上报机器人自己发的消息(缺省 false = OB11 规范行为)。 */
|
|
1336
|
-
reportSelfMessage: z.boolean().default(false),
|
|
1337
|
-
/** 消息内容格式:array = 消息段数组(标准),string = CQ 码字符串。 */
|
|
1338
|
-
messagePostFormat: z.enum(MESSAGE_FORMATS).default("array"),
|
|
1339
|
-
/**
|
|
1340
|
-
* 群文件报形式():false(缺省)= message 事件 + file 段
|
|
1341
|
-
* (go-cqhttp 兼容;此前 file 元素被静默丢弃,本版本起透出);true = 含
|
|
1342
|
-
* fileElement 的群消息改报 group_upload notice 事件(替代 message 事件)。
|
|
1343
|
-
*/
|
|
1344
|
-
groupUploadAsNotice: z.boolean().default(false),
|
|
1345
|
-
/** HTTP 反向服务器列表。 */
|
|
1346
|
-
httpServers: z.array(httpServerSchema).default([]),
|
|
1347
|
-
/** HTTP 正向上报列表。 */
|
|
1348
|
-
httpPostUrls: z.array(httpPostSchema).default([]),
|
|
1349
|
-
/** 反向 WS server 列表。 */
|
|
1350
|
-
wsServers: z.array(wsServerSchema).default([]),
|
|
1351
|
-
/** 正向 WS client 列表。 */
|
|
1352
|
-
wsReverseUrls: z.array(wsReverseSchema).default([])
|
|
1353
|
-
});
|
|
1354
|
-
// src/onebot11/helper/data.ts
|
|
1355
|
-
/** canonical 元素数组 → OB11 segment 数组(无法表达的元素静默跳过)。 */
|
|
1356
|
-
function canonicalToSegments(elements) {
|
|
1357
|
-
const segments = [];
|
|
1358
|
-
for (const el of elements) {
|
|
1359
|
-
const seg = canonicalToSegment(el);
|
|
1360
|
-
if (seg !== null) segments.push(seg);
|
|
1361
|
-
}
|
|
1362
|
-
return segments;
|
|
1363
|
-
}
|
|
1364
|
-
/** OB11 segment 数组 → canonical 元素数组。 */
|
|
1365
|
-
function segmentsToCanonical(segments) {
|
|
1366
|
-
const elements = [];
|
|
1367
|
-
for (const seg of segments) {
|
|
1368
|
-
const el = segmentToCanonical(seg);
|
|
1369
|
-
if (el !== null) elements.push(el);
|
|
1370
|
-
}
|
|
1371
|
-
return elements;
|
|
1372
|
-
}
|
|
1373
|
-
/**
|
|
1374
|
-
* 收集 canonical 元素里需要转换的 at uid / reply NT msgId(接收方向)。
|
|
1375
|
-
* 调用方据此批量 uidToUin(一次异步调用),避免逐元素查询。
|
|
1376
|
-
*/
|
|
1377
|
-
function collectReceiveNeeds(elements) {
|
|
1378
|
-
const atUids = /* @__PURE__ */ new Set();
|
|
1379
|
-
const replyMsgIds = /* @__PURE__ */ new Set();
|
|
1380
|
-
for (const el of elements) if (el.type === "at" && el.target !== "all") atUids.add(el.target);
|
|
1381
|
-
else if (el.type === "reply") replyMsgIds.add(el.messageId);
|
|
1382
|
-
return {
|
|
1383
|
-
atUids: [...atUids],
|
|
1384
|
-
replyMsgIds: [...replyMsgIds]
|
|
1385
|
-
};
|
|
1386
|
-
}
|
|
1387
|
-
/**
|
|
1388
|
-
* canonical 元素数组 → 应用接收方向 ID 转换(at uid→uin、reply NT msgId→OB11 id)。
|
|
1389
|
-
* 转换失败的元素原样保留(uid 未解析 / msgId 未映射——不阻塞上报)。
|
|
1390
|
-
*/
|
|
1391
|
-
function applyReceiveContext(elements, ctx) {
|
|
1392
|
-
if (ctx.uidToUin === void 0 && ctx.msgIdToOb11Id === void 0) return elements;
|
|
1393
|
-
const out = [];
|
|
1394
|
-
for (const el of elements) {
|
|
1395
|
-
if (el.type === "at" && el.target !== "all") {
|
|
1396
|
-
const uin = ctx.uidToUin?.get(el.target);
|
|
1397
|
-
out.push(uin !== void 0 ? {
|
|
1398
|
-
...el,
|
|
1399
|
-
target: uin
|
|
1400
|
-
} : el);
|
|
1401
|
-
continue;
|
|
1402
|
-
}
|
|
1403
|
-
if (el.type === "reply") {
|
|
1404
|
-
const id = ctx.msgIdToOb11Id?.(el.messageId);
|
|
1405
|
-
out.push(id !== void 0 ? {
|
|
1406
|
-
...el,
|
|
1407
|
-
messageId: String(id)
|
|
1408
|
-
} : el);
|
|
1409
|
-
continue;
|
|
1410
|
-
}
|
|
1411
|
-
out.push(el);
|
|
1412
|
-
}
|
|
1413
|
-
return out;
|
|
1414
|
-
}
|
|
1415
|
-
/** at 段:uin → uid(缺省不转换)。 */
|
|
1416
|
-
function translateAtElement(el, ctx) {
|
|
1417
|
-
const uid = ctx.uinToUid?.get(el.target);
|
|
1418
|
-
return uid !== void 0 ? {
|
|
1419
|
-
...el,
|
|
1420
|
-
target: uid
|
|
1421
|
-
} : el;
|
|
1422
|
-
}
|
|
1423
|
-
/** reply 段:OB11 message_id → NT msgId(反查不到原样透传)。 */
|
|
1424
|
-
function translateReplyElement(el, ctx) {
|
|
1425
|
-
const num = Number(el.messageId);
|
|
1426
|
-
if (Number.isNaN(num)) return el;
|
|
1427
|
-
const msgId = ctx.ob11IdToMsgId?.(num);
|
|
1428
|
-
return msgId !== void 0 ? {
|
|
1429
|
-
...el,
|
|
1430
|
-
messageId: msgId
|
|
1431
|
-
} : el;
|
|
1432
|
-
}
|
|
1433
|
-
/**
|
|
1434
|
-
* canonical 元素数组 → 应用发送方向 ID 转换(at uin→uid、reply OB11 id→NT msgId)。
|
|
1435
|
-
* reply 反查不到时原样透传(兼容客户端直接给 NT msgId 的输入,不报错)。
|
|
1436
|
-
*/
|
|
1437
|
-
function applySendContext(elements, ctx) {
|
|
1438
|
-
if (ctx.uinToUid === void 0 && ctx.ob11IdToMsgId === void 0) return elements;
|
|
1439
|
-
const out = [];
|
|
1440
|
-
for (const el of elements) {
|
|
1441
|
-
if (el.type === "at" && el.target !== "all") {
|
|
1442
|
-
out.push(translateAtElement(el, ctx));
|
|
1443
|
-
continue;
|
|
1444
|
-
}
|
|
1445
|
-
if (el.type === "reply") {
|
|
1446
|
-
out.push(translateReplyElement(el, ctx));
|
|
1447
|
-
continue;
|
|
1448
|
-
}
|
|
1449
|
-
out.push(el);
|
|
1450
|
-
}
|
|
1451
|
-
return out;
|
|
1452
|
-
}
|
|
1453
|
-
/** CQ 码字符串 → OB11 segment 数组(未知 CQ 类型保留为 text 段原文)。 */
|
|
1454
|
-
function cqMessageToSegments(text) {
|
|
1455
|
-
const segments = [];
|
|
1456
|
-
for (const part of parseCqMessage(text)) if (typeof part === "string") {
|
|
1457
|
-
if (part.length > 0) segments.push({
|
|
1458
|
-
type: "text",
|
|
1459
|
-
data: { text: part }
|
|
1460
|
-
});
|
|
1461
|
-
} else {
|
|
1462
|
-
const seg = cqCodeToSegment(part);
|
|
1463
|
-
if (seg !== null) segments.push(seg);
|
|
1464
|
-
}
|
|
1465
|
-
return segments;
|
|
1466
|
-
}
|
|
1467
|
-
/** canonical 元素数组 → CQ 码字符串。 */
|
|
1468
|
-
function canonicalToCqMessage(elements) {
|
|
1469
|
-
return segmentsToCqMessage(canonicalToSegments(elements));
|
|
1470
|
-
}
|
|
1471
|
-
/** CQ 码字符串 → canonical 元素数组。 */
|
|
1472
|
-
function cqMessageToCanonical(text) {
|
|
1473
|
-
return segmentsToCanonical(cqMessageToSegments(text));
|
|
1474
|
-
}
|
|
1475
|
-
// src/onebot11/helper/message-info.ts
|
|
1476
|
-
/** RawMessage → OB11 消息信息(message_id 经 MessageUnique 映射)。
|
|
1477
|
-
* ctx(可选):接收方向 ID 转换上下文(at uid→uin、reply NT msgId→OB11 id)。 */
|
|
1478
|
-
function toOb11MessageInfo(msg, unique, ctx = {}) {
|
|
1479
|
-
const elements = applyReceiveContext(toCanonicalElements(msg), ctx);
|
|
1480
|
-
let messageType = "private";
|
|
1481
|
-
if (msg.chatType === ChatType.GROUP) messageType = "group";
|
|
1482
|
-
const info = {
|
|
1483
|
-
message_id: unique.alloc(msg.msgId, {
|
|
1484
|
-
chatType: msg.chatType,
|
|
1485
|
-
peerUid: msg.peerUid
|
|
1486
|
-
}),
|
|
1487
|
-
message_type: messageType,
|
|
1488
|
-
sender: {
|
|
1489
|
-
user_id: Number(msg.senderUin),
|
|
1490
|
-
nickname: senderNickname(msg)
|
|
1491
|
-
},
|
|
1492
|
-
time: toUnixSeconds(msg.msgTime),
|
|
1493
|
-
message: canonicalToSegments(elements),
|
|
1494
|
-
raw_message: canonicalToCqMessage(elements)
|
|
1495
|
-
};
|
|
1496
|
-
if (msg.chatType === ChatType.GROUP) {
|
|
1497
|
-
info.group_id = Number(msg.peerUid);
|
|
1498
|
-
const { sender } = info;
|
|
1499
|
-
sender.role = ctx.senderRole ?? "member";
|
|
1500
|
-
if (msg.sendMemberName !== void 0) sender.card = msg.sendMemberName;
|
|
1501
|
-
} else info.user_id = Number(msg.senderUin);
|
|
1502
|
-
return info;
|
|
1503
|
-
}
|
|
1504
|
-
// src/onebot11/helper/notice.ts
|
|
1505
|
-
/** 群文件业务类型(group_upload 的 file.busid,与 kernel 群文件系列同源语义)。 */
|
|
1506
|
-
const GROUP_FILE_BUS_ID = 102;
|
|
1507
|
-
/**
|
|
1508
|
-
* 检查消息是否含文件元素(group_upload 开关分支判定)。
|
|
1509
|
-
*
|
|
1510
|
-
* ⚠️ 用空值判定(`!= null`)而非 `!== undefined`(Linux 原生宿主):
|
|
1511
|
-
* Windows 原生对象省略未命中的元素变体字段,Linux 3.2.x 原生对象则把**全部**
|
|
1512
|
-
* 变体字段显式置 `null`(`"grayTipElement":null` 等)。用 `!== undefined`
|
|
1513
|
-
* 会把每条普通消息都判成「含该元素」——OB11 入站消息因此全部被误路由到
|
|
1514
|
-
* grayTip notice 分支并静默丢弃(真机复现)。
|
|
1515
|
-
*/
|
|
1516
|
-
function hasFileElement(msg) {
|
|
1517
|
-
return msg.elements.some((el) => el.fileElement != null);
|
|
1518
|
-
}
|
|
1519
|
-
/** 基础字段(time/self_id/post_type)。 */
|
|
1520
|
-
function base(msg, ctx) {
|
|
1521
|
-
return {
|
|
1522
|
-
time: toUnixSeconds(msg.msgTime),
|
|
1523
|
-
self_id: Number(ctx.selfUin),
|
|
1524
|
-
post_type: "notice",
|
|
1525
|
-
group_id: Number(msg.peerUid)
|
|
1526
|
-
};
|
|
1527
|
-
}
|
|
1528
|
-
/** 撤回事件(chatType 分流:GROUP→group_recall / C2C→friend_recall)。 */
|
|
1529
|
-
function toRecall(msg, g, ctx) {
|
|
1530
|
-
if (g?.revokeElement == null) return null;
|
|
1531
|
-
const revoke = g.revokeElement;
|
|
1532
|
-
if (msg.chatType === ChatType.C2C) return {
|
|
1533
|
-
time: toUnixSeconds(msg.msgTime),
|
|
1534
|
-
self_id: Number(ctx.selfUin),
|
|
1535
|
-
post_type: "notice",
|
|
1536
|
-
notice_type: "friend_recall",
|
|
1537
|
-
user_id: toUin(revoke.operatorUid, ctx),
|
|
1538
|
-
message_id: Number(msg.msgSeq)
|
|
1539
|
-
};
|
|
1540
|
-
return {
|
|
1541
|
-
...base(msg, ctx),
|
|
1542
|
-
notice_type: "group_recall",
|
|
1543
|
-
user_id: toUin(revoke.operatorUid, ctx),
|
|
1544
|
-
operator_id: toUin(revoke.operatorUid, ctx),
|
|
1545
|
-
message_id: Number(msg.msgSeq)
|
|
1546
|
-
};
|
|
1547
|
-
}
|
|
1548
|
-
/**
|
|
1549
|
-
* 戳一戳(notify.poke,aioOpGrayTipElement)。
|
|
1550
|
-
*
|
|
1551
|
-
* ⚠️ 待真实 poke 事件验证:aioOp 载荷的完整字段形状未经实测(实体类型仅有
|
|
1552
|
-
* operateType/peerUid 两个已证字段)。当前口径:user_id = 消息发送者,
|
|
1553
|
-
* target_id = aioOp.peerUid(C2C 即对端;群内为目标 uid 的假设待校准),
|
|
1554
|
-
* group_id = 群号(C2C 为 0)。poke 路径始终打 raw 日志积累校准数据。
|
|
1555
|
-
*/
|
|
1556
|
-
function toPoke(msg, g, ctx) {
|
|
1557
|
-
const aioOp = g?.aioOpGrayTipElement;
|
|
1558
|
-
ctx.logger?.warn({ raw: JSON.stringify(g)?.slice(0, 2e3) }, "ob11: poke grayTip raw(待真实事件校准)");
|
|
1559
|
-
const isGroup = msg.chatType === ChatType.GROUP;
|
|
1560
|
-
return {
|
|
1561
|
-
time: toUnixSeconds(msg.msgTime),
|
|
1562
|
-
self_id: Number(ctx.selfUin),
|
|
1563
|
-
post_type: "notice",
|
|
1564
|
-
notice_type: "notify",
|
|
1565
|
-
sub_type: "poke",
|
|
1566
|
-
group_id: isGroup ? Number(msg.peerUid) : 0,
|
|
1567
|
-
user_id: toUin(msg.senderUid, ctx),
|
|
1568
|
-
target_id: toUin(aioOp?.peerUid ?? "", ctx)
|
|
1569
|
-
};
|
|
1570
|
-
}
|
|
1571
|
-
/** 群成员变动映射器表(键 = TipGroupElementType;缺项 = 不可翻译返回 null)。 */
|
|
1572
|
-
const GROUP_CHANGE_BUILDERS = {
|
|
1573
|
-
[TipGroupElementType.MEMBER_ADD]: toMemberAdd,
|
|
1574
|
-
[TipGroupElementType.QUIT]: toQuit,
|
|
1575
|
-
[TipGroupElementType.BLOCK]: toAdminChange,
|
|
1576
|
-
[TipGroupElementType.UNBLOCK]: toAdminChange,
|
|
1577
|
-
[TipGroupElementType.SHUT_UP]: toBan
|
|
1578
|
-
};
|
|
1579
|
-
/** 群成员变动(group_increase / group_decrease / group_admin / group_ban)。 */
|
|
1580
|
-
function toGroupChange(msg, g, ctx) {
|
|
1581
|
-
const grp = g?.groupElement;
|
|
1582
|
-
if (grp == null || grp.type === void 0) return null;
|
|
1583
|
-
const builder = GROUP_CHANGE_BUILDERS[grp.type];
|
|
1584
|
-
if (builder === void 0) return null;
|
|
1585
|
-
return builder({
|
|
1586
|
-
time: toUnixSeconds(msg.msgTime),
|
|
1587
|
-
selfId: Number(ctx.selfUin),
|
|
1588
|
-
groupId: Number(msg.peerUid),
|
|
1589
|
-
memberUid: grp.memberUid ?? "",
|
|
1590
|
-
adminUid: grp.adminUid ?? ""
|
|
1591
|
-
}, grp, ctx);
|
|
1592
|
-
}
|
|
1593
|
-
/** 群成员增加(approve=管理员操作 / invite=普通邀请)。 */
|
|
1594
|
-
function toMemberAdd(common, _grp, ctx) {
|
|
1595
|
-
const { time, selfId, groupId, memberUid, adminUid } = common;
|
|
1596
|
-
return {
|
|
1597
|
-
time,
|
|
1598
|
-
self_id: selfId,
|
|
1599
|
-
post_type: "notice",
|
|
1600
|
-
notice_type: "group_increase",
|
|
1601
|
-
sub_type: adminUid === memberUid ? "approve" : "invite",
|
|
1602
|
-
group_id: groupId,
|
|
1603
|
-
operator_id: toUin(adminUid, ctx),
|
|
1604
|
-
user_id: toUin(memberUid, ctx)
|
|
1605
|
-
};
|
|
1606
|
-
}
|
|
1607
|
-
/** 群成员退出(leave)。 */
|
|
1608
|
-
function toQuit(common, _grp, ctx) {
|
|
1609
|
-
const { time, selfId, groupId, memberUid, adminUid } = common;
|
|
1610
|
-
return {
|
|
1611
|
-
time,
|
|
1612
|
-
self_id: selfId,
|
|
1613
|
-
post_type: "notice",
|
|
1614
|
-
notice_type: "group_decrease",
|
|
1615
|
-
sub_type: "leave",
|
|
1616
|
-
group_id: groupId,
|
|
1617
|
-
operator_id: toUin(adminUid, ctx),
|
|
1618
|
-
user_id: toUin(memberUid, ctx)
|
|
1619
|
-
};
|
|
1620
|
-
}
|
|
1621
|
-
/** 管理员变更(BLOCK=set / UNBLOCK=unset)。 */
|
|
1622
|
-
function toAdminChange(common, grp, ctx) {
|
|
1623
|
-
const { time, selfId, groupId, memberUid, adminUid } = common;
|
|
1624
|
-
return {
|
|
1625
|
-
time,
|
|
1626
|
-
self_id: selfId,
|
|
1627
|
-
post_type: "notice",
|
|
1628
|
-
notice_type: "group_admin",
|
|
1629
|
-
sub_type: grp.type === TipGroupElementType.BLOCK ? "set" : "unset",
|
|
1630
|
-
group_id: groupId,
|
|
1631
|
-
user_id: toUin(memberUid === "" ? adminUid : memberUid, ctx)
|
|
1632
|
-
};
|
|
1633
|
-
}
|
|
1634
|
-
/** 禁言(duration>0=ban / 否则 lift_ban)。 */
|
|
1635
|
-
function toBan(common, grp, ctx) {
|
|
1636
|
-
const shutUp = grp.shutUp;
|
|
1637
|
-
const duration = Number(shutUp?.duration ?? 0);
|
|
1638
|
-
return {
|
|
1639
|
-
time: common.time,
|
|
1640
|
-
self_id: common.selfId,
|
|
1641
|
-
post_type: "notice",
|
|
1642
|
-
notice_type: "group_ban",
|
|
1643
|
-
sub_type: duration > 0 ? "ban" : "lift_ban",
|
|
1644
|
-
group_id: common.groupId,
|
|
1645
|
-
operator_id: toUin(shutUp?.admin?.uid ?? common.adminUid, ctx),
|
|
1646
|
-
user_id: toUin(shutUp?.member?.uid ?? common.memberUid, ctx),
|
|
1647
|
-
duration
|
|
1648
|
-
};
|
|
1649
|
-
}
|
|
1650
|
-
/**
|
|
1651
|
-
* 好友添加(friend_add,)。
|
|
1652
|
-
* 数据源 = kernel BuddyCache 快照 diff(Buddy/onBuddyListChange 全量快照对比,
|
|
1653
|
-
* 首帧 baseline 不发)——非 grayTip 路径。user_id 取 coreInfo.uin(顶层 uin 兜底)。
|
|
1654
|
-
*/
|
|
1655
|
-
function toFriendAdd(entry, selfUin) {
|
|
1656
|
-
const uin = entry.coreInfo?.uin ?? entry.uin ?? "";
|
|
1657
|
-
return {
|
|
1658
|
-
time: Math.floor(Date.now() / MS_TO_SEC),
|
|
1659
|
-
self_id: Number(selfUin),
|
|
1660
|
-
post_type: "notice",
|
|
1661
|
-
notice_type: "friend_add",
|
|
1662
|
-
user_id: Number(uin)
|
|
1663
|
-
};
|
|
1664
|
-
}
|
|
1665
|
-
/**
|
|
1666
|
-
* 群文件上传(group_upload,)。
|
|
1667
|
-
* 数据源 = 含 fileElement 的群消息(开关 groupUploadAsNotice=true 时替代
|
|
1668
|
-
* message 事件报出)。file.id 取 fileUuid(缺省文件名)、size 取 fileSize、
|
|
1669
|
-
* busid 固定 102(群文件业务类型,与 kernel GROUP_FILE_BIZ_TYPE 同源语义)。
|
|
1670
|
-
*/
|
|
1671
|
-
function toGroupUpload(msg, selfUin) {
|
|
1672
|
-
const file = msg.elements.find((e) => e.fileElement != null)?.fileElement;
|
|
1673
|
-
if (file === void 0) return null;
|
|
1674
|
-
return {
|
|
1675
|
-
time: toUnixSeconds(msg.msgTime),
|
|
1676
|
-
self_id: Number(selfUin),
|
|
1677
|
-
post_type: "notice",
|
|
1678
|
-
notice_type: "group_upload",
|
|
1679
|
-
group_id: Number(msg.peerUid),
|
|
1680
|
-
user_id: Number(msg.senderUin),
|
|
1681
|
-
file: {
|
|
1682
|
-
id: file.fileUuid ?? file.fileName ?? "",
|
|
1683
|
-
name: file.fileName ?? "",
|
|
1684
|
-
size: Number(file.fileSize ?? 0),
|
|
1685
|
-
busid: GROUP_FILE_BUS_ID
|
|
1686
|
-
}
|
|
1687
|
-
};
|
|
1688
|
-
}
|
|
1689
|
-
/** 单个 grayTip 元素 → notice 事件(null = 不可翻译;未知子类型打 raw 日志)。 */
|
|
1690
|
-
function translateGrayTip(msg, g, ctx) {
|
|
1691
|
-
const subType = g.subElementType;
|
|
1692
|
-
if (subType === GrayTipSubType.REVOKE) return toRecall(msg, g, ctx);
|
|
1693
|
-
if (subType === GrayTipSubType.GROUP) return toGroupChange(msg, g, ctx);
|
|
1694
|
-
if (g.aioOpGrayTipElement != null) return toPoke(msg, g, ctx);
|
|
1695
|
-
logUntranslatedGrayTip(msg, ctx);
|
|
1696
|
-
return null;
|
|
1697
|
-
}
|
|
1698
|
-
function logUntranslatedGrayTip(msg, ctx) {
|
|
1699
|
-
const untranslated = firstUntranslatedGrayTip(msg);
|
|
1700
|
-
if (untranslated !== void 0) ctx.logger?.warn({
|
|
1701
|
-
subType: untranslated.subElementType,
|
|
1702
|
-
raw: JSON.stringify(untranslated)?.slice(0, 2e3)
|
|
1703
|
-
}, "ob11: 未翻译的 grayTip 子类型(raw 校准数据)");
|
|
1704
|
-
}
|
|
1705
|
-
/** RawMessage → OB11 notice 事件(无 grayTip 返回 null)。
|
|
1706
|
-
* 未知/未翻译子类型打 raw JSON 日志(校准数据积累)。 */
|
|
1707
|
-
function toOb11NoticeEvent(msg, ctx) {
|
|
1708
|
-
for (const el of msg.elements) {
|
|
1709
|
-
const g = el.grayTipElement;
|
|
1710
|
-
if (g == null) continue;
|
|
1711
|
-
const event = translateGrayTip(msg, g, ctx);
|
|
1712
|
-
if (event !== null) return event;
|
|
1713
|
-
}
|
|
1714
|
-
return null;
|
|
1715
|
-
}
|
|
1716
|
-
// src/onebot11/helper/request.ts
|
|
1717
|
-
/**
|
|
1718
|
-
* OB11 request 事件翻译
|
|
1719
|
-
*
|
|
1720
|
-
* 事件源(kernel 事件通道,本次接线):
|
|
1721
|
-
* - `Group/onGroupNotifiesUpdated`(GroupBridge,群系统通知推送)→ group_add / group_invite
|
|
1722
|
-
* - `Buddy/onBuddyReqChange`(FriendBridge,好友申请推送)→ friend
|
|
1723
|
-
*
|
|
1724
|
-
* flag 语义(与应答动作匹配路径一致):
|
|
1725
|
-
* - 群请求 flag = GroupNotify.seq(set_group_add_request 按 `item.seq === flag` 匹配)
|
|
1726
|
-
* - 好友请求 flag = BuddyReq.reqTime(set_friend_add_request 按 `reqTime === flag` 匹配)
|
|
1727
|
-
*
|
|
1728
|
-
* 纯函数:uid→uin 由调用方批量转换后传入。
|
|
1729
|
-
* ⚠️ onBuddyReqChange 回调参数形状未经真实事件校准(wrapper 字符串证据仅有方法名),
|
|
1730
|
-
* narrowBuddyReqs 防御性收窄,未知形状返回 null 由调用方打 raw 日志积累校准数据。
|
|
1731
|
-
*/
|
|
1732
|
-
/**
|
|
1733
|
-
* GroupNotify → OB11 群请求事件(group_add / group_invite)。
|
|
1734
|
-
*
|
|
1735
|
-
* type 语义与 get_group_system_msg 动作同一解释:1/5=邀请(invite)、7=申请(add);
|
|
1736
|
-
* 仅未处理状态(KUNHANDLE)推送——已处理通知重复推送不再发事件。
|
|
1737
|
-
* 非请求类通知(踢人/转让等处理结果回执)返回 null。
|
|
1738
|
-
*/
|
|
1739
|
-
function toOb11GroupRequestEvent(notify, ctx) {
|
|
1740
|
-
if (notify.status !== GroupNotifyMsgStatus.KUNHANDLE) return null;
|
|
1741
|
-
let subType;
|
|
1742
|
-
switch (notify.type) {
|
|
1743
|
-
case GroupNotifyMsgType.INVITED_BY_MEMBER:
|
|
1744
|
-
case GroupNotifyMsgType.INVITED_NEED_ADMINI_STRATOR_PASS:
|
|
1745
|
-
subType = "invite";
|
|
1746
|
-
break;
|
|
1747
|
-
case GroupNotifyMsgType.REQUEST_JOIN_NEED_ADMINI_STRATOR_PASS:
|
|
1748
|
-
subType = "add";
|
|
1749
|
-
break;
|
|
1750
|
-
default: return null;
|
|
1751
|
-
}
|
|
1752
|
-
return {
|
|
1753
|
-
time: Math.floor(Date.now() / MS_TO_SEC),
|
|
1754
|
-
self_id: Number(ctx.selfUin),
|
|
1755
|
-
post_type: "request",
|
|
1756
|
-
request_type: "group",
|
|
1757
|
-
sub_type: subType,
|
|
1758
|
-
group_id: Number(notify.group?.groupCode ?? 0),
|
|
1759
|
-
user_id: toUin(notify.user1?.uid, ctx),
|
|
1760
|
-
comment: notify.postscript ?? "",
|
|
1761
|
-
flag: String(notify.seq)
|
|
1762
|
-
};
|
|
1763
|
-
}
|
|
1764
|
-
/**
|
|
1765
|
-
* BuddyReq → OB11 好友请求事件(friend)。
|
|
1766
|
-
* comment 取验证留言:QQNT 实际字段是 `extWords`,`words` 为旧口径兜底(都缺省空串);
|
|
1767
|
-
* flag = reqTime。
|
|
1768
|
-
*/
|
|
1769
|
-
function toOb11FriendRequestEvent(req, ctx) {
|
|
1770
|
-
const comment = firstNonEmptyString(stringOrUndefined(req["extWords"]), stringOrUndefined(req["words"])) ?? "";
|
|
1771
|
-
return {
|
|
1772
|
-
time: Math.floor(Date.now() / MS_TO_SEC),
|
|
1773
|
-
self_id: Number(ctx.selfUin),
|
|
1774
|
-
post_type: "request",
|
|
1775
|
-
request_type: "friend",
|
|
1776
|
-
user_id: toUin(req.friendUid, ctx),
|
|
1777
|
-
comment,
|
|
1778
|
-
flag: req.reqTime
|
|
1779
|
-
};
|
|
1780
|
-
}
|
|
1781
|
-
// src/onebot11/action/message/forward.ts
|
|
1782
|
-
/**
|
|
1783
|
-
* 消息转发域动作
|
|
1784
|
-
*
|
|
1785
|
-
* - send_group_forward_msg / send_private_forward_msg:messages 每项为
|
|
1786
|
-
* node 元素 `{ type: "node", data: { id } }`——id 是此前 send_msg 返回的 OB11
|
|
1787
|
-
* message_id。经 MessageUnique 反查源 msgId + peer,组装到目标 peer(群直通 /
|
|
1788
|
-
* 私聊 uinToUid)→ MsgApi.sendForwardMessage
|
|
1789
|
-
* - forward_group_single_msg / forward_friend_single_msg:message_id 反查
|
|
1790
|
-
* 源 msgId + peer;group_id/user_id 为目标 → MsgApi.forwardSingleMessage
|
|
1791
|
-
* - get_forward_msg:message_id / id → fetchForwardMessage(getMultiMsg)
|
|
1792
|
-
* → 每条 toOb11MessageInfo → { messages }
|
|
1793
|
-
*/
|
|
1794
|
-
const forwardNodeSchema = z.object({
|
|
1795
|
-
type: z.literal("node").optional(),
|
|
1796
|
-
data: z.object({ id: z.union([z.number(), z.string()]) }).optional()
|
|
1797
|
-
});
|
|
1798
|
-
const sendGroupForwardMsgSchema = z.object({
|
|
1799
|
-
group_id: z.number(),
|
|
1800
|
-
messages: z.array(z.unknown()).max(500).default([])
|
|
1801
|
-
});
|
|
1802
|
-
const sendPrivateForwardMsgSchema = z.object({
|
|
1803
|
-
user_id: z.number(),
|
|
1804
|
-
messages: z.array(z.unknown()).max(500).default([])
|
|
1805
|
-
});
|
|
1806
|
-
const forwardSingleMsgSchema = z.object({
|
|
1807
|
-
message_id: z.union([z.number(), z.string()]),
|
|
1808
|
-
group_id: z.number().optional(),
|
|
1809
|
-
user_id: z.number().optional()
|
|
1810
|
-
});
|
|
1811
|
-
const getForwardMsgSchema = z.object({
|
|
1812
|
-
message_id: z.union([z.number(), z.string()]).optional(),
|
|
1813
|
-
id: z.union([z.number(), z.string()]).optional()
|
|
1814
|
-
});
|
|
1815
|
-
/** 解析 node 元素列表 → 源消息 (msgId, peer) 列表(id 反查,跳过无法解析的项)。 */
|
|
1816
|
-
function resolveSourceMessages(messages, unique) {
|
|
1817
|
-
const out = [];
|
|
1818
|
-
for (const raw of messages) {
|
|
1819
|
-
const parsed = forwardNodeSchema.safeParse(raw);
|
|
1820
|
-
if (parsed.success) {
|
|
1821
|
-
const id = parsed.data.data?.id;
|
|
1822
|
-
if (id !== void 0) {
|
|
1823
|
-
const msgId = unique.getMsgId(Number(id));
|
|
1824
|
-
if (msgId !== void 0) {
|
|
1825
|
-
const peer = unique.getPeer(msgId);
|
|
1826
|
-
if (peer !== void 0) out.push({
|
|
1827
|
-
msgId,
|
|
1828
|
-
peer
|
|
1829
|
-
});
|
|
1830
|
-
}
|
|
1831
|
-
}
|
|
1832
|
-
}
|
|
1833
|
-
}
|
|
1834
|
-
return out;
|
|
1835
|
-
}
|
|
1836
|
-
/** 合并转发发送(群/私聊共用:解析源消息 → 发送 → 映射 message_id)。 */
|
|
1837
|
-
async function sendForward(messages, target, deps) {
|
|
1838
|
-
const sources = resolveSourceMessages(messages, deps.messageUnique);
|
|
1839
|
-
const [firstSource] = sources;
|
|
1840
|
-
if (firstSource === void 0) throw kernelError("合并转发需要至少一条可解析的源消息(node.id)", "INVALID_PARAM");
|
|
1841
|
-
const { msgId } = await deps.msgApi.sendForwardMessage(target, firstSource.peer, sources.map((s) => s.msgId));
|
|
1842
|
-
return { message_id: deps.messageUnique.alloc(msgId, target) };
|
|
1843
|
-
}
|
|
1844
|
-
/** 单条转发共用实现:message_id 反查源消息 + 目标 Peer 解析 → forwardSingleMessage。 */
|
|
1845
|
-
async function forwardSingleMsg(payload, deps) {
|
|
1846
|
-
const { msgId, peer: sourcePeer } = resolveMsgIdAndPeer(payload.message_id, deps.messageUnique);
|
|
1847
|
-
const dstPeer = await resolveTargetPeer(payload, deps, "单条转发需要 group_id 或 user_id");
|
|
1848
|
-
await deps.msgApi.forwardSingleMessage(sourcePeer, [msgId], dstPeer);
|
|
1849
|
-
return null;
|
|
1850
|
-
}
|
|
1851
|
-
/** 消息转发域动作工厂(合并转发 ×2 / get_forward_msg / 单条转发 ×2)。 */
|
|
1852
|
-
function createForwardActions(api) {
|
|
1853
|
-
return [
|
|
1854
|
-
defineOb11Action({
|
|
1855
|
-
name: "send_group_forward_msg",
|
|
1856
|
-
schema: sendGroupForwardMsgSchema,
|
|
1857
|
-
handle: async (payload) => {
|
|
1858
|
-
const target = {
|
|
1859
|
-
chatType: ChatType.GROUP,
|
|
1860
|
-
peerUid: String(payload.group_id)
|
|
1861
|
-
};
|
|
1862
|
-
return await sendForward(payload.messages, target, api);
|
|
1863
|
-
}
|
|
1864
|
-
}),
|
|
1865
|
-
defineOb11Action({
|
|
1866
|
-
name: "send_private_forward_msg",
|
|
1867
|
-
schema: sendPrivateForwardMsgSchema,
|
|
1868
|
-
handle: async (payload) => {
|
|
1869
|
-
const uid = await resolveUid(String(payload.user_id), api.uinToUid);
|
|
1870
|
-
const target = {
|
|
1871
|
-
chatType: ChatType.C2C,
|
|
1872
|
-
peerUid: uid
|
|
1873
|
-
};
|
|
1874
|
-
return await sendForward(payload.messages, target, api);
|
|
1875
|
-
}
|
|
1876
|
-
}),
|
|
1877
|
-
defineOb11Action({
|
|
1878
|
-
name: "get_forward_msg",
|
|
1879
|
-
schema: getForwardMsgSchema,
|
|
1880
|
-
handle: async (payload) => {
|
|
1881
|
-
const id = payload.message_id ?? payload.id;
|
|
1882
|
-
if (id === void 0) throw kernelError("get_forward_msg 需要 message_id 或 id", "INVALID_PARAM");
|
|
1883
|
-
const { msgId, peer } = resolveMsgIdAndPeer(id, api.messageUnique);
|
|
1884
|
-
return { messages: (await api.msgApi.fetchForwardMessage(peer, msgId)).map((msg) => toOb11MessageInfo(msg, api.messageUnique)) };
|
|
1885
|
-
}
|
|
1886
|
-
}),
|
|
1887
|
-
defineOb11Action({
|
|
1888
|
-
name: "forward_group_single_msg",
|
|
1889
|
-
schema: forwardSingleMsgSchema,
|
|
1890
|
-
handle: (payload) => forwardSingleMsg(payload, api)
|
|
1891
|
-
}),
|
|
1892
|
-
defineOb11Action({
|
|
1893
|
-
name: "forward_friend_single_msg",
|
|
1894
|
-
schema: forwardSingleMsgSchema,
|
|
1895
|
-
handle: (payload) => forwardSingleMsg(payload, api)
|
|
1896
|
-
})
|
|
1897
|
-
];
|
|
1898
|
-
}
|
|
1899
|
-
// src/onebot11/action/message/history.ts
|
|
1900
|
-
/**
|
|
1901
|
-
* 消息读取域动作
|
|
1902
|
-
*
|
|
1903
|
-
* - get_msg:message_id → msgId + peer(MessageUnique 反查)→ 拉消息 → OB11 消息信息
|
|
1904
|
-
* - get_group_msg_history(go-cqhttp 扩展)/ get_friend_msg_history(NapCat 扩展):
|
|
1905
|
-
* 拉取历史消息 → at uid 批量转换 → OB11 消息信息数组(共享 fetchAndTranslateHistory)
|
|
1906
|
-
*/
|
|
1907
|
-
const getMsgSchema = z.object({ message_id: z.union([z.number(), z.string()]) });
|
|
1908
|
-
/** 历史消息公共参数(message_seq / count / 反向排序)。 */
|
|
1909
|
-
const msgHistoryParamsSchema = {
|
|
1910
|
-
/** 起始消息序号(message_seq,缺省从最新拉)。 */
|
|
1911
|
-
message_seq: z.union([z.number(), z.string()]).optional(),
|
|
1912
|
-
count: z.number().default(20),
|
|
1913
|
-
/** 是否反向排序(NapCat 扩展)。 */
|
|
1914
|
-
reverse_order: z.boolean().optional(),
|
|
1915
|
-
reverseOrder: z.boolean().optional()
|
|
1916
|
-
};
|
|
1917
|
-
/** 解析 message_seq → 起始 msgId(int32 经 MessageUnique 反查,否则原样透传)。 */
|
|
1918
|
-
function resolveStartMsgId(messageSeq, messageUnique) {
|
|
1919
|
-
if (messageSeq === void 0) return;
|
|
1920
|
-
const raw = String(messageSeq);
|
|
1921
|
-
const shortId = Number(raw);
|
|
1922
|
-
if (Number.isFinite(shortId)) return messageUnique.getMsgId(shortId) ?? raw;
|
|
1923
|
-
return raw;
|
|
1924
|
-
}
|
|
1925
|
-
/**
|
|
1926
|
-
* 拉取历史消息并翻译为 OB11 消息信息数组。
|
|
1927
|
-
* 收集全部消息 at uid → 一次批量 uidToUin → 上下文注入。
|
|
1928
|
-
* 群聊另取发送者角色表(GroupCache 一次整表读取,失败回退缺省 member)。
|
|
1929
|
-
*/
|
|
1930
|
-
async function fetchAndTranslateHistory(peer, messageSeq, count, deps) {
|
|
1931
|
-
const startMsgId = resolveStartMsgId(messageSeq, deps.messageUnique);
|
|
1932
|
-
const opts = { count };
|
|
1933
|
-
if (startMsgId !== void 0) opts.msgId = startMsgId;
|
|
1934
|
-
const msgs = await deps.msgApi.fetchMessages(peer, opts);
|
|
1935
|
-
if (msgs.length === 0) throw kernelError(`消息 ${messageSeq ?? "0"} 不存在`, "NOT_FOUND");
|
|
1936
|
-
const atUids = /* @__PURE__ */ new Set();
|
|
1937
|
-
for (const m of msgs) {
|
|
1938
|
-
const { atUids: uids } = collectReceiveNeeds(toCanonicalElements(m));
|
|
1939
|
-
for (const u of uids) atUids.add(u);
|
|
1940
|
-
}
|
|
1941
|
-
let uidToUin;
|
|
1942
|
-
if (atUids.size > 0) try {
|
|
1943
|
-
uidToUin = await deps.uidToUin([...atUids]);
|
|
1944
|
-
} catch (err) {
|
|
1945
|
-
deps.logger?.warn({
|
|
1946
|
-
count: atUids.size,
|
|
1947
|
-
error: errorMessage(err)
|
|
1948
|
-
}, "ob11: 历史消息 at uid→uin 失败,at 原样");
|
|
1949
|
-
}
|
|
1950
|
-
const ctx = {
|
|
1951
|
-
...uidToUin !== void 0 ? { uidToUin } : {},
|
|
1952
|
-
msgIdToOb11Id: (m) => deps.messageUnique.getMessageId(m)
|
|
1953
|
-
};
|
|
1954
|
-
let senderRoles;
|
|
1955
|
-
if (peer.chatType === ChatType.GROUP) senderRoles = await deps.groupMemberRoles(peer.peerUid);
|
|
1956
|
-
return { messages: msgs.map((msg) => {
|
|
1957
|
-
const role = senderRoles?.get(msg.senderUid);
|
|
1958
|
-
return toOb11MessageInfo(msg, deps.messageUnique, {
|
|
1959
|
-
...ctx,
|
|
1960
|
-
...role !== void 0 ? { senderRole: role } : {}
|
|
1961
|
-
});
|
|
1962
|
-
}) };
|
|
1963
|
-
}
|
|
1964
|
-
const getGroupMsgHistorySchema = z.object({
|
|
1965
|
-
group_id: z.number(),
|
|
1966
|
-
...msgHistoryParamsSchema
|
|
1967
|
-
});
|
|
1968
|
-
const getFriendMsgHistorySchema = z.object({
|
|
1969
|
-
user_id: z.number(),
|
|
1970
|
-
...msgHistoryParamsSchema
|
|
1971
|
-
});
|
|
1972
|
-
/** 消息读取域动作工厂(get_msg / get_group_msg_history / get_friend_msg_history)。 */
|
|
1973
|
-
function createHistoryActions(api) {
|
|
1974
|
-
return [
|
|
1975
|
-
defineOb11Action({
|
|
1976
|
-
name: "get_msg",
|
|
1977
|
-
schema: getMsgSchema,
|
|
1978
|
-
handle: async (payload) => {
|
|
1979
|
-
const { msg } = await fetchMsgById(payload.message_id, api.messageUnique, api.msgApi);
|
|
1980
|
-
const { atUids } = collectReceiveNeeds(toCanonicalElements(msg));
|
|
1981
|
-
let uidToUin;
|
|
1982
|
-
if (atUids.length > 0) try {
|
|
1983
|
-
uidToUin = await api.uidToUin(atUids);
|
|
1984
|
-
} catch (err) {
|
|
1985
|
-
api.logger?.warn({
|
|
1986
|
-
count: atUids.length,
|
|
1987
|
-
error: errorMessage(err)
|
|
1988
|
-
}, "ob11: get_msg at uid→uin 失败,at 原样");
|
|
1989
|
-
}
|
|
1990
|
-
const senderRole = msg.chatType === ChatType.GROUP ? await api.groupMemberRole(msg.peerUid, msg.senderUid) : void 0;
|
|
1991
|
-
const ctx = {
|
|
1992
|
-
...uidToUin !== void 0 ? { uidToUin } : {},
|
|
1993
|
-
...senderRole !== void 0 ? { senderRole } : {},
|
|
1994
|
-
msgIdToOb11Id: (m) => api.messageUnique.getMessageId(m)
|
|
1995
|
-
};
|
|
1996
|
-
return toOb11MessageInfo(msg, api.messageUnique, ctx);
|
|
1997
|
-
}
|
|
1998
|
-
}),
|
|
1999
|
-
defineOb11Action({
|
|
2000
|
-
name: "get_group_msg_history",
|
|
2001
|
-
schema: getGroupMsgHistorySchema,
|
|
2002
|
-
handle: async (payload) => {
|
|
2003
|
-
return await fetchAndTranslateHistory({
|
|
2004
|
-
chatType: ChatType.GROUP,
|
|
2005
|
-
peerUid: String(payload.group_id)
|
|
2006
|
-
}, payload.message_seq, payload.count, api);
|
|
2007
|
-
}
|
|
2008
|
-
}),
|
|
2009
|
-
defineOb11Action({
|
|
2010
|
-
name: "get_friend_msg_history",
|
|
2011
|
-
schema: getFriendMsgHistorySchema,
|
|
2012
|
-
handle: async (payload) => {
|
|
2013
|
-
const uid = await resolveUid(String(payload.user_id), api.uinToUid);
|
|
2014
|
-
return await fetchAndTranslateHistory({
|
|
2015
|
-
chatType: ChatType.C2C,
|
|
2016
|
-
peerUid: uid
|
|
2017
|
-
}, payload.message_seq, payload.count, api);
|
|
2018
|
-
}
|
|
2019
|
-
})
|
|
2020
|
-
];
|
|
2021
|
-
}
|
|
2022
|
-
// src/onebot11/action/message/media.ts
|
|
2023
|
-
/**
|
|
2024
|
-
* 消息媒体域动作
|
|
2025
|
-
*
|
|
2026
|
-
* - get_image / get_record:获取图片/语音文件(图片接主动下载;语音接原生
|
|
2027
|
-
* downloadRichMedia)。message_id 反查 → fetchMsgsByMsgId → 找 PIC/PTT 元素:
|
|
2028
|
-
* - 本地文件解析:NT 相对路径(sourcePath/filePath)按 mediaBaseDir(QQ NT
|
|
2029
|
-
* global 目录)解析为绝对路径,命中磁盘即返回 file
|
|
2030
|
-
* - 图片主动下载:本地未命中且有 picUrl → @napuketto/media downloadUrl 落
|
|
2031
|
-
* cacheDir/media/,返回 file(绝对路径)+ url + file_size/file_name
|
|
2032
|
-
* - 语音主动下载:本地未命中 → kernel MsgApi.downloadPtt(原生
|
|
2033
|
-
* downloadRichMedia + 轮询元素回查)→ filePath 落盘后返回绝对路径;
|
|
2034
|
-
* 失败回退原始 filePath(NT 相对/绝对)+ 元数据,不抛错
|
|
2035
|
-
* - fetch_ptt_text:message_id → MsgApi.fetchPttText(内部:拉消息 → 找 PTT 元素
|
|
2036
|
-
* → translatePtt2Text → 再拉取读 pttElement.text)
|
|
2037
|
-
*/
|
|
2038
|
-
const getMediaSchema = z.object({
|
|
2039
|
-
/** CQ 码 file 字段或 message_id(简化:message_id 反查)。 */
|
|
2040
|
-
file: z.string().optional(),
|
|
2041
|
-
message_id: z.union([z.number(), z.string()]).optional()
|
|
2042
|
-
});
|
|
2043
|
-
const fetchPttTextSchema = z.object({ message_id: z.union([z.number(), z.string()]) });
|
|
2044
|
-
/**
|
|
2045
|
-
* NT 相对路径 → 本地绝对路径(存在才返回)。
|
|
2046
|
-
* 候选:原样绝对路径 / mediaBaseDir 下相对路径(反斜杠归一化)。
|
|
2047
|
-
*/
|
|
2048
|
-
function resolveLocalMediaFile(relPath, deps) {
|
|
2049
|
-
if (relPath === "") return null;
|
|
2050
|
-
if (existsSync(relPath)) return relPath;
|
|
2051
|
-
const base = deps.mediaBaseDir;
|
|
2052
|
-
if (base !== void 0 && base !== "") {
|
|
2053
|
-
const joined = join(base, relPath.replaceAll("\\", "/"));
|
|
2054
|
-
if (existsSync(joined)) return joined;
|
|
2055
|
-
}
|
|
2056
|
-
return null;
|
|
2057
|
-
}
|
|
2058
|
-
/** 图片主动下载(picUrl → cacheDir/media/<uuid>.<ext>;无 cacheDir/url 返回 null)。 */
|
|
2059
|
-
async function downloadImageToCache(url, deps) {
|
|
2060
|
-
const cacheDir = deps.cacheDir;
|
|
2061
|
-
if (cacheDir === void 0 || cacheDir === "") return null;
|
|
2062
|
-
const mediaDir = join(cacheDir, "media");
|
|
2063
|
-
await mkdir(mediaDir, { recursive: true });
|
|
2064
|
-
const dest = join(mediaDir, `${randomUUID()}${inferExtension(null, url)}`);
|
|
2065
|
-
try {
|
|
2066
|
-
await downloadUrl(url, dest);
|
|
2067
|
-
return dest;
|
|
2068
|
-
} catch (err) {
|
|
2069
|
-
deps.logger?.warn({
|
|
2070
|
-
url,
|
|
2071
|
-
error: errorMessage(err)
|
|
2072
|
-
}, "ob11: 图片主动下载失败,get_image 退原始 url");
|
|
2073
|
-
return null;
|
|
2074
|
-
}
|
|
2075
|
-
}
|
|
2076
|
-
/**
|
|
2077
|
-
* 反查消息并提取媒体元素路径。
|
|
2078
|
-
* 返回 null = 消息不存在;extract 返回 undefined = 无匹配元素。
|
|
2079
|
-
*/
|
|
2080
|
-
async function resolveMedia(id, label, deps, extract) {
|
|
2081
|
-
const { msgId, peer } = resolveMsgIdAndPeer(id, deps.messageUnique);
|
|
2082
|
-
const [first] = await deps.msgApi.fetchMsgsByMsgId(peer, [msgId]);
|
|
2083
|
-
if (first === void 0) throw kernelError(`消息 ${id} 不存在或已被撤回`, "NOT_FOUND");
|
|
2084
|
-
for (const el of first.elements) {
|
|
2085
|
-
const found = extract(el);
|
|
2086
|
-
if (found !== void 0) return found;
|
|
2087
|
-
}
|
|
2088
|
-
throw kernelError(`消息 ${id} 不包含${label}`, "NOT_FOUND");
|
|
2089
|
-
}
|
|
2090
|
-
/** 取 id 参数(message_id 优先,file 兜底)。 */
|
|
2091
|
-
function takeId(payload, actionName) {
|
|
2092
|
-
const id = payload.message_id ?? payload.file;
|
|
2093
|
-
if (id === void 0) throw kernelError(`${actionName} 需要 message_id 或 file`, "INVALID_PARAM");
|
|
2094
|
-
return id;
|
|
2095
|
-
}
|
|
2096
|
-
/** 提取 pic 元素 → 媒体信息(url / 本地 file / 元数据;非 pic 元素返回 undefined)。 */
|
|
2097
|
-
function extractPicElement(el, deps) {
|
|
2098
|
-
const pic = el.picElement;
|
|
2099
|
-
if (pic == null) return;
|
|
2100
|
-
const out = {};
|
|
2101
|
-
if (pic.fileSize !== void 0) out.file_size = pic.fileSize;
|
|
2102
|
-
if (pic.fileName !== void 0) out.file_name = pic.fileName;
|
|
2103
|
-
if (pic.picUrl !== void 0) out.url = pic.picUrl;
|
|
2104
|
-
const rel = pic.sourcePath ?? pic.picPath;
|
|
2105
|
-
if (rel !== void 0) {
|
|
2106
|
-
const local = resolveLocalMediaFile(rel, deps);
|
|
2107
|
-
if (local !== null) out.file = local;
|
|
2108
|
-
}
|
|
2109
|
-
return out;
|
|
2110
|
-
}
|
|
2111
|
-
/** 原生下载语音 → 元素回查本地路径;下载失败/未命中 null(warn 留痕,不抛错)。 */
|
|
2112
|
-
async function downloadPttFallback(msgId, peer, id, deps) {
|
|
2113
|
-
try {
|
|
2114
|
-
const downloaded = await deps.msgApi.downloadPtt(msgId, peer);
|
|
2115
|
-
const rel = downloaded.filePath;
|
|
2116
|
-
if (rel !== void 0 && rel !== "") {
|
|
2117
|
-
const localAfter = resolveLocalMediaFile(rel, deps);
|
|
2118
|
-
if (localAfter !== null) return {
|
|
2119
|
-
...downloaded.fileSize !== void 0 ? { file_size: downloaded.fileSize } : {},
|
|
2120
|
-
...downloaded.fileName !== void 0 ? { file_name: downloaded.fileName } : {},
|
|
2121
|
-
file: localAfter
|
|
2122
|
-
};
|
|
2123
|
-
}
|
|
2124
|
-
} catch (err) {
|
|
2125
|
-
deps.logger?.warn({
|
|
2126
|
-
message_id: id,
|
|
2127
|
-
error: errorMessage(err)
|
|
2128
|
-
}, "ob11: 语音原生下载失败,get_record 回退原始路径");
|
|
2129
|
-
}
|
|
2130
|
-
return null;
|
|
2131
|
-
}
|
|
2132
|
-
/** 消息媒体域动作工厂(get_image / get_record / fetch_ptt_text)。 */
|
|
2133
|
-
function createMediaActions(api) {
|
|
2134
|
-
return [
|
|
2135
|
-
defineOb11Action({
|
|
2136
|
-
name: "get_image",
|
|
2137
|
-
schema: getMediaSchema,
|
|
2138
|
-
handle: async (payload) => {
|
|
2139
|
-
const base = await resolveMedia(takeId(payload, "get_image"), "图片", api, (el) => extractPicElement(el, api));
|
|
2140
|
-
if (base.file === void 0 && base.url !== void 0) {
|
|
2141
|
-
const downloaded = await downloadImageToCache(base.url, api);
|
|
2142
|
-
if (downloaded !== null) base.file = downloaded;
|
|
2143
|
-
}
|
|
2144
|
-
return base;
|
|
2145
|
-
}
|
|
2146
|
-
}),
|
|
2147
|
-
defineOb11Action({
|
|
2148
|
-
name: "get_record",
|
|
2149
|
-
schema: getMediaSchema,
|
|
2150
|
-
handle: async (payload) => {
|
|
2151
|
-
const id = takeId(payload, "get_record");
|
|
2152
|
-
const { msgId, peer } = resolveMsgIdAndPeer(id, api.messageUnique);
|
|
2153
|
-
const [first] = await api.msgApi.fetchMsgsByMsgId(peer, [msgId]);
|
|
2154
|
-
if (first === void 0) throw kernelError(`消息 ${id} 不存在或已被撤回`, "NOT_FOUND");
|
|
2155
|
-
const ptt = first.elements.find((e) => e.pttElement != null)?.pttElement;
|
|
2156
|
-
if (ptt == null || ptt.filePath === void 0) throw kernelError(`消息 ${id} 不包含语音`, "NOT_FOUND");
|
|
2157
|
-
const meta = () => ({
|
|
2158
|
-
...ptt.fileSize !== void 0 ? { file_size: ptt.fileSize } : {},
|
|
2159
|
-
...ptt.fileName !== void 0 ? { file_name: ptt.fileName } : {}
|
|
2160
|
-
});
|
|
2161
|
-
const local = resolveLocalMediaFile(ptt.filePath, api);
|
|
2162
|
-
if (local !== null) return {
|
|
2163
|
-
...meta(),
|
|
2164
|
-
file: local
|
|
2165
|
-
};
|
|
2166
|
-
return await downloadPttFallback(msgId, peer, id, api) ?? {
|
|
2167
|
-
...meta(),
|
|
2168
|
-
file: ptt.filePath
|
|
2169
|
-
};
|
|
2170
|
-
}
|
|
2171
|
-
}),
|
|
2172
|
-
defineOb11Action({
|
|
2173
|
-
name: "fetch_ptt_text",
|
|
2174
|
-
schema: fetchPttTextSchema,
|
|
2175
|
-
handle: async (payload) => {
|
|
2176
|
-
const { msgId, peer } = resolveMsgIdAndPeer(payload.message_id, api.messageUnique);
|
|
2177
|
-
return { text: await api.msgApi.fetchPttText(msgId, peer) };
|
|
2178
|
-
}
|
|
2179
|
-
})
|
|
2180
|
-
];
|
|
2181
|
-
}
|
|
2182
|
-
// src/onebot11/action/message/ops.ts
|
|
2183
|
-
/**
|
|
2184
|
-
* 消息操作域动作
|
|
2185
|
-
*
|
|
2186
|
-
* - delete_msg:撤回消息(OB11 标准只有 message_id,peer 经 MessageUnique 反查;
|
|
2187
|
-
* 群聊管理员 / 私聊 2 分钟内可撤回)
|
|
2188
|
-
* - mark_msg_as_read:OB11 标准以 user_id 为参数,NapCat 扩展同时支持 group_id;
|
|
2189
|
-
* mark_private_msg_as_read / mark_group_msg_as_read 为细分同名动作
|
|
2190
|
-
* - set_msg_emoji_like:message_id → 拉消息取 msgSeq → MsgApi.setMsgEmojiLike
|
|
2191
|
-
* - set_input_status:user_id → uinToUid → MsgApi.setInputStatus(1=输入中,0=停止)
|
|
2192
|
-
*/
|
|
2193
|
-
const deleteMsgSchema = z.object({ message_id: z.union([z.number(), z.string()]) });
|
|
2194
|
-
const markMsgAsReadSchema = z.object({
|
|
2195
|
-
user_id: z.number().optional(),
|
|
2196
|
-
group_id: z.number().optional()
|
|
2197
|
-
}).refine((v) => v.user_id !== void 0 || v.group_id !== void 0, { message: "mark_msg_as_read 需要 user_id 或 group_id" });
|
|
2198
|
-
const markPrivateMsgAsReadSchema = z.object({ user_id: z.number() });
|
|
2199
|
-
const markGroupMsgAsReadSchema = z.object({ group_id: z.number() });
|
|
2200
|
-
const setMsgEmojiLikeSchema = z.object({
|
|
2201
|
-
message_id: z.union([z.number(), z.string()]),
|
|
2202
|
-
/** 表情 ID(如 105 点赞)。 */
|
|
2203
|
-
emoji_id: z.number(),
|
|
2204
|
-
/** 表情类型(默认 1)。 */
|
|
2205
|
-
emoji_type: z.number().optional(),
|
|
2206
|
-
/** 是否点赞(false 取消)。 */
|
|
2207
|
-
like: z.boolean().optional()
|
|
2208
|
-
});
|
|
2209
|
-
const setInputStatusSchema = z.object({
|
|
2210
|
-
user_id: z.number(),
|
|
2211
|
-
/** 输入事件类型:1=输入中,0=停止。 */
|
|
2212
|
-
event_type: z.number().optional()
|
|
2213
|
-
});
|
|
2214
|
-
/** 输入中事件类型。 */
|
|
2215
|
-
const EVENT_TYPE_TYPING = 1;
|
|
2216
|
-
/**
|
|
2217
|
-
* 消息操作域动作工厂(delete_msg / mark_msg_as_read 系列 / set_msg_emoji_like /
|
|
2218
|
-
* set_input_status)。
|
|
2219
|
-
*/
|
|
2220
|
-
function createMsgOpsActions(api) {
|
|
2221
|
-
return [
|
|
2222
|
-
defineOb11Action({
|
|
2223
|
-
name: "delete_msg",
|
|
2224
|
-
schema: deleteMsgSchema,
|
|
2225
|
-
handle: async (payload) => {
|
|
2226
|
-
const { msgId, peer } = resolveMsgIdAndPeer(payload.message_id, api.messageUnique);
|
|
2227
|
-
await api.msgApi.recallMessage(peer, [msgId]);
|
|
2228
|
-
return null;
|
|
2229
|
-
}
|
|
2230
|
-
}),
|
|
2231
|
-
defineOb11Action({
|
|
2232
|
-
name: "mark_msg_as_read",
|
|
2233
|
-
schema: markMsgAsReadSchema,
|
|
2234
|
-
handle: async (payload) => {
|
|
2235
|
-
if (payload.group_id !== void 0) {
|
|
2236
|
-
await api.msgApi.markRead({
|
|
2237
|
-
chatType: ChatType.GROUP,
|
|
2238
|
-
peerUid: String(payload.group_id)
|
|
2239
|
-
});
|
|
2240
|
-
return null;
|
|
2241
|
-
}
|
|
2242
|
-
if (payload.user_id !== void 0) {
|
|
2243
|
-
const uid = await resolveUid(String(payload.user_id), api.uinToUid);
|
|
2244
|
-
await api.msgApi.markRead({
|
|
2245
|
-
chatType: ChatType.C2C,
|
|
2246
|
-
peerUid: uid
|
|
2247
|
-
});
|
|
2248
|
-
}
|
|
2249
|
-
return null;
|
|
2250
|
-
}
|
|
2251
|
-
}),
|
|
2252
|
-
defineOb11Action({
|
|
2253
|
-
name: "mark_private_msg_as_read",
|
|
2254
|
-
schema: markPrivateMsgAsReadSchema,
|
|
2255
|
-
handle: async (payload) => {
|
|
2256
|
-
const uid = await resolveUid(String(payload.user_id), api.uinToUid);
|
|
2257
|
-
await api.msgApi.markRead({
|
|
2258
|
-
chatType: ChatType.C2C,
|
|
2259
|
-
peerUid: uid
|
|
2260
|
-
});
|
|
2261
|
-
return null;
|
|
2262
|
-
}
|
|
2263
|
-
}),
|
|
2264
|
-
defineOb11Action({
|
|
2265
|
-
name: "mark_group_msg_as_read",
|
|
2266
|
-
schema: markGroupMsgAsReadSchema,
|
|
2267
|
-
handle: async (payload) => {
|
|
2268
|
-
await api.msgApi.markRead({
|
|
2269
|
-
chatType: ChatType.GROUP,
|
|
2270
|
-
peerUid: String(payload.group_id)
|
|
2271
|
-
});
|
|
2272
|
-
return null;
|
|
2273
|
-
}
|
|
2274
|
-
}),
|
|
2275
|
-
defineOb11Action({
|
|
2276
|
-
name: "set_msg_emoji_like",
|
|
2277
|
-
schema: setMsgEmojiLikeSchema,
|
|
2278
|
-
handle: async (payload) => {
|
|
2279
|
-
const { msg, peer } = await fetchMsgById(payload.message_id, api.messageUnique, api.msgApi);
|
|
2280
|
-
await api.msgApi.setMsgEmojiLike(peer, {
|
|
2281
|
-
msgSeq: msg.msgSeq,
|
|
2282
|
-
emojiId: String(payload.emoji_id),
|
|
2283
|
-
emojiType: String(payload.emoji_type ?? 1),
|
|
2284
|
-
like: payload.like ?? true
|
|
2285
|
-
});
|
|
2286
|
-
return null;
|
|
2287
|
-
}
|
|
2288
|
-
}),
|
|
2289
|
-
defineOb11Action({
|
|
2290
|
-
name: "set_input_status",
|
|
2291
|
-
schema: setInputStatusSchema,
|
|
2292
|
-
handle: async (payload) => {
|
|
2293
|
-
const uid = await resolveUid(String(payload.user_id), api.uinToUid);
|
|
2294
|
-
await api.msgApi.setInputStatus({
|
|
2295
|
-
chatType: ChatType.C2C,
|
|
2296
|
-
peerUid: uid
|
|
2297
|
-
}, payload.event_type ?? EVENT_TYPE_TYPING);
|
|
2298
|
-
return null;
|
|
2299
|
-
}
|
|
2300
|
-
})
|
|
2301
|
-
];
|
|
2302
|
-
}
|
|
2303
|
-
// src/onebot11/action/message/send.ts
|
|
2304
|
-
const sendMsgSchema = z.object({
|
|
2305
|
-
message_type: z.enum(["group", "private"]).optional(),
|
|
2306
|
-
user_id: z.number().optional(),
|
|
2307
|
-
group_id: z.number().optional(),
|
|
2308
|
-
message: z.union([z.string(), z.array(z.unknown()).max(200)]),
|
|
2309
|
-
auto_escape: z.boolean().optional()
|
|
2310
|
-
});
|
|
2311
|
-
/** send_private / send_group 共用的消息与转义字段(上界见 action/limits.ts)。 */
|
|
2312
|
-
const sendMsgBodyFields = {
|
|
2313
|
-
message: z.union([z.string(), z.array(z.unknown()).max(200)]),
|
|
2314
|
-
auto_escape: z.boolean().optional()
|
|
2315
|
-
};
|
|
2316
|
-
const sendPrivateMsgSchema = z.object({
|
|
2317
|
-
user_id: z.number(),
|
|
2318
|
-
...sendMsgBodyFields
|
|
2319
|
-
});
|
|
2320
|
-
const sendGroupMsgSchema = z.object({
|
|
2321
|
-
group_id: z.number(),
|
|
2322
|
-
...sendMsgBodyFields
|
|
2323
|
-
});
|
|
2324
|
-
/** 共享发送核心:解析 Peer → canonical 翻译(含 auto_escape)→ sendMessage → 映射 message_id。 */
|
|
2325
|
-
async function sendOb11Message(payload, deps) {
|
|
2326
|
-
const peer = await resolveTargetPeer(payload, deps, "send_msg 需要 group_id 或 user_id");
|
|
2327
|
-
let canonical;
|
|
2328
|
-
if (Array.isArray(payload.message)) canonical = segmentsToCanonical(payload.message);
|
|
2329
|
-
else canonical = cqMessageToCanonical(payload.message);
|
|
2330
|
-
const atUins = [];
|
|
2331
|
-
for (const el of canonical) if (el.type === "at" && el.target !== "all") atUins.push(el.target);
|
|
2332
|
-
let uinToUid;
|
|
2333
|
-
if (atUins.length > 0) try {
|
|
2334
|
-
uinToUid = await deps.uinToUid(atUins);
|
|
2335
|
-
} catch (err) {
|
|
2336
|
-
deps.logger?.warn({
|
|
2337
|
-
count: atUins.length,
|
|
2338
|
-
error: errorMessage(err)
|
|
2339
|
-
}, "ob11: at uin→uid 失败,at 段原样发送");
|
|
2340
|
-
}
|
|
2341
|
-
canonical = applySendContext(canonical, {
|
|
2342
|
-
...uinToUid !== void 0 ? { uinToUid } : {},
|
|
2343
|
-
ob11IdToMsgId: (id) => deps.messageUnique.getMsgId(id)
|
|
2344
|
-
});
|
|
2345
|
-
if (payload.auto_escape === true) canonical = canonical.map((el) => {
|
|
2346
|
-
if (el.type === "text") return {
|
|
2347
|
-
...el,
|
|
2348
|
-
text: escapeText(el.text)
|
|
2349
|
-
};
|
|
2350
|
-
return el;
|
|
2351
|
-
});
|
|
2352
|
-
canonical = await ensureVoiceSilk(canonical, deps.logger);
|
|
2353
|
-
const prepared = await prepareVideoElements(canonical);
|
|
2354
|
-
try {
|
|
2355
|
-
const { msgId } = await deps.msgApi.sendMessage(peer, prepared.elements);
|
|
2356
|
-
return { message_id: deps.messageUnique.alloc(msgId, peer) };
|
|
2357
|
-
} finally {
|
|
2358
|
-
await prepared.cleanup();
|
|
2359
|
-
}
|
|
2360
|
-
}
|
|
2361
|
-
/** CQ 特殊字符转义(auto_escape,&、[、]、, 前置 &)。 */
|
|
2362
|
-
function escapeText(text) {
|
|
2363
|
-
return text.replaceAll("&", "&").replaceAll("[", "[").replaceAll("]", "]").replaceAll(",", ",");
|
|
2364
|
-
}
|
|
2365
|
-
/** 语音元素统一转 silk:非 silk 自动转码(QQ 语音格式),已是 silk 原样。 */
|
|
2366
|
-
async function ensureVoiceSilk(elements, logger) {
|
|
2367
|
-
const out = [];
|
|
2368
|
-
for (const el of elements) if (el.type === "voice") out.push({
|
|
2369
|
-
...el,
|
|
2370
|
-
path: await ensureSilk(el.path, logger)
|
|
2371
|
-
});
|
|
2372
|
-
else out.push(el);
|
|
2373
|
-
return out;
|
|
2374
|
-
}
|
|
2375
|
-
/** 消息发送域动作工厂(send_msg / send_private_msg / send_group_msg)。 */
|
|
2376
|
-
function createSendActions(api) {
|
|
2377
|
-
const deps = api;
|
|
2378
|
-
return [
|
|
2379
|
-
defineOb11Action({
|
|
2380
|
-
name: "send_msg",
|
|
2381
|
-
schema: sendMsgSchema,
|
|
2382
|
-
handle: (payload) => sendOb11Message(payload, deps)
|
|
2383
|
-
}),
|
|
2384
|
-
defineOb11Action({
|
|
2385
|
-
name: "send_private_msg",
|
|
2386
|
-
schema: sendPrivateMsgSchema,
|
|
2387
|
-
handle: (payload) => sendOb11Message(payload, deps)
|
|
2388
|
-
}),
|
|
2389
|
-
defineOb11Action({
|
|
2390
|
-
name: "send_group_msg",
|
|
2391
|
-
schema: sendGroupMsgSchema,
|
|
2392
|
-
handle: (payload) => sendOb11Message(payload, deps)
|
|
2393
|
-
})
|
|
2394
|
-
];
|
|
2395
|
-
}
|
|
2396
|
-
// src/onebot11/action/system/account.ts
|
|
2397
|
-
/**
|
|
2398
|
-
* 账号票据与资料域动作
|
|
2399
|
-
*
|
|
2400
|
-
* - get_cookies:kernel TicketApi.getCookies,domain 缺省 v2.qq.com
|
|
2401
|
-
* (NapCat 行为);user_id 缺省用机器人自身 uin
|
|
2402
|
-
* - get_clientkey:kernel TicketApi.getClientKey
|
|
2403
|
-
* - get_csrf_token / get_credentials:qun.qq.com cookies 的 skey → bkn
|
|
2404
|
-
* (csrf 等价物);get_credentials 返回指定域名 cookies + bkn
|
|
2405
|
-
* - set_self_longnick / set_qq_profile / set_qq_avatar:kernel ProfileApi;
|
|
2406
|
-
* set_qq_profile 的 sex 忽略,头像 URL 需先经 cacheDir 下载
|
|
2407
|
-
*/
|
|
2408
|
-
/** URL 前缀(头像在线文件识别)。 */
|
|
2409
|
-
const URL_PREFIX = /^https?:\/\//;
|
|
2410
|
-
/** 默认域名。 */
|
|
2411
|
-
const DEFAULT_DOMAIN = "v2.qq.com";
|
|
2412
|
-
/** 默认域名(bkn 计算用)。 */
|
|
2413
|
-
const BKN_DOMAIN = "qun.qq.com";
|
|
2414
|
-
const getCookiesSchema = z.object({
|
|
2415
|
-
domain: z.string().optional(),
|
|
2416
|
-
user_id: z.number().optional()
|
|
2417
|
-
});
|
|
2418
|
-
const getClientkeySchema = z.object({});
|
|
2419
|
-
const getCsrfTokenSchema = z.object({});
|
|
2420
|
-
const getCredentialsSchema = z.object({ domain: z.string().optional() });
|
|
2421
|
-
const setSelfLongnickSchema = z.object({ longNick: z.string() });
|
|
2422
|
-
const setQQProfileSchema = z.object({
|
|
2423
|
-
nickname: z.string(),
|
|
2424
|
-
personal_note: z.string().optional(),
|
|
2425
|
-
sex: z.union([z.number(), z.string()]).optional()
|
|
2426
|
-
});
|
|
2427
|
-
const setQQAvatarSchema = z.object({
|
|
2428
|
-
/** 本地路径(URL 需先下载,由装配方 cacheDir 支持)。 */
|
|
2429
|
-
file: z.string() });
|
|
2430
|
-
/** URL 头像下载到缓存目录(cacheDir 缺省抛错)。 */
|
|
2431
|
-
async function downloadAvatarToCache(url, cacheDir) {
|
|
2432
|
-
if (cacheDir === void 0 || cacheDir === "") throw kernelError("set_qq_avatar 处理 URL 需要缓存目录(装配方未注入)", "INVALID_STATE");
|
|
2433
|
-
const safeName = basename(new URL(url).pathname) || "avatar.bin";
|
|
2434
|
-
const filePath = join(cacheDir, `avatar-${Date.now()}-${safeName}`);
|
|
2435
|
-
return await downloadBufferToFile(url, filePath, void 0, "头像下载失败");
|
|
2436
|
-
}
|
|
2437
|
-
/**
|
|
2438
|
-
* 账号票据与资料域动作工厂(cookies / clientkey / csrf_token / credentials /
|
|
2439
|
-
* self_longnick / qq_profile / qq_avatar)。
|
|
2440
|
-
*/
|
|
2441
|
-
function createSystemAccountActions(api) {
|
|
2442
|
-
return [
|
|
2443
|
-
defineOb11Action({
|
|
2444
|
-
name: "get_clientkey",
|
|
2445
|
-
schema: getClientkeySchema,
|
|
2446
|
-
handle: async () => {
|
|
2447
|
-
const raw = await api.ticketApi.getClientKey();
|
|
2448
|
-
return {
|
|
2449
|
-
clientKey: raw.clientKey,
|
|
2450
|
-
keyIndex: raw.keyIndex,
|
|
2451
|
-
expireTime: raw.expireTime,
|
|
2452
|
-
url: raw.url
|
|
2453
|
-
};
|
|
2454
|
-
}
|
|
2455
|
-
}),
|
|
2456
|
-
defineOb11Action({
|
|
2457
|
-
name: "get_cookies",
|
|
2458
|
-
schema: getCookiesSchema,
|
|
2459
|
-
handle: (payload) => {
|
|
2460
|
-
const domain = payload.domain ?? DEFAULT_DOMAIN;
|
|
2461
|
-
let uin = api.selfUin;
|
|
2462
|
-
if (payload.user_id !== void 0) uin = String(payload.user_id);
|
|
2463
|
-
return api.ticketApi.getCookies(domain, uin);
|
|
2464
|
-
}
|
|
2465
|
-
}),
|
|
2466
|
-
defineOb11Action({
|
|
2467
|
-
name: "get_csrf_token",
|
|
2468
|
-
schema: getCsrfTokenSchema,
|
|
2469
|
-
handle: async () => {
|
|
2470
|
-
const skey = (await api.ticketApi.getCookies(BKN_DOMAIN, api.selfUin))["skey"] ?? "";
|
|
2471
|
-
return { token: Number(TicketApi.getBkn(skey)) };
|
|
2472
|
-
}
|
|
2473
|
-
}),
|
|
2474
|
-
defineOb11Action({
|
|
2475
|
-
name: "get_credentials",
|
|
2476
|
-
schema: getCredentialsSchema,
|
|
2477
|
-
handle: async (payload) => {
|
|
2478
|
-
const domain = payload.domain ?? BKN_DOMAIN;
|
|
2479
|
-
const cookies = await api.ticketApi.getCookies(domain, api.selfUin);
|
|
2480
|
-
return {
|
|
2481
|
-
cookies,
|
|
2482
|
-
csrf_token: Number(TicketApi.getBkn(cookies["skey"] ?? ""))
|
|
2483
|
-
};
|
|
2484
|
-
}
|
|
2485
|
-
}),
|
|
2486
|
-
defineOb11Action({
|
|
2487
|
-
name: "set_self_longnick",
|
|
2488
|
-
schema: setSelfLongnickSchema,
|
|
2489
|
-
handle: async (payload) => {
|
|
2490
|
-
await api.profileApi.setLongNick(payload.longNick);
|
|
2491
|
-
return null;
|
|
2492
|
-
}
|
|
2493
|
-
}),
|
|
2494
|
-
defineOb11Action({
|
|
2495
|
-
name: "set_qq_profile",
|
|
2496
|
-
schema: setQQProfileSchema,
|
|
2497
|
-
handle: async (payload) => {
|
|
2498
|
-
await api.profileApi.setNickName(payload.nickname);
|
|
2499
|
-
if (payload.personal_note !== void 0) await api.profileApi.setLongNick(payload.personal_note);
|
|
2500
|
-
return null;
|
|
2501
|
-
}
|
|
2502
|
-
}),
|
|
2503
|
-
defineOb11Action({
|
|
2504
|
-
name: "set_qq_avatar",
|
|
2505
|
-
schema: setQQAvatarSchema,
|
|
2506
|
-
handle: async (payload) => {
|
|
2507
|
-
let filePath = payload.file;
|
|
2508
|
-
if (URL_PREFIX.test(filePath)) filePath = await downloadAvatarToCache(filePath, api.cacheDir);
|
|
2509
|
-
if (!existsSync(filePath)) throw kernelError(`头像文件不存在: ${filePath}`, "NOT_FOUND");
|
|
2510
|
-
await api.profileApi.setHeader(filePath);
|
|
2511
|
-
return null;
|
|
2512
|
-
}
|
|
2513
|
-
})
|
|
2514
|
-
];
|
|
2515
|
-
}
|
|
2516
|
-
// src/onebot11/action/system/file.ts
|
|
2517
|
-
/**
|
|
2518
|
-
* 文件收发域动作
|
|
2519
|
-
*
|
|
2520
|
-
* - download_file:url → fetch 下载 → 存 cacheDir(缺省抛错)→ 返回
|
|
2521
|
-
* { file }。文件名:download-<timestamp>-<basename>(headers 等扩展字段忽略)
|
|
2522
|
-
* - upload_group_file / upload_private_file——**闪传通道**
|
|
2523
|
-
*
|
|
2524
|
-
* ⚠️ 语义降级(探测依据见 kernel design §15):
|
|
2525
|
-
* QQ NT 没有任何「把文件传进群文件列表」的 NAPI,`sendMsg` 带 fileElement 时原生走的
|
|
2526
|
-
* 文件传输命令被服务端拒绝(`170019002`,逐维扫参无效),`fileUuid` 永远拿不到。唯一实测
|
|
2527
|
-
* 可用的投递通道是闪传:上传文件集 → 发分享卡片。因此本动作:
|
|
2528
|
-
* - 对端收到的是「分享链接卡片」(`qfile.qq.com`),**不是 fileElement 文件消息**,
|
|
2529
|
-
* 也**不进群文件列表**;
|
|
2530
|
-
* - 返回的 `file_id` 是闪传文件集 id,只可自留,**不能**喂给 delete_group_file /
|
|
2531
|
-
* get_group_file_download_url 等群文件动作;
|
|
2532
|
-
* - `name` 作为文件集名称(卡片标题);`folder` 忽略(闪传没有目录概念)。
|
|
2533
|
-
*
|
|
2534
|
-
* 输入只接受本地路径与 `file://` URI:远程 `http(s)://` / `base64://` 需要下载缓存与媒体
|
|
2535
|
-
* 依赖,当前未接(明确报错,不静默失败)。
|
|
2536
|
-
*/
|
|
2537
|
-
/** 路径分隔符(取文件名用)。 */
|
|
2538
|
-
const PATH_SEPARATORS = /[\\/]/;
|
|
2539
|
-
const downloadFileSchema = z.object({
|
|
2540
|
-
url: z.string(),
|
|
2541
|
-
thread_count: z.number().optional(),
|
|
2542
|
-
headers: z.record(z.string(), z.string()).optional()
|
|
2543
|
-
});
|
|
2544
|
-
const uploadGroupFileSchema = z.object({
|
|
2545
|
-
group_id: z.number(),
|
|
2546
|
-
file: z.string().min(1),
|
|
2547
|
-
name: z.string().optional(),
|
|
2548
|
-
/** go-cqhttp 兼容字段:闪传无目录概念,忽略。 */
|
|
2549
|
-
folder: z.string().optional()
|
|
2550
|
-
});
|
|
2551
|
-
const uploadPrivateFileSchema = z.object({
|
|
2552
|
-
user_id: z.number(),
|
|
2553
|
-
file: z.string().min(1),
|
|
2554
|
-
name: z.string().optional()
|
|
2555
|
-
});
|
|
2556
|
-
/** 本地路径 / file:// 展开;远程 URI 明确拒绝(未接下载缓存)。 */
|
|
2557
|
-
function resolveLocalFile(file) {
|
|
2558
|
-
if (file.startsWith("http://") || file.startsWith("https://") || file.startsWith("base64://")) throw kernelError("upload_group_file/upload_private_file 目前只支持本地路径与 file:// URI(远程 URI 需要下载缓存,未接入)", "INVALID_PARAM");
|
|
2559
|
-
if (file.startsWith("file://")) return fileUriToPath(file);
|
|
2560
|
-
return file;
|
|
2561
|
-
}
|
|
2562
|
-
/** 取路径末段作为缺省文件集名(卡片标题)。 */
|
|
2563
|
-
function basename$1(path) {
|
|
2564
|
-
const parts = path.split(PATH_SEPARATORS);
|
|
2565
|
-
const last = parts[parts.length - 1] ?? "";
|
|
2566
|
-
return last === "" ? "文件" : last;
|
|
2567
|
-
}
|
|
2568
|
-
/** 文件收发域动作工厂(download_file / upload_group_file / upload_private_file)。 */
|
|
2569
|
-
function createSystemFileActions(api) {
|
|
2570
|
-
return [
|
|
2571
|
-
defineOb11Action({
|
|
2572
|
-
name: "download_file",
|
|
2573
|
-
schema: downloadFileSchema,
|
|
2574
|
-
handle: async (payload) => {
|
|
2575
|
-
const { cacheDir } = api;
|
|
2576
|
-
if (cacheDir === void 0 || cacheDir === "") throw kernelError("download_file 未配置缓存目录(装配方未注入)", "INVALID_STATE");
|
|
2577
|
-
const safeName = basename(new URL(payload.url).pathname) || "download.bin";
|
|
2578
|
-
const filePath = join(cacheDir, `download-${Date.now()}-${safeName}`);
|
|
2579
|
-
const init = {};
|
|
2580
|
-
if (payload.headers !== void 0) init.headers = payload.headers;
|
|
2581
|
-
await downloadBufferToFile(payload.url, filePath, init);
|
|
2582
|
-
return { file: filePath };
|
|
2583
|
-
}
|
|
2584
|
-
}),
|
|
2585
|
-
defineOb11Action({
|
|
2586
|
-
name: "upload_group_file",
|
|
2587
|
-
schema: uploadGroupFileSchema,
|
|
2588
|
-
handle: async (payload) => {
|
|
2589
|
-
const path = resolveLocalFile(payload.file);
|
|
2590
|
-
const peer = {
|
|
2591
|
-
chatType: ChatType.GROUP,
|
|
2592
|
-
peerUid: String(payload.group_id)
|
|
2593
|
-
};
|
|
2594
|
-
return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.name ?? basename$1(path) })).fileSetId };
|
|
2595
|
-
}
|
|
2596
|
-
}),
|
|
2597
|
-
defineOb11Action({
|
|
2598
|
-
name: "upload_private_file",
|
|
2599
|
-
schema: uploadPrivateFileSchema,
|
|
2600
|
-
handle: async (payload) => {
|
|
2601
|
-
const path = resolveLocalFile(payload.file);
|
|
2602
|
-
const peer = await resolveTargetPeer({ user_id: payload.user_id }, api, "upload_private_file 需要 user_id");
|
|
2603
|
-
return { file_id: (await api.flashTransferApi.sendFile(peer, [path], { name: payload.name ?? basename$1(path) })).fileSetId };
|
|
2604
|
-
}
|
|
2605
|
-
})
|
|
2606
|
-
];
|
|
2607
|
-
}
|
|
2608
|
-
// src/onebot11/action/system/info.ts
|
|
2609
|
-
/**
|
|
2610
|
-
* 系统信息域动作——只读信息查询,多为本地组装。
|
|
2611
|
-
*
|
|
2612
|
-
* - get_login_info:self 由装配方注入(接 kernel selfInfo 取真实昵称)
|
|
2613
|
-
* - get_version_info:appVersion 由装配方注入(kernel wrapper 版本或
|
|
2614
|
-
* NAPUTO_QQ_VERSION)
|
|
2615
|
-
* - get_status:返回与心跳 status 同构的 OB11Status(online/good)
|
|
2616
|
-
* - get_robot_uin_range:NapCat 从配置返回;这里给通用范围(min/max)
|
|
2617
|
-
* - translate_en2zh:kernel RichMediaApi.translateWords(词条数组限长)
|
|
2618
|
-
*/
|
|
2619
|
-
/** QQ 号下限。 */
|
|
2620
|
-
const UIN_MIN = 10001;
|
|
2621
|
-
/** QQ 号上限。 */
|
|
2622
|
-
const UIN_MAX = 4294967295;
|
|
2623
|
-
const getLoginInfoSchema = z.object({});
|
|
2624
|
-
const getVersionInfoSchema = z.object({});
|
|
2625
|
-
const getStatusSchema = z.object({});
|
|
2626
|
-
const getRobotUinRangeSchema = z.object({});
|
|
2627
|
-
const translateEn2ZhSchema = z.object({ words: z.array(z.string()).max(MAX_TRANSLATE_WORDS) });
|
|
2628
|
-
/**
|
|
2629
|
-
* 系统信息域动作工厂(login_info / version_info / status / robot_uin_range /
|
|
2630
|
-
* translate_en2zh)。
|
|
2631
|
-
*/
|
|
2632
|
-
function createSystemInfoActions(api) {
|
|
2633
|
-
return [
|
|
2634
|
-
defineOb11Action({
|
|
2635
|
-
name: "get_login_info",
|
|
2636
|
-
schema: getLoginInfoSchema,
|
|
2637
|
-
handle: () => Promise.resolve({
|
|
2638
|
-
user_id: Number(api.self.uin),
|
|
2639
|
-
nickname: api.self.nickname
|
|
2640
|
-
})
|
|
2641
|
-
}),
|
|
2642
|
-
defineOb11Action({
|
|
2643
|
-
name: "get_version_info",
|
|
2644
|
-
schema: getVersionInfoSchema,
|
|
2645
|
-
handle: () => Promise.resolve({
|
|
2646
|
-
app_name: "napuketto-qq",
|
|
2647
|
-
app_version: api.appVersion,
|
|
2648
|
-
protocol_version: "v11"
|
|
2649
|
-
})
|
|
2650
|
-
}),
|
|
2651
|
-
defineOb11Action({
|
|
2652
|
-
name: "get_status",
|
|
2653
|
-
schema: getStatusSchema,
|
|
2654
|
-
handle: () => Promise.resolve({
|
|
2655
|
-
online: true,
|
|
2656
|
-
good: true
|
|
2657
|
-
})
|
|
2658
|
-
}),
|
|
2659
|
-
defineOb11Action({
|
|
2660
|
-
name: "get_robot_uin_range",
|
|
2661
|
-
schema: getRobotUinRangeSchema,
|
|
2662
|
-
handle: () => Promise.resolve({
|
|
2663
|
-
min: UIN_MIN,
|
|
2664
|
-
max: UIN_MAX
|
|
2665
|
-
})
|
|
2666
|
-
}),
|
|
2667
|
-
defineOb11Action({
|
|
2668
|
-
name: "translate_en2zh",
|
|
2669
|
-
schema: translateEn2ZhSchema,
|
|
2670
|
-
handle: async (payload) => {
|
|
2671
|
-
return { words: await api.richMediaApi.translateWords(payload.words) };
|
|
2672
|
-
}
|
|
2673
|
-
})
|
|
2674
|
-
];
|
|
2675
|
-
}
|
|
2676
|
-
// src/onebot11/action/system/status.ts
|
|
2677
|
-
/**
|
|
2678
|
-
* 系统状态与维护域动作
|
|
2679
|
-
*
|
|
2680
|
-
* - set_online_status:status/ext_status/battery_status 见 NapCat 状态表
|
|
2681
|
-
* (在线 10 / 离开 30 / 隐身 40 / 忙碌 50 / Q我吧 60 / 请勿打扰 70 等)
|
|
2682
|
-
* - set_diy_online_status:customStatus(faceId/wording/faceType)随
|
|
2683
|
-
* setStatus 一并提交;status 缺省 10(在线)
|
|
2684
|
-
* - can_send_image / can_send_record:本地恒 true
|
|
2685
|
-
* - clean_cache:cleanCache 回调由装配方注入(boot.cjs 接 kernel
|
|
2686
|
-
* PathWrapper.clearCache),未配置时明确报错(不静默)
|
|
2687
|
-
* - bot_exit / set_restart:exit/restart 回调由装配方注入(boot.cjs 接
|
|
2688
|
-
* 进程控制),未配置时明确报错;重启缺省退化为退出
|
|
2689
|
-
*/
|
|
2690
|
-
/** 默认在线状态值。 */
|
|
2691
|
-
const STATUS_ONLINE = 10;
|
|
2692
|
-
const setOnlineStatusSchema = z.object({
|
|
2693
|
-
status: z.number().optional(),
|
|
2694
|
-
ext_status: z.number().optional(),
|
|
2695
|
-
battery_status: z.number().optional()
|
|
2696
|
-
});
|
|
2697
|
-
const setDiyOnlineStatusSchema = z.object({
|
|
2698
|
-
status: z.number().optional(),
|
|
2699
|
-
/** 自定义状态文案。 */
|
|
2700
|
-
wording: z.string(),
|
|
2701
|
-
/** 表情 ID。 */
|
|
2702
|
-
face_id: z.string().optional(),
|
|
2703
|
-
/** 表情类型。 */
|
|
2704
|
-
face_type: z.string().optional()
|
|
2705
|
-
});
|
|
2706
|
-
const canSendImageSchema = z.object({});
|
|
2707
|
-
const canSendRecordSchema = z.object({});
|
|
2708
|
-
const cleanCacheSchema = z.object({});
|
|
2709
|
-
const botExitSchema = z.object({});
|
|
2710
|
-
/**
|
|
2711
|
-
* 系统状态与维护域动作工厂(set_online_status ×2 / can_send ×2 / clean_cache /
|
|
2712
|
-
* bot_exit / set_restart)。
|
|
2713
|
-
*/
|
|
2714
|
-
function createSystemStatusActions(api) {
|
|
2715
|
-
return [
|
|
2716
|
-
defineOb11Action({
|
|
2717
|
-
name: "set_online_status",
|
|
2718
|
-
schema: setOnlineStatusSchema,
|
|
2719
|
-
handle: async (payload) => {
|
|
2720
|
-
await api.msgApi.setOnlineStatus({
|
|
2721
|
-
status: payload.status ?? STATUS_ONLINE,
|
|
2722
|
-
extStatus: payload.ext_status ?? 0,
|
|
2723
|
-
batteryStatus: payload.battery_status ?? 0
|
|
2724
|
-
});
|
|
2725
|
-
return null;
|
|
2726
|
-
}
|
|
2727
|
-
}),
|
|
2728
|
-
defineOb11Action({
|
|
2729
|
-
name: "set_diy_online_status",
|
|
2730
|
-
schema: setDiyOnlineStatusSchema,
|
|
2731
|
-
handle: async (payload) => {
|
|
2732
|
-
const customStatus = {
|
|
2733
|
-
faceId: payload.face_id ?? "",
|
|
2734
|
-
wording: payload.wording,
|
|
2735
|
-
faceType: payload.face_type ?? "1"
|
|
2736
|
-
};
|
|
2737
|
-
await api.msgApi.setOnlineStatus({
|
|
2738
|
-
status: payload.status ?? STATUS_ONLINE,
|
|
2739
|
-
extStatus: 0,
|
|
2740
|
-
batteryStatus: 0,
|
|
2741
|
-
customStatus
|
|
2742
|
-
});
|
|
2743
|
-
return null;
|
|
2744
|
-
}
|
|
2745
|
-
}),
|
|
2746
|
-
defineOb11Action({
|
|
2747
|
-
name: "can_send_image",
|
|
2748
|
-
schema: canSendImageSchema,
|
|
2749
|
-
handle: async () => ({ yes: true })
|
|
2750
|
-
}),
|
|
2751
|
-
defineOb11Action({
|
|
2752
|
-
name: "can_send_record",
|
|
2753
|
-
schema: canSendRecordSchema,
|
|
2754
|
-
handle: async () => ({ yes: true })
|
|
2755
|
-
}),
|
|
2756
|
-
defineOb11Action({
|
|
2757
|
-
name: "clean_cache",
|
|
2758
|
-
schema: cleanCacheSchema,
|
|
2759
|
-
handle: async () => {
|
|
2760
|
-
if (api.cleanCache === void 0) throw kernelError("clean_cache 未配置(装配方未注入清理回调)", "INVALID_STATE");
|
|
2761
|
-
await api.cleanCache();
|
|
2762
|
-
return null;
|
|
2763
|
-
}
|
|
2764
|
-
}),
|
|
2765
|
-
defineOb11Action({
|
|
2766
|
-
name: "bot_exit",
|
|
2767
|
-
schema: botExitSchema,
|
|
2768
|
-
handle: async () => {
|
|
2769
|
-
if (api.exit === void 0) throw kernelError("bot_exit 未配置(装配方未注入退出回调)", "INVALID_STATE");
|
|
2770
|
-
await api.exit();
|
|
2771
|
-
return null;
|
|
2772
|
-
}
|
|
2773
|
-
}),
|
|
2774
|
-
defineOb11Action({
|
|
2775
|
-
name: "set_restart",
|
|
2776
|
-
schema: botExitSchema,
|
|
2777
|
-
handle: async () => {
|
|
2778
|
-
const restart = api.restart ?? api.exit;
|
|
2779
|
-
if (restart === void 0) throw kernelError("set_restart 未配置(装配方未注入重启回调)", "INVALID_STATE");
|
|
2780
|
-
await restart();
|
|
2781
|
-
return null;
|
|
2782
|
-
}
|
|
2783
|
-
})
|
|
2784
|
-
];
|
|
2785
|
-
}
|
|
2786
|
-
// src/onebot11/action/index.ts
|
|
2787
|
-
/**
|
|
2788
|
-
* OneBot 11 动作注册表
|
|
2789
|
-
* 各协议维护自己的 ActionRegistry,由协议 adapter 挂到请求分发。
|
|
2790
|
-
* deps 收敛为 { api: OneBotApi } 单聚合对象。
|
|
2791
|
-
*
|
|
2792
|
-
* 同时是 action 域 barrel:re-export ob11ErrorCodeMap / resolveUid(base-action)/
|
|
2793
|
-
* AtAllRemainInfo,协议外部只从本入口消费动作面。动作按领域分文件(message/ group/
|
|
2794
|
-
* friend/ system/),各领域文件导出 create*Actions 工厂,此处遍历注册——新增动作在
|
|
2795
|
-
* 领域文件的工厂里登记即可。
|
|
2796
|
-
*/
|
|
2797
|
-
/** 全部领域工厂(18 个:message×5 + group×7 + friend×2 + system×4)。 */
|
|
2798
|
-
const ACTION_FACTORIES = [
|
|
2799
|
-
createSendActions,
|
|
2800
|
-
createHistoryActions,
|
|
2801
|
-
createMsgOpsActions,
|
|
2802
|
-
createMediaActions,
|
|
2803
|
-
createForwardActions,
|
|
2804
|
-
createGroupManageActions,
|
|
2805
|
-
createGroupQueryActions,
|
|
2806
|
-
createGroupEssenceActions,
|
|
2807
|
-
createGroupNotifyActions,
|
|
2808
|
-
createGroupSystemMsgActions,
|
|
2809
|
-
createGroupFileQueryActions,
|
|
2810
|
-
createGroupFileOpActions,
|
|
2811
|
-
createFriendQueryActions,
|
|
2812
|
-
createFriendManageActions,
|
|
2813
|
-
createSystemInfoActions,
|
|
2814
|
-
createSystemStatusActions,
|
|
2815
|
-
createSystemAccountActions,
|
|
2816
|
-
createSystemFileActions
|
|
2817
|
-
];
|
|
2818
|
-
/** 构建 OB11 动作注册表(81 个动作,领域工厂遍历注册)。 */
|
|
2819
|
-
function createOb11ActionRegistry(deps) {
|
|
2820
|
-
const registry = new ActionRegistry();
|
|
2821
|
-
for (const factory of ACTION_FACTORIES) for (const action of factory(deps.api)) registry.register(action);
|
|
2822
|
-
return registry;
|
|
2823
|
-
}
|
|
2824
|
-
// src/onebot11/api/onebot-api.ts
|
|
2825
|
-
/**
|
|
2826
|
-
* OneBot 11 动作统一依赖聚合。
|
|
2827
|
-
* 各动作经 `Pick<OneBotApi, ...>` 取所需成员;注册处只构造一次本对象。
|
|
2828
|
-
*/
|
|
2829
|
-
var OneBotApi = class {
|
|
2830
|
-
/** kernel 消息 API(send_msg 等消息类动作用)。 */
|
|
2831
|
-
msgApi;
|
|
2832
|
-
/** kernel 群 API。 */
|
|
2833
|
-
groupApi;
|
|
2834
|
-
/** kernel 群通知 API(群请求/禁言列表用)。 */
|
|
2835
|
-
groupNotifyApi;
|
|
2836
|
-
/** kernel 好友 API。 */
|
|
2837
|
-
friendApi;
|
|
2838
|
-
/** kernel 票据 API(get_clientkey/get_cookies 用)。 */
|
|
2839
|
-
ticketApi;
|
|
2840
|
-
/** kernel 富媒体 API(群文件/翻译用)。 */
|
|
2841
|
-
richMediaApi;
|
|
2842
|
-
/** kernel 闪传 API(文件投递:分享卡片,见 flash-transfer.ts 语义说明)。 */
|
|
2843
|
-
flashTransferApi;
|
|
2844
|
-
/** kernel 资料 API(签名/昵称/头像用)。 */
|
|
2845
|
-
profileApi;
|
|
2846
|
-
/** kernel 点赞 API(send_like 用)。 */
|
|
2847
|
-
profileLikeApi;
|
|
2848
|
-
/** kernel 群空间 web API(精华/荣誉用)。 */
|
|
2849
|
-
webApi;
|
|
2850
|
-
/** 群/成员缓存(翻译层只读消费,缺失惰性回填)。 */
|
|
2851
|
-
groupCache;
|
|
2852
|
-
/** OB11 message_id ↔ NT msgId 双向映射(收链路与动作共用同一映射空间)。 */
|
|
2853
|
-
messageUnique;
|
|
2854
|
-
/** 登录身份(get_login_info 用)。 */
|
|
2855
|
-
self;
|
|
2856
|
-
/** 机器人自身 uin(get_cookies / csrf 用)。 */
|
|
2857
|
-
selfUin;
|
|
2858
|
-
/** 运行版本(get_version_info 用)。 */
|
|
2859
|
-
appVersion;
|
|
2860
|
-
/** 缓存清理回调(clean_cache 用)。 */
|
|
2861
|
-
cleanCache;
|
|
2862
|
-
/** 缓存目录(download_file 用)。 */
|
|
2863
|
-
cacheDir;
|
|
2864
|
-
/** QQ NT global 目录(媒体 NT 相对路径解析用)。 */
|
|
2865
|
-
mediaBaseDir;
|
|
2866
|
-
/** 进程退出回调(bot_exit 用)。 */
|
|
2867
|
-
exit;
|
|
2868
|
-
/** 进程重启回调(set_restart 用)。 */
|
|
2869
|
-
restart;
|
|
2870
|
-
/** 降级分支可观测出口(缺省静默)。 */
|
|
2871
|
-
logger;
|
|
2872
|
-
constructor(opts) {
|
|
2873
|
-
this.msgApi = opts.msgApi;
|
|
2874
|
-
this.groupApi = opts.groupApi;
|
|
2875
|
-
this.groupNotifyApi = opts.groupNotifyApi;
|
|
2876
|
-
this.friendApi = opts.friendApi;
|
|
2877
|
-
this.ticketApi = opts.ticketApi;
|
|
2878
|
-
this.richMediaApi = opts.richMediaApi;
|
|
2879
|
-
this.flashTransferApi = opts.flashTransferApi;
|
|
2880
|
-
this.profileApi = opts.profileApi;
|
|
2881
|
-
this.profileLikeApi = opts.profileLikeApi;
|
|
2882
|
-
this.webApi = opts.webApi;
|
|
2883
|
-
this.groupCache = opts.groupCache;
|
|
2884
|
-
this.messageUnique = new MessageUnique();
|
|
2885
|
-
this.self = opts.self;
|
|
2886
|
-
this.selfUin = opts.self.uin;
|
|
2887
|
-
this.appVersion = opts.system.appVersion;
|
|
2888
|
-
this.cleanCache = opts.system.cleanCache;
|
|
2889
|
-
this.cacheDir = opts.system.cacheDir;
|
|
2890
|
-
this.mediaBaseDir = opts.system.mediaBaseDir;
|
|
2891
|
-
this.exit = opts.system.exit;
|
|
2892
|
-
this.restart = opts.system.restart;
|
|
2893
|
-
this.logger = opts.logger;
|
|
2894
|
-
}
|
|
2895
|
-
/**
|
|
2896
|
-
* uin→uid 转换(委托 groupApi;私聊目标/成员 user_id 用)。
|
|
2897
|
-
* 类字段箭头函数:动作会把本方法作为回调裸传(resolveUid 等),必须绑定实例,
|
|
2898
|
-
* 脱绑调用 this 为 undefined 会炸 groupApi(issue #110 侧报)。
|
|
2899
|
-
*/
|
|
2900
|
-
uinToUid = (uins) => {
|
|
2901
|
-
return this.groupApi.uinToUid(uins);
|
|
2902
|
-
};
|
|
2903
|
-
/** uid→uin 转换(委托 groupApi;notice/grayTip 用;同 uinToUid 绑定实例)。 */
|
|
2904
|
-
uidToUin = (uids) => {
|
|
2905
|
-
return this.groupApi.uidToUin(uids);
|
|
2906
|
-
};
|
|
2907
|
-
/**
|
|
2908
|
-
* 群成员角色(GroupCache 缓存优先,缺失惰性回填;sender.role 判定用)。
|
|
2909
|
-
* 未装配缓存 / 成员不在群 / 查询失败 → undefined(调用方回退缺省 "member",
|
|
2910
|
-
* 不阻塞消息上报)。
|
|
2911
|
-
*/
|
|
2912
|
-
async groupMemberRole(groupCode, uid) {
|
|
2913
|
-
if (this.groupCache === void 0) return;
|
|
2914
|
-
try {
|
|
2915
|
-
const member = await this.groupCache.getMember(groupCode, uid);
|
|
2916
|
-
return member === void 0 ? void 0 : GroupApi.roleToString(member.role);
|
|
2917
|
-
} catch (err) {
|
|
2918
|
-
this.logger?.warn({
|
|
2919
|
-
group: groupCode,
|
|
2920
|
-
uid,
|
|
2921
|
-
error: errorMessage(err)
|
|
2922
|
-
}, "ob11: 群成员缓存读取失败,sender.role 回退 member");
|
|
2923
|
-
return;
|
|
2924
|
-
}
|
|
2925
|
-
}
|
|
2926
|
-
/**
|
|
2927
|
-
* 群成员角色表(历史消息批量用:一次整表读取,uid → role)。
|
|
2928
|
-
* 失败语义同 groupMemberRole。
|
|
2929
|
-
*/
|
|
2930
|
-
async groupMemberRoles(groupCode) {
|
|
2931
|
-
if (this.groupCache === void 0) return;
|
|
2932
|
-
try {
|
|
2933
|
-
const out = /* @__PURE__ */ new Map();
|
|
2934
|
-
for (const member of await this.groupCache.getMembers(groupCode)) out.set(member.uid, GroupApi.roleToString(member.role));
|
|
2935
|
-
return out;
|
|
2936
|
-
} catch (err) {
|
|
2937
|
-
this.logger?.warn({
|
|
2938
|
-
group: groupCode,
|
|
2939
|
-
error: errorMessage(err)
|
|
2940
|
-
}, "ob11: 群成员表缓存读取失败,历史 role 回退 member");
|
|
2941
|
-
return;
|
|
2942
|
-
}
|
|
2943
|
-
}
|
|
2944
|
-
};
|
|
2945
|
-
// src/onebot11/enrichment.ts
|
|
2946
|
-
/** 资料详情兜底的单批上限(好友申请批通常只有个位数,超限多为历史积压)。 */
|
|
2947
|
-
const MAX_PROFILE_LOOKUPS = 10;
|
|
2948
|
-
/** OB11 收链路异步回填器。 */
|
|
2949
|
-
var Ob11Enrichment = class {
|
|
2950
|
-
api;
|
|
2951
|
-
calibLogger;
|
|
2952
|
-
constructor(deps) {
|
|
2953
|
-
this.api = deps.api;
|
|
2954
|
-
this.calibLogger = deps.logger;
|
|
2955
|
-
}
|
|
2956
|
-
/**
|
|
2957
|
-
* uid 批量 → uin(失败退空 Map:翻译层退化为 uid 数值,不阻塞请求上报)。
|
|
2958
|
-
*
|
|
2959
|
-
* 群成员口径(`getUinByUids`)解析不到的 uid 用资料详情兜底(issue #122):
|
|
2960
|
-
* 好友申请的申请人通常不在任何群里,群口径必然失败,不回退会让 `user_id` 恒 0。
|
|
2961
|
-
*/
|
|
2962
|
-
async uidToUinMap(uids) {
|
|
2963
|
-
if (uids.length === 0) return /* @__PURE__ */ new Map();
|
|
2964
|
-
let map;
|
|
2965
|
-
try {
|
|
2966
|
-
map = await this.api.uidToUin(uids);
|
|
2967
|
-
} catch (err) {
|
|
2968
|
-
this.calibLogger?.warn({
|
|
2969
|
-
count: uids.length,
|
|
2970
|
-
error: errorMessage(err)
|
|
2971
|
-
}, "ob11: 请求 uid→uin 批量转换失败,退用 uid");
|
|
2972
|
-
map = /* @__PURE__ */ new Map();
|
|
2973
|
-
}
|
|
2974
|
-
await this.fillMissingUins(uids, map);
|
|
2975
|
-
return map;
|
|
2976
|
-
}
|
|
2977
|
-
/**
|
|
2978
|
-
* 群口径未命中的 uid 逐个走 `profileApi.getUinByUid` 兜底(原地补 map)。
|
|
2979
|
-
* fail-soft:单条失败 / 查不到保持未命中(翻译层退 0);条数设上限,防历史积压
|
|
2980
|
-
* 批次把逐条 IPC 打满。
|
|
2981
|
-
*/
|
|
2982
|
-
async fillMissingUins(uids, map) {
|
|
2983
|
-
const missing = [...new Set(uids)].filter((uid) => uid !== "" && !map.has(uid));
|
|
2984
|
-
for (const uid of missing.slice(0, MAX_PROFILE_LOOKUPS)) try {
|
|
2985
|
-
const uin = await this.api.profileApi.getUinByUid(uid);
|
|
2986
|
-
if (uin !== null) map.set(uid, uin);
|
|
2987
|
-
} catch (err) {
|
|
2988
|
-
this.calibLogger?.debug({ error: errorMessage(err) }, "ob11: uid→uin 资料兜底失败(该 uid 退 0)");
|
|
2989
|
-
}
|
|
2990
|
-
if (missing.length > MAX_PROFILE_LOOKUPS) this.calibLogger?.debug({
|
|
2991
|
-
missing: missing.length,
|
|
2992
|
-
limit: MAX_PROFILE_LOOKUPS
|
|
2993
|
-
}, "ob11: 待兜底 uid 超上限,其余保持未命中");
|
|
2994
|
-
}
|
|
2995
|
-
/**
|
|
2996
|
-
* notice uid 批量转换(空集退空 Map)。失败上抛不吞:grayTip 解析宽容但
|
|
2997
|
-
* uid 查询炸掉时整个 notice 丢弃(与原 adapter 行为一致,调用方 catch)。
|
|
2998
|
-
*/
|
|
2999
|
-
async noticeUidMap(uids) {
|
|
3000
|
-
if (uids.length === 0) return /* @__PURE__ */ new Map();
|
|
3001
|
-
return this.api.uidToUin(uids);
|
|
3002
|
-
}
|
|
3003
|
-
/**
|
|
3004
|
-
* 消息事件翻译上下文(接收方向 ID 转换)。
|
|
3005
|
-
* at uid → 一次批量 uidToUin;群消息另查发送者角色(GroupCache 缓存优先,
|
|
3006
|
-
* 失败回退缺省 member);msgId → OB11 id 经 messageUnique 反查。
|
|
3007
|
-
*/
|
|
3008
|
-
async messageContext(msg) {
|
|
3009
|
-
const { atUids } = collectReceiveNeeds(toCanonicalElements(msg));
|
|
3010
|
-
let uidToUin;
|
|
3011
|
-
if (atUids.length > 0) try {
|
|
3012
|
-
uidToUin = await this.api.uidToUin(atUids);
|
|
3013
|
-
} catch (err) {
|
|
3014
|
-
this.calibLogger?.warn({
|
|
3015
|
-
count: atUids.length,
|
|
3016
|
-
error: errorMessage(err)
|
|
3017
|
-
}, "ob11: 消息 at uid→uin 失败,at 原样");
|
|
3018
|
-
}
|
|
3019
|
-
const senderRole = msg.chatType === ChatType.GROUP ? await this.api.groupMemberRole(msg.peerUid, msg.senderUid) : void 0;
|
|
3020
|
-
return {
|
|
3021
|
-
...uidToUin !== void 0 ? { uidToUin } : {},
|
|
3022
|
-
...senderRole !== void 0 ? { senderRole } : {},
|
|
3023
|
-
msgIdToOb11Id: (msgId) => this.api.messageUnique.getMessageId(msgId)
|
|
3024
|
-
};
|
|
3025
|
-
}
|
|
3026
|
-
/** sysmsg 规则的 uid→uin 解析器(collectUids 声明才批量转换;失败/缺省恒 0)。 */
|
|
3027
|
-
async sysMsgUinResolver(rule, tree, env) {
|
|
3028
|
-
if (rule.collectUids === void 0) return () => 0;
|
|
3029
|
-
const uids = rule.collectUids(tree, env).filter((uid) => uid !== "");
|
|
3030
|
-
if (uids.length === 0) return () => 0;
|
|
3031
|
-
try {
|
|
3032
|
-
const map = await this.api.uidToUin(uids);
|
|
3033
|
-
return (uid) => Number(map.get(uid) ?? 0);
|
|
3034
|
-
} catch (err) {
|
|
3035
|
-
this.calibLogger?.warn({
|
|
3036
|
-
msgType: env.msgType,
|
|
3037
|
-
subType: env.subType,
|
|
3038
|
-
count: uids.length,
|
|
3039
|
-
error: errorMessage(err)
|
|
3040
|
-
}, "ob11: sysmsg uid→uin 失败,实体 uin 恒 0");
|
|
3041
|
-
return () => 0;
|
|
3042
|
-
}
|
|
3043
|
-
}
|
|
3044
|
-
/**
|
|
3045
|
-
* 精华 message_id 反查:msgSeq → 近段历史扫描(60 条,对齐 milky
|
|
3046
|
-
* resolveMsgIdBySeq fallback 层)→ MessageUnique.alloc 幂等分配(可被 get_msg
|
|
3047
|
-
* 反查的正确空间,对照 recall 的 msgSeq 错位)。未命中返回 null(跳过事件)。
|
|
3048
|
-
*/
|
|
3049
|
-
async resolveEssenceMsgId(groupCode, seq) {
|
|
3050
|
-
const peer = {
|
|
3051
|
-
chatType: ChatType.GROUP,
|
|
3052
|
-
peerUid: groupCode
|
|
3053
|
-
};
|
|
3054
|
-
const hit = (await this.api.msgApi.fetchMessages(peer, { count: 60 }).catch((err) => {
|
|
3055
|
-
this.calibLogger?.debug({
|
|
3056
|
-
group: groupCode,
|
|
3057
|
-
error: errorMessage(err)
|
|
3058
|
-
}, "ob11: 精华反查近段历史拉取失败");
|
|
3059
|
-
return [];
|
|
3060
|
-
})).find((m) => Number(m.msgSeq) === seq);
|
|
3061
|
-
if (hit === void 0) {
|
|
3062
|
-
this.calibLogger?.warn({
|
|
3063
|
-
group: groupCode,
|
|
3064
|
-
seq
|
|
3065
|
-
}, "ob11: 精华 message_id 反查未命中(跳过事件)");
|
|
3066
|
-
return null;
|
|
3067
|
-
}
|
|
3068
|
-
return this.api.messageUnique.alloc(hit.msgId, peer);
|
|
3069
|
-
}
|
|
3070
|
-
};
|
|
3071
|
-
// src/onebot11/inbound/essence.ts
|
|
3072
|
-
/** OB11 精华域处理器(串行 diff 同步 + group_essence notice 广播)。 */
|
|
3073
|
-
var Ob11InboundEssence = class {
|
|
3074
|
-
deps;
|
|
3075
|
-
essenceSync;
|
|
3076
|
-
constructor(deps) {
|
|
3077
|
-
this.deps = deps;
|
|
3078
|
-
this.essenceSync = new EssenceListSync({
|
|
3079
|
-
fetchList: (groupCode) => deps.api.webApi.getEssenceMsgList(groupCode),
|
|
3080
|
-
onAdded: (groupCode, added) => this.broadcastDiff(groupCode, added, "add"),
|
|
3081
|
-
onRemoved: (groupCode, removed, prev) => this.broadcastDiff(groupCode, removed.map((seq) => ({
|
|
3082
|
-
messageSeq: seq,
|
|
3083
|
-
senderUin: prev.get(seq)?.senderUin ?? null,
|
|
3084
|
-
operatorUin: null,
|
|
3085
|
-
addDigestTime: null
|
|
3086
|
-
})), "delete"),
|
|
3087
|
-
onFetchError: (g, err) => deps.logger?.warn({
|
|
3088
|
-
group: g,
|
|
3089
|
-
err: String(err)
|
|
3090
|
-
}, "ob11: 精华列表拉取失败(diff 跳过)")
|
|
3091
|
-
});
|
|
3092
|
-
}
|
|
3093
|
-
/** sysmsg 732:1 加速触发器:抽取群号踢入串行链(抽取失败 → false 落校准路径)。 */
|
|
3094
|
-
triggerFromSysMsg(tree) {
|
|
3095
|
-
const hit = extractEssenceSetSysMsg(tree);
|
|
3096
|
-
if (hit === null) return false;
|
|
3097
|
-
this.essenceSync.enqueue(String(hit.groupCode));
|
|
3098
|
-
return true;
|
|
3099
|
-
}
|
|
3100
|
-
/** 精华列表变更:拉全量列表 diff(唯一发射路径;参数收窄失败走校准日志)。 */
|
|
3101
|
-
change(arg) {
|
|
3102
|
-
const groupCode = narrowEssenceGroupArg(arg);
|
|
3103
|
-
if (groupCode === null) {
|
|
3104
|
-
this.deps.logger?.warn({ raw: truncRaw(JSON.stringify(arg)) }, "ob11: onGroupEssenceListChange 未知参数形状");
|
|
3105
|
-
return;
|
|
3106
|
-
}
|
|
3107
|
-
this.essenceSync.enqueue(groupCode);
|
|
3108
|
-
}
|
|
3109
|
-
/** diff 逐条广播(add/delete 共用):sender 必填 → message_id 反查 → notice 装配。 */
|
|
3110
|
-
async broadcastDiff(groupCode, items, subType) {
|
|
3111
|
-
const { enrich, broadcast, selfUin } = this.deps;
|
|
3112
|
-
for (const item of items) {
|
|
3113
|
-
const senderId = numericUin(item.senderUin);
|
|
3114
|
-
if (senderId === null) {
|
|
3115
|
-
const detail = subType === "add" ? "新增 sender_uin 缺失" : "移除 sender 不可得";
|
|
3116
|
-
this.deps.logger?.warn({
|
|
3117
|
-
group: groupCode,
|
|
3118
|
-
seq: item.messageSeq
|
|
3119
|
-
}, `ob11: 精华${detail}(跳过事件)`);
|
|
3120
|
-
continue;
|
|
3121
|
-
}
|
|
3122
|
-
const messageId = await enrich.resolveEssenceMsgId(groupCode, item.messageSeq);
|
|
3123
|
-
if (messageId === null) continue;
|
|
3124
|
-
const operatorId = numericUin(item.operatorUin);
|
|
3125
|
-
broadcast({
|
|
3126
|
-
time: item.addDigestTime ?? Math.floor(Date.now() / 1e3),
|
|
3127
|
-
self_id: Number(selfUin),
|
|
3128
|
-
post_type: "notice",
|
|
3129
|
-
notice_type: "group_essence",
|
|
3130
|
-
sub_type: subType,
|
|
3131
|
-
group_id: Number(groupCode),
|
|
3132
|
-
sender_id: senderId,
|
|
3133
|
-
...operatorId !== null ? { operator_id: operatorId } : {},
|
|
3134
|
-
message_id: messageId
|
|
3135
|
-
});
|
|
3136
|
-
}
|
|
3137
|
-
}
|
|
3138
|
-
};
|
|
3139
|
-
// src/onebot11/helper/notice-extra.ts
|
|
3140
|
-
/**
|
|
3141
|
-
* OB11 notice 事件翻译·扩展源(c3)
|
|
3142
|
-
*
|
|
3143
|
-
* 数据源 = kernel 桥 新接线回调(notice.ts 的 grayTip 路径之外):
|
|
3144
|
-
* - Msg/onRecvOfflineFileMsg → OB11 offline_file notice(翻译)
|
|
3145
|
-
* - Msg/onRecvSysMsg / Msg/onRecvOnlineFileMsg / Group/onGroupEssenceListChange
|
|
3146
|
-
* → 暂不翻译(adapter 侧 raw 校准日志;sys msg 为群名片/头衔/精华等系统
|
|
3147
|
-
* 事件的总载体,真实 payload 到达后回填翻译)
|
|
3148
|
-
*
|
|
3149
|
-
* ⚠️ payload 形状未经真实事件校准(方法名证据 = wrapper.node 字符串,见 kernel
|
|
3150
|
-
* listeners 注释)——防御性收窄:未知形状返回 null,调用方打 raw 日志积累校准
|
|
3151
|
-
* 数据(与 narrowBuddyReqs 同模式)。翻译纯函数。
|
|
3152
|
-
*/
|
|
3153
|
-
/** 候选 uin 字段(按优先级取第一个数字串;uid 串不硬转——待校准)。 */
|
|
3154
|
-
function pickUin(item) {
|
|
3155
|
-
for (const key of [
|
|
3156
|
-
"senderUin",
|
|
3157
|
-
"fromUin",
|
|
3158
|
-
"peerUin"
|
|
3159
|
-
]) {
|
|
3160
|
-
const v = item[key];
|
|
3161
|
-
if (typeof v === "string" && v !== "" && Number.isFinite(Number(v))) return v;
|
|
3162
|
-
}
|
|
3163
|
-
return "0";
|
|
3164
|
-
}
|
|
3165
|
-
/** 候选 url 字段(fileUrl / url;未知为空串)。 */
|
|
3166
|
-
function pickUrl(item) {
|
|
3167
|
-
for (const key of ["fileUrl", "url"]) {
|
|
3168
|
-
const v = item[key];
|
|
3169
|
-
if (typeof v === "string" && v !== "") return v;
|
|
3170
|
-
}
|
|
3171
|
-
return "";
|
|
3172
|
-
}
|
|
3173
|
-
/** 单个候选对象 → 归一化项(不可识别返回 null)。接受两类形状:
|
|
3174
|
-
* ① RawMessage 型(elements[].fileElement——离线文件以消息推送到达的假设,
|
|
3175
|
-
* 与 onRecvOfflineFileMsg 挂在 MsgService、UpdateC2CFileMsg 字符串一致)
|
|
3176
|
-
* ② 专用实体型(顶层 fileName 或 fileInfo.fileName——getNewOfflineFileList 族) */
|
|
3177
|
-
function narrowItem(item) {
|
|
3178
|
-
if (typeof item !== "object" || item === null) return null;
|
|
3179
|
-
const obj = item;
|
|
3180
|
-
if (Array.isArray(obj["elements"])) {
|
|
3181
|
-
const file = obj["elements"].find((e) => typeof e === "object" && e !== null && "fileElement" in e)?.fileElement;
|
|
3182
|
-
if (file == null) return null;
|
|
3183
|
-
return {
|
|
3184
|
-
senderUin: pickUin(obj),
|
|
3185
|
-
name: typeof file["fileName"] === "string" ? file["fileName"] : "",
|
|
3186
|
-
size: Number(file["fileSize"] ?? 0),
|
|
3187
|
-
url: pickUrl(file)
|
|
3188
|
-
};
|
|
3189
|
-
}
|
|
3190
|
-
const file = obj["fileInfo"] ?? obj;
|
|
3191
|
-
if (typeof file["fileName"] !== "string") return null;
|
|
3192
|
-
return {
|
|
3193
|
-
senderUin: pickUin(obj),
|
|
3194
|
-
name: file["fileName"],
|
|
3195
|
-
size: Number(file["fileSize"] ?? 0),
|
|
3196
|
-
url: pickUrl(file)
|
|
3197
|
-
};
|
|
3198
|
-
}
|
|
3199
|
-
/**
|
|
3200
|
-
* onRecvOfflineFileMsg 参数 → 归一化项列表(防御性收窄)。
|
|
3201
|
-
* 接受数组 / 单对象;全部不可识别返回 null(调用方打 raw 日志)。
|
|
3202
|
-
* 空数组同样返回 null(无文件可翻译,与未知形状同走日志路径无害)。
|
|
3203
|
-
*/
|
|
3204
|
-
function narrowOfflineFiles(arg) {
|
|
3205
|
-
const narrowed = (Array.isArray(arg) ? arg : [arg]).map(narrowItem).filter((v) => v !== null);
|
|
3206
|
-
return narrowed.length > 0 ? narrowed : null;
|
|
3207
|
-
}
|
|
3208
|
-
/** 归一化项 → OB11 offline_file notice(time 取当前时刻,friend_add 同款)。 */
|
|
3209
|
-
function toOfflineFileNotice(item, selfUin) {
|
|
3210
|
-
return {
|
|
3211
|
-
time: Math.floor(Date.now() / MS_TO_SEC),
|
|
3212
|
-
self_id: Number(selfUin),
|
|
3213
|
-
post_type: "notice",
|
|
3214
|
-
notice_type: "offline_file",
|
|
3215
|
-
user_id: Number(item.senderUin),
|
|
3216
|
-
file: {
|
|
3217
|
-
name: item.name,
|
|
3218
|
-
size: item.size,
|
|
3219
|
-
url: item.url
|
|
3220
|
-
}
|
|
3221
|
-
};
|
|
3222
|
-
}
|
|
3223
|
-
// src/onebot11/inbound/file-notice.ts
|
|
3224
|
-
/** OB11 轻量通知域处理器(文件 / 好友新增等无独立翻译链的通知)。 */
|
|
3225
|
-
var Ob11InboundFileNotice = class {
|
|
3226
|
-
deps;
|
|
3227
|
-
constructor(deps) {
|
|
3228
|
-
this.deps = deps;
|
|
3229
|
-
}
|
|
3230
|
-
/**
|
|
3231
|
-
* 离线文件(c3):Msg/onRecvOfflineFileMsg → OB11 offline_file
|
|
3232
|
-
* notice(payload 形状待校准:防御性收窄,未知形状 raw 日志积累)。
|
|
3233
|
-
*/
|
|
3234
|
-
offlineFile(arg) {
|
|
3235
|
-
const items = narrowOfflineFiles(arg);
|
|
3236
|
-
if (items === null) {
|
|
3237
|
-
this.deps.logger?.warn({ raw: truncRaw(JSON.stringify(arg)) }, "ob11: onRecvOfflineFileMsg 未知参数形状");
|
|
3238
|
-
return;
|
|
3239
|
-
}
|
|
3240
|
-
for (const item of items) this.deps.broadcast(toOfflineFileNotice(item, this.deps.selfUin));
|
|
3241
|
-
}
|
|
3242
|
-
/** 在线文件:OB11 无对应通知类型;debug 级 raw 校准日志。 */
|
|
3243
|
-
onlineFile(arg) {
|
|
3244
|
-
this.deps.logger?.debug({ raw: sliceRaw(JSON.stringify(arg)) }, "ob11: onRecvOnlineFileMsg raw(校准数据)");
|
|
3245
|
-
}
|
|
3246
|
-
/** 好友列表变化:快照字段较多,raw 日志保留积累校准数据(翻译走 friendAdd)。 */
|
|
3247
|
-
buddyList(evt, arg) {
|
|
3248
|
-
this.deps.logger?.info({ raw: truncRaw(JSON.stringify(arg)) }, `ob11: ${evt} raw(friend_add 校准数据)`);
|
|
3249
|
-
}
|
|
3250
|
-
/** 好友缓存 diff 新增()→ friend_add notice(翻译纯函数)。 */
|
|
3251
|
-
friendAdd(entry) {
|
|
3252
|
-
this.deps.broadcast(toFriendAdd(entry, this.deps.selfUin));
|
|
3253
|
-
}
|
|
3254
|
-
};
|
|
3255
|
-
// src/onebot11/helper/message-event.ts
|
|
3256
|
-
/** RawMessage → OB11 消息事件(message_id 经 MessageUnique 映射并记录 peer)。
|
|
3257
|
-
* messageFormat 决定 message 字段格式:array = 消息段数组(标准),string = CQ 码字符串。
|
|
3258
|
-
* ctx(可选):接收方向 ID 转换上下文(at uid→uin、reply NT msgId→OB11 id)。 */
|
|
3259
|
-
function toOb11MessageEvent(msg, selfUin, unique, messageFormat = "array", ctx = {}) {
|
|
3260
|
-
const elements = applyReceiveContext(toCanonicalElements(msg), ctx);
|
|
3261
|
-
const segments = canonicalToSegments(elements);
|
|
3262
|
-
const time = toUnixSeconds(msg.msgTime);
|
|
3263
|
-
const selfId = Number(selfUin);
|
|
3264
|
-
const userId = Number(msg.senderUin);
|
|
3265
|
-
const base = {
|
|
3266
|
-
time,
|
|
3267
|
-
self_id: selfId,
|
|
3268
|
-
post_type: "message",
|
|
3269
|
-
message_id: unique.alloc(msg.msgId, {
|
|
3270
|
-
chatType: msg.chatType,
|
|
3271
|
-
peerUid: msg.peerUid
|
|
3272
|
-
}),
|
|
3273
|
-
message: messageFormat === "string" ? canonicalToCqMessage(elements) : segments,
|
|
3274
|
-
raw_message: canonicalToCqMessage(elements),
|
|
3275
|
-
font: 0
|
|
3276
|
-
};
|
|
3277
|
-
if (msg.chatType === ChatType.GROUP) {
|
|
3278
|
-
const sender = {
|
|
3279
|
-
user_id: userId,
|
|
3280
|
-
nickname: senderNickname(msg),
|
|
3281
|
-
role: ctx.senderRole ?? "member"
|
|
3282
|
-
};
|
|
3283
|
-
if (msg.sendMemberName !== void 0) sender.card = msg.sendMemberName;
|
|
3284
|
-
return {
|
|
3285
|
-
...base,
|
|
3286
|
-
message_type: "group",
|
|
3287
|
-
sub_type: "normal",
|
|
3288
|
-
group_id: Number(msg.peerUid),
|
|
3289
|
-
user_id: userId,
|
|
3290
|
-
sender
|
|
3291
|
-
};
|
|
3292
|
-
}
|
|
3293
|
-
let subType = "friend";
|
|
3294
|
-
if (msg.chatType === ChatType.C2C_TEMP) subType = "group";
|
|
3295
|
-
const sender = {
|
|
3296
|
-
user_id: userId,
|
|
3297
|
-
nickname: senderNickname(msg)
|
|
3298
|
-
};
|
|
3299
|
-
return {
|
|
3300
|
-
...base,
|
|
3301
|
-
message_type: "private",
|
|
3302
|
-
sub_type: subType,
|
|
3303
|
-
user_id: userId,
|
|
3304
|
-
sender
|
|
3305
|
-
};
|
|
3306
|
-
}
|
|
3307
|
-
// src/onebot11/inbound/message.ts
|
|
3308
|
-
/** OB11 消息域处理器(Msg/onRecvMsg 分流与翻译派发)。 */
|
|
3309
|
-
var Ob11InboundMessage = class {
|
|
3310
|
-
deps;
|
|
3311
|
-
reportSelfMessage = false;
|
|
3312
|
-
messageFormat = "array";
|
|
3313
|
-
/** 群文件报形式():true = fileElement 群消息报 group_upload notice 替代 message。 */
|
|
3314
|
-
groupUploadAsNotice = false;
|
|
3315
|
-
constructor(deps) {
|
|
3316
|
-
this.deps = deps;
|
|
3317
|
-
}
|
|
3318
|
-
/** 刷新收链路开关(start / subscribeOnly / reload 共用)。 */
|
|
3319
|
-
applyConfig(config) {
|
|
3320
|
-
this.reportSelfMessage = config.reportSelfMessage;
|
|
3321
|
-
this.messageFormat = config.messagePostFormat;
|
|
3322
|
-
this.groupUploadAsNotice = config.groupUploadAsNotice;
|
|
3323
|
-
}
|
|
3324
|
-
/** 单条收向消息:grayTip→notice / 自消息过滤 / 群文件开关 / message 事件。 */
|
|
3325
|
-
handleRawMessage(msg) {
|
|
3326
|
-
if (hasGrayTip(msg)) {
|
|
3327
|
-
this.broadcastNotice(msg).catch((err) => {
|
|
3328
|
-
this.deps.logger?.debug({ err: errorMessage(err) }, "ob11: notice 翻译失败(整个事件丢弃)");
|
|
3329
|
-
});
|
|
3330
|
-
return;
|
|
3331
|
-
}
|
|
3332
|
-
if (!this.reportSelfMessage && String(msg.senderUin) === this.deps.selfUin) return;
|
|
3333
|
-
if (this.groupUploadAsNotice && msg.chatType === ChatType.GROUP && hasFileElement(msg)) {
|
|
3334
|
-
const notice = toGroupUpload(msg, this.deps.selfUin);
|
|
3335
|
-
if (notice !== null) {
|
|
3336
|
-
this.deps.broadcast(notice);
|
|
3337
|
-
return;
|
|
3338
|
-
}
|
|
3339
|
-
}
|
|
3340
|
-
this.broadcastMessageEvent(msg).catch((err) => logEventFailure(this.deps.logger, "ob11: message 事件翻译失败(单条丢弃)", err));
|
|
3341
|
-
}
|
|
3342
|
-
/**
|
|
3343
|
-
* 广播消息事件:回填 ctx 后交纯函数翻译;ID 转换在 enrichment 批量完成。
|
|
3344
|
-
*/
|
|
3345
|
-
async broadcastMessageEvent(msg) {
|
|
3346
|
-
const ctx = await this.deps.enrich.messageContext(msg);
|
|
3347
|
-
this.deps.broadcast(toOb11MessageEvent(msg, this.deps.selfUin, this.deps.api.messageUnique, this.messageFormat, ctx));
|
|
3348
|
-
}
|
|
3349
|
-
/** 广播 grayTip → notice 事件(批量 uidToUin 后翻译,纯函数)。 */
|
|
3350
|
-
async broadcastNotice(msg) {
|
|
3351
|
-
const uidToUin = await this.deps.enrich.noticeUidMap(collectGrayTipUids(msg));
|
|
3352
|
-
const notice = toOb11NoticeEvent(msg, {
|
|
3353
|
-
selfUin: this.deps.selfUin,
|
|
3354
|
-
uidToUin,
|
|
3355
|
-
...this.deps.logger !== void 0 ? { logger: this.deps.logger } : {}
|
|
3356
|
-
});
|
|
3357
|
-
if (notice !== null) this.deps.broadcast(notice);
|
|
3358
|
-
}
|
|
3359
|
-
};
|
|
3360
|
-
// src/onebot11/inbound/request.ts
|
|
3361
|
-
/** OB11 请求域处理器(群通知 / 好友申请的 uid 回填与广播)。 */
|
|
3362
|
-
var Ob11InboundRequest = class {
|
|
3363
|
-
deps;
|
|
3364
|
-
/** 已广播申请的 `${friendUid}:${reqTime}`(实例级,跨 reloadTransports 保留)。 */
|
|
3365
|
-
dedup = new BuddyReqDedup();
|
|
3366
|
-
/** 历史积压基准(订阅时刷新:重连后以此刻为界)。 */
|
|
3367
|
-
baselineSec = startupBaselineSec();
|
|
3368
|
-
constructor(deps) {
|
|
3369
|
-
this.deps = deps;
|
|
3370
|
-
}
|
|
3371
|
-
/** 刷新启动基准(pipeline subscribe 时调用)。 */
|
|
3372
|
-
markStartup() {
|
|
3373
|
-
this.baselineSec = startupBaselineSec();
|
|
3374
|
-
}
|
|
3375
|
-
/** 群系统通知 → group request 事件(批量 uidToUin 后翻译,纯函数)。 */
|
|
3376
|
-
async groupNotifies(doubt, notifies) {
|
|
3377
|
-
if (doubt || !Array.isArray(notifies)) return;
|
|
3378
|
-
const ctx = await this.requestCtx(collectGroupNotifyUids(notifies));
|
|
3379
|
-
for (const notify of notifies) {
|
|
3380
|
-
const event = toOb11GroupRequestEvent(notify, ctx);
|
|
3381
|
-
if (event !== null) this.deps.broadcast(event);
|
|
3382
|
-
}
|
|
3383
|
-
}
|
|
3384
|
-
/** 好友申请 → friend request 事件(防御收窄;未知形状 raw warn 校准)。 */
|
|
3385
|
-
buddyReqs(arg) {
|
|
3386
|
-
this.broadcastBuddyReqs(arg).catch((err) => logEventFailure(this.deps.logger, "ob11: friend request 翻译失败(整批丢弃)", err));
|
|
3387
|
-
}
|
|
3388
|
-
/** 好友申请翻译派发(flag=reqTime;uid→uin 批量失败退空 Map)。 */
|
|
3389
|
-
async broadcastBuddyReqs(arg) {
|
|
3390
|
-
if (batchUnreadNums(arg) === 0) {
|
|
3391
|
-
this.deps.logger?.debug({}, "ob11: onBuddyReqChange unreadNums=0(整批跳过)");
|
|
3392
|
-
return;
|
|
3393
|
-
}
|
|
3394
|
-
const reqs = narrowBuddyReqs(arg);
|
|
3395
|
-
if (reqs === null) {
|
|
3396
|
-
this.deps.logger?.warn({ raw: truncRaw(JSON.stringify(arg)) }, "ob11: onBuddyReqChange 未知参数形状");
|
|
3397
|
-
return;
|
|
3398
|
-
}
|
|
3399
|
-
const fresh = filterBuddyReqs(reqs, this.baselineSec).filter((req) => this.dedup.claim(req));
|
|
3400
|
-
if (fresh.length < reqs.length) this.deps.logger?.debug({
|
|
3401
|
-
total: reqs.length,
|
|
3402
|
-
kept: fresh.length
|
|
3403
|
-
}, "ob11: 好友申请过滤(历史积压 / 已读 / 已处理 / 重复)");
|
|
3404
|
-
if (fresh.length === 0) return;
|
|
3405
|
-
const ctx = await this.requestCtx(fresh.map((r) => r.friendUid).filter((uid) => uid !== ""));
|
|
3406
|
-
for (const req of fresh) this.deps.broadcast(toOb11FriendRequestEvent(req, ctx));
|
|
3407
|
-
}
|
|
3408
|
-
/** request 翻译上下文(uid→uin 批量;失败退空 Map 不阻塞上报)。 */
|
|
3409
|
-
async requestCtx(uids) {
|
|
3410
|
-
return {
|
|
3411
|
-
selfUin: this.deps.selfUin,
|
|
3412
|
-
uidToUin: await this.deps.enrich.uidToUinMap(uids)
|
|
3413
|
-
};
|
|
3414
|
-
}
|
|
3415
|
-
};
|
|
3416
|
-
/** 收集群系统通知涉及的 uid(user1/user2 双方,空 uid 跳过)。 */
|
|
3417
|
-
function collectGroupNotifyUids(notifies) {
|
|
3418
|
-
const uids = [];
|
|
3419
|
-
for (const notify of notifies) for (const user of [notify.user1, notify.user2]) if (typeof user?.uid === "string" && user.uid !== "") uids.push(user.uid);
|
|
3420
|
-
return uids;
|
|
3421
|
-
}
|
|
3422
|
-
// src/onebot11/helper/sysmsg.ts
|
|
3423
|
-
/**
|
|
3424
|
-
* OB11 sysmsg 识别表(自 helper/sysmsg.ts 瘦身——解码层上移
|
|
3425
|
-
* shared/sysmsg.ts 共享,milky.md §0.8.3/§0.8.6)
|
|
3426
|
-
*
|
|
3427
|
-
* 本模块只保留 OB11 侧内容:
|
|
3428
|
-
* - SysMsgNoticeKind:sysmsg 可映射的 OB11 notice 种类(event/notice.ts 既有类型)
|
|
3429
|
-
* - KIND_TABLE:(msgType, subType) → 规则(键 = 原生分发键)
|
|
3430
|
-
* - OBSERVED_UNNAMED_SYSMSG_KEYS:已观测但未命名的键(不广播,防校准日志噪音)
|
|
3431
|
-
* - recognizeSysMsg:绑定 OB11 表的识别入口
|
|
3432
|
-
*
|
|
3433
|
-
* 解码原语(decodeProtoTree / extractSysMsgEnvelope / narrowSysMsgBlobs 等)
|
|
3434
|
-
* 从 `shared/sysmsg.js` 导入使用。
|
|
3435
|
-
*/
|
|
3436
|
-
/**
|
|
3437
|
-
* (msgType, subType) → 规则表(键 = 原生分发键,design.md §7.1)。
|
|
3438
|
-
*
|
|
3439
|
-
* 不再是空表:732:21(群名片变更)为轮录制取得的首个
|
|
3440
|
-
* 实证条目。card/title 等其余判别值仍无样本支撑,宁可漏报不错报;未识别
|
|
3441
|
-
* 一律走结构化校准日志,不广播。
|
|
3442
|
-
*/
|
|
3443
|
-
const KIND_TABLE = /* @__PURE__ */ new Map([["732:21", {
|
|
3444
|
-
kind: "group_card",
|
|
3445
|
-
collectUids: (_tree, env) => {
|
|
3446
|
-
const subject = env.strings[1];
|
|
3447
|
-
return subject?.startsWith("u_") === true ? [subject] : [];
|
|
3448
|
-
},
|
|
3449
|
-
extract: (_tree, env, uinOf, ctx) => {
|
|
3450
|
-
const [groupCode, subject, cardNew, cardOld] = env.strings;
|
|
3451
|
-
if (groupCode === void 0 || subject === void 0 || !NUMERIC_RE.test(groupCode) || !subject.startsWith("u_")) return null;
|
|
3452
|
-
return {
|
|
3453
|
-
time: ctx.time,
|
|
3454
|
-
self_id: ctx.selfUin,
|
|
3455
|
-
post_type: "notice",
|
|
3456
|
-
notice_type: "group_card",
|
|
3457
|
-
group_id: Number(groupCode),
|
|
3458
|
-
user_id: uinOf(subject),
|
|
3459
|
-
card_new: cardNew ?? "",
|
|
3460
|
-
card_old: cardOld ?? ""
|
|
3461
|
-
};
|
|
3462
|
-
}
|
|
3463
|
-
}]]);
|
|
3464
|
-
/** (msgType, subType) → 识别结果(绑定 OB11 表;table 参数供单测注入合成规则)。 */
|
|
3465
|
-
function recognizeOb11SysMsg(msgType, subType, table = KIND_TABLE) {
|
|
3466
|
-
return recognizeSysMsg(msgType, subType, table, OBSERVED_UNNAMED_SYSMSG_KEYS);
|
|
3467
|
-
}
|
|
3468
|
-
// src/onebot11/inbound/sysmsg.ts
|
|
3469
|
-
/**
|
|
3470
|
-
* OB11 inbound sysmsg 域(自 event-pipeline.ts 拆出)
|
|
3471
|
-
*
|
|
3472
|
-
* Msg/onRecvSysMsg 总闸:参数收窄(未知形状 raw warn)→ 单条字节块走
|
|
3473
|
-
* shared/sysmsg.ts 的 processSysMsgBlob 通用管线(解码 → 信封 → 识别 →
|
|
3474
|
-
* 分流)。表命中做两件事:732:1 精华加速触发器(表外,踢入 essence 域的串行
|
|
3475
|
-
* diff 链)与识别表规则广播(uid→uin 经 enrichment 批量回填后 extract);
|
|
3476
|
-
* 未识别 / 提取失败落校准路径,不广播半成品。
|
|
3477
|
-
*/
|
|
3478
|
-
/** OB11 sysmsg 域处理器(解码识别分流 + 精华触发器)。 */
|
|
3479
|
-
var Ob11InboundSysMsg = class {
|
|
3480
|
-
deps;
|
|
3481
|
-
constructor(deps) {
|
|
3482
|
-
this.deps = deps;
|
|
3483
|
-
}
|
|
3484
|
-
/** onRecvSysMsg 总闸:参数收窄(未知形状 raw warn)→ 逐块走通用管线。 */
|
|
3485
|
-
handleRawArg(arg) {
|
|
3486
|
-
const blobs = narrowSysMsgBlobs(arg);
|
|
3487
|
-
if (blobs === null) {
|
|
3488
|
-
this.deps.logger?.warn({ raw: truncRaw(JSON.stringify(arg)) }, "ob11: onRecvSysMsg 未知参数形状");
|
|
3489
|
-
return;
|
|
3490
|
-
}
|
|
3491
|
-
for (const blob of blobs) processSysMsgBlob(blob, {
|
|
3492
|
-
scope: "ob11",
|
|
3493
|
-
logger: this.deps.logger,
|
|
3494
|
-
decodeFailLevel: "warn",
|
|
3495
|
-
recognize: (msgType, subType) => recognizeOb11SysMsg(msgType, subType),
|
|
3496
|
-
onNotice: (tree, env, rec) => this.handleRecognized(tree, env, rec)
|
|
3497
|
-
});
|
|
3498
|
-
}
|
|
3499
|
-
/**
|
|
3500
|
-
* 已解码 sysmsg 分流(732:1 精华触发器 / 识别表规则广播);返回 true =
|
|
3501
|
-
* 已消费。提取失败返回 false 落入校准路径(不硬广播半成品事件)。
|
|
3502
|
-
*/
|
|
3503
|
-
async handleRecognized(tree, env, rec) {
|
|
3504
|
-
if (env.msgType === 732 && env.subType === 1 && this.deps.essence.triggerFromSysMsg(tree)) return true;
|
|
3505
|
-
if (rec.kind !== "notice") return false;
|
|
3506
|
-
const uinOf = await this.deps.enrich.sysMsgUinResolver(rec.rule, tree, env);
|
|
3507
|
-
const ctx = {
|
|
3508
|
-
selfUin: Number(this.deps.selfUin),
|
|
3509
|
-
time: env.time ?? Math.floor(Date.now() / 1e3)
|
|
3510
|
-
};
|
|
3511
|
-
const event = rec.rule.extract(tree, env, uinOf, ctx);
|
|
3512
|
-
if (event === null) return false;
|
|
3513
|
-
this.deps.broadcast(event);
|
|
3514
|
-
return true;
|
|
3515
|
-
}
|
|
3516
|
-
};
|
|
3517
|
-
// src/onebot11/event-pipeline.ts
|
|
3518
|
-
/**
|
|
3519
|
-
* OB11 收链路订阅接线板:管理 unsubscribes 与 kernel 频道 → 领域处理器路由;
|
|
3520
|
-
* 域处理在 inbound/,异步回填在 enrichment.ts。
|
|
3521
|
-
*/
|
|
3522
|
-
var Ob11EventPipeline = class {
|
|
3523
|
-
deps;
|
|
3524
|
-
essence;
|
|
3525
|
-
message;
|
|
3526
|
-
sysMsg;
|
|
3527
|
-
request;
|
|
3528
|
-
fileNotice;
|
|
3529
|
-
unsubscribes = [];
|
|
3530
|
-
constructor(deps) {
|
|
3531
|
-
this.deps = deps;
|
|
3532
|
-
const enrich = new Ob11Enrichment({
|
|
3533
|
-
api: deps.api,
|
|
3534
|
-
logger: deps.logger
|
|
3535
|
-
});
|
|
3536
|
-
this.essence = new Ob11InboundEssence({
|
|
3537
|
-
...deps,
|
|
3538
|
-
enrich
|
|
3539
|
-
});
|
|
3540
|
-
this.message = new Ob11InboundMessage({
|
|
3541
|
-
...deps,
|
|
3542
|
-
enrich
|
|
3543
|
-
});
|
|
3544
|
-
this.sysMsg = new Ob11InboundSysMsg({
|
|
3545
|
-
...deps,
|
|
3546
|
-
enrich,
|
|
3547
|
-
essence: this.essence
|
|
3548
|
-
});
|
|
3549
|
-
this.request = new Ob11InboundRequest({
|
|
3550
|
-
...deps,
|
|
3551
|
-
enrich
|
|
3552
|
-
});
|
|
3553
|
-
this.fileNotice = new Ob11InboundFileNotice(deps);
|
|
3554
|
-
}
|
|
3555
|
-
applyConfig(config) {
|
|
3556
|
-
this.message.applyConfig(config);
|
|
3557
|
-
}
|
|
3558
|
-
/** 订阅 kernel 事件(消息 + 群 + 好友 + 好友缓存,幂等;路由到 inbound/)。 */
|
|
3559
|
-
subscribe() {
|
|
3560
|
-
if (this.unsubscribes.length > 0) return;
|
|
3561
|
-
this.request.markStartup();
|
|
3562
|
-
const { msgChannel, groupChannel, friendChannel, buddyCacheEvents } = this.deps;
|
|
3563
|
-
this.unsubscribes.push(subscribeRawMessages(msgChannel, (msg) => this.message.handleRawMessage(msg), { logger: this.deps.logger }), msgChannel.on("Msg/onRecvOfflineFileMsg", (a) => this.fileNotice.offlineFile(a)), msgChannel.on("Msg/onRecvSysMsg", (a) => this.sysMsg.handleRawArg(a)), msgChannel.on("Msg/onRecvOnlineFileMsg", (a) => this.fileNotice.onlineFile(a)));
|
|
3564
|
-
if (groupChannel !== void 0) this.unsubscribes.push(groupChannel.on("Group/onGroupNotifiesUpdated", (doubt, notifies) => {
|
|
3565
|
-
this.request.groupNotifies(doubt, notifies).catch((err) => logEventFailure(this.deps.logger, "ob11: group request 翻译失败(整批丢弃)", err));
|
|
3566
|
-
}), groupChannel.on("Group/onGroupEssenceListChange", (a) => this.essence.change(a)));
|
|
3567
|
-
if (friendChannel !== void 0) {
|
|
3568
|
-
this.unsubscribes.push(friendChannel.on("Buddy/onBuddyReqChange", (a) => this.request.buddyReqs(a)));
|
|
3569
|
-
for (const evt of ["Buddy/onBuddyListChange", "Buddy/onBuddyListChangedV2"]) this.unsubscribes.push(friendChannel.on(evt, (a) => this.fileNotice.buddyList(evt, a)));
|
|
3570
|
-
}
|
|
3571
|
-
if (buddyCacheEvents !== void 0) this.unsubscribes.push(buddyCacheEvents.on("BuddyCache/onBuddyAdded", (e) => this.fileNotice.friendAdd(e)));
|
|
3572
|
-
}
|
|
3573
|
-
unsubscribeAll() {
|
|
3574
|
-
for (const off of this.unsubscribes) off();
|
|
3575
|
-
this.unsubscribes = [];
|
|
3576
|
-
}
|
|
3577
|
-
};
|
|
3578
|
-
// src/onebot11/transport.ts
|
|
3579
|
-
/**
|
|
3580
|
-
* OB11 传输装配
|
|
3581
|
-
*
|
|
3582
|
-
* 按 OB11Config 创建/装配 network 传输适配器:
|
|
3583
|
-
* - HTTP 反向(http.enabled):HttpServer 接收第三方调用 → handleRequest → 响应
|
|
3584
|
-
* - WS 反向(ws.enabled):WsServer 第三方连入 → handleRequest(echo 透传)+ 事件广播
|
|
3585
|
-
* - HTTP 正向(httpPost.enabled):HttpClient 事件上报(fire-and-forget)
|
|
3586
|
-
* - WS 正向(wsReverse.enabled):WsClient 主动连第三方(双向)
|
|
3587
|
-
*
|
|
3588
|
-
* 鉴权:token 存在时校验 Authorization: Bearer <token> / access_token 查询参数。
|
|
3589
|
-
* 返回 transports(事件上报用,注册到 broadcaster)与 close(停止时关闭全部)。
|
|
3590
|
-
*/
|
|
3591
|
-
/** Authorization 头前缀。 */
|
|
3592
|
-
const BEARER_PREFIX = "Bearer ";
|
|
3593
|
-
/** 校验 URL 查询参数里的 access_token(WS client 连接 URL 可能带)。
|
|
3594
|
-
* ⚠️ req.url 是纯路径(无 origin),new URL(相对路径) 必抛——
|
|
3595
|
-
* E2E 实测抓到的 bug(查询参数鉴权从未生效,WS 全被 4401 关闭),
|
|
3596
|
-
* 用 dummy base 解析。 */
|
|
3597
|
-
function hasAccessTokenQuery(url, token) {
|
|
3598
|
-
try {
|
|
3599
|
-
return new URL(url, "http://localhost").searchParams.get("access_token") === token;
|
|
3600
|
-
} catch {
|
|
3601
|
-
return false;
|
|
3602
|
-
}
|
|
3603
|
-
}
|
|
3604
|
-
/** 校验 Authorization: Bearer <token> 头。 */
|
|
3605
|
-
function checkBearer(auth, token) {
|
|
3606
|
-
if (auth === void 0 || !auth.startsWith(BEARER_PREFIX)) return false;
|
|
3607
|
-
return auth.slice(7) === token;
|
|
3608
|
-
}
|
|
3609
|
-
/** 构造鉴权钩子(token 未配置则不鉴权)。 */
|
|
3610
|
-
function makeAuthorize(token) {
|
|
3611
|
-
if (token === void 0 || token === "") return;
|
|
3612
|
-
return (ctx) => {
|
|
3613
|
-
if (checkBearer(ctx.headers["authorization"] ?? ctx.headers["Authorization"], token) || ctx.headers["authorization"] === token) return true;
|
|
3614
|
-
return hasAccessTokenQuery(ctx.url, token);
|
|
3615
|
-
};
|
|
3616
|
-
}
|
|
3617
|
-
/**
|
|
3618
|
-
* OneBot 客户端标识头:koishi 的 onebot 适配器按
|
|
3619
|
-
* x-client-role === "Universal" 与 x-self-id 校验 WS 连接(NapCat 同款头),
|
|
3620
|
-
* 缺失会被 close(1008) 拒绝——连接虽握手成功但应用层不认。
|
|
3621
|
-
*/
|
|
3622
|
-
function oneBotClientHeaders(selfUin) {
|
|
3623
|
-
return {
|
|
3624
|
-
"X-Self-ID": selfUin,
|
|
3625
|
-
"x-client-role": "Universal",
|
|
3626
|
-
"User-Agent": "OneBot/11"
|
|
3627
|
-
};
|
|
3628
|
-
}
|
|
3629
|
-
/** 按配置装配 OB11 传输。 */
|
|
3630
|
-
function assembleOb11Transports(opts) {
|
|
3631
|
-
const { config, broadcaster, handleRequest, selfUin } = opts;
|
|
3632
|
-
const servers = [];
|
|
3633
|
-
const transports = [];
|
|
3634
|
-
assembleHttpServers(config, handleRequest, servers);
|
|
3635
|
-
assembleWsServers(config, handleRequest, servers);
|
|
3636
|
-
assembleHttpPosts(config, selfUin, transports);
|
|
3637
|
-
assembleWsReverses(config, selfUin, handleRequest, transports);
|
|
3638
|
-
for (const t of transports) broadcaster.register(t);
|
|
3639
|
-
for (const s of servers) broadcaster.register(s);
|
|
3640
|
-
return {
|
|
3641
|
-
servers,
|
|
3642
|
-
transports,
|
|
3643
|
-
close: async () => {
|
|
3644
|
-
await Promise.all([...servers, ...transports].map((t) => t.close()));
|
|
3645
|
-
for (const t of [...servers, ...transports]) broadcaster.unregister(t);
|
|
3646
|
-
}
|
|
3647
|
-
};
|
|
3648
|
-
}
|
|
3649
|
-
/** 装配 HTTP 反向 server 列表(每实例一个 HttpServer,共享 handleRequest)。 */
|
|
3650
|
-
function assembleHttpServers(config, handleRequest, servers) {
|
|
3651
|
-
for (const item of config.httpServers) if (item.enabled) {
|
|
3652
|
-
const options = {
|
|
3653
|
-
host: item.host,
|
|
3654
|
-
port: item.port
|
|
3655
|
-
};
|
|
3656
|
-
const authorize = makeAuthorize(item.token ?? config.token);
|
|
3657
|
-
if (authorize !== void 0) options.authorize = authorize;
|
|
3658
|
-
const server = new HttpServer(options);
|
|
3659
|
-
server.onRequest = handleRequest;
|
|
3660
|
-
servers.push(server);
|
|
3661
|
-
}
|
|
3662
|
-
}
|
|
3663
|
-
/** 装配反向 WS server 列表(每实例一个 WsServer,心跳 ping + 鉴权)。 */
|
|
3664
|
-
function assembleWsServers(config, handleRequest, servers) {
|
|
3665
|
-
for (const item of config.wsServers) if (item.enabled) {
|
|
3666
|
-
const options = {
|
|
3667
|
-
host: item.host,
|
|
3668
|
-
port: item.port,
|
|
3669
|
-
heartbeat: { intervalMs: item.heartbeatInterval }
|
|
3670
|
-
};
|
|
3671
|
-
const authorize = makeAuthorize(item.token ?? config.token);
|
|
3672
|
-
if (authorize !== void 0) options.authorize = authorize;
|
|
3673
|
-
const server = new WsServer(options);
|
|
3674
|
-
server.onRequest = handleRequest;
|
|
3675
|
-
servers.push(server);
|
|
3676
|
-
}
|
|
3677
|
-
}
|
|
3678
|
-
/** 装配 HTTP 正向上报 client 列表(fire-and-forget)。 */
|
|
3679
|
-
function assembleHttpPosts(config, selfUin, transports) {
|
|
3680
|
-
for (const item of config.httpPostUrls) if (item.enabled && item.url !== void 0) {
|
|
3681
|
-
const headers = {
|
|
3682
|
-
"x-self-id": selfUin,
|
|
3683
|
-
...authorizeHeader(item.token ?? config.token) ?? {}
|
|
3684
|
-
};
|
|
3685
|
-
const options = {
|
|
3686
|
-
url: item.url,
|
|
3687
|
-
headers
|
|
3688
|
-
};
|
|
3689
|
-
if (item.timeoutMs !== void 0) options.timeoutMs = item.timeoutMs;
|
|
3690
|
-
transports.push(new HttpClient(options));
|
|
3691
|
-
}
|
|
3692
|
-
}
|
|
3693
|
-
/** 装配正向 WS client 列表(双向,心跳 + 重连 + 证书选项)。 */
|
|
3694
|
-
function assembleWsReverses(config, selfUin, handleRequest, transports) {
|
|
3695
|
-
for (const item of config.wsReverseUrls) if (item.enabled && item.url !== void 0) {
|
|
3696
|
-
const headers = {
|
|
3697
|
-
...oneBotClientHeaders(selfUin),
|
|
3698
|
-
...authorizeHeader(item.token ?? config.token) ?? {}
|
|
3699
|
-
};
|
|
3700
|
-
const reconnect = {
|
|
3701
|
-
enabled: true,
|
|
3702
|
-
delayMs: item.reconnectDelayMs
|
|
3703
|
-
};
|
|
3704
|
-
if (item.maxReconnectAttempts !== void 0) reconnect.maxAttempts = item.maxReconnectAttempts;
|
|
3705
|
-
const options = {
|
|
3706
|
-
url: item.url,
|
|
3707
|
-
headers,
|
|
3708
|
-
heartbeat: { intervalMs: item.heartbeatInterval },
|
|
3709
|
-
reconnect,
|
|
3710
|
-
rejectUnauthorized: item.rejectUnauthorized
|
|
3711
|
-
};
|
|
3712
|
-
const client = new WsClient(options);
|
|
3713
|
-
client.onRequest = handleRequest;
|
|
3714
|
-
transports.push(client);
|
|
3715
|
-
}
|
|
3716
|
-
}
|
|
3717
|
-
/** token → Authorization 头(client 上报/连接用)。 */
|
|
3718
|
-
function authorizeHeader(token) {
|
|
3719
|
-
if (token === void 0 || token === "") return;
|
|
3720
|
-
return { authorization: `${BEARER_PREFIX}${token}` };
|
|
3721
|
-
}
|
|
3722
|
-
// src/onebot11/adapter.ts
|
|
3723
|
-
/** OneBot 11 协议适配器。 */
|
|
3724
|
-
var NapukettoOneBot11Adapter = class extends BaseProtocolAdapter {
|
|
3725
|
-
protocol = "onebot11";
|
|
3726
|
-
selfUin;
|
|
3727
|
-
oneBotApi;
|
|
3728
|
-
/** 动作注册表(公共只读:IPC 桥等装配方枚举动作名直接挂载)。 */
|
|
3729
|
-
registry;
|
|
3730
|
-
/** 收链路事件管道(订阅 / 过滤 / 翻译派发,拆出)。 */
|
|
3731
|
-
pipeline;
|
|
3732
|
-
transports = null;
|
|
3733
|
-
heartbeatTimer = null;
|
|
3734
|
-
/** IPC 桥模式标记(subscribeOnly 启动;reload 时跳过传输重建)。 */
|
|
3735
|
-
subscribedOnly = false;
|
|
3736
|
-
constructor(opts) {
|
|
3737
|
-
super({
|
|
3738
|
-
config: opts.config,
|
|
3739
|
-
broadcaster: opts.broadcaster,
|
|
3740
|
-
hooks: {
|
|
3741
|
-
onStart: (config) => this.startTransports(config),
|
|
3742
|
-
onStop: () => this.stopAll(),
|
|
3743
|
-
onReload: (config) => this.reloadTransports(config)
|
|
3744
|
-
}
|
|
3745
|
-
});
|
|
3746
|
-
this.selfUin = opts.self.uin;
|
|
3747
|
-
this.oneBotApi = new OneBotApi(opts);
|
|
3748
|
-
this.pipeline = new Ob11EventPipeline({
|
|
3749
|
-
selfUin: this.selfUin,
|
|
3750
|
-
api: this.oneBotApi,
|
|
3751
|
-
broadcast: (event) => this.broadcastEvent(event),
|
|
3752
|
-
...opts.logger !== void 0 ? { logger: opts.logger } : {},
|
|
3753
|
-
msgChannel: opts.msgChannel,
|
|
3754
|
-
...opts.groupChannel !== void 0 ? { groupChannel: opts.groupChannel } : {},
|
|
3755
|
-
...opts.friendChannel !== void 0 ? { friendChannel: opts.friendChannel } : {},
|
|
3756
|
-
...opts.buddyCacheEvents !== void 0 ? { buddyCacheEvents: opts.buddyCacheEvents } : {}
|
|
3757
|
-
});
|
|
3758
|
-
this.registry = createOb11ActionRegistry({ api: this.oneBotApi });
|
|
3759
|
-
}
|
|
3760
|
-
/**
|
|
3761
|
-
* 配置热更新(实现):stop 旧传输/心跳/退订 → 按新配置重建。
|
|
3762
|
-
* IPC 桥模式(subscribeOnly,无传输)只刷新上报开关字段,不重建。
|
|
3763
|
-
*/
|
|
3764
|
-
async reloadTransports(config) {
|
|
3765
|
-
if (this.subscribedOnly) {
|
|
3766
|
-
this.pipeline.applyConfig(config);
|
|
3767
|
-
return;
|
|
3768
|
-
}
|
|
3769
|
-
await this.stopAll();
|
|
3770
|
-
await this.startTransports(config);
|
|
3771
|
-
}
|
|
3772
|
-
/** 启动传输:装配(HTTP/WS)+ 打开 server/client + 广播 lifecycle enable + 起心跳。 */
|
|
3773
|
-
async startTransports(config) {
|
|
3774
|
-
this.subscribedOnly = false;
|
|
3775
|
-
this.pipeline.applyConfig(config);
|
|
3776
|
-
const broadcaster = this.getBroadcaster();
|
|
3777
|
-
if (broadcaster !== void 0) {
|
|
3778
|
-
this.transports = assembleOb11Transports({
|
|
3779
|
-
config,
|
|
3780
|
-
broadcaster,
|
|
3781
|
-
selfUin: this.selfUin,
|
|
3782
|
-
handleRequest: (req, respond) => {
|
|
3783
|
-
this.handleRequest(req, respond).catch((err) => {
|
|
3784
|
-
let message = String(err);
|
|
3785
|
-
if (err instanceof Error) message = err.message;
|
|
3786
|
-
respond({
|
|
3787
|
-
status: "failed",
|
|
3788
|
-
retcode: 999,
|
|
3789
|
-
data: null,
|
|
3790
|
-
message,
|
|
3791
|
-
...echoFieldOf(req)
|
|
3792
|
-
});
|
|
3793
|
-
});
|
|
3794
|
-
}
|
|
3795
|
-
});
|
|
3796
|
-
await Promise.all(this.transports.servers.map((s) => s.open()));
|
|
3797
|
-
await Promise.all(this.transports.transports.map((t) => t.open()));
|
|
3798
|
-
}
|
|
3799
|
-
this.pipeline.subscribe();
|
|
3800
|
-
this.broadcastEvent({
|
|
3801
|
-
time: Math.floor(Date.now() / MS_TO_SEC),
|
|
3802
|
-
self_id: Number(this.selfUin),
|
|
3803
|
-
post_type: "meta_event",
|
|
3804
|
-
meta_event_type: "lifecycle",
|
|
3805
|
-
sub_type: "enable"
|
|
3806
|
-
});
|
|
3807
|
-
this.startHeartbeat(config.heartbeatInterval);
|
|
3808
|
-
}
|
|
3809
|
-
/** 心跳 meta 事件(interval 毫秒,0 关闭;启动前清理残留定时器防重复)。 */
|
|
3810
|
-
startHeartbeat(intervalMs) {
|
|
3811
|
-
if (intervalMs <= 0) return;
|
|
3812
|
-
if (this.heartbeatTimer !== null) clearInterval(this.heartbeatTimer);
|
|
3813
|
-
this.heartbeatTimer = setInterval(() => {
|
|
3814
|
-
this.broadcastEvent({
|
|
3815
|
-
time: Math.floor(Date.now() / MS_TO_SEC),
|
|
3816
|
-
self_id: Number(this.selfUin),
|
|
3817
|
-
post_type: "meta_event",
|
|
3818
|
-
meta_event_type: "heartbeat",
|
|
3819
|
-
interval: intervalMs,
|
|
3820
|
-
status: {
|
|
3821
|
-
online: true,
|
|
3822
|
-
good: true
|
|
3823
|
-
}
|
|
3824
|
-
});
|
|
3825
|
-
}, intervalMs);
|
|
3826
|
-
}
|
|
3827
|
-
/** 停止:心跳 + 传输 + 退订。 */
|
|
3828
|
-
async stopAll() {
|
|
3829
|
-
if (this.heartbeatTimer !== null) {
|
|
3830
|
-
clearInterval(this.heartbeatTimer);
|
|
3831
|
-
this.heartbeatTimer = null;
|
|
3832
|
-
}
|
|
3833
|
-
this.pipeline.unsubscribeAll();
|
|
3834
|
-
if (this.transports !== null) {
|
|
3835
|
-
await this.transports.close();
|
|
3836
|
-
this.transports = null;
|
|
3837
|
-
}
|
|
3838
|
-
}
|
|
3839
|
-
/**
|
|
3840
|
-
* 仅启动接收链路(IPC 桥模式):订阅消息通道维护 messageUnique +
|
|
3841
|
-
* 灰色通知翻译;与 start() 的差别仅在传输层(无 HTTP/WS、无心跳、无 lifecycle)。
|
|
3842
|
-
* 配置经 seed 装配(load() 返回内存初值)。
|
|
3843
|
-
*/
|
|
3844
|
-
async subscribeOnly() {
|
|
3845
|
-
const config = await this.config.load();
|
|
3846
|
-
this.pipeline.applyConfig(config);
|
|
3847
|
-
this.subscribedOnly = true;
|
|
3848
|
-
this.pipeline.subscribe();
|
|
3849
|
-
}
|
|
3850
|
-
/** 仅退订(与 subscribeOnly 配对的进程级清理;传输关闭仍走 stop())。 */
|
|
3851
|
-
unsubscribeOnly() {
|
|
3852
|
-
this.subscribedOnly = false;
|
|
3853
|
-
this.pipeline.unsubscribeAll();
|
|
3854
|
-
}
|
|
3855
|
-
/** 请求分发(挂到 transport 的 onRequest):{ action, params, echo } → 注册表分发。 */
|
|
3856
|
-
async handleRequest(req, respond) {
|
|
3857
|
-
const parsed = req ?? {};
|
|
3858
|
-
const { action: rawAction, echo } = parsed;
|
|
3859
|
-
const params = parsed.params ?? {};
|
|
3860
|
-
let action = "";
|
|
3861
|
-
if (typeof rawAction === "string") action = rawAction;
|
|
3862
|
-
if (action === "") {
|
|
3863
|
-
respond({
|
|
3864
|
-
status: "failed",
|
|
3865
|
-
retcode: 404,
|
|
3866
|
-
data: null,
|
|
3867
|
-
message: "请求缺少 action",
|
|
3868
|
-
...echo !== void 0 ? { echo } : {}
|
|
3869
|
-
});
|
|
3870
|
-
return;
|
|
3871
|
-
}
|
|
3872
|
-
const act = this.registry.get(action);
|
|
3873
|
-
if (act === void 0) {
|
|
3874
|
-
respond({
|
|
3875
|
-
status: "failed",
|
|
3876
|
-
retcode: 404,
|
|
3877
|
-
data: null,
|
|
3878
|
-
message: `未知动作: ${action}`,
|
|
3879
|
-
...echo !== void 0 ? { echo } : {}
|
|
3880
|
-
});
|
|
3881
|
-
return;
|
|
3882
|
-
}
|
|
3883
|
-
let result;
|
|
3884
|
-
if (echo === void 0) result = await act.handle(params);
|
|
3885
|
-
else result = await act.websocketHandle(params, echo);
|
|
3886
|
-
respond(result);
|
|
3887
|
-
}
|
|
3888
|
-
};
|
|
3889
|
-
/** 请求体 echo 字段提取(透传用;非对象 / 缺省 / undefined 返回空对象)。 */
|
|
3890
|
-
function echoFieldOf(req) {
|
|
3891
|
-
if (req !== null && typeof req === "object") {
|
|
3892
|
-
const echo = req.echo;
|
|
3893
|
-
if (echo !== void 0) return { echo };
|
|
3894
|
-
}
|
|
3895
|
-
return {};
|
|
3896
|
-
}
|
|
3897
|
-
export { MessageUnique, NapukettoOneBot11Adapter, OneBotApi, assembleOb11Transports, canonicalToCqMessage, canonicalToSegments, cqMessageToCanonical, cqMessageToSegments, createOb11ActionRegistry, encodeCqCode, escapeCqParam, escapeCqText, ob11ConfigSchema, ob11ErrorCodeMap, parseCqMessage, segmentsToCanonical, segmentsToCqMessage, serializeCqParts, unescapeCqText };
|
|
3898
|
-
|
|
3899
|
-
//# sourceMappingURL=index.mjs.map
|
|
1
|
+
export { y as MessageUnique, t as NapukettoOneBot11Adapter, r as OneBotApi, n as assembleOb11Transports, a as canonicalToCqMessage, o as canonicalToSegments, s as cqMessageToCanonical, c as cqMessageToSegments, i as createOb11ActionRegistry, f as encodeCqCode, p as escapeCqParam, m as escapeCqText, u as ob11ConfigSchema, v as ob11ErrorCodeMap, h as parseCqMessage, l as segmentsToCanonical, d as segmentsToCqMessage, g as serializeCqParts, _ as unescapeCqText } from "../onebot11-BikYDo3k.mjs";
|