@alemonjs/qq-bot 2.1.38 → 2.1.40
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 +2 -0
- package/lib/format.d.ts +4 -3
- package/lib/format.js +11 -8
- package/lib/materials.d.ts +15 -0
- package/lib/materials.js +170 -0
- package/lib/register.js +88 -0
- package/lib/sends.js +15 -14
- package/package.json +7 -4
- package/LICENSE +0 -21
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/format.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { DataEnums, DataMarkDown } from "alemonjs";
|
|
2
2
|
//#region src/format.d.ts
|
|
3
|
+
type QQMarkdownContext = 'group' | 'c2c' | 'guild';
|
|
3
4
|
/** 群聊、私聊和频道共用有序正文;提及等原生文本由发送上下文提供。 */
|
|
4
|
-
declare const formatQQContent: (items: DataEnums[], renderNative: (item: DataEnums) => string, plain?: boolean, hideUnsupported?: boolean | number) => string;
|
|
5
|
+
declare const formatQQContent: (items: DataEnums[], renderNative: (item: DataEnums) => string, plain?: boolean, hideUnsupported?: boolean | number, context?: QQMarkdownContext) => string;
|
|
5
6
|
/**
|
|
6
7
|
* 将结构化 Markdown 子元素数组转为可读纯文本
|
|
7
8
|
*/
|
|
@@ -24,6 +25,6 @@ declare const markdownRawToText: (raw: string, hideUnsupported?: boolean | numbe
|
|
|
24
25
|
* 其余类型降级为文本
|
|
25
26
|
*/
|
|
26
27
|
declare const dataEnumToText: (item: DataEnums, hideUnsupported?: boolean | number) => string;
|
|
27
|
-
declare const createMarkdownText: (data: DataMarkDown['value']) => string;
|
|
28
|
+
declare const createMarkdownText: (data: DataMarkDown['value'], context?: QQMarkdownContext) => string;
|
|
28
29
|
//#endregion
|
|
29
|
-
export { buttonsToText, createMarkdownText, dataEnumToText, formatQQContent, markdownRawToText, markdownToText };
|
|
30
|
+
export { QQMarkdownContext, buttonsToText, createMarkdownText, dataEnumToText, formatQQContent, markdownRawToText, markdownToText };
|
package/lib/format.js
CHANGED
|
@@ -2,9 +2,9 @@ import { joinMarkdownParts, renderMarkdownBlockquote } from "alemonjs/markdown";
|
|
|
2
2
|
|
|
3
3
|
//#region src/format.ts
|
|
4
4
|
/** 群聊、私聊和频道共用有序正文;提及等原生文本由发送上下文提供。 */
|
|
5
|
-
const formatQQContent = (items, renderNative, plain = false, hideUnsupported) => {
|
|
5
|
+
const formatQQContent = (items, renderNative, plain = false, hideUnsupported, context = "group") => {
|
|
6
6
|
return items.map((item) => {
|
|
7
|
-
if (item.type === "Markdown") return plain ? markdownToText(item.value, hideUnsupported) : createMarkdownText(item.value);
|
|
7
|
+
if (item.type === "Markdown") return plain ? markdownToText(item.value, hideUnsupported) : createMarkdownText(item.value, context);
|
|
8
8
|
if (item.type === "MarkdownOriginal") {
|
|
9
9
|
const text = plain ? markdownRawToText(item.value, hideUnsupported) : item.value;
|
|
10
10
|
return text ? `\n\n${text}\n\n` : "";
|
|
@@ -111,6 +111,7 @@ const dataEnumToText = (item, hideUnsupported) => {
|
|
|
111
111
|
default: return "";
|
|
112
112
|
}
|
|
113
113
|
};
|
|
114
|
+
const escapeAttribute = (value) => value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
114
115
|
const mdFormatters = {
|
|
115
116
|
"MD.title": (value) => `# ${value} `,
|
|
116
117
|
"MD.subtitle": (value) => `## ${value} `,
|
|
@@ -120,7 +121,7 @@ const mdFormatters = {
|
|
|
120
121
|
"MD.italic": (value) => `__${value}__ `,
|
|
121
122
|
"MD.italicStar": (value) => `*${value}* `,
|
|
122
123
|
"MD.strikethrough": (value) => `~~${value}~~ `,
|
|
123
|
-
"MD.blockquote": (value) => renderMarkdownBlockquote(value, createMarkdownText),
|
|
124
|
+
"MD.blockquote": (value, _options, context) => renderMarkdownBlockquote(value, (children) => createMarkdownText(children, context)),
|
|
124
125
|
"MD.newline": () => "\n",
|
|
125
126
|
"MD.link": (value) => {
|
|
126
127
|
if (!value?.text && !value?.url) return "";
|
|
@@ -136,15 +137,17 @@ const mdFormatters = {
|
|
|
136
137
|
return `<qqbot-at-user id="${value}" />`;
|
|
137
138
|
},
|
|
138
139
|
"MD.content": (value) => `${value}`,
|
|
139
|
-
"MD.button": (title, options) => {
|
|
140
|
+
"MD.button": (title, options, context) => {
|
|
140
141
|
const { data, autoEnter } = options || {};
|
|
141
|
-
|
|
142
|
-
return `<qqbot-cmd-
|
|
142
|
+
const text = String(data ?? title ?? "");
|
|
143
|
+
if (autoEnter && context === "c2c") return `<qqbot-cmd-enter text="${escapeAttribute(text)}" />`;
|
|
144
|
+
const inputText = text.slice(0, 80).replace(/[\uD800-\uDBFF]$/u, "");
|
|
145
|
+
return `<qqbot-cmd-input text="${escapeAttribute(inputText)}" show="${escapeAttribute(String(title ?? ""))}" />`;
|
|
143
146
|
}
|
|
144
147
|
};
|
|
145
|
-
const createMarkdownText = (data) => {
|
|
148
|
+
const createMarkdownText = (data, context = "group") => {
|
|
146
149
|
return joinMarkdownParts(data, data.map((mdItem) => {
|
|
147
|
-
if (mdFormatters[mdItem.type]) return mdFormatters[mdItem.type](mdItem?.value, mdItem?.options);
|
|
150
|
+
if (mdFormatters[mdItem.type]) return mdFormatters[mdItem.type](mdItem?.value, mdItem?.options, context);
|
|
148
151
|
if (mdItem.type === "MD.list" && typeof mdItem.value !== "string") return `${mdItem.value.map((listItem) => {
|
|
149
152
|
return typeof listItem.value === "object" ? `\n${listItem.value.index}. ${listItem.value.text}` : `\n- ${listItem.value}`;
|
|
150
153
|
}).join("")}\n`;
|
|
@@ -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 };
|
package/lib/materials.js
ADDED
|
@@ -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 "
|
|
181
|
-
if (item.options?.belong === "user") return
|
|
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
|
|
186
|
+
if (item.options?.belong === "user") return `<qqbot-at-user id="${value}" />`;
|
|
187
187
|
return "";
|
|
188
188
|
};
|
|
189
189
|
/** 从消息数据中提取文本内容 */
|
|
@@ -231,7 +231,7 @@ const buildBaseParams = (tag, messageId, interactionTag) => {
|
|
|
231
231
|
return { msg_id: messageId };
|
|
232
232
|
};
|
|
233
233
|
/** 构建 Markdown 和按钮参数 */
|
|
234
|
-
const buildMdAndButtonsParams = (val) => {
|
|
234
|
+
const buildMdAndButtonsParams = (val, context = "group") => {
|
|
235
235
|
const items = val.filter((item) => item.type === "Markdown" || item.type === "MarkdownOriginal" || item.type === "BT.group" || item.type === "ButtonTemplate");
|
|
236
236
|
if (items.length === 0) return null;
|
|
237
237
|
const params = {};
|
|
@@ -255,7 +255,7 @@ const buildMdAndButtonsParams = (val) => {
|
|
|
255
255
|
}
|
|
256
256
|
} else params["keyboard"] = { content: createButtonsData(item.value) };
|
|
257
257
|
} else if (item.type === "Markdown" && typeof item?.value !== "string") {
|
|
258
|
-
const content = createMarkdownText(item.value);
|
|
258
|
+
const content = createMarkdownText(item.value, context);
|
|
259
259
|
if (content) {
|
|
260
260
|
if (params["markdown"]?.content) params["markdown"].content += content;
|
|
261
261
|
else params["markdown"] = { content };
|
|
@@ -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({
|
|
@@ -334,7 +335,7 @@ const resolveMediaUrl = async (media, uploadMedia) => {
|
|
|
334
335
|
/** 移除富媒体占位符(dataEnumToText 降级产生的 [视频]/[音频]/[附件]) */
|
|
335
336
|
const stripMediaPlaceholders = (text) => text.replace(/\[附件[^\]]*\]/g, "").replace(/\[音频\]/g, "").replace(/\[视频\]/g, "").trim();
|
|
336
337
|
/** Open API 通用发送逻辑(群组 / C2C) */
|
|
337
|
-
const sendOpenApiMessage = async (content, val, baseParams, uploadMedia, sendMessage, label, options) => {
|
|
338
|
+
const sendOpenApiMessage = async (content, val, baseParams, uploadMedia, sendMessage, label, context, options) => {
|
|
338
339
|
if (options?.wakeup && (options.replyId || options.eventId) || options?.replyId && options?.eventId) return [createResult(ResultCode.FailParams, "wakeup, replyId and eventId are mutually exclusive", null)];
|
|
339
340
|
if (options?.wakeup || options?.replyId || options?.eventId) {
|
|
340
341
|
baseParams = {};
|
|
@@ -362,7 +363,7 @@ const sendOpenApiMessage = async (content, val, baseParams, uploadMedia, sendMes
|
|
|
362
363
|
...res.ext_info?.ref_idx !== void 0 && { referenceId: res.ext_info.ref_idx }
|
|
363
364
|
})];
|
|
364
365
|
}
|
|
365
|
-
if (config.hideUnsupported === true && !content && !buildMdAndButtonsParams(val) && !buildArkParams(val)) {
|
|
366
|
+
if (config.hideUnsupported === true && !content && !buildMdAndButtonsParams(val, context) && !buildArkParams(val)) {
|
|
366
367
|
logger.info("[qq-bot] hideUnsupported: 消息内容转换后为空,跳过发送");
|
|
367
368
|
return [];
|
|
368
369
|
}
|
|
@@ -382,9 +383,9 @@ const sendOpenApiMessage = async (content, val, baseParams, uploadMedia, sendMes
|
|
|
382
383
|
}
|
|
383
384
|
return [];
|
|
384
385
|
}
|
|
385
|
-
const mdParams = buildMdAndButtonsParams(val);
|
|
386
|
+
const mdParams = buildMdAndButtonsParams(val, context);
|
|
386
387
|
if (mdParams) {
|
|
387
|
-
if (mdParams.markdown?.content) mdParams.markdown.content = formatQQContent(val, (item) => extractContent([item], "group"));
|
|
388
|
+
if (mdParams.markdown?.content) mdParams.markdown.content = formatQQContent(val, (item) => extractContent([item], "group"), false, void 0, context);
|
|
388
389
|
if (mdParams.markdown && options?.forceVerifyImageResource !== void 0) mdParams.markdown.force_verify_image_resource = options.forceVerifyImageResource;
|
|
389
390
|
const res = await sendMessage({
|
|
390
391
|
msg_type: 2,
|
|
@@ -453,7 +454,7 @@ const sendGuildMessage = async (content, val, baseParams, sendMessage, label, mo
|
|
|
453
454
|
}, imageBuffer);
|
|
454
455
|
return [createResult(ResultCode.Ok, label, { id: res?.id })];
|
|
455
456
|
}
|
|
456
|
-
if (config.hideUnsupported && !content && !buildMdAndButtonsParams(val) && !buildArkParams(val)) {
|
|
457
|
+
if (config.hideUnsupported && !content && !buildMdAndButtonsParams(val, "guild") && !buildArkParams(val)) {
|
|
457
458
|
logger.info("[qq-bot] hideUnsupported: 消息内容转换后为空,跳过发送");
|
|
458
459
|
return [];
|
|
459
460
|
}
|
|
@@ -468,9 +469,9 @@ const sendGuildMessage = async (content, val, baseParams, sendMessage, label, mo
|
|
|
468
469
|
}
|
|
469
470
|
return [];
|
|
470
471
|
}
|
|
471
|
-
const mdParams = buildMdAndButtonsParams(val);
|
|
472
|
+
const mdParams = buildMdAndButtonsParams(val, "guild");
|
|
472
473
|
if (mdParams) {
|
|
473
|
-
if (mdParams.markdown?.content) mdParams.markdown.content = formatQQContent(val, (item) => extractContent([item], mode));
|
|
474
|
+
if (mdParams.markdown?.content) mdParams.markdown.content = formatQQContent(val, (item) => extractContent([item], mode), false, void 0, "guild");
|
|
474
475
|
const res = await sendMessage({
|
|
475
476
|
content: "",
|
|
476
477
|
...mdParams,
|
|
@@ -511,7 +512,7 @@ const GROUP_AT_MESSAGE_CREATE = async (client, event, val, options) => {
|
|
|
511
512
|
const baseParams = buildBaseParams(event._tag, event.MessageId, "INTERACTION_CREATE_GROUP");
|
|
512
513
|
const content = extractContent(val, "group");
|
|
513
514
|
try {
|
|
514
|
-
return await sendOpenApiMessage(content, val, baseParams, (data) => client.postRichMediaByGroup(event.ChannelId, data), (data) => client.groupOpenMessages(event.ChannelId, data), "client.groupOpenMessages", options);
|
|
515
|
+
return await sendOpenApiMessage(content, val, baseParams, (data) => client.postRichMediaByGroup(event.ChannelId, data), (data) => client.groupOpenMessages(event.ChannelId, data), "client.groupOpenMessages", "group", options);
|
|
515
516
|
} catch (err) {
|
|
516
517
|
return [createResult(ResultCode.Fail, err?.response?.data ?? err?.message ?? err, null)];
|
|
517
518
|
}
|
|
@@ -523,7 +524,7 @@ const C2C_MESSAGE_CREATE = async (client, event, val, options) => {
|
|
|
523
524
|
const baseParams = buildBaseParams(event._tag, event.MessageId, "INTERACTION_CREATE_C2C");
|
|
524
525
|
const content = extractContent(val, "group");
|
|
525
526
|
try {
|
|
526
|
-
return await sendOpenApiMessage(content, val, baseParams, (data) => client.postRichMediaByUser(event.UserId, data), (data) => client.usersOpenMessages(event.UserId, data), "client.usersOpenMessages", options);
|
|
527
|
+
return await sendOpenApiMessage(content, val, baseParams, (data) => client.postRichMediaByUser(event.UserId, data), (data) => client.usersOpenMessages(event.UserId, data), "client.usersOpenMessages", "c2c", options);
|
|
527
528
|
} catch (err) {
|
|
528
529
|
return [createResult(ResultCode.Fail, err?.response?.data ?? err?.message ?? err, null)];
|
|
529
530
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alemonjs/qq-bot",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.40",
|
|
4
4
|
"description": "QQ官方平台",
|
|
5
5
|
"author": "lemonade",
|
|
6
6
|
"license": "MIT",
|
|
@@ -12,10 +12,13 @@
|
|
|
12
12
|
"test:send": "yarn build && node tests/use-send.notice.mjs",
|
|
13
13
|
"test:channel": "yarn --cwd ../alemonjs build && yarn build && node tests/channel.contract.mjs",
|
|
14
14
|
"test:qr": "yarn build && node tests/qr-auth.mjs",
|
|
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",
|
|
15
|
+
"test:non-channel": "yarn build && node tests/markdown-buttons.contract.mjs && 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",
|
|
21
|
+
"test:buttons": "yarn build && node tests/markdown-buttons.contract.mjs"
|
|
19
22
|
},
|
|
20
23
|
"dependencies": {
|
|
21
24
|
"@noble/curves": "^1.7.0",
|
|
@@ -99,5 +102,5 @@
|
|
|
99
102
|
"type": "git",
|
|
100
103
|
"url": "https://github.com/lemonade-lab/alemonjs.git"
|
|
101
104
|
},
|
|
102
|
-
"gitHead": "
|
|
105
|
+
"gitHead": "c6aa5616afe091a37610dad22fbb2d2618d943b8"
|
|
103
106
|
}
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
The MIT License (MIT)
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2013-present, Yuxi (Evan) You
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in
|
|
13
|
-
all copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIdED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
-
THE SOFTWARE.
|