@milerliu/feishu 0.1.5

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/src/media.ts ADDED
@@ -0,0 +1,515 @@
1
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk";
2
+ import type { FeishuConfig } from "./types.js";
3
+ import { createFeishuClient } from "./client.js";
4
+ import { resolveReceiveIdType, normalizeFeishuTarget } from "./targets.js";
5
+ import fs from "fs";
6
+ import path from "path";
7
+ import os from "os";
8
+ import { Readable } from "stream";
9
+
10
+ export type DownloadImageResult = {
11
+ buffer: Buffer;
12
+ contentType?: string;
13
+ };
14
+
15
+ export type DownloadMessageResourceResult = {
16
+ buffer: Buffer;
17
+ contentType?: string;
18
+ fileName?: string;
19
+ };
20
+
21
+ /**
22
+ * Download an image from Feishu using image_key.
23
+ * Used for downloading images sent in messages.
24
+ */
25
+ export async function downloadImageFeishu(params: {
26
+ cfg: ClawdbotConfig;
27
+ imageKey: string;
28
+ }): Promise<DownloadImageResult> {
29
+ const { cfg, imageKey } = params;
30
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
31
+ if (!feishuCfg) {
32
+ throw new Error("Feishu channel not configured");
33
+ }
34
+
35
+ const client = createFeishuClient(feishuCfg);
36
+
37
+ const response = await client.im.image.get({
38
+ path: { image_key: imageKey },
39
+ });
40
+
41
+ const responseAny = response as any;
42
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
43
+ throw new Error(`Feishu image download failed: ${responseAny.msg || `code ${responseAny.code}`}`);
44
+ }
45
+
46
+ // Handle various response formats from Feishu SDK
47
+ let buffer: Buffer;
48
+
49
+ if (Buffer.isBuffer(response)) {
50
+ buffer = response;
51
+ } else if (response instanceof ArrayBuffer) {
52
+ buffer = Buffer.from(response);
53
+ } else if (responseAny.data && Buffer.isBuffer(responseAny.data)) {
54
+ buffer = responseAny.data;
55
+ } else if (responseAny.data instanceof ArrayBuffer) {
56
+ buffer = Buffer.from(responseAny.data);
57
+ } else if (typeof responseAny.getReadableStream === "function") {
58
+ // SDK provides getReadableStream method
59
+ const stream = responseAny.getReadableStream();
60
+ const chunks: Buffer[] = [];
61
+ for await (const chunk of stream) {
62
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
63
+ }
64
+ buffer = Buffer.concat(chunks);
65
+ } else if (typeof responseAny.writeFile === "function") {
66
+ // SDK provides writeFile method - use a temp file
67
+ const tmpPath = path.join(os.tmpdir(), `feishu_img_${Date.now()}_${imageKey}`);
68
+ await responseAny.writeFile(tmpPath);
69
+ buffer = await fs.promises.readFile(tmpPath);
70
+ await fs.promises.unlink(tmpPath).catch(() => {}); // cleanup
71
+ } else if (typeof responseAny[Symbol.asyncIterator] === "function") {
72
+ // Response is an async iterable
73
+ const chunks: Buffer[] = [];
74
+ for await (const chunk of responseAny) {
75
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
76
+ }
77
+ buffer = Buffer.concat(chunks);
78
+ } else if (typeof responseAny.read === "function") {
79
+ // Response is a Readable stream
80
+ const chunks: Buffer[] = [];
81
+ for await (const chunk of responseAny as Readable) {
82
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
83
+ }
84
+ buffer = Buffer.concat(chunks);
85
+ } else {
86
+ // Debug: log what we actually received
87
+ const keys = Object.keys(responseAny);
88
+ const types = keys.map(k => `${k}: ${typeof responseAny[k]}`).join(", ");
89
+ throw new Error(
90
+ `Feishu image download failed: unexpected response format. Keys: [${types}]`,
91
+ );
92
+ }
93
+
94
+ return { buffer };
95
+ }
96
+
97
+ /**
98
+ * Download a message resource (file/image/audio/video) from Feishu.
99
+ * Used for downloading files, audio, and video from messages.
100
+ */
101
+ export async function downloadMessageResourceFeishu(params: {
102
+ cfg: ClawdbotConfig;
103
+ messageId: string;
104
+ fileKey: string;
105
+ type: "image" | "file";
106
+ }): Promise<DownloadMessageResourceResult> {
107
+ const { cfg, messageId, fileKey, type } = params;
108
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
109
+ if (!feishuCfg) {
110
+ throw new Error("Feishu channel not configured");
111
+ }
112
+
113
+ const client = createFeishuClient(feishuCfg);
114
+
115
+ const response = await client.im.messageResource.get({
116
+ path: { message_id: messageId, file_key: fileKey },
117
+ params: { type },
118
+ });
119
+
120
+ const responseAny = response as any;
121
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
122
+ throw new Error(
123
+ `Feishu message resource download failed: ${responseAny.msg || `code ${responseAny.code}`}`,
124
+ );
125
+ }
126
+
127
+ // Handle various response formats from Feishu SDK
128
+ let buffer: Buffer;
129
+
130
+ if (Buffer.isBuffer(response)) {
131
+ buffer = response;
132
+ } else if (response instanceof ArrayBuffer) {
133
+ buffer = Buffer.from(response);
134
+ } else if (responseAny.data && Buffer.isBuffer(responseAny.data)) {
135
+ buffer = responseAny.data;
136
+ } else if (responseAny.data instanceof ArrayBuffer) {
137
+ buffer = Buffer.from(responseAny.data);
138
+ } else if (typeof responseAny.getReadableStream === "function") {
139
+ // SDK provides getReadableStream method
140
+ const stream = responseAny.getReadableStream();
141
+ const chunks: Buffer[] = [];
142
+ for await (const chunk of stream) {
143
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
144
+ }
145
+ buffer = Buffer.concat(chunks);
146
+ } else if (typeof responseAny.writeFile === "function") {
147
+ // SDK provides writeFile method - use a temp file
148
+ const tmpPath = path.join(os.tmpdir(), `feishu_${Date.now()}_${fileKey}`);
149
+ await responseAny.writeFile(tmpPath);
150
+ buffer = await fs.promises.readFile(tmpPath);
151
+ await fs.promises.unlink(tmpPath).catch(() => {}); // cleanup
152
+ } else if (typeof responseAny[Symbol.asyncIterator] === "function") {
153
+ // Response is an async iterable
154
+ const chunks: Buffer[] = [];
155
+ for await (const chunk of responseAny) {
156
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
157
+ }
158
+ buffer = Buffer.concat(chunks);
159
+ } else if (typeof responseAny.read === "function") {
160
+ // Response is a Readable stream
161
+ const chunks: Buffer[] = [];
162
+ for await (const chunk of responseAny as Readable) {
163
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
164
+ }
165
+ buffer = Buffer.concat(chunks);
166
+ } else {
167
+ // Debug: log what we actually received
168
+ const keys = Object.keys(responseAny);
169
+ const types = keys.map(k => `${k}: ${typeof responseAny[k]}`).join(", ");
170
+ throw new Error(
171
+ `Feishu message resource download failed: unexpected response format. Keys: [${types}]`,
172
+ );
173
+ }
174
+
175
+ return { buffer };
176
+ }
177
+
178
+ export type UploadImageResult = {
179
+ imageKey: string;
180
+ };
181
+
182
+ export type UploadFileResult = {
183
+ fileKey: string;
184
+ };
185
+
186
+ export type SendMediaResult = {
187
+ messageId: string;
188
+ chatId: string;
189
+ };
190
+
191
+ /**
192
+ * Upload an image to Feishu and get an image_key for sending.
193
+ * Supports: JPEG, PNG, WEBP, GIF, TIFF, BMP, ICO
194
+ */
195
+ export async function uploadImageFeishu(params: {
196
+ cfg: ClawdbotConfig;
197
+ image: Buffer | string; // Buffer or file path
198
+ imageType?: "message" | "avatar";
199
+ }): Promise<UploadImageResult> {
200
+ const { cfg, image, imageType = "message" } = params;
201
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
202
+ if (!feishuCfg) {
203
+ throw new Error("Feishu channel not configured");
204
+ }
205
+
206
+ const client = createFeishuClient(feishuCfg);
207
+
208
+ // SDK expects a Readable stream, not a Buffer
209
+ // Use type assertion since SDK actually accepts any Readable at runtime
210
+ const imageStream =
211
+ typeof image === "string" ? fs.createReadStream(image) : Readable.from(image);
212
+
213
+ const response = await client.im.image.create({
214
+ data: {
215
+ image_type: imageType,
216
+ image: imageStream as any,
217
+ },
218
+ });
219
+
220
+ // SDK v1.30+ returns data directly without code wrapper on success
221
+ // On error, it throws or returns { code, msg }
222
+ const responseAny = response as any;
223
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
224
+ throw new Error(`Feishu image upload failed: ${responseAny.msg || `code ${responseAny.code}`}`);
225
+ }
226
+
227
+ const imageKey = responseAny.image_key ?? responseAny.data?.image_key;
228
+ if (!imageKey) {
229
+ throw new Error("Feishu image upload failed: no image_key returned");
230
+ }
231
+
232
+ return { imageKey };
233
+ }
234
+
235
+ /**
236
+ * Upload a file to Feishu and get a file_key for sending.
237
+ * Max file size: 30MB
238
+ */
239
+ export async function uploadFileFeishu(params: {
240
+ cfg: ClawdbotConfig;
241
+ file: Buffer | string; // Buffer or file path
242
+ fileName: string;
243
+ fileType: "opus" | "mp4" | "pdf" | "doc" | "xls" | "ppt" | "stream";
244
+ duration?: number; // Required for audio/video files, in milliseconds
245
+ }): Promise<UploadFileResult> {
246
+ const { cfg, file, fileName, fileType, duration } = params;
247
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
248
+ if (!feishuCfg) {
249
+ throw new Error("Feishu channel not configured");
250
+ }
251
+
252
+ const client = createFeishuClient(feishuCfg);
253
+
254
+ // SDK expects a Readable stream, not a Buffer
255
+ // Use type assertion since SDK actually accepts any Readable at runtime
256
+ const fileStream =
257
+ typeof file === "string" ? fs.createReadStream(file) : Readable.from(file);
258
+
259
+ const response = await client.im.file.create({
260
+ data: {
261
+ file_type: fileType,
262
+ file_name: fileName,
263
+ file: fileStream as any,
264
+ ...(duration !== undefined && { duration }),
265
+ },
266
+ });
267
+
268
+ // SDK v1.30+ returns data directly without code wrapper on success
269
+ const responseAny = response as any;
270
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
271
+ throw new Error(`Feishu file upload failed: ${responseAny.msg || `code ${responseAny.code}`}`);
272
+ }
273
+
274
+ const fileKey = responseAny.file_key ?? responseAny.data?.file_key;
275
+ if (!fileKey) {
276
+ throw new Error("Feishu file upload failed: no file_key returned");
277
+ }
278
+
279
+ return { fileKey };
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
+ }): Promise<SendMediaResult> {
291
+ const { cfg, to, imageKey, replyToMessageId } = params;
292
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
293
+ if (!feishuCfg) {
294
+ throw new Error("Feishu channel not configured");
295
+ }
296
+
297
+ const client = createFeishuClient(feishuCfg);
298
+ const receiveId = normalizeFeishuTarget(to);
299
+ if (!receiveId) {
300
+ throw new Error(`Invalid Feishu target: ${to}`);
301
+ }
302
+
303
+ const receiveIdType = resolveReceiveIdType(receiveId);
304
+ const content = JSON.stringify({ image_key: imageKey });
305
+
306
+ if (replyToMessageId) {
307
+ const response = await client.im.message.reply({
308
+ path: { message_id: replyToMessageId },
309
+ data: {
310
+ content,
311
+ msg_type: "image",
312
+ },
313
+ });
314
+
315
+ if (response.code !== 0) {
316
+ throw new Error(`Feishu image reply failed: ${response.msg || `code ${response.code}`}`);
317
+ }
318
+
319
+ return {
320
+ messageId: response.data?.message_id ?? "unknown",
321
+ chatId: receiveId,
322
+ };
323
+ }
324
+
325
+ const response = await client.im.message.create({
326
+ params: { receive_id_type: receiveIdType },
327
+ data: {
328
+ receive_id: receiveId,
329
+ content,
330
+ msg_type: "image",
331
+ },
332
+ });
333
+
334
+ if (response.code !== 0) {
335
+ throw new Error(`Feishu image send failed: ${response.msg || `code ${response.code}`}`);
336
+ }
337
+
338
+ return {
339
+ messageId: response.data?.message_id ?? "unknown",
340
+ chatId: receiveId,
341
+ };
342
+ }
343
+
344
+ /**
345
+ * Send a file message using a file_key
346
+ */
347
+ export async function sendFileFeishu(params: {
348
+ cfg: ClawdbotConfig;
349
+ to: string;
350
+ fileKey: string;
351
+ replyToMessageId?: string;
352
+ }): Promise<SendMediaResult> {
353
+ const { cfg, to, fileKey, replyToMessageId } = params;
354
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
355
+ if (!feishuCfg) {
356
+ throw new Error("Feishu channel not configured");
357
+ }
358
+
359
+ const client = createFeishuClient(feishuCfg);
360
+ const receiveId = normalizeFeishuTarget(to);
361
+ if (!receiveId) {
362
+ throw new Error(`Invalid Feishu target: ${to}`);
363
+ }
364
+
365
+ const receiveIdType = resolveReceiveIdType(receiveId);
366
+ const content = JSON.stringify({ file_key: fileKey });
367
+
368
+ if (replyToMessageId) {
369
+ const response = await client.im.message.reply({
370
+ path: { message_id: replyToMessageId },
371
+ data: {
372
+ content,
373
+ msg_type: "file",
374
+ },
375
+ });
376
+
377
+ if (response.code !== 0) {
378
+ throw new Error(`Feishu file reply failed: ${response.msg || `code ${response.code}`}`);
379
+ }
380
+
381
+ return {
382
+ messageId: response.data?.message_id ?? "unknown",
383
+ chatId: receiveId,
384
+ };
385
+ }
386
+
387
+ const response = await client.im.message.create({
388
+ params: { receive_id_type: receiveIdType },
389
+ data: {
390
+ receive_id: receiveId,
391
+ content,
392
+ msg_type: "file",
393
+ },
394
+ });
395
+
396
+ if (response.code !== 0) {
397
+ throw new Error(`Feishu file send failed: ${response.msg || `code ${response.code}`}`);
398
+ }
399
+
400
+ return {
401
+ messageId: response.data?.message_id ?? "unknown",
402
+ chatId: receiveId,
403
+ };
404
+ }
405
+
406
+ /**
407
+ * Helper to detect file type from extension
408
+ */
409
+ export function detectFileType(
410
+ fileName: string,
411
+ ): "opus" | "mp4" | "pdf" | "doc" | "xls" | "ppt" | "stream" {
412
+ const ext = path.extname(fileName).toLowerCase();
413
+ switch (ext) {
414
+ case ".opus":
415
+ case ".ogg":
416
+ return "opus";
417
+ case ".mp4":
418
+ case ".mov":
419
+ case ".avi":
420
+ return "mp4";
421
+ case ".pdf":
422
+ return "pdf";
423
+ case ".doc":
424
+ case ".docx":
425
+ return "doc";
426
+ case ".xls":
427
+ case ".xlsx":
428
+ return "xls";
429
+ case ".ppt":
430
+ case ".pptx":
431
+ return "ppt";
432
+ default:
433
+ return "stream";
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Check if a string is a local file path (not a URL)
439
+ */
440
+ function isLocalPath(urlOrPath: string): boolean {
441
+ // Starts with / or ~ or drive letter (Windows)
442
+ if (urlOrPath.startsWith("/") || urlOrPath.startsWith("~") || /^[a-zA-Z]:/.test(urlOrPath)) {
443
+ return true;
444
+ }
445
+ // Try to parse as URL - if it fails or has no protocol, it's likely a local path
446
+ try {
447
+ const url = new URL(urlOrPath);
448
+ return url.protocol === "file:";
449
+ } catch {
450
+ return true; // Not a valid URL, treat as local path
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Upload and send media (image or file) from URL, local path, or buffer
456
+ */
457
+ export async function sendMediaFeishu(params: {
458
+ cfg: ClawdbotConfig;
459
+ to: string;
460
+ mediaUrl?: string;
461
+ mediaBuffer?: Buffer;
462
+ fileName?: string;
463
+ replyToMessageId?: string;
464
+ }): Promise<SendMediaResult> {
465
+ const { cfg, to, mediaUrl, mediaBuffer, fileName, replyToMessageId } = params;
466
+
467
+ let buffer: Buffer;
468
+ let name: string;
469
+
470
+ if (mediaBuffer) {
471
+ buffer = mediaBuffer;
472
+ name = fileName ?? "file";
473
+ } else if (mediaUrl) {
474
+ if (isLocalPath(mediaUrl)) {
475
+ // Local file path - read directly
476
+ const filePath = mediaUrl.startsWith("~")
477
+ ? mediaUrl.replace("~", process.env.HOME ?? "")
478
+ : mediaUrl.replace("file://", "");
479
+
480
+ if (!fs.existsSync(filePath)) {
481
+ throw new Error(`Local file not found: ${filePath}`);
482
+ }
483
+ buffer = fs.readFileSync(filePath);
484
+ name = fileName ?? path.basename(filePath);
485
+ } else {
486
+ // Remote URL - fetch
487
+ const response = await fetch(mediaUrl);
488
+ if (!response.ok) {
489
+ throw new Error(`Failed to fetch media from URL: ${response.status}`);
490
+ }
491
+ buffer = Buffer.from(await response.arrayBuffer());
492
+ name = fileName ?? (path.basename(new URL(mediaUrl).pathname) || "file");
493
+ }
494
+ } else {
495
+ throw new Error("Either mediaUrl or mediaBuffer must be provided");
496
+ }
497
+
498
+ // Determine if it's an image based on extension
499
+ const ext = path.extname(name).toLowerCase();
500
+ const isImage = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".ico", ".tiff"].includes(ext);
501
+
502
+ if (isImage) {
503
+ const { imageKey } = await uploadImageFeishu({ cfg, image: buffer });
504
+ return sendImageFeishu({ cfg, to, imageKey, replyToMessageId });
505
+ } else {
506
+ const fileType = detectFileType(name);
507
+ const { fileKey } = await uploadFileFeishu({
508
+ cfg,
509
+ file: buffer,
510
+ fileName: name,
511
+ fileType,
512
+ });
513
+ return sendFileFeishu({ cfg, to, fileKey, replyToMessageId });
514
+ }
515
+ }
package/src/mention.ts ADDED
@@ -0,0 +1,121 @@
1
+ import type { FeishuMessageEvent } from "./bot.js";
2
+
3
+ /**
4
+ * Mention target user info
5
+ */
6
+ export type MentionTarget = {
7
+ openId: string;
8
+ name: string;
9
+ key: string; // Placeholder in original message, e.g. @_user_1
10
+ };
11
+
12
+ /**
13
+ * Extract mention targets from message event (excluding the bot itself)
14
+ */
15
+ export function extractMentionTargets(
16
+ event: FeishuMessageEvent,
17
+ botOpenId?: string,
18
+ ): MentionTarget[] {
19
+ const mentions = event.message.mentions ?? [];
20
+
21
+ return mentions
22
+ .filter((m) => {
23
+ // Exclude the bot itself
24
+ if (botOpenId && m.id.open_id === botOpenId) return false;
25
+ // Must have open_id
26
+ return !!m.id.open_id;
27
+ })
28
+ .map((m) => ({
29
+ openId: m.id.open_id!,
30
+ name: m.name,
31
+ key: m.key,
32
+ }));
33
+ }
34
+
35
+ /**
36
+ * Check if message is a mention forward request
37
+ * Rules:
38
+ * - Group: message mentions bot + at least one other user
39
+ * - DM: message mentions any user (no need to mention bot)
40
+ */
41
+ export function isMentionForwardRequest(
42
+ event: FeishuMessageEvent,
43
+ botOpenId?: string,
44
+ ): boolean {
45
+ const mentions = event.message.mentions ?? [];
46
+ if (mentions.length === 0) return false;
47
+
48
+ const isDirectMessage = event.message.chat_type === "p2p";
49
+ const hasOtherMention = mentions.some((m) => m.id.open_id !== botOpenId);
50
+
51
+ if (isDirectMessage) {
52
+ // DM: trigger if any non-bot user is mentioned
53
+ return hasOtherMention;
54
+ } else {
55
+ // Group: need to mention both bot and other users
56
+ const hasBotMention = mentions.some((m) => m.id.open_id === botOpenId);
57
+ return hasBotMention && hasOtherMention;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Extract message body from text (remove @ placeholders)
63
+ */
64
+ export function extractMessageBody(text: string, allMentionKeys: string[]): string {
65
+ let result = text;
66
+
67
+ // Remove all @ placeholders
68
+ for (const key of allMentionKeys) {
69
+ result = result.replace(new RegExp(key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), "");
70
+ }
71
+
72
+ return result.replace(/\s+/g, " ").trim();
73
+ }
74
+
75
+ /**
76
+ * Format @mention for text message
77
+ */
78
+ export function formatMentionForText(target: MentionTarget): string {
79
+ return `<at user_id="${target.openId}">${target.name}</at>`;
80
+ }
81
+
82
+ /**
83
+ * Format @everyone for text message
84
+ */
85
+ export function formatMentionAllForText(): string {
86
+ return `<at user_id="all">Everyone</at>`;
87
+ }
88
+
89
+ /**
90
+ * Format @mention for card message (lark_md)
91
+ */
92
+ export function formatMentionForCard(target: MentionTarget): string {
93
+ return `<at id=${target.openId}></at>`;
94
+ }
95
+
96
+ /**
97
+ * Format @everyone for card message
98
+ */
99
+ export function formatMentionAllForCard(): string {
100
+ return `<at id=all></at>`;
101
+ }
102
+
103
+ /**
104
+ * Build complete message with @mentions (text format)
105
+ */
106
+ export function buildMentionedMessage(targets: MentionTarget[], message: string): string {
107
+ if (targets.length === 0) return message;
108
+
109
+ const mentionParts = targets.map((t) => formatMentionForText(t));
110
+ return `${mentionParts.join(" ")} ${message}`;
111
+ }
112
+
113
+ /**
114
+ * Build card content with @mentions (Markdown format)
115
+ */
116
+ export function buildMentionedCardContent(targets: MentionTarget[], message: string): string {
117
+ if (targets.length === 0) return message;
118
+
119
+ const mentionParts = targets.map((t) => formatMentionForCard(t));
120
+ return `${mentionParts.join(" ")} ${message}`;
121
+ }