@zhin.js/adapter-qq 5.0.2 → 5.0.3

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.
Files changed (116) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +51 -417
  3. package/adapters/qq.ts +45 -0
  4. package/agent/tools/add_role.ts +2 -2
  5. package/agent/tools/channel_info.ts +2 -2
  6. package/agent/tools/create_role.ts +2 -2
  7. package/agent/tools/list_channels.ts +2 -2
  8. package/agent/tools/list_guilds.ts +2 -2
  9. package/agent/tools/list_roles.ts +2 -2
  10. package/agent/tools/member_detail.ts +2 -2
  11. package/agent/tools/remove_role.ts +2 -2
  12. package/lib/endpoint.d.ts +69 -0
  13. package/lib/endpoint.js +315 -0
  14. package/lib/index.d.ts +6 -0
  15. package/lib/index.js +6 -0
  16. package/lib/platform-permit.d.ts +16 -0
  17. package/lib/{src/platform-permit.js → platform-permit.js} +1 -2
  18. package/lib/protocol.d.ts +96 -0
  19. package/lib/protocol.js +129 -0
  20. package/lib/qq-agent-deps.d.ts +21 -0
  21. package/lib/qq-agent-deps.js +30 -0
  22. package/lib/webhook.d.ts +18 -0
  23. package/lib/webhook.js +100 -0
  24. package/lib/ws.d.ts +24 -0
  25. package/lib/ws.js +118 -0
  26. package/package.json +44 -40
  27. package/plugin.ts +13 -0
  28. package/schema.json +51 -0
  29. package/src/endpoint.ts +314 -600
  30. package/src/index.ts +56 -186
  31. package/src/platform-permit.ts +1 -1
  32. package/src/protocol.ts +229 -0
  33. package/src/qq-agent-deps.ts +49 -12
  34. package/src/webhook.ts +127 -0
  35. package/src/ws.ts +172 -0
  36. package/client/Dashboard.tsx +0 -230
  37. package/client/index.tsx +0 -11
  38. package/client/tsconfig.json +0 -7
  39. package/client/utils/api.ts +0 -30
  40. package/dist/index.js +0 -30
  41. package/lib/agent/tools/add_role.js +0 -23
  42. package/lib/agent/tools/add_role.js.map +0 -1
  43. package/lib/agent/tools/channel_info.js +0 -19
  44. package/lib/agent/tools/channel_info.js.map +0 -1
  45. package/lib/agent/tools/create_role.js +0 -22
  46. package/lib/agent/tools/create_role.js.map +0 -1
  47. package/lib/agent/tools/list_channels.js +0 -20
  48. package/lib/agent/tools/list_channels.js.map +0 -1
  49. package/lib/agent/tools/list_guilds.js +0 -17
  50. package/lib/agent/tools/list_guilds.js.map +0 -1
  51. package/lib/agent/tools/list_roles.js +0 -20
  52. package/lib/agent/tools/list_roles.js.map +0 -1
  53. package/lib/agent/tools/member_detail.js +0 -20
  54. package/lib/agent/tools/member_detail.js.map +0 -1
  55. package/lib/agent/tools/remove_role.js +0 -23
  56. package/lib/agent/tools/remove_role.js.map +0 -1
  57. package/lib/package.json +0 -105
  58. package/lib/src/adapter.js +0 -81
  59. package/lib/src/adapter.js.map +0 -1
  60. package/lib/src/endpoint.js +0 -600
  61. package/lib/src/endpoint.js.map +0 -1
  62. package/lib/src/gateway-config.js +0 -32
  63. package/lib/src/gateway-config.js.map +0 -1
  64. package/lib/src/group-at-normalize.js +0 -68
  65. package/lib/src/group-at-normalize.js.map +0 -1
  66. package/lib/src/inbound-action.js +0 -57
  67. package/lib/src/inbound-action.js.map +0 -1
  68. package/lib/src/inbound-normalize.js +0 -47
  69. package/lib/src/inbound-normalize.js.map +0 -1
  70. package/lib/src/index.js +0 -194
  71. package/lib/src/index.js.map +0 -1
  72. package/lib/src/mention-enrich.js +0 -52
  73. package/lib/src/mention-enrich.js.map +0 -1
  74. package/lib/src/outbound-keyboard.js +0 -100
  75. package/lib/src/outbound-keyboard.js.map +0 -1
  76. package/lib/src/outbound-markdown.js +0 -189
  77. package/lib/src/outbound-markdown.js.map +0 -1
  78. package/lib/src/outbound-media.js +0 -51
  79. package/lib/src/outbound-media.js.map +0 -1
  80. package/lib/src/outbound-mixed-media.js +0 -78
  81. package/lib/src/outbound-mixed-media.js.map +0 -1
  82. package/lib/src/platform-permit.js.map +0 -1
  83. package/lib/src/qq-agent-deps.js +0 -10
  84. package/lib/src/qq-agent-deps.js.map +0 -1
  85. package/lib/src/qq-bind-api.js +0 -90
  86. package/lib/src/qq-bind-api.js.map +0 -1
  87. package/lib/src/qq-bind-flow.js +0 -86
  88. package/lib/src/qq-bind-flow.js.map +0 -1
  89. package/lib/src/qq-bind-persist.js +0 -52
  90. package/lib/src/qq-bind-persist.js.map +0 -1
  91. package/lib/src/qq-endpoint-manager.js +0 -159
  92. package/lib/src/qq-endpoint-manager.js.map +0 -1
  93. package/lib/src/sdk-version.js +0 -19
  94. package/lib/src/sdk-version.js.map +0 -1
  95. package/lib/src/segment-mapper.js +0 -2
  96. package/lib/src/segment-mapper.js.map +0 -1
  97. package/lib/src/types.js +0 -2
  98. package/lib/src/types.js.map +0 -1
  99. package/plugin.yml +0 -3
  100. package/src/adapter.ts +0 -97
  101. package/src/gateway-config.ts +0 -48
  102. package/src/group-at-normalize.ts +0 -75
  103. package/src/inbound-action.ts +0 -87
  104. package/src/inbound-normalize.ts +0 -57
  105. package/src/mention-enrich.ts +0 -71
  106. package/src/outbound-keyboard.ts +0 -117
  107. package/src/outbound-markdown.ts +0 -212
  108. package/src/outbound-media.ts +0 -58
  109. package/src/outbound-mixed-media.ts +0 -101
  110. package/src/qq-bind-api.ts +0 -145
  111. package/src/qq-bind-flow.ts +0 -127
  112. package/src/qq-bind-persist.ts +0 -71
  113. package/src/qq-endpoint-manager.ts +0 -199
  114. package/src/sdk-version.ts +0 -21
  115. package/src/segment-mapper.ts +0 -1
  116. package/src/types.ts +0 -52
@@ -1,117 +0,0 @@
1
- /**
2
- * 将 core keyboard 段转为 qq-official-bot 可识别的 button / markdown 段。
3
- * @see https://bot.q.qq.com/wiki/develop/api-v2/server-inter/message/trans/msg-btn.html
4
- */
5
- import { isKeyboardSegment, KeyboardSegment, type ButtonData, type KeyboardSegmentData, type MessageSegment, type SendContent } from 'zhin.js';
6
-
7
-
8
- function asKeyboardData(item: unknown): KeyboardSegmentData | null {
9
- if (item instanceof KeyboardSegment) return item.data;
10
- if (item != null && typeof item === "object" && isKeyboardSegment(item as MessageSegment)) {
11
- return (item as MessageSegment).data as KeyboardSegmentData;
12
- }
13
- return null;
14
- }
15
-
16
- type QqButton = {
17
- id: string;
18
- render_data: { label: string; visited_label: string; style: number };
19
- action: {
20
- type: number;
21
- permission: { type: number };
22
- data: string;
23
- click_limit: number;
24
- unsupport_tips: string;
25
- enter?: boolean;
26
- reply?: boolean;
27
- };
28
- };
29
-
30
- function coreButtonToQq(btn: ButtonData): QqButton {
31
- const isCommand = btn.mode === 'command';
32
- const action: QqButton['action'] = {
33
- type: isCommand ? 2 : 1,
34
- permission: { type: 2 },
35
- data: btn.payload,
36
- click_limit: btn.disabled ? 0 : 10,
37
- unsupport_tips: btn.disabled ? "该按钮不可用" : "",
38
- };
39
- if (isCommand) {
40
- if (btn.command?.enter != null) action.enter = btn.command.enter;
41
- if (btn.command?.reply != null) action.reply = btn.command.reply;
42
- }
43
- return {
44
- id: btn.id,
45
- render_data: {
46
- label: btn.label,
47
- visited_label: btn.label,
48
- style: 0,
49
- },
50
- action,
51
- };
52
- }
53
-
54
- function keyboardDataToQqSegments(data: KeyboardSegmentData): MessageSegment[] {
55
- const out: MessageSegment[] = [];
56
- for (const row of data.rows) {
57
- out.push({
58
- type: "button",
59
- data: {
60
- buttons: row.map(coreButtonToQq),
61
- },
62
- } as MessageSegment);
63
- }
64
- return out;
65
- }
66
-
67
- /** QQ 官方出站:keyboard → button 行;前置 text 合并为 markdown(按钮消息需带 markdown) */
68
- export function expandKeyboardSegmentsForQq(content: SendContent): SendContent {
69
- const items = Array.isArray(content) ? content : [content];
70
- const out: (string | MessageSegment)[] = [];
71
- const textParts: string[] = [];
72
-
73
- for (const item of items) {
74
- if (typeof item === "string") {
75
- textParts.push(item);
76
- continue;
77
- }
78
- const keyboardData = asKeyboardData(item);
79
- if (keyboardData) {
80
- if (textParts.length > 0) {
81
- out.push({
82
- type: "markdown",
83
- data: { content: textParts.join("\n") },
84
- } as MessageSegment);
85
- textParts.length = 0;
86
- }
87
- out.push(...keyboardDataToQqSegments(keyboardData));
88
- continue;
89
- }
90
-
91
- if (item.type === "text") {
92
- const t = item.data?.text ?? item.data?.content ?? "";
93
- if (t) textParts.push(String(t));
94
- continue;
95
- }
96
-
97
- if (textParts.length > 0) {
98
- out.push({
99
- type: "markdown",
100
- data: { content: textParts.join("\n") },
101
- } as MessageSegment);
102
- textParts.length = 0;
103
- }
104
- out.push(item as MessageSegment);
105
- }
106
-
107
- if (textParts.length > 0) {
108
- out.push({
109
- type: "markdown",
110
- data: { content: textParts.join("\n") },
111
- } as MessageSegment);
112
- }
113
-
114
- if (out.length === 0) return { type: "text", data: { text: "" } };
115
- if (out.length === 1) return out[0]!;
116
- return out;
117
- }
@@ -1,212 +0,0 @@
1
- /**
2
- * 将 AI 出站纯文本段合并为 QQ Markdown 消息(msg_type=2)。
3
- * 图文混排时合并为单条 Markdown(图片语法见 QQ 官方文档)。
4
- */
5
- import { segment, type MessageElement, type MessageSegment, type SendContent } from "zhin.js";
6
- import { resolveMediaFile } from "./outbound-media.js";
7
-
8
- function isMessageSegment(seg: MessageElement): seg is MessageSegment {
9
- return typeof seg.type === "string";
10
- }
11
-
12
- export type OutboundMarkdownMode = boolean | "auto";
13
-
14
- const BLOCKING_RICH_TYPES = new Set([
15
- "audio",
16
- "video",
17
- "file",
18
- "markdown",
19
- "ark",
20
- "embed",
21
- "keyboard",
22
- "button",
23
- "face",
24
- ]);
25
-
26
- const TEXT_IMAGE_MIX_TYPES = new Set(["text", "at", "image"]);
27
-
28
- function textSegment(text: string): MessageSegment {
29
- return { type: "text", data: { text } };
30
- }
31
-
32
- export function asOutboundSegments(content: SendContent): MessageSegment[] {
33
- if (typeof content === "string") return [textSegment(content)];
34
- if (!Array.isArray(content)) {
35
- return isMessageSegment(content) ? [content] : [];
36
- }
37
- return content.flatMap((item) =>
38
- typeof item === "string" ? [textSegment(item)] : isMessageSegment(item) ? [item] : [],
39
- );
40
- }
41
-
42
- export function splitReplyPrefix(segments: MessageSegment[]): {
43
- prefix: MessageSegment[];
44
- body: MessageSegment[];
45
- } {
46
- const prefix: MessageSegment[] = [];
47
- let i = 0;
48
- while (i < segments.length && segments[i].type === "reply") {
49
- prefix.push(segments[i]);
50
- i++;
51
- }
52
- return { prefix, body: segments.slice(i) };
53
- }
54
-
55
- function textFromSegment(seg: MessageSegment): string {
56
- if (seg.type !== "text") return "";
57
- return seg.data.text ?? seg.data.content ?? "";
58
- }
59
-
60
- function isRemoteUrl(value: string): boolean {
61
- return /^https?:\/\//i.test(value);
62
- }
63
-
64
- function isInlineMedia(value: string): boolean {
65
- return value.startsWith("base64://")
66
- || /^data:[^/]+\/[^;]+;base64,/i.test(value)
67
- || value.startsWith("file://")
68
- || (value.startsWith("/") && !isRemoteUrl(value));
69
- }
70
-
71
- /** QQ Markdown 图片语法:![说明 #宽 #高](公网 URL) */
72
- export function formatQqMarkdownImage(
73
- url: string,
74
- data: Record<string, unknown> = {},
75
- ): string {
76
- const width = typeof data.width === "number" && data.width > 0 ? data.width : 200;
77
- const height = typeof data.height === "number" && data.height > 0 ? data.height : width;
78
- const label = typeof data.name === "string" && data.name.trim() ? data.name.trim() : "图片";
79
- return `![${label} #${width}px #${height}px](${url})`;
80
- }
81
-
82
- /** 将 image 段解析为 Markdown 可嵌入的 URL(https 或 data URI) */
83
- export function resolveImageMarkdownUrl(data: Record<string, unknown>): string | null {
84
- const url = typeof data.url === "string" ? data.url : undefined;
85
- const file = resolveMediaFile(data);
86
-
87
- if (url && isRemoteUrl(url)) return url;
88
- if (file && isRemoteUrl(file)) return file;
89
-
90
- const inline = file ?? (url && isInlineMedia(url) ? url : undefined);
91
- if (!inline) return null;
92
-
93
- if (inline.startsWith("base64://")) {
94
- return `data:image/png;base64,${inline.slice(9)}`;
95
- }
96
- if (/^data:[^/]+\/[^;]+;base64,/i.test(inline)) {
97
- return inline;
98
- }
99
- return null;
100
- }
101
-
102
- export function isTextImageMixedBody(body: MessageSegment[]): boolean {
103
- if (body.length === 0) return false;
104
- if (body.some((seg) => !TEXT_IMAGE_MIX_TYPES.has(seg.type))) return false;
105
- const hasImage = body.some((seg) => seg.type === "image");
106
- const hasText = body.some((seg) => seg.type === "text" || seg.type === "at");
107
- return hasImage && hasText;
108
- }
109
-
110
- /** 图文混排且含 base64/本地图(无法直接嵌入 Markdown 公网 URL) */
111
- export function isTextImageMixedWithInlineMedia(body: MessageSegment[]): boolean {
112
- if (!isTextImageMixedBody(body)) return false;
113
- return body.some((seg) => {
114
- if (seg.type !== "image") return false;
115
- const url = typeof seg.data.url === "string" ? seg.data.url : undefined;
116
- const file = resolveMediaFile(seg.data);
117
- if (url && isRemoteUrl(url)) return false;
118
- if (file && isRemoteUrl(file)) return false;
119
- return Boolean(resolveMediaFile(seg.data) || (url && isInlineMedia(url)));
120
- });
121
- }
122
-
123
- function segmentToMarkdownPart(seg: MessageSegment): string {
124
- if (seg.type === "text") return textFromSegment(seg);
125
- if (seg.type === "at") return `<@${String(seg.data.user_id ?? "")}>`;
126
- if (seg.type === "image") {
127
- const src = resolveImageMarkdownUrl(seg.data);
128
- return src ? formatQqMarkdownImage(src, seg.data) : "";
129
- }
130
- return "";
131
- }
132
-
133
- function shouldConvertTextOnly(mode: OutboundMarkdownMode | undefined, bodyText: string): boolean {
134
- if (mode === false) return false;
135
- if (mode === true) return bodyText.trim().length > 0;
136
- return hasMarkdownHint(bodyText);
137
- }
138
-
139
- function hasMarkdownHint(text: string): boolean {
140
- if (text.includes('**') || text.includes('__') || text.includes('`')) return true;
141
- if (text.includes('](') || text.includes('|')) return true;
142
- return text.split('\n').some((line) => {
143
- const trimmed = line.trimStart();
144
- return trimmed.startsWith('# ') || trimmed.startsWith('## ')
145
- || trimmed.startsWith('> ')
146
- || trimmed.startsWith('- ')
147
- || trimmed.startsWith('* ')
148
- || trimmed.startsWith('+ ');
149
- });
150
- }
151
-
152
- function mergeTextImageToMarkdown(
153
- prefix: MessageSegment[],
154
- body: MessageSegment[],
155
- ): SendContent | null {
156
- if (body.some((seg) => seg.type === "image" && !resolveImageMarkdownUrl(seg.data))) {
157
- return null;
158
- }
159
- const merged = body.map(segmentToMarkdownPart).join("");
160
- if (!merged.trim()) return null;
161
- return [...prefix, segment("markdown", { content: merged })];
162
- }
163
-
164
- /**
165
- * 出站归一化:保留 leading `reply`,将连续 text 或 text+image 合并为单条 markdown 段。
166
- * 含内联 base64 图的图文混排须走 outbound-mixed-media(msg_type=7),此处不处理。
167
- */
168
- export function normalizeOutboundMarkdown(
169
- content: SendContent,
170
- mode: OutboundMarkdownMode | undefined = "auto",
171
- ): SendContent {
172
- const segments = asOutboundSegments(content);
173
- if (segments.length === 0) return content;
174
-
175
- const { prefix, body } = splitReplyPrefix(segments);
176
- if (body.length === 0) return content;
177
- if (mode === false) return content;
178
-
179
- if (body.some((seg) => BLOCKING_RICH_TYPES.has(seg.type))) {
180
- return content;
181
- }
182
-
183
- if (body.some((seg) => seg.type === "markdown")) {
184
- return content;
185
- }
186
-
187
- if (isTextImageMixedBody(body)) {
188
- if (isTextImageMixedWithInlineMedia(body)) {
189
- return content;
190
- }
191
- const mixed = mergeTextImageToMarkdown(prefix, body);
192
- return mixed ?? content;
193
- }
194
-
195
- if (body.some((seg) => seg.type === "image")) {
196
- return content;
197
- }
198
-
199
- if (body.some((seg) => seg.type !== "text" && seg.type !== "at")) {
200
- return content;
201
- }
202
-
203
- const merged = body
204
- .map((seg) => (seg.type === "at"
205
- ? `<@${String(seg.data.user_id ?? "")}>`
206
- : textFromSegment(seg)))
207
- .join("");
208
-
209
- if (!shouldConvertTextOnly(mode, merged)) return content;
210
-
211
- return [...prefix, segment("markdown", { content: merged })];
212
- }
@@ -1,58 +0,0 @@
1
- /**
2
- * QQ 官方出站媒体归一化。
3
- * qq-official-bot 的 formatMediaData 对 data.url 直接当远程 URL 上传;
4
- * base64:// / data:...;base64 须走 data.file 才会解析为 file_data。
5
- */
6
- import type { MessageElement, MessageSegment, SendContent } from "zhin.js";
7
-
8
- const MEDIA_TYPES = new Set(["image", "audio", "video", "file"]);
9
-
10
- function isMessageSegment(seg: MessageElement): seg is MessageSegment {
11
- return typeof seg.type === "string";
12
- }
13
-
14
- function isRemoteUrl(value: string): boolean {
15
- return /^https?:\/\//i.test(value);
16
- }
17
-
18
- function isInlineBase64(value: string): boolean {
19
- return value.startsWith("base64://") || /^data:[^/]+\/[^;]+;base64,/i.test(value);
20
- }
21
-
22
- /** 解析 image/audio/video/file 段的本地或内联 payload(供 mixed-media 上传复用) */
23
- export function resolveMediaFile(data: Record<string, unknown>): string | undefined {
24
- const url = typeof data.url === "string" ? data.url : undefined;
25
- const file = typeof data.file === "string" ? data.file : undefined;
26
- const base64 = typeof data.base64 === "string" ? data.base64 : undefined;
27
-
28
- if (file && !isRemoteUrl(file)) return file;
29
- if (url && isInlineBase64(url)) return url;
30
- if (url && !isRemoteUrl(url) && (url.startsWith("file://") || url.startsWith("/"))) return url;
31
- if (base64) return base64.startsWith("base64://") ? base64 : `base64://${base64}`;
32
- return undefined;
33
- }
34
-
35
- function normalizeMediaSegment(seg: MessageSegment): MessageSegment {
36
- if (!MEDIA_TYPES.has(seg.type)) return seg;
37
-
38
- const data = { ...seg.data } as Record<string, unknown>;
39
- const file = resolveMediaFile(data);
40
- if (!file) return seg;
41
-
42
- delete data.url;
43
- delete data.base64;
44
- data.file = file;
45
- return { type: seg.type, data } as MessageSegment;
46
- }
47
-
48
- /** 将 Zhin 出站 image/base64 段转为 qq-official-bot 可识别的 file 字段 */
49
- export function normalizeOutboundMedia(content: SendContent): SendContent {
50
- if (typeof content === "string") return content;
51
- if (!Array.isArray(content)) {
52
- return isMessageSegment(content) ? normalizeMediaSegment(content) : content;
53
- }
54
- return content.map((item) => {
55
- if (typeof item === "string") return item;
56
- return isMessageSegment(item) ? normalizeMediaSegment(item) : item;
57
- });
58
- }
@@ -1,101 +0,0 @@
1
- /**
2
- * QQ 群/私聊图文混排(msg_type=7)。
3
- * 内联 base64 图无法作为 Markdown 公网 URL,须先上传 file_info 再与文本同条发送。
4
- */
5
- import { randomInt } from "node:crypto";
6
- import type { MessageSegment, SendContent } from "zhin.js";
7
- import {
8
- asOutboundSegments,
9
- isTextImageMixedWithInlineMedia,
10
- splitReplyPrefix,
11
- } from "./outbound-markdown.js";
12
- import { resolveMediaFile } from "./outbound-media.js";
13
-
14
- function textFromSegment(seg: MessageSegment): string {
15
- if (seg.type !== "text") return "";
16
- return seg.data.text ?? seg.data.content ?? "";
17
- }
18
-
19
- function isRemoteUrl(value: string): boolean {
20
- return /^https?:\/\//i.test(value);
21
- }
22
-
23
- function extractInlineFileData(source: string): string {
24
- if (source.startsWith("base64://")) return source.slice(9);
25
- if (/^data:[^/]+\/[^;]+;base64,/i.test(source)) {
26
- return source.replace(/^data:[^/]+\/[^;]+;base64,/i, "");
27
- }
28
- return source;
29
- }
30
-
31
- export function buildQqImageUploadPayload(
32
- imageSeg: MessageSegment,
33
- ): { file_type: 1; url?: string; file_data?: string } {
34
- const data = imageSeg.data;
35
- const url = typeof data.url === "string" ? data.url : undefined;
36
- const file = resolveMediaFile(data);
37
- const remote = [url, file].find((item) => item && isRemoteUrl(item));
38
- if (remote) {
39
- return { file_type: 1, url: remote };
40
- }
41
- const inline = file ?? url;
42
- if (!inline) {
43
- throw new Error("QQ 图文混排:图片段缺少 url/file/base64");
44
- }
45
- return { file_type: 1, file_data: extractInlineFileData(inline) };
46
- }
47
-
48
- export function buildTextImageMixedBodyText(body: MessageSegment[]): string {
49
- return body
50
- .map((seg) => {
51
- if (seg.type === "text") return textFromSegment(seg);
52
- if (seg.type === "at") return `<@${String(seg.data.user_id ?? "")}>`;
53
- return "";
54
- })
55
- .join("");
56
- }
57
-
58
- export function firstImageSegment(body: MessageSegment[]): MessageSegment | undefined {
59
- return body.find((seg) => seg.type === "image");
60
- }
61
-
62
- export function shouldSendTextImageMixedMedia(
63
- content: SendContent,
64
- mode: boolean | "auto" | undefined,
65
- ): boolean {
66
- if (mode === false) return false;
67
- const { body } = splitReplyPrefix(asOutboundSegments(content));
68
- return isTextImageMixedWithInlineMedia(body);
69
- }
70
-
71
- export interface QqMixedMediaMessagePayload {
72
- msg_type: 7;
73
- content: string;
74
- media: { file_info: string };
75
- msg_seq: number;
76
- msg_id?: string;
77
- event_id?: string;
78
- }
79
-
80
- export function buildMixedMediaMessagePayload(
81
- content: SendContent,
82
- fileInfo: string,
83
- ): QqMixedMediaMessagePayload {
84
- const segments = asOutboundSegments(content);
85
- const { prefix, body } = splitReplyPrefix(segments);
86
- const payload: QqMixedMediaMessagePayload = {
87
- msg_type: 7,
88
- content: buildTextImageMixedBodyText(body),
89
- media: { file_info: fileInfo },
90
- msg_seq: randomInt(1, 1_000_000),
91
- };
92
- const reply = prefix[prefix.length - 1];
93
- if (reply?.type === "reply") {
94
- if (typeof reply.data.event_id === "string") {
95
- payload.event_id = reply.data.event_id;
96
- } else if (reply.data.id != null) {
97
- payload.msg_id = String(reply.data.id);
98
- }
99
- }
100
- return payload;
101
- }
@@ -1,145 +0,0 @@
1
- /**
2
- * QQ Bot 扫码绑定协议(内联)
3
- * Protocol aligned with @tencent-connect/qqbot-connector@1.1.0 qqbot-session — inlined to avoid runtime dependency.
4
- */
5
- import { createDecipheriv, randomBytes } from 'node:crypto';
6
-
7
- export type QQBotEnv = 'production' | 'test';
8
-
9
- const HOSTS: Record<QQBotEnv, string> = {
10
- production: 'q.qq.com',
11
- test: 'test.q.qq.com',
12
- };
13
-
14
- export enum BindStatus {
15
- NONE = 0,
16
- PENDING = 1,
17
- COMPLETED = 2,
18
- EXPIRED = 3,
19
- }
20
-
21
- export function getQQBotHost(env: QQBotEnv = 'production'): string {
22
- return HOSTS[env];
23
- }
24
-
25
- export function generateBindKey(): string {
26
- return randomBytes(32).toString('base64');
27
- }
28
-
29
- export function buildConnectUrl(taskId: string, source = 'zhin'): string {
30
- return `https://${getQQBotHost('production')}/qqbot/openclaw/connect.html?task_id=${encodeURIComponent(taskId)}&source=${encodeURIComponent(source)}&_wv=2`;
31
- }
32
-
33
- /**
34
- * AES-256-GCM 解密 base64 密文。
35
- * 密文格式: IV(12 bytes) + ciphertext + AuthTag(16 bytes)
36
- */
37
- export function decryptSecret(encryptedBase64: string, keyBase64: string): string {
38
- const key = Buffer.from(keyBase64, 'base64');
39
- const payload = Buffer.from(encryptedBase64, 'base64');
40
- const iv = payload.subarray(0, 12);
41
- const authTag = payload.subarray(payload.length - 16);
42
- const ciphertext = payload.subarray(12, payload.length - 16);
43
- const decipher = createDecipheriv('aes-256-gcm', key, iv);
44
- decipher.setAuthTag(authTag);
45
- return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
46
- }
47
-
48
- interface LiteApiResponse<T> {
49
- retcode: number;
50
- msg?: string;
51
- data?: T;
52
- }
53
-
54
- async function postJson<T>(
55
- url: string,
56
- body: Record<string, unknown>,
57
- timeoutMs: number,
58
- ): Promise<LiteApiResponse<T>> {
59
- const controller = new AbortController();
60
- const timer = setTimeout(() => controller.abort(), timeoutMs);
61
- try {
62
- const res = await fetch(url, {
63
- method: 'POST',
64
- headers: {
65
- 'Content-Type': 'application/json',
66
- Accept: 'application/json',
67
- },
68
- body: JSON.stringify(body),
69
- signal: controller.signal,
70
- });
71
- if (!res.ok) {
72
- throw new Error(`HTTP ${res.status} from ${url}`);
73
- }
74
- return (await res.json()) as LiteApiResponse<T>;
75
- } finally {
76
- clearTimeout(timer);
77
- }
78
- }
79
-
80
- export interface BindTaskResult {
81
- taskId: string;
82
- key: string;
83
- }
84
-
85
- export async function createBindTask(
86
- env: QQBotEnv = 'production',
87
- timeoutMs = 10_000,
88
- ): Promise<BindTaskResult> {
89
- const url = `https://${getQQBotHost(env)}/lite/create_bind_task`;
90
- const key = generateBindKey();
91
- const res = await postJson<{ task_id?: string }>(url, { key }, timeoutMs);
92
- if (res.retcode !== 0) {
93
- throw new Error(res.msg ?? 'create_bind_task failed');
94
- }
95
- if (!res.data?.task_id) {
96
- throw new Error('create_bind_task: missing task_id');
97
- }
98
- return { taskId: res.data.task_id, key };
99
- }
100
-
101
- export interface PollBindResultOk {
102
- status: BindStatus;
103
- botAppId: string;
104
- botEncryptSecret: string;
105
- /** 扫码绑定开发者 QQ 的 OpenID(poll_bind_result 返回) */
106
- userOpenId: string;
107
- }
108
-
109
- export function parsePollBindResultData(data: {
110
- status?: number;
111
- bot_appid?: string | number;
112
- bot_encrypt_secret?: string;
113
- user_openid?: string;
114
- userOpenid?: string;
115
- openid?: string;
116
- } | undefined): PollBindResultOk {
117
- return {
118
- status: (data?.status ?? BindStatus.NONE) as BindStatus,
119
- botAppId: String(data?.bot_appid ?? ''),
120
- botEncryptSecret: data?.bot_encrypt_secret ?? '',
121
- userOpenId: String(
122
- data?.user_openid ?? data?.userOpenid ?? data?.openid ?? '',
123
- ),
124
- };
125
- }
126
-
127
- export async function pollBindResult(
128
- taskId: string,
129
- env: QQBotEnv = 'production',
130
- timeoutMs = 10_000,
131
- ): Promise<PollBindResultOk> {
132
- const url = `https://${getQQBotHost(env)}/lite/poll_bind_result`;
133
- const res = await postJson<{
134
- status?: number;
135
- bot_appid?: string | number;
136
- bot_encrypt_secret?: string;
137
- user_openid?: string;
138
- userOpenid?: string;
139
- openid?: string;
140
- }>(url, { task_id: taskId }, timeoutMs);
141
- if (res.retcode !== 0) {
142
- throw new Error(res.msg ?? 'poll_bind_result failed');
143
- }
144
- return parsePollBindResultData(res.data);
145
- }