@bobotu/feishu-fork 0.1.0

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 (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +922 -0
  3. package/index.ts +65 -0
  4. package/openclaw.plugin.json +10 -0
  5. package/package.json +72 -0
  6. package/skills/feishu-doc/SKILL.md +161 -0
  7. package/skills/feishu-doc/references/block-types.md +102 -0
  8. package/skills/feishu-drive/SKILL.md +96 -0
  9. package/skills/feishu-perm/SKILL.md +90 -0
  10. package/skills/feishu-task/SKILL.md +210 -0
  11. package/skills/feishu-wiki/SKILL.md +96 -0
  12. package/src/accounts.ts +140 -0
  13. package/src/bitable-tools/actions.ts +199 -0
  14. package/src/bitable-tools/common.ts +90 -0
  15. package/src/bitable-tools/index.ts +1 -0
  16. package/src/bitable-tools/meta.ts +80 -0
  17. package/src/bitable-tools/register.ts +195 -0
  18. package/src/bitable-tools/schemas.ts +221 -0
  19. package/src/bot.ts +1125 -0
  20. package/src/channel.ts +334 -0
  21. package/src/client.ts +114 -0
  22. package/src/config-schema.ts +237 -0
  23. package/src/dedup.ts +54 -0
  24. package/src/directory.ts +165 -0
  25. package/src/doc-tools/actions.ts +341 -0
  26. package/src/doc-tools/common.ts +33 -0
  27. package/src/doc-tools/index.ts +2 -0
  28. package/src/doc-tools/register.ts +90 -0
  29. package/src/doc-tools/schemas.ts +85 -0
  30. package/src/doc-write-service.ts +711 -0
  31. package/src/drive-tools/actions.ts +182 -0
  32. package/src/drive-tools/common.ts +18 -0
  33. package/src/drive-tools/index.ts +2 -0
  34. package/src/drive-tools/register.ts +71 -0
  35. package/src/drive-tools/schemas.ts +67 -0
  36. package/src/dynamic-agent.ts +135 -0
  37. package/src/external-keys.ts +19 -0
  38. package/src/media.ts +510 -0
  39. package/src/mention.ts +121 -0
  40. package/src/monitor.ts +323 -0
  41. package/src/onboarding.ts +449 -0
  42. package/src/outbound.ts +40 -0
  43. package/src/perm-tools/actions.ts +111 -0
  44. package/src/perm-tools/common.ts +18 -0
  45. package/src/perm-tools/index.ts +2 -0
  46. package/src/perm-tools/register.ts +65 -0
  47. package/src/perm-tools/schemas.ts +52 -0
  48. package/src/policy.ts +117 -0
  49. package/src/probe.ts +147 -0
  50. package/src/reactions.ts +160 -0
  51. package/src/reply-dispatcher.ts +240 -0
  52. package/src/runtime.ts +14 -0
  53. package/src/send.ts +391 -0
  54. package/src/streaming-card.ts +211 -0
  55. package/src/targets.ts +58 -0
  56. package/src/task-tools/actions.ts +590 -0
  57. package/src/task-tools/common.ts +18 -0
  58. package/src/task-tools/constants.ts +13 -0
  59. package/src/task-tools/index.ts +1 -0
  60. package/src/task-tools/register.ts +263 -0
  61. package/src/task-tools/schemas.ts +567 -0
  62. package/src/text/markdown-links.ts +104 -0
  63. package/src/tools-common/feishu-api.ts +184 -0
  64. package/src/tools-common/tool-context.ts +23 -0
  65. package/src/tools-common/tool-exec.ts +73 -0
  66. package/src/tools-config.ts +22 -0
  67. package/src/types.ts +79 -0
  68. package/src/typing.ts +75 -0
  69. package/src/wiki-tools/actions.ts +166 -0
  70. package/src/wiki-tools/common.ts +18 -0
  71. package/src/wiki-tools/index.ts +2 -0
  72. package/src/wiki-tools/register.ts +66 -0
  73. package/src/wiki-tools/schemas.ts +55 -0
package/src/media.ts ADDED
@@ -0,0 +1,510 @@
1
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk";
2
+ import { createFeishuClient } from "./client.js";
3
+ import { resolveFeishuAccount } from "./accounts.js";
4
+ import { getFeishuRuntime } from "./runtime.js";
5
+ import { resolveReceiveIdType, normalizeFeishuTarget } from "./targets.js";
6
+ import fs from "fs";
7
+ import path from "path";
8
+ import os from "os";
9
+ import { Readable } from "stream";
10
+
11
+ export type DownloadImageResult = {
12
+ buffer: Buffer;
13
+ contentType?: string;
14
+ };
15
+
16
+ export type DownloadMessageResourceResult = {
17
+ buffer: Buffer;
18
+ contentType?: string;
19
+ fileName?: string;
20
+ };
21
+
22
+ /**
23
+ * Download an image from Feishu using image_key.
24
+ * Used for downloading images sent in messages.
25
+ */
26
+ export async function downloadImageFeishu(params: {
27
+ cfg: ClawdbotConfig;
28
+ imageKey: string;
29
+ accountId?: string;
30
+ }): Promise<DownloadImageResult> {
31
+ const { cfg, imageKey, accountId } = params;
32
+ const account = resolveFeishuAccount({ cfg, accountId });
33
+ if (!account.configured) {
34
+ throw new Error(`Feishu account "${account.accountId}" not configured`);
35
+ }
36
+
37
+ const client = createFeishuClient(account);
38
+
39
+ const response = await client.im.image.get({
40
+ path: { image_key: imageKey },
41
+ });
42
+
43
+ const responseAny = response as any;
44
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
45
+ throw new Error(`Feishu image download failed: ${responseAny.msg || `code ${responseAny.code}`}`);
46
+ }
47
+
48
+ // Handle various response formats from Feishu SDK
49
+ let buffer: Buffer;
50
+
51
+ if (Buffer.isBuffer(response)) {
52
+ buffer = response;
53
+ } else if (response instanceof ArrayBuffer) {
54
+ buffer = Buffer.from(response);
55
+ } else if (responseAny.data && Buffer.isBuffer(responseAny.data)) {
56
+ buffer = responseAny.data;
57
+ } else if (responseAny.data instanceof ArrayBuffer) {
58
+ buffer = Buffer.from(responseAny.data);
59
+ } else if (typeof responseAny.getReadableStream === "function") {
60
+ // SDK provides getReadableStream method
61
+ const stream = responseAny.getReadableStream();
62
+ const chunks: Buffer[] = [];
63
+ for await (const chunk of stream) {
64
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
65
+ }
66
+ buffer = Buffer.concat(chunks);
67
+ } else if (typeof responseAny.writeFile === "function") {
68
+ // SDK provides writeFile method - use a temp file
69
+ const tmpPath = path.join(os.tmpdir(), `feishu_img_${Date.now()}_${imageKey}`);
70
+ await responseAny.writeFile(tmpPath);
71
+ buffer = await fs.promises.readFile(tmpPath);
72
+ await fs.promises.unlink(tmpPath).catch(() => {}); // cleanup
73
+ } else if (typeof responseAny[Symbol.asyncIterator] === "function") {
74
+ // Response is an async iterable
75
+ const chunks: Buffer[] = [];
76
+ for await (const chunk of responseAny) {
77
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
78
+ }
79
+ buffer = Buffer.concat(chunks);
80
+ } else if (typeof responseAny.read === "function") {
81
+ // Response is a Readable stream
82
+ const chunks: Buffer[] = [];
83
+ for await (const chunk of responseAny as Readable) {
84
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
85
+ }
86
+ buffer = Buffer.concat(chunks);
87
+ } else {
88
+ // Debug: log what we actually received
89
+ const keys = Object.keys(responseAny);
90
+ const types = keys.map(k => `${k}: ${typeof responseAny[k]}`).join(", ");
91
+ throw new Error(
92
+ `Feishu image download failed: unexpected response format. Keys: [${types}]`,
93
+ );
94
+ }
95
+
96
+ return { buffer };
97
+ }
98
+
99
+ /**
100
+ * Download a message resource (file/image/audio/video) from Feishu.
101
+ * Used for downloading files, audio, and video from messages.
102
+ */
103
+ export async function downloadMessageResourceFeishu(params: {
104
+ cfg: ClawdbotConfig;
105
+ messageId: string;
106
+ fileKey: string;
107
+ type: "image" | "file";
108
+ accountId?: string;
109
+ }): Promise<DownloadMessageResourceResult> {
110
+ const { cfg, messageId, fileKey, type, accountId } = params;
111
+ const account = resolveFeishuAccount({ cfg, accountId });
112
+ if (!account.configured) {
113
+ throw new Error(`Feishu account "${account.accountId}" not configured`);
114
+ }
115
+
116
+ const client = createFeishuClient(account);
117
+
118
+ const response = await client.im.messageResource.get({
119
+ path: { message_id: messageId, file_key: fileKey },
120
+ params: { type },
121
+ });
122
+
123
+ const responseAny = response as any;
124
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
125
+ throw new Error(
126
+ `Feishu message resource download failed: ${responseAny.msg || `code ${responseAny.code}`}`,
127
+ );
128
+ }
129
+
130
+ // Handle various response formats from Feishu SDK
131
+ let buffer: Buffer;
132
+
133
+ if (Buffer.isBuffer(response)) {
134
+ buffer = response;
135
+ } else if (response instanceof ArrayBuffer) {
136
+ buffer = Buffer.from(response);
137
+ } else if (responseAny.data && Buffer.isBuffer(responseAny.data)) {
138
+ buffer = responseAny.data;
139
+ } else if (responseAny.data instanceof ArrayBuffer) {
140
+ buffer = Buffer.from(responseAny.data);
141
+ } else if (typeof responseAny.getReadableStream === "function") {
142
+ // SDK provides getReadableStream method
143
+ const stream = responseAny.getReadableStream();
144
+ const chunks: Buffer[] = [];
145
+ for await (const chunk of stream) {
146
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
147
+ }
148
+ buffer = Buffer.concat(chunks);
149
+ } else if (typeof responseAny.writeFile === "function") {
150
+ // SDK provides writeFile method - use a temp file
151
+ const tmpPath = path.join(os.tmpdir(), `feishu_${Date.now()}_${fileKey}`);
152
+ await responseAny.writeFile(tmpPath);
153
+ buffer = await fs.promises.readFile(tmpPath);
154
+ await fs.promises.unlink(tmpPath).catch(() => {}); // cleanup
155
+ } else if (typeof responseAny[Symbol.asyncIterator] === "function") {
156
+ // Response is an async iterable
157
+ const chunks: Buffer[] = [];
158
+ for await (const chunk of responseAny) {
159
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
160
+ }
161
+ buffer = Buffer.concat(chunks);
162
+ } else if (typeof responseAny.read === "function") {
163
+ // Response is a Readable stream
164
+ const chunks: Buffer[] = [];
165
+ for await (const chunk of responseAny as Readable) {
166
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
167
+ }
168
+ buffer = Buffer.concat(chunks);
169
+ } else {
170
+ // Debug: log what we actually received
171
+ const keys = Object.keys(responseAny);
172
+ const types = keys.map(k => `${k}: ${typeof responseAny[k]}`).join(", ");
173
+ throw new Error(
174
+ `Feishu message resource download failed: unexpected response format. Keys: [${types}]`,
175
+ );
176
+ }
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 account = resolveFeishuAccount({ cfg, accountId });
206
+ if (!account.configured) {
207
+ throw new Error(`Feishu account "${account.accountId}" not configured`);
208
+ }
209
+
210
+ const client = createFeishuClient(account);
211
+
212
+ // SDK expects a Readable stream, not a Buffer
213
+ // Use type assertion since SDK actually accepts any Readable at runtime
214
+ const imageStream =
215
+ typeof image === "string" ? fs.createReadStream(image) : Readable.from(image);
216
+
217
+ const response = await client.im.image.create({
218
+ data: {
219
+ image_type: imageType,
220
+ image: imageStream as any,
221
+ },
222
+ });
223
+
224
+ // SDK v1.30+ returns data directly without code wrapper on success
225
+ // On error, it throws or returns { code, msg }
226
+ const responseAny = response as any;
227
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
228
+ throw new Error(`Feishu image upload failed: ${responseAny.msg || `code ${responseAny.code}`}`);
229
+ }
230
+
231
+ const imageKey = responseAny.image_key ?? responseAny.data?.image_key;
232
+ if (!imageKey) {
233
+ throw new Error("Feishu image upload failed: no image_key returned");
234
+ }
235
+
236
+ return { imageKey };
237
+ }
238
+
239
+ /**
240
+ * Upload a file to Feishu and get a file_key for sending.
241
+ * Max file size: 30MB
242
+ */
243
+ export async function uploadFileFeishu(params: {
244
+ cfg: ClawdbotConfig;
245
+ file: Buffer | string; // Buffer or file path
246
+ fileName: string;
247
+ fileType: "opus" | "mp4" | "pdf" | "doc" | "xls" | "ppt" | "stream";
248
+ duration?: number; // Required for audio/video files, in milliseconds
249
+ accountId?: string;
250
+ }): Promise<UploadFileResult> {
251
+ const { cfg, file, fileName, fileType, duration, accountId } = params;
252
+ const account = resolveFeishuAccount({ cfg, accountId });
253
+ if (!account.configured) {
254
+ throw new Error(`Feishu account "${account.accountId}" not configured`);
255
+ }
256
+
257
+ const client = createFeishuClient(account);
258
+
259
+ // SDK expects a Readable stream, not a Buffer
260
+ // Use type assertion since SDK actually accepts any Readable at runtime
261
+ const fileStream =
262
+ typeof file === "string" ? fs.createReadStream(file) : Readable.from(file);
263
+
264
+ const response = await client.im.file.create({
265
+ data: {
266
+ file_type: fileType,
267
+ file_name: fileName,
268
+ file: fileStream as any,
269
+ ...(duration !== undefined && { duration }),
270
+ },
271
+ });
272
+
273
+ // SDK v1.30+ returns data directly without code wrapper on success
274
+ const responseAny = response as any;
275
+ if (responseAny.code !== undefined && responseAny.code !== 0) {
276
+ throw new Error(`Feishu file upload failed: ${responseAny.msg || `code ${responseAny.code}`}`);
277
+ }
278
+
279
+ const fileKey = responseAny.file_key ?? responseAny.data?.file_key;
280
+ if (!fileKey) {
281
+ throw new Error("Feishu file upload failed: no file_key returned");
282
+ }
283
+
284
+ return { fileKey };
285
+ }
286
+
287
+ /**
288
+ * Send an image message using an image_key
289
+ */
290
+ export async function sendImageFeishu(params: {
291
+ cfg: ClawdbotConfig;
292
+ to: string;
293
+ imageKey: string;
294
+ replyToMessageId?: string;
295
+ accountId?: string;
296
+ }): Promise<SendMediaResult> {
297
+ const { cfg, to, imageKey, replyToMessageId, accountId } = params;
298
+ const account = resolveFeishuAccount({ cfg, accountId });
299
+ if (!account.configured) {
300
+ throw new Error(`Feishu account "${account.accountId}" not configured`);
301
+ }
302
+
303
+ const client = createFeishuClient(account);
304
+ const receiveId = normalizeFeishuTarget(to);
305
+ if (!receiveId) {
306
+ throw new Error(`Invalid Feishu target: ${to}`);
307
+ }
308
+
309
+ const receiveIdType = resolveReceiveIdType(receiveId);
310
+ const content = JSON.stringify({ image_key: imageKey });
311
+
312
+ if (replyToMessageId) {
313
+ const response = await client.im.message.reply({
314
+ path: { message_id: replyToMessageId },
315
+ data: {
316
+ content,
317
+ msg_type: "image",
318
+ },
319
+ });
320
+
321
+ if (response.code !== 0) {
322
+ throw new Error(`Feishu image reply failed: ${response.msg || `code ${response.code}`}`);
323
+ }
324
+
325
+ return {
326
+ messageId: response.data?.message_id ?? "unknown",
327
+ chatId: receiveId,
328
+ };
329
+ }
330
+
331
+ const response = await client.im.message.create({
332
+ params: { receive_id_type: receiveIdType },
333
+ data: {
334
+ receive_id: receiveId,
335
+ content,
336
+ msg_type: "image",
337
+ },
338
+ });
339
+
340
+ if (response.code !== 0) {
341
+ throw new Error(`Feishu image send failed: ${response.msg || `code ${response.code}`}`);
342
+ }
343
+
344
+ return {
345
+ messageId: response.data?.message_id ?? "unknown",
346
+ chatId: receiveId,
347
+ };
348
+ }
349
+
350
+ /**
351
+ * Send a file message using a file_key
352
+ */
353
+ export async function sendFileFeishu(params: {
354
+ cfg: ClawdbotConfig;
355
+ to: string;
356
+ fileKey: string;
357
+ /** Use "audio" for audio, "media" for video, "file" for documents */
358
+ msgType?: "file" | "audio" | "media";
359
+ replyToMessageId?: string;
360
+ accountId?: string;
361
+ }): Promise<SendMediaResult> {
362
+ const { cfg, to, fileKey, replyToMessageId, accountId } = params;
363
+ const msgType = params.msgType ?? "file";
364
+ const account = resolveFeishuAccount({ cfg, accountId });
365
+ if (!account.configured) {
366
+ throw new Error(`Feishu account "${account.accountId}" not configured`);
367
+ }
368
+
369
+ const client = createFeishuClient(account);
370
+ const receiveId = normalizeFeishuTarget(to);
371
+ if (!receiveId) {
372
+ throw new Error(`Invalid Feishu target: ${to}`);
373
+ }
374
+
375
+ const receiveIdType = resolveReceiveIdType(receiveId);
376
+ const content = JSON.stringify({ file_key: fileKey });
377
+
378
+ if (replyToMessageId) {
379
+ const response = await client.im.message.reply({
380
+ path: { message_id: replyToMessageId },
381
+ data: {
382
+ content,
383
+ msg_type: msgType,
384
+ },
385
+ });
386
+
387
+ if (response.code !== 0) {
388
+ throw new Error(`Feishu file reply failed: ${response.msg || `code ${response.code}`}`);
389
+ }
390
+
391
+ return {
392
+ messageId: response.data?.message_id ?? "unknown",
393
+ chatId: receiveId,
394
+ };
395
+ }
396
+
397
+ const response = await client.im.message.create({
398
+ params: { receive_id_type: receiveIdType },
399
+ data: {
400
+ receive_id: receiveId,
401
+ content,
402
+ msg_type: msgType,
403
+ },
404
+ });
405
+
406
+ if (response.code !== 0) {
407
+ throw new Error(`Feishu file send failed: ${response.msg || `code ${response.code}`}`);
408
+ }
409
+
410
+ return {
411
+ messageId: response.data?.message_id ?? "unknown",
412
+ chatId: receiveId,
413
+ };
414
+ }
415
+
416
+ /**
417
+ * Helper to detect file type from extension
418
+ */
419
+ export function detectFileType(
420
+ fileName: string,
421
+ ): "opus" | "mp4" | "pdf" | "doc" | "xls" | "ppt" | "stream" {
422
+ const ext = path.extname(fileName).toLowerCase();
423
+ switch (ext) {
424
+ case ".opus":
425
+ case ".ogg":
426
+ return "opus";
427
+ case ".mp4":
428
+ case ".mov":
429
+ case ".avi":
430
+ return "mp4";
431
+ case ".pdf":
432
+ return "pdf";
433
+ case ".doc":
434
+ case ".docx":
435
+ return "doc";
436
+ case ".xls":
437
+ case ".xlsx":
438
+ return "xls";
439
+ case ".ppt":
440
+ case ".pptx":
441
+ return "ppt";
442
+ default:
443
+ return "stream";
444
+ }
445
+ }
446
+
447
+ /**
448
+ * Upload and send media (image or file) from URL, local path, or buffer
449
+ */
450
+ export async function sendMediaFeishu(params: {
451
+ cfg: ClawdbotConfig;
452
+ to: string;
453
+ mediaUrl?: string;
454
+ mediaBuffer?: Buffer;
455
+ fileName?: string;
456
+ replyToMessageId?: string;
457
+ accountId?: string;
458
+ }): Promise<SendMediaResult> {
459
+ const { cfg, to, mediaUrl, mediaBuffer, fileName, replyToMessageId, accountId } = params;
460
+ const account = resolveFeishuAccount({ cfg, accountId });
461
+ if (!account.configured) {
462
+ throw new Error(`Feishu account "${account.accountId}" not configured`);
463
+ }
464
+ const mediaMaxBytes = (account.config?.mediaMaxMb ?? 30) * 1024 * 1024;
465
+
466
+ let buffer: Buffer;
467
+ let name: string;
468
+
469
+ if (mediaBuffer) {
470
+ buffer = mediaBuffer;
471
+ name = fileName ?? "file";
472
+ } else if (mediaUrl) {
473
+ const loaded = await getFeishuRuntime().media.loadWebMedia(mediaUrl, {
474
+ maxBytes: mediaMaxBytes,
475
+ optimizeImages: false,
476
+ });
477
+ buffer = loaded.buffer;
478
+ name = fileName ?? loaded.fileName ?? "file";
479
+ } else {
480
+ throw new Error("Either mediaUrl or mediaBuffer must be provided");
481
+ }
482
+
483
+ // Determine if it's an image based on extension
484
+ const ext = path.extname(name).toLowerCase();
485
+ const isImage = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".ico", ".tiff"].includes(ext);
486
+
487
+ if (isImage) {
488
+ const { imageKey } = await uploadImageFeishu({ cfg, image: buffer, accountId });
489
+ return sendImageFeishu({ cfg, to, imageKey, replyToMessageId, accountId });
490
+ } else {
491
+ const fileType = detectFileType(name);
492
+ const { fileKey } = await uploadFileFeishu({
493
+ cfg,
494
+ file: buffer,
495
+ fileName: name,
496
+ fileType,
497
+ accountId,
498
+ });
499
+ // Feishu requires msg_type "audio" for audio, "media" for video, "file" for documents
500
+ const msgType = fileType === "opus" ? "audio" : fileType === "mp4" ? "media" : "file";
501
+ return sendFileFeishu({
502
+ cfg,
503
+ to,
504
+ fileKey,
505
+ msgType,
506
+ replyToMessageId,
507
+ accountId,
508
+ });
509
+ }
510
+ }
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
+ }