@nextclaw/channel-plugin-feishu 0.2.13 → 0.2.14
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 +3 -1
- package/index.ts +65 -0
- package/openclaw.plugin.json +3 -7
- package/package.json +33 -9
- package/skills/feishu-doc/SKILL.md +211 -0
- package/skills/feishu-doc/references/block-types.md +103 -0
- package/skills/feishu-drive/SKILL.md +97 -0
- package/skills/feishu-perm/SKILL.md +119 -0
- package/skills/feishu-wiki/SKILL.md +111 -0
- package/src/accounts.test.ts +371 -0
- package/src/accounts.ts +244 -0
- package/src/async.ts +62 -0
- package/src/bitable.ts +725 -0
- package/src/bot.card-action.test.ts +63 -0
- package/src/bot.checkBotMentioned.test.ts +193 -0
- package/src/bot.stripBotMention.test.ts +134 -0
- package/src/bot.test.ts +2107 -0
- package/src/bot.ts +1556 -0
- package/src/card-action.ts +79 -0
- package/src/channel.test.ts +48 -0
- package/src/channel.ts +369 -0
- package/src/chat-schema.ts +24 -0
- package/src/chat.test.ts +89 -0
- package/src/chat.ts +130 -0
- package/src/client.test.ts +324 -0
- package/src/client.ts +196 -0
- package/src/config-schema.test.ts +247 -0
- package/src/config-schema.ts +306 -0
- package/src/dedup.ts +203 -0
- package/src/directory.test.ts +40 -0
- package/src/directory.ts +156 -0
- package/src/doc-schema.ts +182 -0
- package/src/docx-batch-insert.test.ts +90 -0
- package/src/docx-batch-insert.ts +187 -0
- package/src/docx-color-text.ts +149 -0
- package/src/docx-table-ops.ts +298 -0
- package/src/docx.account-selection.test.ts +70 -0
- package/src/docx.test.ts +445 -0
- package/src/docx.ts +1460 -0
- package/src/drive-schema.ts +46 -0
- package/src/drive.ts +228 -0
- package/src/dynamic-agent.ts +131 -0
- package/src/external-keys.test.ts +20 -0
- package/src/external-keys.ts +19 -0
- package/src/feishu-command-handler.ts +59 -0
- package/src/media.test.ts +523 -0
- package/src/media.ts +484 -0
- package/src/mention.ts +133 -0
- package/src/monitor.account.ts +562 -0
- package/src/monitor.reaction.test.ts +653 -0
- package/src/monitor.startup.test.ts +190 -0
- package/src/monitor.startup.ts +64 -0
- package/src/monitor.state.defaults.test.ts +46 -0
- package/src/monitor.state.ts +155 -0
- package/src/monitor.test-mocks.ts +45 -0
- package/src/monitor.transport.ts +264 -0
- package/src/monitor.ts +95 -0
- package/src/monitor.webhook-e2e.test.ts +214 -0
- package/src/monitor.webhook-security.test.ts +142 -0
- package/src/monitor.webhook.test-helpers.ts +98 -0
- package/src/onboarding.status.test.ts +25 -0
- package/src/onboarding.test.ts +143 -0
- package/src/onboarding.ts +489 -0
- package/src/outbound.test.ts +356 -0
- package/src/outbound.ts +176 -0
- package/src/perm-schema.ts +52 -0
- package/src/perm.ts +176 -0
- package/src/policy.test.ts +154 -0
- package/src/policy.ts +123 -0
- package/src/post.test.ts +105 -0
- package/src/post.ts +274 -0
- package/src/probe.test.ts +270 -0
- package/src/probe.ts +156 -0
- package/src/reactions.ts +153 -0
- package/src/reply-dispatcher.test.ts +513 -0
- package/src/reply-dispatcher.ts +397 -0
- package/src/runtime.ts +6 -0
- package/src/secret-input.ts +13 -0
- package/src/send-message.ts +71 -0
- package/src/send-result.ts +29 -0
- package/src/send-target.test.ts +74 -0
- package/src/send-target.ts +29 -0
- package/src/send.reply-fallback.test.ts +189 -0
- package/src/send.test.ts +168 -0
- package/src/send.ts +481 -0
- package/src/streaming-card.test.ts +54 -0
- package/src/streaming-card.ts +374 -0
- package/src/targets.test.ts +70 -0
- package/src/targets.ts +107 -0
- package/src/tool-account-routing.test.ts +129 -0
- package/src/tool-account.ts +70 -0
- package/src/tool-factory-test-harness.ts +76 -0
- package/src/tool-result.test.ts +32 -0
- package/src/tool-result.ts +14 -0
- package/src/tools-config.test.ts +21 -0
- package/src/tools-config.ts +22 -0
- package/src/types.ts +103 -0
- package/src/typing.test.ts +144 -0
- package/src/typing.ts +210 -0
- package/src/wiki-schema.ts +55 -0
- package/src/wiki.ts +233 -0
- package/index.js +0 -27
package/src/media.ts
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { Readable } from "stream";
|
|
4
|
+
import { withTempDownloadPath, type ClawdbotConfig } from "openclaw/plugin-sdk/feishu";
|
|
5
|
+
import { resolveFeishuAccount } from "./accounts.js";
|
|
6
|
+
import { createFeishuClient } from "./client.js";
|
|
7
|
+
import { normalizeFeishuExternalKey } from "./external-keys.js";
|
|
8
|
+
import { getFeishuRuntime } from "./runtime.js";
|
|
9
|
+
import { assertFeishuMessageApiSuccess, toFeishuSendResult } from "./send-result.js";
|
|
10
|
+
import { resolveFeishuSendTarget } from "./send-target.js";
|
|
11
|
+
|
|
12
|
+
const FEISHU_MEDIA_HTTP_TIMEOUT_MS = 120_000;
|
|
13
|
+
|
|
14
|
+
export type DownloadImageResult = {
|
|
15
|
+
buffer: Buffer;
|
|
16
|
+
contentType?: string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type DownloadMessageResourceResult = {
|
|
20
|
+
buffer: Buffer;
|
|
21
|
+
contentType?: string;
|
|
22
|
+
fileName?: string;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
function createConfiguredFeishuMediaClient(params: { cfg: ClawdbotConfig; accountId?: string }): {
|
|
26
|
+
account: ReturnType<typeof resolveFeishuAccount>;
|
|
27
|
+
client: ReturnType<typeof createFeishuClient>;
|
|
28
|
+
} {
|
|
29
|
+
const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
|
|
30
|
+
if (!account.configured) {
|
|
31
|
+
throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
account,
|
|
36
|
+
client: createFeishuClient({
|
|
37
|
+
...account,
|
|
38
|
+
httpTimeoutMs: FEISHU_MEDIA_HTTP_TIMEOUT_MS,
|
|
39
|
+
}),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function extractFeishuUploadKey(
|
|
44
|
+
response: unknown,
|
|
45
|
+
params: {
|
|
46
|
+
key: "image_key" | "file_key";
|
|
47
|
+
errorPrefix: string;
|
|
48
|
+
},
|
|
49
|
+
): string {
|
|
50
|
+
// SDK v1.30+ returns data directly without code wrapper on success.
|
|
51
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK response type
|
|
52
|
+
const responseAny = response as any;
|
|
53
|
+
if (responseAny.code !== undefined && responseAny.code !== 0) {
|
|
54
|
+
throw new Error(`${params.errorPrefix}: ${responseAny.msg || `code ${responseAny.code}`}`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const key = responseAny[params.key] ?? responseAny.data?.[params.key];
|
|
58
|
+
if (!key) {
|
|
59
|
+
throw new Error(`${params.errorPrefix}: no ${params.key} returned`);
|
|
60
|
+
}
|
|
61
|
+
return key;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function readFeishuResponseBuffer(params: {
|
|
65
|
+
response: unknown;
|
|
66
|
+
tmpDirPrefix: string;
|
|
67
|
+
errorPrefix: string;
|
|
68
|
+
}): Promise<Buffer> {
|
|
69
|
+
const { response } = params;
|
|
70
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK response type
|
|
71
|
+
const responseAny = response as any;
|
|
72
|
+
if (responseAny.code !== undefined && responseAny.code !== 0) {
|
|
73
|
+
throw new Error(`${params.errorPrefix}: ${responseAny.msg || `code ${responseAny.code}`}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (Buffer.isBuffer(response)) {
|
|
77
|
+
return response;
|
|
78
|
+
}
|
|
79
|
+
if (response instanceof ArrayBuffer) {
|
|
80
|
+
return Buffer.from(response);
|
|
81
|
+
}
|
|
82
|
+
if (responseAny.data && Buffer.isBuffer(responseAny.data)) {
|
|
83
|
+
return responseAny.data;
|
|
84
|
+
}
|
|
85
|
+
if (responseAny.data instanceof ArrayBuffer) {
|
|
86
|
+
return Buffer.from(responseAny.data);
|
|
87
|
+
}
|
|
88
|
+
if (typeof responseAny.getReadableStream === "function") {
|
|
89
|
+
const stream = responseAny.getReadableStream();
|
|
90
|
+
const chunks: Buffer[] = [];
|
|
91
|
+
for await (const chunk of stream) {
|
|
92
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
93
|
+
}
|
|
94
|
+
return Buffer.concat(chunks);
|
|
95
|
+
}
|
|
96
|
+
if (typeof responseAny.writeFile === "function") {
|
|
97
|
+
return await withTempDownloadPath({ prefix: params.tmpDirPrefix }, async (tmpPath) => {
|
|
98
|
+
await responseAny.writeFile(tmpPath);
|
|
99
|
+
return await fs.promises.readFile(tmpPath);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (typeof responseAny[Symbol.asyncIterator] === "function") {
|
|
103
|
+
const chunks: Buffer[] = [];
|
|
104
|
+
for await (const chunk of responseAny) {
|
|
105
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
106
|
+
}
|
|
107
|
+
return Buffer.concat(chunks);
|
|
108
|
+
}
|
|
109
|
+
if (typeof responseAny.read === "function") {
|
|
110
|
+
const chunks: Buffer[] = [];
|
|
111
|
+
for await (const chunk of responseAny as Readable) {
|
|
112
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
113
|
+
}
|
|
114
|
+
return Buffer.concat(chunks);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const keys = Object.keys(responseAny);
|
|
118
|
+
const types = keys.map((k) => `${k}: ${typeof responseAny[k]}`).join(", ");
|
|
119
|
+
throw new Error(`${params.errorPrefix}: unexpected response format. Keys: [${types}]`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Download an image from Feishu using image_key.
|
|
124
|
+
* Used for downloading images sent in messages.
|
|
125
|
+
*/
|
|
126
|
+
export async function downloadImageFeishu(params: {
|
|
127
|
+
cfg: ClawdbotConfig;
|
|
128
|
+
imageKey: string;
|
|
129
|
+
accountId?: string;
|
|
130
|
+
}): Promise<DownloadImageResult> {
|
|
131
|
+
const { cfg, imageKey, accountId } = params;
|
|
132
|
+
const normalizedImageKey = normalizeFeishuExternalKey(imageKey);
|
|
133
|
+
if (!normalizedImageKey) {
|
|
134
|
+
throw new Error("Feishu image download failed: invalid image_key");
|
|
135
|
+
}
|
|
136
|
+
const { client } = createConfiguredFeishuMediaClient({ cfg, accountId });
|
|
137
|
+
|
|
138
|
+
const response = await client.im.image.get({
|
|
139
|
+
path: { image_key: normalizedImageKey },
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
const buffer = await readFeishuResponseBuffer({
|
|
143
|
+
response,
|
|
144
|
+
tmpDirPrefix: "openclaw-feishu-img-",
|
|
145
|
+
errorPrefix: "Feishu image download failed",
|
|
146
|
+
});
|
|
147
|
+
return { buffer };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Download a message resource (file/image/audio/video) from Feishu.
|
|
152
|
+
* Used for downloading files, audio, and video from messages.
|
|
153
|
+
*/
|
|
154
|
+
export async function downloadMessageResourceFeishu(params: {
|
|
155
|
+
cfg: ClawdbotConfig;
|
|
156
|
+
messageId: string;
|
|
157
|
+
fileKey: string;
|
|
158
|
+
type: "image" | "file";
|
|
159
|
+
accountId?: string;
|
|
160
|
+
}): Promise<DownloadMessageResourceResult> {
|
|
161
|
+
const { cfg, messageId, fileKey, type, accountId } = params;
|
|
162
|
+
const normalizedFileKey = normalizeFeishuExternalKey(fileKey);
|
|
163
|
+
if (!normalizedFileKey) {
|
|
164
|
+
throw new Error("Feishu message resource download failed: invalid file_key");
|
|
165
|
+
}
|
|
166
|
+
const { client } = createConfiguredFeishuMediaClient({ cfg, accountId });
|
|
167
|
+
|
|
168
|
+
const response = await client.im.messageResource.get({
|
|
169
|
+
path: { message_id: messageId, file_key: normalizedFileKey },
|
|
170
|
+
params: { type },
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
const buffer = await readFeishuResponseBuffer({
|
|
174
|
+
response,
|
|
175
|
+
tmpDirPrefix: "openclaw-feishu-resource-",
|
|
176
|
+
errorPrefix: "Feishu message resource download failed",
|
|
177
|
+
});
|
|
178
|
+
return { buffer };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export type UploadImageResult = {
|
|
182
|
+
imageKey: string;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
export type UploadFileResult = {
|
|
186
|
+
fileKey: string;
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export type SendMediaResult = {
|
|
190
|
+
messageId: string;
|
|
191
|
+
chatId: string;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Upload an image to Feishu and get an image_key for sending.
|
|
196
|
+
* Supports: JPEG, PNG, WEBP, GIF, TIFF, BMP, ICO
|
|
197
|
+
*/
|
|
198
|
+
export async function uploadImageFeishu(params: {
|
|
199
|
+
cfg: ClawdbotConfig;
|
|
200
|
+
image: Buffer | string; // Buffer or file path
|
|
201
|
+
imageType?: "message" | "avatar";
|
|
202
|
+
accountId?: string;
|
|
203
|
+
}): Promise<UploadImageResult> {
|
|
204
|
+
const { cfg, image, imageType = "message", accountId } = params;
|
|
205
|
+
const { client } = createConfiguredFeishuMediaClient({ cfg, accountId });
|
|
206
|
+
|
|
207
|
+
// SDK accepts Buffer directly or fs.ReadStream for file paths
|
|
208
|
+
// Using Readable.from(buffer) causes issues with form-data library
|
|
209
|
+
// See: https://github.com/larksuite/node-sdk/issues/121
|
|
210
|
+
const imageData = typeof image === "string" ? fs.createReadStream(image) : image;
|
|
211
|
+
|
|
212
|
+
const response = await client.im.image.create({
|
|
213
|
+
data: {
|
|
214
|
+
image_type: imageType,
|
|
215
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK accepts Buffer or ReadStream
|
|
216
|
+
image: imageData as any,
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
imageKey: extractFeishuUploadKey(response, {
|
|
222
|
+
key: "image_key",
|
|
223
|
+
errorPrefix: "Feishu image upload failed",
|
|
224
|
+
}),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Sanitize a filename for safe use in Feishu multipart/form-data uploads.
|
|
230
|
+
* Strips control characters and multipart-injection vectors (CWE-93) while
|
|
231
|
+
* preserving the original UTF-8 display name (Chinese, emoji, etc.).
|
|
232
|
+
*
|
|
233
|
+
* Previous versions percent-encoded non-ASCII characters, but the Feishu
|
|
234
|
+
* `im.file.create` API uses `file_name` as a literal display name — it does
|
|
235
|
+
* NOT decode percent-encoding — so encoded filenames appeared as garbled text
|
|
236
|
+
* in chat (regression in v2026.3.2).
|
|
237
|
+
*/
|
|
238
|
+
export function sanitizeFileNameForUpload(fileName: string): string {
|
|
239
|
+
return fileName.replace(/[\x00-\x1F\x7F\r\n"\\]/g, "_");
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Upload a file to Feishu and get a file_key for sending.
|
|
244
|
+
* Max file size: 30MB
|
|
245
|
+
*/
|
|
246
|
+
export async function uploadFileFeishu(params: {
|
|
247
|
+
cfg: ClawdbotConfig;
|
|
248
|
+
file: Buffer | string; // Buffer or file path
|
|
249
|
+
fileName: string;
|
|
250
|
+
fileType: "opus" | "mp4" | "pdf" | "doc" | "xls" | "ppt" | "stream";
|
|
251
|
+
duration?: number; // Required for audio/video files, in milliseconds
|
|
252
|
+
accountId?: string;
|
|
253
|
+
}): Promise<UploadFileResult> {
|
|
254
|
+
const { cfg, file, fileName, fileType, duration, accountId } = params;
|
|
255
|
+
const { client } = createConfiguredFeishuMediaClient({ cfg, accountId });
|
|
256
|
+
|
|
257
|
+
// SDK accepts Buffer directly or fs.ReadStream for file paths
|
|
258
|
+
// Using Readable.from(buffer) causes issues with form-data library
|
|
259
|
+
// See: https://github.com/larksuite/node-sdk/issues/121
|
|
260
|
+
const fileData = typeof file === "string" ? fs.createReadStream(file) : file;
|
|
261
|
+
|
|
262
|
+
const safeFileName = sanitizeFileNameForUpload(fileName);
|
|
263
|
+
|
|
264
|
+
const response = await client.im.file.create({
|
|
265
|
+
data: {
|
|
266
|
+
file_type: fileType,
|
|
267
|
+
file_name: safeFileName,
|
|
268
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK accepts Buffer or ReadStream
|
|
269
|
+
file: fileData as any,
|
|
270
|
+
...(duration !== undefined && { duration }),
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
return {
|
|
275
|
+
fileKey: extractFeishuUploadKey(response, {
|
|
276
|
+
key: "file_key",
|
|
277
|
+
errorPrefix: "Feishu file upload failed",
|
|
278
|
+
}),
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Send an image message using an image_key
|
|
284
|
+
*/
|
|
285
|
+
export async function sendImageFeishu(params: {
|
|
286
|
+
cfg: ClawdbotConfig;
|
|
287
|
+
to: string;
|
|
288
|
+
imageKey: string;
|
|
289
|
+
replyToMessageId?: string;
|
|
290
|
+
replyInThread?: boolean;
|
|
291
|
+
accountId?: string;
|
|
292
|
+
}): Promise<SendMediaResult> {
|
|
293
|
+
const { cfg, to, imageKey, replyToMessageId, replyInThread, accountId } = params;
|
|
294
|
+
const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
|
|
295
|
+
cfg,
|
|
296
|
+
to,
|
|
297
|
+
accountId,
|
|
298
|
+
});
|
|
299
|
+
const content = JSON.stringify({ image_key: imageKey });
|
|
300
|
+
|
|
301
|
+
if (replyToMessageId) {
|
|
302
|
+
const response = await client.im.message.reply({
|
|
303
|
+
path: { message_id: replyToMessageId },
|
|
304
|
+
data: {
|
|
305
|
+
content,
|
|
306
|
+
msg_type: "image",
|
|
307
|
+
...(replyInThread ? { reply_in_thread: true } : {}),
|
|
308
|
+
},
|
|
309
|
+
});
|
|
310
|
+
assertFeishuMessageApiSuccess(response, "Feishu image reply failed");
|
|
311
|
+
return toFeishuSendResult(response, receiveId);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const response = await client.im.message.create({
|
|
315
|
+
params: { receive_id_type: receiveIdType },
|
|
316
|
+
data: {
|
|
317
|
+
receive_id: receiveId,
|
|
318
|
+
content,
|
|
319
|
+
msg_type: "image",
|
|
320
|
+
},
|
|
321
|
+
});
|
|
322
|
+
assertFeishuMessageApiSuccess(response, "Feishu image send failed");
|
|
323
|
+
return toFeishuSendResult(response, receiveId);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Send a file message using a file_key
|
|
328
|
+
*/
|
|
329
|
+
export async function sendFileFeishu(params: {
|
|
330
|
+
cfg: ClawdbotConfig;
|
|
331
|
+
to: string;
|
|
332
|
+
fileKey: string;
|
|
333
|
+
/** Use "audio" for audio, "media" for video (mp4), "file" for documents */
|
|
334
|
+
msgType?: "file" | "audio" | "media";
|
|
335
|
+
replyToMessageId?: string;
|
|
336
|
+
replyInThread?: boolean;
|
|
337
|
+
accountId?: string;
|
|
338
|
+
}): Promise<SendMediaResult> {
|
|
339
|
+
const { cfg, to, fileKey, replyToMessageId, replyInThread, accountId } = params;
|
|
340
|
+
const msgType = params.msgType ?? "file";
|
|
341
|
+
const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
|
|
342
|
+
cfg,
|
|
343
|
+
to,
|
|
344
|
+
accountId,
|
|
345
|
+
});
|
|
346
|
+
const content = JSON.stringify({ file_key: fileKey });
|
|
347
|
+
|
|
348
|
+
if (replyToMessageId) {
|
|
349
|
+
const response = await client.im.message.reply({
|
|
350
|
+
path: { message_id: replyToMessageId },
|
|
351
|
+
data: {
|
|
352
|
+
content,
|
|
353
|
+
msg_type: msgType,
|
|
354
|
+
...(replyInThread ? { reply_in_thread: true } : {}),
|
|
355
|
+
},
|
|
356
|
+
});
|
|
357
|
+
assertFeishuMessageApiSuccess(response, "Feishu file reply failed");
|
|
358
|
+
return toFeishuSendResult(response, receiveId);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const response = await client.im.message.create({
|
|
362
|
+
params: { receive_id_type: receiveIdType },
|
|
363
|
+
data: {
|
|
364
|
+
receive_id: receiveId,
|
|
365
|
+
content,
|
|
366
|
+
msg_type: msgType,
|
|
367
|
+
},
|
|
368
|
+
});
|
|
369
|
+
assertFeishuMessageApiSuccess(response, "Feishu file send failed");
|
|
370
|
+
return toFeishuSendResult(response, receiveId);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Helper to detect file type from extension
|
|
375
|
+
*/
|
|
376
|
+
export function detectFileType(
|
|
377
|
+
fileName: string,
|
|
378
|
+
): "opus" | "mp4" | "pdf" | "doc" | "xls" | "ppt" | "stream" {
|
|
379
|
+
const ext = path.extname(fileName).toLowerCase();
|
|
380
|
+
switch (ext) {
|
|
381
|
+
case ".opus":
|
|
382
|
+
case ".ogg":
|
|
383
|
+
return "opus";
|
|
384
|
+
case ".mp4":
|
|
385
|
+
case ".mov":
|
|
386
|
+
case ".avi":
|
|
387
|
+
return "mp4";
|
|
388
|
+
case ".pdf":
|
|
389
|
+
return "pdf";
|
|
390
|
+
case ".doc":
|
|
391
|
+
case ".docx":
|
|
392
|
+
return "doc";
|
|
393
|
+
case ".xls":
|
|
394
|
+
case ".xlsx":
|
|
395
|
+
return "xls";
|
|
396
|
+
case ".ppt":
|
|
397
|
+
case ".pptx":
|
|
398
|
+
return "ppt";
|
|
399
|
+
default:
|
|
400
|
+
return "stream";
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Upload and send media (image or file) from URL, local path, or buffer.
|
|
406
|
+
* When mediaUrl is a local path, mediaLocalRoots (from core outbound context)
|
|
407
|
+
* must be passed so loadWebMedia allows the path (post CVE-2026-26321).
|
|
408
|
+
*/
|
|
409
|
+
export async function sendMediaFeishu(params: {
|
|
410
|
+
cfg: ClawdbotConfig;
|
|
411
|
+
to: string;
|
|
412
|
+
mediaUrl?: string;
|
|
413
|
+
mediaBuffer?: Buffer;
|
|
414
|
+
fileName?: string;
|
|
415
|
+
replyToMessageId?: string;
|
|
416
|
+
replyInThread?: boolean;
|
|
417
|
+
accountId?: string;
|
|
418
|
+
/** Allowed roots for local path reads; required for local filePath to work. */
|
|
419
|
+
mediaLocalRoots?: readonly string[];
|
|
420
|
+
}): Promise<SendMediaResult> {
|
|
421
|
+
const {
|
|
422
|
+
cfg,
|
|
423
|
+
to,
|
|
424
|
+
mediaUrl,
|
|
425
|
+
mediaBuffer,
|
|
426
|
+
fileName,
|
|
427
|
+
replyToMessageId,
|
|
428
|
+
replyInThread,
|
|
429
|
+
accountId,
|
|
430
|
+
mediaLocalRoots,
|
|
431
|
+
} = params;
|
|
432
|
+
const account = resolveFeishuAccount({ cfg, accountId });
|
|
433
|
+
if (!account.configured) {
|
|
434
|
+
throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
435
|
+
}
|
|
436
|
+
const mediaMaxBytes = (account.config?.mediaMaxMb ?? 30) * 1024 * 1024;
|
|
437
|
+
|
|
438
|
+
let buffer: Buffer;
|
|
439
|
+
let name: string;
|
|
440
|
+
|
|
441
|
+
if (mediaBuffer) {
|
|
442
|
+
buffer = mediaBuffer;
|
|
443
|
+
name = fileName ?? "file";
|
|
444
|
+
} else if (mediaUrl) {
|
|
445
|
+
const loaded = await getFeishuRuntime().media.loadWebMedia(mediaUrl, {
|
|
446
|
+
maxBytes: mediaMaxBytes,
|
|
447
|
+
optimizeImages: false,
|
|
448
|
+
localRoots: mediaLocalRoots?.length ? mediaLocalRoots : undefined,
|
|
449
|
+
});
|
|
450
|
+
buffer = loaded.buffer;
|
|
451
|
+
name = fileName ?? loaded.fileName ?? "file";
|
|
452
|
+
} else {
|
|
453
|
+
throw new Error("Either mediaUrl or mediaBuffer must be provided");
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Determine if it's an image based on extension
|
|
457
|
+
const ext = path.extname(name).toLowerCase();
|
|
458
|
+
const isImage = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".ico", ".tiff"].includes(ext);
|
|
459
|
+
|
|
460
|
+
if (isImage) {
|
|
461
|
+
const { imageKey } = await uploadImageFeishu({ cfg, image: buffer, accountId });
|
|
462
|
+
return sendImageFeishu({ cfg, to, imageKey, replyToMessageId, replyInThread, accountId });
|
|
463
|
+
} else {
|
|
464
|
+
const fileType = detectFileType(name);
|
|
465
|
+
const { fileKey } = await uploadFileFeishu({
|
|
466
|
+
cfg,
|
|
467
|
+
file: buffer,
|
|
468
|
+
fileName: name,
|
|
469
|
+
fileType,
|
|
470
|
+
accountId,
|
|
471
|
+
});
|
|
472
|
+
// Feishu API: opus -> "audio", mp4/video -> "media" (playable), others -> "file"
|
|
473
|
+
const msgType = fileType === "opus" ? "audio" : fileType === "mp4" ? "media" : "file";
|
|
474
|
+
return sendFileFeishu({
|
|
475
|
+
cfg,
|
|
476
|
+
to,
|
|
477
|
+
fileKey,
|
|
478
|
+
msgType,
|
|
479
|
+
replyToMessageId,
|
|
480
|
+
replyInThread,
|
|
481
|
+
accountId,
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
}
|
package/src/mention.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { FeishuMessageEvent } from "./bot.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Escape regex metacharacters so user-controlled mention fields are treated literally.
|
|
5
|
+
*/
|
|
6
|
+
export function escapeRegExp(input: string): string {
|
|
7
|
+
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Mention target user info
|
|
12
|
+
*/
|
|
13
|
+
export type MentionTarget = {
|
|
14
|
+
openId: string;
|
|
15
|
+
name: string;
|
|
16
|
+
key: string; // Placeholder in original message, e.g. @_user_1
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Extract mention targets from message event (excluding the bot itself)
|
|
21
|
+
*/
|
|
22
|
+
export function extractMentionTargets(
|
|
23
|
+
event: FeishuMessageEvent,
|
|
24
|
+
botOpenId?: string,
|
|
25
|
+
): MentionTarget[] {
|
|
26
|
+
const mentions = event.message.mentions ?? [];
|
|
27
|
+
|
|
28
|
+
return mentions
|
|
29
|
+
.filter((m) => {
|
|
30
|
+
// Exclude the bot itself
|
|
31
|
+
if (botOpenId && m.id.open_id === botOpenId) {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
// Must have open_id
|
|
35
|
+
return !!m.id.open_id;
|
|
36
|
+
})
|
|
37
|
+
.map((m) => ({
|
|
38
|
+
openId: m.id.open_id!,
|
|
39
|
+
name: m.name,
|
|
40
|
+
key: m.key,
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Check if message is a mention forward request
|
|
46
|
+
* Rules:
|
|
47
|
+
* - Group: message mentions bot + at least one other user
|
|
48
|
+
* - DM: message mentions any user (no need to mention bot)
|
|
49
|
+
*/
|
|
50
|
+
export function isMentionForwardRequest(event: FeishuMessageEvent, botOpenId?: string): boolean {
|
|
51
|
+
const mentions = event.message.mentions ?? [];
|
|
52
|
+
if (mentions.length === 0) {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const isDirectMessage = event.message.chat_type !== "group";
|
|
57
|
+
const hasOtherMention = mentions.some((m) => m.id.open_id !== botOpenId);
|
|
58
|
+
|
|
59
|
+
if (isDirectMessage) {
|
|
60
|
+
// DM: trigger if any non-bot user is mentioned
|
|
61
|
+
return hasOtherMention;
|
|
62
|
+
} else {
|
|
63
|
+
// Group: need to mention both bot and other users
|
|
64
|
+
const hasBotMention = mentions.some((m) => m.id.open_id === botOpenId);
|
|
65
|
+
return hasBotMention && hasOtherMention;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Extract message body from text (remove @ placeholders)
|
|
71
|
+
*/
|
|
72
|
+
export function extractMessageBody(text: string, allMentionKeys: string[]): string {
|
|
73
|
+
let result = text;
|
|
74
|
+
|
|
75
|
+
// Remove all @ placeholders
|
|
76
|
+
for (const key of allMentionKeys) {
|
|
77
|
+
result = result.replace(new RegExp(escapeRegExp(key), "g"), "");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return result.replace(/\s+/g, " ").trim();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Format @mention for text message
|
|
85
|
+
*/
|
|
86
|
+
export function formatMentionForText(target: MentionTarget): string {
|
|
87
|
+
return `<at user_id="${target.openId}">${target.name}</at>`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Format @everyone for text message
|
|
92
|
+
*/
|
|
93
|
+
export function formatMentionAllForText(): string {
|
|
94
|
+
return `<at user_id="all">Everyone</at>`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Format @mention for card message (lark_md)
|
|
99
|
+
*/
|
|
100
|
+
export function formatMentionForCard(target: MentionTarget): string {
|
|
101
|
+
return `<at id=${target.openId}></at>`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Format @everyone for card message
|
|
106
|
+
*/
|
|
107
|
+
export function formatMentionAllForCard(): string {
|
|
108
|
+
return `<at id=all></at>`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Build complete message with @mentions (text format)
|
|
113
|
+
*/
|
|
114
|
+
export function buildMentionedMessage(targets: MentionTarget[], message: string): string {
|
|
115
|
+
if (targets.length === 0) {
|
|
116
|
+
return message;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const mentionParts = targets.map((t) => formatMentionForText(t));
|
|
120
|
+
return `${mentionParts.join(" ")} ${message}`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Build card content with @mentions (Markdown format)
|
|
125
|
+
*/
|
|
126
|
+
export function buildMentionedCardContent(targets: MentionTarget[], message: string): string {
|
|
127
|
+
if (targets.length === 0) {
|
|
128
|
+
return message;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const mentionParts = targets.map((t) => formatMentionForCard(t));
|
|
132
|
+
return `${mentionParts.join(" ")} ${message}`;
|
|
133
|
+
}
|