@alemonjs/qq-bot 2.1.38 → 2.1.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,8 @@ AlemonJS 的 QQ 开放平台适配器,用于连接官方机器人接口,将
13
13
 
14
14
  三层限流、QQ 文本清洗、引用索引、群历史、LLM 上下文和 C2C 自动 typing 的配置与用法见 [消息处理与会话上下文](../alemonjs/docs/message-context.md)。
15
15
 
16
+ Markdown 图片支持使用 `Media.image(source)` 自动准备 QQ 素材,也可通过媒体 Hook 提前上传、查询与删除,见[图片来源与平台资源](../alemonjs/docs/media.md)。
17
+
16
18
  ## 配置
17
19
 
18
20
  ### 基础配置
package/lib/config.d.ts CHANGED
@@ -44,7 +44,7 @@ declare const getQQBotBots: () => {
44
44
  bots: Map<string, Options$1>;
45
45
  defaultBot?: string;
46
46
  };
47
- declare const getIdentity: (UserId: string) => readonly [boolean, string];
48
- declare const getMaster: (UserId: string) => readonly [boolean, string];
47
+ declare const getIdentity: (UserId: string) => readonly [any, any];
48
+ declare const getMaster: (UserId: string) => readonly [any, any];
49
49
  //#endregion
50
50
  export { Options, getIdentity, getMaster, getQQBotBots, getQQBotConfig, platform, platformFullName };
@@ -3,66 +3,25 @@ import { OutgoingMessage } from "alemonjs";
3
3
  //#region src/framework-actions.d.ts
4
4
  declare const toQQMessage: (content: OutgoingMessage) => {
5
5
  msg_type: 0 | 2 | 3 | 7;
6
- content: string;
6
+ content: any;
7
7
  markdown: {
8
- content: string;
9
- custom_template_id: string;
10
- template_id: number;
11
- params: {
12
- key: string;
13
- values: string[];
14
- }[];
15
- force_verify_image_resource: boolean;
8
+ content: any;
9
+ custom_template_id: any;
10
+ template_id: any;
11
+ params: any;
12
+ force_verify_image_resource: any;
16
13
  };
17
14
  media: {
18
- file_info: string;
15
+ file_info: any;
19
16
  };
20
17
  ark: {
21
- template_id: number;
22
- kv: {
23
- key: string;
24
- value: string;
25
- obj: {
26
- obj_kv: {
27
- key: string;
28
- value: string;
29
- }[];
30
- }[];
31
- }[];
18
+ template_id: any;
19
+ kv: any;
32
20
  };
33
21
  keyboard: {
34
- id: string;
22
+ id: any;
35
23
  content: {
36
- rows: {
37
- buttons: {
38
- id: string;
39
- group_id: string;
40
- render_data: {
41
- label: string;
42
- visited_label: string;
43
- style: number;
44
- };
45
- action: {
46
- type: number;
47
- data: string;
48
- permission: {
49
- type: number;
50
- specify_user_ids: string[];
51
- specify_role_ids: string[];
52
- };
53
- enter: boolean;
54
- reply: boolean;
55
- unsupport_tips: string;
56
- anchor: number;
57
- click_limit: number;
58
- modal: {
59
- content: string;
60
- confirm_text: string;
61
- cancel_text: string;
62
- };
63
- };
64
- }[];
65
- }[];
24
+ rows: any;
66
25
  };
67
26
  };
68
27
  };
@@ -70,6 +29,6 @@ declare const toQQMessage: (content: OutgoingMessage) => {
70
29
  declare const handleFrameworkAction: (client: QQBotAPI, data: {
71
30
  action: string;
72
31
  payload: any;
73
- }, botId: string) => Promise<import("alemonjs/common").Result<any>[]>;
32
+ }, botId: string) => Promise<ClientAPIMessageResult[]>;
74
33
  //#endregion
75
34
  export { handleFrameworkAction, toQQMessage };
package/lib/hook.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { QQBotAPI } from "./sdk/api.js";
2
1
  import { SUBSCRIBE_MESSAGE_STATUS_TYPE } from "./message/group/SUBSCRIBE_MESSAGE_STATUS.js";
3
2
  import { GROUP_MEMBER_ADD } from "./message/group/GROUP_MEMBER_ADD.js";
4
3
  import { GROUP_MEMBER_REMOVE } from "./message/group/GROUP_MEMBER_REMOVE.js";
@@ -77,7 +76,7 @@ declare const useValue: <T extends EventKeys>(event: Events[T]) => readonly [Eve
77
76
  * @param event
78
77
  * @returns
79
78
  */
80
- declare const useClient: <T extends EventKeys>(event: Events[T]) => readonly [QQBotAPI, EventValues[T]];
79
+ declare const useClient: <T extends EventKeys>(event: Events[T]) => readonly [any, EventValues[T]];
81
80
  /**
82
81
  * 判断当前模式
83
82
  * @param event
package/lib/index.d.ts CHANGED
@@ -7,6 +7,6 @@ import { useClient, useMode, useValue } from "./hook.js";
7
7
  import { QQBotGroupEventMap } from "./sdk/message.group.js";
8
8
  import { QQBotPublicEventMap } from "./sdk/message.public.js";
9
9
  //#region src/index.d.ts
10
- declare const _default: () => any;
10
+ declare const _default: any;
11
11
  //#endregion
12
12
  export { QQBotAPI as API, type ApiRequestData, type ButtonType, type FileType, type GlobalMuteRule, type GroupAction, type JoinApprovalStrategy, type JoinRequest, type KeyboardType, type MarkdownType, type MemberMuteState, type MessageType, type Options, type QQBotArkData, type QQBotAttachment, type QQBotBlacklistUser, type QQBotGroupEventMap, type QQBotGroupMember, type QQBotInteractionResolved, type QQBotMenu, type QQBotMenuItem, type QQBotMessageContent, type QQBotMessageElement, type QQBotMessageResult, type QQBotMessageUser, type QQBotPage, type QQBotPanel, type QQBotPanelCreate, type QQBotPanelRecord, type QQBotPanelScope, type QQBotPublicEventMap, type QQTextSanitizerOptions, type SetMemberMuteState, type StreamMessageData, type StreamMessageResult, type UploadConfig, type UploadPart, type UploadPartFinishData, type UploadPrepareData, type UploadPrepareResult, type VerifyInfo, _default as default, platform, sanitizeQQText, useClient, useMode, useValue };
@@ -0,0 +1,15 @@
1
+ import { QQBotAPI } from "./sdk/api.js";
2
+ import { MediaResource, MediaResourcePage, MediaSourceInput } from "alemonjs";
3
+ //#region src/materials.d.ts
4
+ /** Bot-scoped Markdown image materials. No access token is forwarded to COS. */
5
+ declare class QQImageMaterials {
6
+ #private;
7
+ private readonly client;
8
+ private readonly botId;
9
+ constructor(client: QQBotAPI, botId: string);
10
+ upload(source: MediaSourceInput): Promise<MediaResource>;
11
+ list(cursor?: string): Promise<MediaResourcePage>;
12
+ delete(resource: MediaResource): Promise<{}>;
13
+ }
14
+ //#endregion
15
+ export { QQImageMaterials };
@@ -0,0 +1,170 @@
1
+ import axios from "axios";
2
+ import { createHash } from "node:crypto";
3
+ import { basename, extname } from "node:path";
4
+ import { readFile, stat } from "node:fs/promises";
5
+ import { fileTypeFromBuffer } from "file-type";
6
+
7
+ //#region src/materials.ts
8
+ const LIMIT = 10485760;
9
+ const supported = {
10
+ "image/png": [".png"],
11
+ "image/jpeg": [".jpg", ".jpeg"],
12
+ "image/gif": [".gif"],
13
+ "image/webp": [".webp"]
14
+ };
15
+ /** Bot-scoped Markdown image materials. No access token is forwarded to COS. */
16
+ var QQImageMaterials = class {
17
+ client;
18
+ botId;
19
+ #cache = /* @__PURE__ */ new Map();
20
+ #pending = /* @__PURE__ */ new Map();
21
+ constructor(client, botId) {
22
+ this.client = client;
23
+ this.botId = botId;
24
+ }
25
+ #resource(raw) {
26
+ if (typeof raw?.image_id !== "string" || typeof raw.url !== "string" || !raw.url.startsWith("qqbot-media://image/v1/")) throw new Error("QQ returned an invalid Markdown image resource");
27
+ return {
28
+ kind: "media-resource",
29
+ type: "image",
30
+ id: raw.image_id,
31
+ owner: {
32
+ platform: "qq-bot",
33
+ botId: this.botId
34
+ },
35
+ usage: "markdown",
36
+ reference: raw.url,
37
+ name: raw.file_name,
38
+ expiration: {
39
+ mode: "sliding",
40
+ ...Number.isSafeInteger(raw.ttl) && raw.ttl > 0 && { windowSeconds: raw.ttl },
41
+ ...Number.isFinite(raw.expires_at) && { expiresAt: raw.expires_at * 1e3 }
42
+ }
43
+ };
44
+ }
45
+ async upload(source) {
46
+ const values = [
47
+ source?.url,
48
+ source?.data,
49
+ source?.filePath
50
+ ].filter((value) => value !== void 0);
51
+ if (values.length !== 1 || values.some((value) => typeof value !== "string" || !value)) throw new Error("Provide exactly one image source");
52
+ let bytes;
53
+ let name = source.name;
54
+ if (source.filePath) {
55
+ const info = await stat(source.filePath);
56
+ if (!info.isFile() || info.size > LIMIT) throw new Error("Markdown image must be a regular file no larger than 10 MiB");
57
+ bytes = await readFile(source.filePath);
58
+ name ??= basename(source.filePath);
59
+ } else if (source.url) {
60
+ const url = new URL(source.url);
61
+ if (!["http:", "https:"].includes(url.protocol)) throw new Error("Image URL must use HTTP or HTTPS");
62
+ const response = await axios.get(source.url, {
63
+ responseType: "arraybuffer",
64
+ timeout: 2e4,
65
+ maxContentLength: LIMIT,
66
+ headers: {
67
+ Authorization: null,
68
+ Cookie: null
69
+ }
70
+ });
71
+ bytes = Buffer.from(response.data);
72
+ name ??= basename(url.pathname) || void 0;
73
+ } else {
74
+ const data = source.data.replace(/^base64:\/\//, "");
75
+ if (data.length > Math.ceil(LIMIT / 3) * 4 || !/^[a-z\d+/]*={0,2}$/i.test(data) || data.length % 4 !== 0) throw new Error("Invalid or oversized base64 image");
76
+ bytes = Buffer.from(data, "base64");
77
+ }
78
+ if (!bytes.length || bytes.length > LIMIT) throw new Error("Markdown image must contain at most 10 MiB of image data");
79
+ const detected = await fileTypeFromBuffer(bytes);
80
+ if (!detected || !supported[detected.mime]) throw new Error("QQ Markdown materials support PNG, JPEG, GIF and WebP images");
81
+ if (!name || !source.name && !extname(name)) name = `${name || "image"}.${detected.ext}`;
82
+ if (!supported[detected.mime].includes(extname(name).toLowerCase())) throw new Error("Image filename extension must match its actual MIME type");
83
+ const key = `${createHash("sha256").update(bytes).digest("hex")}:${name}:${detected.mime}`;
84
+ const cached = this.#cache.get(key);
85
+ if (cached && cached.until > Date.now()) return structuredClone(cached.resource);
86
+ const pending = this.#pending.get(key);
87
+ if (pending !== void 0) return structuredClone(await pending);
88
+ if (this.#pending.size >= 100) throw new Error("Too many concurrent material uploads");
89
+ const task = this.#upload(bytes, name, detected.mime).then((resource) => {
90
+ if (this.#cache.size >= 100) this.#cache.delete(this.#cache.keys().next().value);
91
+ const lifetime = resource.expiration?.windowSeconds ?? 0;
92
+ if (lifetime > 0) this.#cache.set(key, {
93
+ resource,
94
+ until: Date.now() + lifetime * 1e3
95
+ });
96
+ return resource;
97
+ });
98
+ this.#pending.set(key, task);
99
+ try {
100
+ return structuredClone(await task);
101
+ } finally {
102
+ this.#pending.delete(key);
103
+ }
104
+ }
105
+ async #upload(bytes, name, mime) {
106
+ const prepared = await this.client.groupService({
107
+ method: "POST",
108
+ url: "/v2/media-images/prepare",
109
+ data: {
110
+ file_name: name,
111
+ file_size: bytes.length,
112
+ content_type: mime,
113
+ md5: createHash("md5").update(bytes).digest("hex"),
114
+ sha1: createHash("sha1").update(bytes).digest("hex")
115
+ }
116
+ });
117
+ const uploadUrl = new URL(prepared.presigned_url);
118
+ if (!["http:", "https:"].includes(uploadUrl.protocol) || !prepared.upload_id) throw new Error("QQ returned an invalid material upload task");
119
+ const uploaded = await axios.put(prepared.presigned_url, bytes, {
120
+ timeout: 2e4,
121
+ maxBodyLength: LIMIT,
122
+ maxRedirects: 0,
123
+ headers: {
124
+ "Content-Type": mime,
125
+ Authorization: null,
126
+ Cookie: null
127
+ }
128
+ }).catch(() => {
129
+ throw new Error("Markdown image binary upload failed");
130
+ });
131
+ const md5 = String(uploaded.headers.etag ?? "").replace(/^"|"$/g, "").toLowerCase();
132
+ if (md5 !== createHash("md5").update(bytes).digest("hex")) throw new Error("Markdown image upload returned an invalid ETag");
133
+ const completed = await this.client.groupService({
134
+ method: "POST",
135
+ url: "/v2/media-images/complete",
136
+ data: {
137
+ upload_id: prepared.upload_id,
138
+ md5
139
+ }
140
+ });
141
+ return {
142
+ ...this.#resource(completed),
143
+ name
144
+ };
145
+ }
146
+ async list(cursor) {
147
+ const raw = await this.client.groupService({
148
+ method: "GET",
149
+ url: "/v2/media-images",
150
+ params: { cursor }
151
+ });
152
+ return {
153
+ Items: raw.images.map((item) => this.#resource(item)),
154
+ NextCursor: raw.next_cursor || void 0,
155
+ Total: raw.total
156
+ };
157
+ }
158
+ async delete(resource) {
159
+ if (resource.owner?.platform !== "qq-bot" || resource.owner.botId !== this.botId || resource.usage !== "markdown" || !resource.id) throw new Error("Image resource does not belong to this bot and usage");
160
+ await this.client.groupService({
161
+ method: "DELETE",
162
+ url: `/v2/media-images/${encodeURIComponent(resource.id)}/delete`
163
+ });
164
+ for (const [key, entry] of this.#cache) if (entry.resource.id === resource.id) this.#cache.delete(key);
165
+ return {};
166
+ }
167
+ };
168
+
169
+ //#endregion
170
+ export { QQImageMaterials };
package/lib/register.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { getIdentity, getMaster, getQQBotConfig, platform } from "./config.js";
2
+ import { QQImageMaterials } from "./materials.js";
2
3
  import { sanitizeQQText } from "./text-sanitizer.js";
3
4
  import { AT_MESSAGE_CREATE, C2C_MESSAGE_CREATE, DIRECT_MESSAGE_CREATE, GROUP_AT_MESSAGE_CREATE, MESSAGE_CREATE } from "./sends.js";
4
5
  import { normalizeFrameworkEvent, normalizeMessageUser } from "./framework-events.js";
@@ -973,6 +974,11 @@ const register = (client, options) => {
973
974
  }
974
975
  }
975
976
  };
977
+ const materials = new QQImageMaterials(client, botId);
978
+ const assertResource = (resource, usage, target) => {
979
+ if (resource.kind !== "media-resource" || resource.type !== "image" || resource.owner?.platform !== "qq-bot" || resource.owner.botId !== botId || resource.usage !== usage || !resource.id || !resource.reference) throw new Error("Image resource does not belong to this bot or usage");
980
+ if (resource.target && (!target || resource.target.scope !== target.scope || resource.target.targetId !== target.targetId)) throw new Error("Image resource belongs to another conversation");
981
+ };
976
982
  const onactions = async (data, consume) => {
977
983
  const event = data.payload.event ?? {};
978
984
  const requestedBot = data.payload.params?.target?.BotId ?? data.payload.target?.BotId ?? data.payload.BotId ?? event.BotId;
@@ -1003,6 +1009,88 @@ const register = (client, options) => {
1003
1009
  return;
1004
1010
  }
1005
1011
  }
1012
+ if (data.action.startsWith("media.resource.")) {
1013
+ const params = data.payload.params ?? {};
1014
+ const target = normalizeTarget(params.target ?? data.payload.target);
1015
+ let result;
1016
+ if (data.action === "media.resource.capabilities") result = { usages: {
1017
+ message: {
1018
+ upload: true,
1019
+ list: false,
1020
+ delete: false
1021
+ },
1022
+ markdown: {
1023
+ upload: true,
1024
+ list: true,
1025
+ delete: true,
1026
+ maxBytes: 10485760,
1027
+ maxItems: 100
1028
+ }
1029
+ } };
1030
+ else if (data.action === "media.resource.list") {
1031
+ if (params.usage !== "markdown") throw new Error("QQ resource listing is only available for Markdown images");
1032
+ result = await materials.list(params.cursor);
1033
+ } else if (data.action === "media.resource.delete") {
1034
+ assertResource(params.resource, "markdown");
1035
+ result = await materials.delete(params.resource);
1036
+ } else if (data.action === "media.resource.upload" || data.action === "media.resource.resolve") {
1037
+ if (!["message", "markdown"].includes(params.usage)) throw new Error("Invalid image resource usage");
1038
+ if (data.action === "media.resource.resolve" && params.usage === "markdown" && config.markdownToText) throw new Error("Markdown images cannot be embedded when markdownToText is enabled");
1039
+ const image = params.image;
1040
+ if (image?.kind === "media-resource") {
1041
+ assertResource(image, params.usage, target);
1042
+ result = image;
1043
+ } else {
1044
+ if (image && (image.kind !== "media-source" || image.type !== "image")) throw new Error("Expected an image source");
1045
+ if (!image && params.type !== "image") throw new Error("Expected image upload type");
1046
+ const source = image ? image.source : params.source;
1047
+ if (params.usage === "markdown") result = await materials.upload(source);
1048
+ else {
1049
+ if (!target) throw new Error("A target is required for message image resources");
1050
+ const uploaded = await uploadMedia(target, {
1051
+ ...source,
1052
+ type: "image",
1053
+ send: false
1054
+ });
1055
+ result = {
1056
+ kind: "media-resource",
1057
+ type: "image",
1058
+ id: uploaded.fileId,
1059
+ reference: uploaded.fileId,
1060
+ owner: {
1061
+ platform,
1062
+ botId
1063
+ },
1064
+ usage: "message",
1065
+ target: {
1066
+ ...target,
1067
+ BotId: botId
1068
+ },
1069
+ name: source.name,
1070
+ expiration: {
1071
+ mode: "fixed",
1072
+ expiresAt: "expiresAt" in uploaded ? uploaded.expiresAt : void 0
1073
+ }
1074
+ };
1075
+ }
1076
+ }
1077
+ } else throw new Error("Unsupported media resource operation");
1078
+ consume([createResult(ResultCode.Ok, data.action, result)]);
1079
+ return;
1080
+ }
1081
+ if (data.action === "message.send" && data.payload.params?.format) {
1082
+ const target = normalizeTarget(data.payload.target);
1083
+ const validate = (items) => {
1084
+ for (const item of items) {
1085
+ if (item.media) {
1086
+ if (item.type !== "Image") throw new Error("Structured media must be prepared through useMessage before sending");
1087
+ assertResource(item.media, "message", target);
1088
+ }
1089
+ if ((item.type === "Markdown" || item.type === "MD.blockquote") && Array.isArray(item.value)) validate(item.value);
1090
+ }
1091
+ };
1092
+ validate(data.payload.params.format);
1093
+ }
1006
1094
  const handled = await handleFrameworkAction(client, data, botId);
1007
1095
  if (handled) {
1008
1096
  consume(handled);
package/lib/sends.js CHANGED
@@ -177,13 +177,13 @@ const formatMention = (item, mode) => {
177
177
  const value = item.value;
178
178
  const isEmptyMention = value === "everyone" || value === "all" || value === "" || typeof value !== "string";
179
179
  if (mode === "guild-public") {
180
- if (isEmptyMention) return "@everyone";
181
- if (item.options?.belong === "user") return `<@!${value}>`;
180
+ if (isEmptyMention) return "<qqbot-at-everyone />";
181
+ if (item.options?.belong === "user") return `<qqbot-at-user id="${value}" />`;
182
182
  if (item.options?.belong === "channel") return `<#${value}>`;
183
183
  return "";
184
184
  }
185
185
  if (isEmptyMention) return "";
186
- if (item.options?.belong === "user") return `<@${value}>`;
186
+ if (item.options?.belong === "user") return `<qqbot-at-user id="${value}" />`;
187
187
  return "";
188
188
  };
189
189
  /** 从消息数据中提取文本内容 */
@@ -321,6 +321,7 @@ const resolveFileData = async (item) => {
321
321
  */
322
322
  const resolveMediaUrl = async (media, uploadMedia) => {
323
323
  for (const item of media) {
324
+ if (item.type === "Image" && item.media?.kind === "media-resource") return item.media.reference;
324
325
  const fileData = await resolveFileData(item);
325
326
  if (fileData) {
326
327
  const fileInfo = await uploadMedia({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alemonjs/qq-bot",
3
- "version": "2.1.38",
3
+ "version": "2.1.39",
4
4
  "description": "QQ官方平台",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",
@@ -15,7 +15,9 @@
15
15
  "test:non-channel": "yarn build && node tests/non-channel.contract.mjs && node tests/framework.contract.mjs && node tests/non-channel.transport.mjs && node tests/media-upload.contract.mjs && node tests/routing.contract.mjs && node tests/lifecycle.contract.mjs && node tests/http-diagnostics.contract.mjs && node tests/webhook-ingress.contract.mjs && node tests/text-sanitizer.contract.mjs && tsc -p tests/tsconfig.non-channel.json",
16
16
  "docs:snapshot": "python3 scripts/snapshot-official.py",
17
17
  "test:http": "yarn build && node tests/http-diagnostics.contract.mjs && node tests/webhook-ingress.contract.mjs",
18
- "test:text": "yarn build && node tests/text-sanitizer.contract.mjs"
18
+ "test:text": "yarn build && node tests/text-sanitizer.contract.mjs",
19
+ "test:materials": "yarn build && node tests/materials.contract.mjs",
20
+ "test:mention": "yarn build && node tests/everyone.contract.mjs"
19
21
  },
20
22
  "dependencies": {
21
23
  "@noble/curves": "^1.7.0",
@@ -99,5 +101,5 @@
99
101
  "type": "git",
100
102
  "url": "https://github.com/lemonade-lab/alemonjs.git"
101
103
  },
102
- "gitHead": "e736f4e180a8694f8c9eb1796a23fdfadcc48f3e"
104
+ "gitHead": "114f342c08cb3ebbfee39b1c93fb30607d276083"
103
105
  }