@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/send.ts ADDED
@@ -0,0 +1,475 @@
1
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk";
2
+ import type { FeishuConfig, FeishuSendResult } from "./types.js";
3
+ import type { MentionTarget } from "./mention.js";
4
+ import { buildMentionedMessage, buildMentionedCardContent } from "./mention.js";
5
+ import { createFeishuClient } from "./client.js";
6
+ import { resolveReceiveIdType, normalizeFeishuTarget } from "./targets.js";
7
+ import { getFeishuRuntime } from "./runtime.js";
8
+
9
+ export type FeishuMessageInfo = {
10
+ messageId: string;
11
+ chatId: string;
12
+ senderId?: string;
13
+ senderOpenId?: string;
14
+ content: string;
15
+ contentType: string;
16
+ createTime?: number;
17
+ };
18
+
19
+ /**
20
+ * Send text with streaming effect using Feishu streaming update card.
21
+ * This creates an initial card and then streams updates to it.
22
+ * Uses the official Feishu streaming update card API.
23
+ */
24
+ export async function sendStreamingMessageFeishu(params: {
25
+ cfg: ClawdbotConfig;
26
+ to: string;
27
+ text: string;
28
+ /** Mention target users */
29
+ mentions?: MentionTarget[];
30
+ }): Promise<FeishuSendResult> {
31
+ const { cfg, to, text, mentions } = params;
32
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
33
+ if (!feishuCfg) {
34
+ throw new Error("Feishu channel not configured");
35
+ }
36
+
37
+ const client = createFeishuClient(feishuCfg);
38
+ const receiveId = normalizeFeishuTarget(to);
39
+ if (!receiveId) {
40
+ throw new Error(`Invalid Feishu target: ${to}`);
41
+ }
42
+
43
+ const receiveIdType = resolveReceiveIdType(receiveId);
44
+ const tableMode = getFeishuRuntime().channel.text.resolveMarkdownTableMode({
45
+ cfg,
46
+ channel: "feishu",
47
+ });
48
+
49
+ // Build message content (with @mention support)
50
+ let rawText = text ?? "";
51
+ if (mentions && mentions.length > 0) {
52
+ rawText = buildMentionedCardContent(mentions, rawText);
53
+ }
54
+ const messageText = getFeishuRuntime().channel.text.convertMarkdownTables(rawText, tableMode);
55
+
56
+ // Build initial card with streaming_update header for proper streaming behavior
57
+ const initialCard = {
58
+ header: {
59
+ title: {
60
+ tag: "plain_text",
61
+ content: "AI 回复",
62
+ },
63
+ },
64
+ config: {
65
+ wide_screen_mode: true,
66
+ streaming_update: true, // Enable streaming update mode
67
+ },
68
+ elements: [
69
+ {
70
+ tag: "markdown",
71
+ content: "",
72
+ },
73
+ ],
74
+ };
75
+
76
+ const content = JSON.stringify(initialCard);
77
+
78
+ // Create initial card with empty content
79
+ const response = await client.im.message.create({
80
+ params: { receive_id_type: receiveIdType },
81
+ data: {
82
+ receive_id: receiveId,
83
+ content,
84
+ msg_type: "interactive",
85
+ },
86
+ });
87
+
88
+ if (response.code !== 0) {
89
+ throw new Error(`Feishu streaming card creation failed: ${response.msg || `code ${response.code}`}`);
90
+ }
91
+
92
+ const messageId = response.data?.message_id ?? "unknown";
93
+
94
+ // Extract card_id from response if available
95
+ const cardData = response.data as Record<string, unknown> | undefined;
96
+ const cardId = cardData?.card_id as string | undefined;
97
+
98
+ if (!cardId) {
99
+ console.warn('No card_id returned, falling back to regular card send');
100
+ // Fallback: send as regular card if no card_id
101
+ const fallbackCard = buildMarkdownCard(messageText);
102
+ return sendCardFeishu({ cfg, to, card: fallbackCard });
103
+ }
104
+
105
+ // Stream the content updates using card_id
106
+ // Split content into chunks for streaming effect
107
+ const chunkSize = 300; // Smaller chunks for smoother streaming
108
+ const chunks: string[] = [];
109
+
110
+ for (let i = 0; i < messageText.length; i += chunkSize) {
111
+ chunks.push(messageText.slice(i, i + chunkSize));
112
+ }
113
+
114
+ // Send updates with small delay between each using the correct API
115
+ for (let i = 0; i < chunks.length; i++) {
116
+ const partialContent = chunks.slice(0, i + 1).join("");
117
+
118
+ const updateCard = {
119
+ header: {
120
+ title: {
121
+ tag: "plain_text",
122
+ content: "AI 回复",
123
+ },
124
+ },
125
+ config: {
126
+ wide_screen_mode: true,
127
+ streaming_update: true,
128
+ },
129
+ elements: [
130
+ {
131
+ tag: "markdown",
132
+ content: partialContent,
133
+ },
134
+ ],
135
+ };
136
+
137
+ const updateContent = JSON.stringify(updateCard);
138
+
139
+ // Use PATCH /im/message/:message_id with card_id for streaming update
140
+ // Note: This is the official streaming update method
141
+ try {
142
+ const updateResponse = await (client.im.message as Record<string, unknown>).patch?.({
143
+ path: { message_id: messageId },
144
+ data: {
145
+ msg_type: "interactive",
146
+ content: updateContent,
147
+ },
148
+ }) ?? { code: -1, msg: "API not available" };
149
+
150
+ if ((updateResponse as Record<string, unknown>).code !== 0) {
151
+ console.error(`Feishu streaming update failed: ${(updateResponse as Record<string, unknown>).msg}`);
152
+ }
153
+ } catch (err) {
154
+ console.error(`Feishu streaming update error: ${err}`);
155
+ }
156
+
157
+ // Add small delay between updates for streaming effect
158
+ if (i < chunks.length - 1) {
159
+ await new Promise((resolve) => setTimeout(resolve, 150));
160
+ }
161
+ }
162
+
163
+ return {
164
+ messageId,
165
+ chatId: receiveId,
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Get a message by its ID.
171
+ * Useful for fetching quoted/replied message content.
172
+ */
173
+ export async function getMessageFeishu(params: {
174
+ cfg: ClawdbotConfig;
175
+ messageId: string;
176
+ }): Promise<FeishuMessageInfo | null> {
177
+ const { cfg, messageId } = params;
178
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
179
+ if (!feishuCfg) {
180
+ throw new Error("Feishu channel not configured");
181
+ }
182
+
183
+ const client = createFeishuClient(feishuCfg);
184
+
185
+ try {
186
+ const response = (await client.im.message.get({
187
+ path: { message_id: messageId },
188
+ })) as {
189
+ code?: number;
190
+ msg?: string;
191
+ data?: {
192
+ items?: Array<{
193
+ message_id?: string;
194
+ chat_id?: string;
195
+ msg_type?: string;
196
+ body?: { content?: string };
197
+ sender?: {
198
+ id?: string;
199
+ id_type?: string;
200
+ sender_type?: string;
201
+ };
202
+ create_time?: string;
203
+ }>;
204
+ };
205
+ };
206
+
207
+ if (response.code !== 0) {
208
+ return null;
209
+ }
210
+
211
+ const item = response.data?.items?.[0];
212
+ if (!item) {
213
+ return null;
214
+ }
215
+
216
+ // Parse content based on message type
217
+ let content = item.body?.content ?? "";
218
+ try {
219
+ const parsed = JSON.parse(content);
220
+ if (item.msg_type === "text" && parsed.text) {
221
+ content = parsed.text;
222
+ }
223
+ } catch {
224
+ // Keep raw content if parsing fails
225
+ }
226
+
227
+ return {
228
+ messageId: item.message_id ?? messageId,
229
+ chatId: item.chat_id ?? "",
230
+ senderId: item.sender?.id,
231
+ senderOpenId: item.sender?.id_type === "open_id" ? item.sender?.id : undefined,
232
+ content,
233
+ contentType: item.msg_type ?? "text",
234
+ createTime: item.create_time ? parseInt(item.create_time, 10) : undefined,
235
+ };
236
+ } catch {
237
+ return null;
238
+ }
239
+ }
240
+
241
+ export type SendFeishuMessageParams = {
242
+ cfg: ClawdbotConfig;
243
+ to: string;
244
+ text: string;
245
+ replyToMessageId?: string;
246
+ /** Mention target users */
247
+ mentions?: MentionTarget[];
248
+ };
249
+
250
+ export async function sendMessageFeishu(params: SendFeishuMessageParams): Promise<FeishuSendResult> {
251
+ const { cfg, to, text, replyToMessageId, mentions } = params;
252
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
253
+ if (!feishuCfg) {
254
+ throw new Error("Feishu channel not configured");
255
+ }
256
+
257
+ const client = createFeishuClient(feishuCfg);
258
+ const receiveId = normalizeFeishuTarget(to);
259
+ if (!receiveId) {
260
+ throw new Error(`Invalid Feishu target: ${to}`);
261
+ }
262
+
263
+ const receiveIdType = resolveReceiveIdType(receiveId);
264
+ const tableMode = getFeishuRuntime().channel.text.resolveMarkdownTableMode({
265
+ cfg,
266
+ channel: "feishu",
267
+ });
268
+
269
+ // Build message content (with @mention support)
270
+ let rawText = text ?? "";
271
+ if (mentions && mentions.length > 0) {
272
+ rawText = buildMentionedMessage(mentions, rawText);
273
+ }
274
+ const messageText = getFeishuRuntime().channel.text.convertMarkdownTables(rawText, tableMode);
275
+
276
+ const content = JSON.stringify({ text: messageText });
277
+
278
+ if (replyToMessageId) {
279
+ const response = await client.im.message.reply({
280
+ path: { message_id: replyToMessageId },
281
+ data: {
282
+ content,
283
+ msg_type: "text",
284
+ },
285
+ });
286
+
287
+ if (response.code !== 0) {
288
+ throw new Error(`Feishu reply failed: ${response.msg || `code ${response.code}`}`);
289
+ }
290
+
291
+ return {
292
+ messageId: response.data?.message_id ?? "unknown",
293
+ chatId: receiveId,
294
+ };
295
+ }
296
+
297
+ const response = await client.im.message.create({
298
+ params: { receive_id_type: receiveIdType },
299
+ data: {
300
+ receive_id: receiveId,
301
+ content,
302
+ msg_type: "text",
303
+ },
304
+ });
305
+
306
+ if (response.code !== 0) {
307
+ throw new Error(`Feishu send failed: ${response.msg || `code ${response.code}`}`);
308
+ }
309
+
310
+ return {
311
+ messageId: response.data?.message_id ?? "unknown",
312
+ chatId: receiveId,
313
+ };
314
+ }
315
+
316
+ export type SendFeishuCardParams = {
317
+ cfg: ClawdbotConfig;
318
+ to: string;
319
+ card: Record<string, unknown>;
320
+ replyToMessageId?: string;
321
+ };
322
+
323
+ export async function sendCardFeishu(params: SendFeishuCardParams): Promise<FeishuSendResult> {
324
+ const { cfg, to, card, replyToMessageId } = params;
325
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
326
+ if (!feishuCfg) {
327
+ throw new Error("Feishu channel not configured");
328
+ }
329
+
330
+ const client = createFeishuClient(feishuCfg);
331
+ const receiveId = normalizeFeishuTarget(to);
332
+ if (!receiveId) {
333
+ throw new Error(`Invalid Feishu target: ${to}`);
334
+ }
335
+
336
+ const receiveIdType = resolveReceiveIdType(receiveId);
337
+ const content = JSON.stringify(card);
338
+
339
+ if (replyToMessageId) {
340
+ const response = await client.im.message.reply({
341
+ path: { message_id: replyToMessageId },
342
+ data: {
343
+ content,
344
+ msg_type: "interactive",
345
+ },
346
+ });
347
+
348
+ if (response.code !== 0) {
349
+ throw new Error(`Feishu card reply failed: ${response.msg || `code ${response.code}`}`);
350
+ }
351
+
352
+ return {
353
+ messageId: response.data?.message_id ?? "unknown",
354
+ chatId: receiveId,
355
+ };
356
+ }
357
+
358
+ const response = await client.im.message.create({
359
+ params: { receive_id_type: receiveIdType },
360
+ data: {
361
+ receive_id: receiveId,
362
+ content,
363
+ msg_type: "interactive",
364
+ },
365
+ });
366
+
367
+ if (response.code !== 0) {
368
+ throw new Error(`Feishu card send failed: ${response.msg || `code ${response.code}`}`);
369
+ }
370
+
371
+ return {
372
+ messageId: response.data?.message_id ?? "unknown",
373
+ chatId: receiveId,
374
+ };
375
+ }
376
+
377
+ export async function updateCardFeishu(params: {
378
+ cfg: ClawdbotConfig;
379
+ messageId: string;
380
+ card: Record<string, unknown>;
381
+ }): Promise<void> {
382
+ const { cfg, messageId, card } = params;
383
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
384
+ if (!feishuCfg) {
385
+ throw new Error("Feishu channel not configured");
386
+ }
387
+
388
+ const client = createFeishuClient(feishuCfg);
389
+ const content = JSON.stringify(card);
390
+
391
+ const response = await client.im.message.patch({
392
+ path: { message_id: messageId },
393
+ data: { content },
394
+ });
395
+
396
+ if (response.code !== 0) {
397
+ throw new Error(`Feishu card update failed: ${response.msg || `code ${response.code}`}`);
398
+ }
399
+ }
400
+
401
+ /**
402
+ * Build a Feishu interactive card with markdown content.
403
+ * Cards render markdown properly (code blocks, tables, links, etc.)
404
+ */
405
+ export function buildMarkdownCard(text: string): Record<string, unknown> {
406
+ return {
407
+ config: {
408
+ wide_screen_mode: true,
409
+ },
410
+ elements: [
411
+ {
412
+ tag: "markdown",
413
+ content: text,
414
+ },
415
+ ],
416
+ };
417
+ }
418
+
419
+ /**
420
+ * Send a message as a markdown card (interactive message).
421
+ * This renders markdown properly in Feishu (code blocks, tables, bold/italic, etc.)
422
+ */
423
+ export async function sendMarkdownCardFeishu(params: {
424
+ cfg: ClawdbotConfig;
425
+ to: string;
426
+ text: string;
427
+ replyToMessageId?: string;
428
+ /** Mention target users */
429
+ mentions?: MentionTarget[];
430
+ }): Promise<FeishuSendResult> {
431
+ const { cfg, to, text, replyToMessageId, mentions } = params;
432
+ // Build message content (with @mention support)
433
+ let cardText = text;
434
+ if (mentions && mentions.length > 0) {
435
+ cardText = buildMentionedCardContent(mentions, text);
436
+ }
437
+ const card = buildMarkdownCard(cardText);
438
+ return sendCardFeishu({ cfg, to, card, replyToMessageId });
439
+ }
440
+
441
+ /**
442
+ * Edit an existing text message.
443
+ * Note: Feishu only allows editing messages within 24 hours.
444
+ */
445
+ export async function editMessageFeishu(params: {
446
+ cfg: ClawdbotConfig;
447
+ messageId: string;
448
+ text: string;
449
+ }): Promise<void> {
450
+ const { cfg, messageId, text } = params;
451
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
452
+ if (!feishuCfg) {
453
+ throw new Error("Feishu channel not configured");
454
+ }
455
+
456
+ const client = createFeishuClient(feishuCfg);
457
+ const tableMode = getFeishuRuntime().channel.text.resolveMarkdownTableMode({
458
+ cfg,
459
+ channel: "feishu",
460
+ });
461
+ const messageText = getFeishuRuntime().channel.text.convertMarkdownTables(text ?? "", tableMode);
462
+ const content = JSON.stringify({ text: messageText });
463
+
464
+ const response = await client.im.message.update({
465
+ path: { message_id: messageId },
466
+ data: {
467
+ msg_type: "text",
468
+ content,
469
+ },
470
+ });
471
+
472
+ if (response.code !== 0) {
473
+ throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
474
+ }
475
+ }
package/src/targets.ts ADDED
@@ -0,0 +1,58 @@
1
+ import type { FeishuIdType } from "./types.js";
2
+
3
+ const CHAT_ID_PREFIX = "oc_";
4
+ const OPEN_ID_PREFIX = "ou_";
5
+ const USER_ID_REGEX = /^[a-zA-Z0-9_-]+$/;
6
+
7
+ export function detectIdType(id: string): FeishuIdType | null {
8
+ const trimmed = id.trim();
9
+ if (trimmed.startsWith(CHAT_ID_PREFIX)) return "chat_id";
10
+ if (trimmed.startsWith(OPEN_ID_PREFIX)) return "open_id";
11
+ if (USER_ID_REGEX.test(trimmed)) return "user_id";
12
+ return null;
13
+ }
14
+
15
+ export function normalizeFeishuTarget(raw: string): string | null {
16
+ const trimmed = raw.trim();
17
+ if (!trimmed) return null;
18
+
19
+ const lowered = trimmed.toLowerCase();
20
+ if (lowered.startsWith("chat:")) {
21
+ return trimmed.slice("chat:".length).trim() || null;
22
+ }
23
+ if (lowered.startsWith("user:")) {
24
+ return trimmed.slice("user:".length).trim() || null;
25
+ }
26
+ if (lowered.startsWith("open_id:")) {
27
+ return trimmed.slice("open_id:".length).trim() || null;
28
+ }
29
+
30
+ return trimmed;
31
+ }
32
+
33
+ export function formatFeishuTarget(id: string, type?: FeishuIdType): string {
34
+ const trimmed = id.trim();
35
+ if (type === "chat_id" || trimmed.startsWith(CHAT_ID_PREFIX)) {
36
+ return `chat:${trimmed}`;
37
+ }
38
+ if (type === "open_id" || trimmed.startsWith(OPEN_ID_PREFIX)) {
39
+ return `user:${trimmed}`;
40
+ }
41
+ return trimmed;
42
+ }
43
+
44
+ export function resolveReceiveIdType(id: string): "chat_id" | "open_id" | "user_id" {
45
+ const trimmed = id.trim();
46
+ if (trimmed.startsWith(CHAT_ID_PREFIX)) return "chat_id";
47
+ if (trimmed.startsWith(OPEN_ID_PREFIX)) return "open_id";
48
+ return "open_id";
49
+ }
50
+
51
+ export function looksLikeFeishuId(raw: string): boolean {
52
+ const trimmed = raw.trim();
53
+ if (!trimmed) return false;
54
+ if (/^(chat|user|open_id):/i.test(trimmed)) return true;
55
+ if (trimmed.startsWith(CHAT_ID_PREFIX)) return true;
56
+ if (trimmed.startsWith(OPEN_ID_PREFIX)) return true;
57
+ return false;
58
+ }
package/src/types.ts ADDED
@@ -0,0 +1,55 @@
1
+ import type { FeishuConfigSchema, FeishuGroupSchema, z } from "./config-schema.js";
2
+ import type { MentionTarget } from "./mention.js";
3
+
4
+ export type FeishuConfig = z.infer<typeof FeishuConfigSchema>;
5
+ export type FeishuGroupConfig = z.infer<typeof FeishuGroupSchema>;
6
+
7
+ export type FeishuDomain = "feishu" | "lark";
8
+ export type FeishuConnectionMode = "websocket" | "webhook";
9
+
10
+ export type ResolvedFeishuAccount = {
11
+ accountId: string;
12
+ enabled: boolean;
13
+ configured: boolean;
14
+ appId?: string;
15
+ domain: FeishuDomain;
16
+ };
17
+
18
+ export type FeishuIdType = "open_id" | "user_id" | "union_id" | "chat_id";
19
+
20
+ export type FeishuMessageContext = {
21
+ chatId: string;
22
+ messageId: string;
23
+ senderId: string;
24
+ senderOpenId: string;
25
+ senderName?: string;
26
+ chatType: "p2p" | "group";
27
+ mentionedBot: boolean;
28
+ rootId?: string;
29
+ parentId?: string;
30
+ content: string;
31
+ contentType: string;
32
+ /** Mention forward targets (excluding the bot itself) */
33
+ mentionTargets?: MentionTarget[];
34
+ /** Extracted message body (after removing @ placeholders) */
35
+ mentionMessageBody?: string;
36
+ };
37
+
38
+ export type FeishuSendResult = {
39
+ messageId: string;
40
+ chatId: string;
41
+ };
42
+
43
+ export type FeishuProbeResult = {
44
+ ok: boolean;
45
+ error?: string;
46
+ appId?: string;
47
+ botName?: string;
48
+ botOpenId?: string;
49
+ };
50
+
51
+ export type FeishuMediaInfo = {
52
+ path: string;
53
+ contentType?: string;
54
+ placeholder: string;
55
+ };
package/src/typing.ts ADDED
@@ -0,0 +1,73 @@
1
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk";
2
+ import type { FeishuConfig } from "./types.js";
3
+ import { createFeishuClient } from "./client.js";
4
+
5
+ // Feishu emoji types for typing indicator
6
+ // See: https://open.feishu.cn/document/server-docs/im-v1/message-reaction/emojis-introduce
7
+ // Full list: https://github.com/go-lark/lark/blob/main/emoji.go
8
+ const TYPING_EMOJI = "Typing"; // Typing indicator emoji
9
+
10
+ export type TypingIndicatorState = {
11
+ messageId: string;
12
+ reactionId: string | null;
13
+ };
14
+
15
+ /**
16
+ * Add a typing indicator (reaction) to a message
17
+ */
18
+ export async function addTypingIndicator(params: {
19
+ cfg: ClawdbotConfig;
20
+ messageId: string;
21
+ }): Promise<TypingIndicatorState> {
22
+ const { cfg, messageId } = params;
23
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
24
+ if (!feishuCfg) {
25
+ return { messageId, reactionId: null };
26
+ }
27
+
28
+ const client = createFeishuClient(feishuCfg);
29
+
30
+ try {
31
+ const response = await client.im.messageReaction.create({
32
+ path: { message_id: messageId },
33
+ data: {
34
+ reaction_type: { emoji_type: TYPING_EMOJI },
35
+ },
36
+ });
37
+
38
+ const reactionId = (response as any)?.data?.reaction_id ?? null;
39
+ return { messageId, reactionId };
40
+ } catch (err) {
41
+ // Silently fail - typing indicator is not critical
42
+ console.log(`[feishu] failed to add typing indicator: ${err}`);
43
+ return { messageId, reactionId: null };
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Remove a typing indicator (reaction) from a message
49
+ */
50
+ export async function removeTypingIndicator(params: {
51
+ cfg: ClawdbotConfig;
52
+ state: TypingIndicatorState;
53
+ }): Promise<void> {
54
+ const { cfg, state } = params;
55
+ if (!state.reactionId) return;
56
+
57
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
58
+ if (!feishuCfg) return;
59
+
60
+ const client = createFeishuClient(feishuCfg);
61
+
62
+ try {
63
+ await client.im.messageReaction.delete({
64
+ path: {
65
+ message_id: state.messageId,
66
+ reaction_id: state.reactionId,
67
+ },
68
+ });
69
+ } catch (err) {
70
+ // Silently fail - cleanup is not critical
71
+ console.log(`[feishu] failed to remove typing indicator: ${err}`);
72
+ }
73
+ }