larkmate 0.1.6 → 0.1.7

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 CHANGED
@@ -44,12 +44,12 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
44
44
  - [x] 按会话、发送者和时间范围分页导出消息到本地文件
45
45
  - [x] 读取文本、富文本及部分图片和文件元数据
46
46
  - [x] 发送文本、引用回复、@ 用户或机器人、发送文件
47
- - [ ] 全局搜索历史消息
48
- - [ ] 编辑或撤回消息
49
- - [ ] 转发或收藏消息
50
- - [ ] 发送图片消息、下载图片或附件
51
- - [ ] 给消息添加表情回应
52
- - [ ] 获取消息链接
47
+ - [x] 全局搜索消息(分页)
48
+ - [x] 编辑文本消息或撤回消息
49
+ - [x] 转发或收藏消息
50
+ - [x] 发送图片消息、下载图片或附件
51
+ - [x] 给消息添加和取消表情回应
52
+ - [x] 获取消息链接
53
53
  - 群聊
54
54
  - [x] 查询群信息和成员
55
55
  - [x] 修改群名称和介绍、解散群聊
package/bin/larkmate.js CHANGED
@@ -10,7 +10,7 @@ import { FeishuError } from '../src/errors.js';
10
10
  import { exportMessages } from '../src/export-messages.js';
11
11
 
12
12
  const program = new Command();
13
- program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.6');
13
+ program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.7');
14
14
  program.option('--credentials-file <path>', 'read LarkMate credentials.json');
15
15
  program.exitOverride();
16
16
 
@@ -36,6 +36,11 @@ program.command('status').description('Check the current user login.')
36
36
  program.command('search').description('Search users, bots and groups.')
37
37
  .requiredOption('--query <text>', 'search text')
38
38
  .action(async options => output(await (await client()).search(options.query)));
39
+ program.command('search-messages').description('Search accessible messages across conversations.')
40
+ .requiredOption('--query <text>', 'search text')
41
+ .option('--limit <number>', 'results per page, 1 to 100', '20')
42
+ .option('--cursor <cursor>', 'continue the same query from the previous page')
43
+ .action(async o => output(await (await client()).searchMessages({ query: o.query, limit: Number(o.limit), cursor: o.cursor })));
39
44
 
40
45
  program.command('chats').description('List a page of inbox chats without opening them.')
41
46
  .option('--limit <number>', 'inbox cards per page, 1 to 100', '50')
@@ -180,6 +185,49 @@ program.command('send-file').description('Upload and send a local file as the us
180
185
  .requiredOption('--chat <id>', 'numeric chat ID')
181
186
  .requiredOption('--file <path>', 'local file path')
182
187
  .action(async options => output(await (await client()).sendFile({ chatId: options.chat, path: options.file })));
188
+ program.command('send-image').description('Upload and send a local image as the user.')
189
+ .requiredOption('--chat <id>', 'numeric chat ID')
190
+ .requiredOption('--file <path>', 'local PNG, JPEG, GIF or WebP file')
191
+ .action(async o => output(await (await client()).sendImage({ chatId: o.chat, path: o.file })));
192
+
193
+ for (const [name, remove] of [['reaction-add', false], ['reaction-remove', true]]) {
194
+ program.command(name).description(remove ? 'Remove a reaction from a message.' : 'Add a reaction to a message.')
195
+ .requiredOption('--message <id>', 'numeric message ID')
196
+ .option('--emoji <name>', 'Feishu reaction name', 'DarkThumbsup')
197
+ .action(async o => output(await (await client()).reaction({ messageId: o.message, emoji: o.emoji, remove })));
198
+ }
199
+ program.command('download-file').description('Download a message file or image to a new local file.')
200
+ .requiredOption('--chat <id>', 'numeric chat ID')
201
+ .requiredOption('--message <id>', 'numeric message ID')
202
+ .requiredOption('--key <key>', 'file or image key from history')
203
+ .requiredOption('--output <path>', 'new local output file')
204
+ .action(async o => output(await (await client()).downloadFile({ chatId: o.chat, messageId: o.message, key: o.key, output: o.output })));
205
+ program.command('message-link').description('Get the native link to a message.')
206
+ .requiredOption('--chat <id>', 'numeric chat ID')
207
+ .requiredOption('--message <id>', 'numeric message ID')
208
+ .action(async o => output(await (await client()).messageLink({ chatId: o.chat, messageId: o.message })));
209
+ program.command('message-edit').description('Replace the text of your own message.')
210
+ .requiredOption('--message <id>', 'numeric message ID')
211
+ .requiredOption('--text <text>', 'replacement text')
212
+ .action(async o => output(await (await client()).editMessage({ messageId: o.message, text: o.text })));
213
+ program.command('message-forward').description('Forward one message to a chat.')
214
+ .requiredOption('--chat <id>', 'source numeric chat ID')
215
+ .requiredOption('--message <id>', 'numeric message ID')
216
+ .requiredOption('--to <id>', 'target numeric chat ID')
217
+ .action(async o => output(await (await client()).forwardMessage({ chatId: o.chat, messageId: o.message, targetChatId: o.to })));
218
+ program.command('message-recall').description('Recall a message.')
219
+ .requiredOption('--message <id>', 'numeric message ID')
220
+ .action(async o => output(await (await client()).recallMessage(o.message)));
221
+ program.command('favorite-add').description('Add a message to your favorites.')
222
+ .requiredOption('--chat <id>', 'numeric chat ID')
223
+ .requiredOption('--message <id>', 'numeric message ID')
224
+ .action(async o => output(await (await client()).favoriteMessage({ chatId: o.chat, messageId: o.message })));
225
+ program.command('favorite-remove').description('Remove an item from your favorites.')
226
+ .requiredOption('--favorite <id>', 'favorite ID returned by favorite-add')
227
+ .action(async o => output(await (await client()).removeFavorite(o.favorite)));
228
+ program.command('favorites').description('Read the first page of your favorite messages.')
229
+ .option('--limit <number>', 'maximum items, 1 to 100', '50')
230
+ .action(async o => output(await (await client()).favorites({ limit: Number(o.limit) })));
183
231
 
184
232
  program.command('group-create').description('Create a group as the user.')
185
233
  .requiredOption('--name <name>', 'group name')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "larkmate",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "A small, user-identity Feishu CLI with a modular gateway client",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
package/proto/lark.proto CHANGED
@@ -79,6 +79,11 @@ message PutMessageRequest {
79
79
  optional bool isNotified = 7;
80
80
  optional bool sendToChat = 8;
81
81
  optional int32 version = 9;
82
+ optional bool isReplyInThread = 12;
83
+ optional bool isShare = 15;
84
+ optional bytes aiInfoContext = 16;
85
+ optional bool syncToChat = 17;
86
+ optional int32 observedField20 = 20;
82
87
  }
83
88
 
84
89
  // --- Receive Messages (WebSocket push) ---
@@ -375,6 +380,7 @@ message SearchCommonRequestHeader {
375
380
  optional SearchContext searchContext = 5;
376
381
  optional string locale = 6;
377
382
  optional int32 pageSize = 11;
383
+ optional SearchStorageInfo storageInfo = 12;
378
384
 
379
385
  message SearchContext {
380
386
  optional string tagName = 1;
@@ -406,6 +412,7 @@ enum SearchEntityType {
406
412
  SEARCH_USER = 1;
407
413
  SEARCH_BOT = 2;
408
414
  SEARCH_GROUP_CHAT = 3;
415
+ SEARCH_MESSAGE = 5;
409
416
  }
410
417
 
411
418
  message UniversalSearchResponse {
@@ -414,9 +421,16 @@ message UniversalSearchResponse {
414
421
  }
415
422
 
416
423
  message SearchResponseHeader {
424
+ optional string searchSession = 1;
425
+ optional int32 sessionSeqId = 2;
417
426
  optional int32 total = 3;
418
427
  optional bool hasMore = 4;
428
+ optional string paginationToken = 5;
429
+ optional SearchStorageInfo storageInfo = 7;
430
+ optional int32 errorCode = 9;
431
+ optional bool secondaryStageSearchable = 11;
419
432
  }
433
+ message SearchStorageInfo { optional bool isNeedColdData = 1; optional int32 timeSize = 2; optional int32 timeUnit = 3; optional string timeText = 4; optional int32 hasMoreInfo = 5; }
420
434
 
421
435
  message SearchResult {
422
436
  optional string id = 1;
@@ -424,6 +438,17 @@ message SearchResult {
424
438
  optional string titleHighlighted = 3;
425
439
  optional string summaryHighlighted = 4;
426
440
  optional string avatarKey = 6;
441
+ optional SearchResultMeta meta = 7;
442
+ }
443
+ message SearchResultMeta { optional SearchMessageMeta message = 5; }
444
+ message SearchMessageMeta {
445
+ optional string messageId = 1;
446
+ optional int32 type = 2;
447
+ optional int64 createTime = 3;
448
+ optional int64 updateTime = 4;
449
+ optional int32 position = 5;
450
+ optional string chatId = 6;
451
+ optional string senderId = 8;
427
452
  }
428
453
 
429
454
  // --- User Info (cmd=5023) ---
@@ -489,8 +514,44 @@ message CompleteFileUploadRequest {
489
514
  optional string fileName = 4;
490
515
  optional string mime = 5;
491
516
  }
492
- message CompleteFileUploadResponse { optional int32 code = 1; }
517
+ message CompleteFileUploadResponse { optional int32 code = 1; optional string fileKey = 2; }
493
518
  message PutMessageResponse { optional MessageEntity message = 1; }
519
+ // User reaction operations (web gateway commands 25 and 26).
520
+ message MessageReactionRequest {
521
+ optional string messageId = 1;
522
+ optional string reactionType = 2;
523
+ optional int32 reactionStrategyVersion = 3;
524
+ }
525
+ message MessageLinkRequest {
526
+ optional uint64 chatId = 1;
527
+ optional int32 type = 2;
528
+ optional uint64 messageId = 3;
529
+ }
530
+ message MessageLinkResponse { optional string token = 1; optional string url = 2; }
531
+ message EditMessageContent { optional RichText richText = 1; optional bytes extra = 4; }
532
+ message EditMessageRequest {
533
+ optional uint64 messageId = 1;
534
+ optional string cid = 2;
535
+ optional int32 type = 3;
536
+ optional EditMessageContent content = 4;
537
+ }
538
+ message ForwardTarget { optional int32 type = 1; }
539
+ message ForwardMessageRequest {
540
+ optional string sourceChatId = 1;
541
+ optional string messageId = 2;
542
+ map<string, string> targetCids = 3;
543
+ optional int32 type = 4;
544
+ map<string, ForwardTarget> targets = 6;
545
+ optional bytes extra = 9;
546
+ }
547
+ message RecallMessageRequest { optional string messageId = 1; }
548
+ message FavoriteTarget { optional int64 id = 1; optional int32 type = 2; optional int64 chatId = 3; }
549
+ message PutFavoriteRequest { repeated FavoriteTarget favs = 1; }
550
+ message PutFavoriteResponse { repeated int64 ids = 1; }
551
+ message DeleteFavoriteRequest { repeated int64 ids = 1; }
552
+ message FavoriteObject { optional int64 id = 1; optional int64 createTime = 2; optional int32 type = 3; optional bytes content = 4; }
553
+ message PullAllFavoritesRequest { optional int64 lastId = 1; optional int32 count = 2; }
554
+ message PullAllFavoritesResponse { repeated FavoriteObject favs = 1; optional bool hasMore = 2; }
494
555
  message FileContent {
495
556
  optional string key = 1;
496
557
  optional string name = 2;
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: larkmate
3
- description: 使用 LarkMate 以当前飞书网页用户身份查询和管理会话、读取消息、发送文本或文件、操作群组,以及查询录制妙记、申请访问和导出文字记录。当用户要求使用 LarkMate 或需要这些个人飞书操作时使用;不负责飞书文档或日历。
3
+ description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、搜索与操作消息、收发文件及图片、管理群组,以及查询录制妙记、申请访问权限和导出文字记录。当用户要求使用 LarkMate 或需要执行上述个人飞书操作时使用;不负责飞书文档或日历。
4
4
  ---
5
5
 
6
6
  # LarkMate
@@ -9,10 +9,10 @@ description: 使用 LarkMate 以当前飞书网页用户身份查询和管理会
9
9
 
10
10
  根据任务读取所需参考:
11
11
 
12
- - 查找会话、阅读历史、会话状态和标签: [会话与消息](references/chats.md)。
13
- - 发送消息或文件、管理群组和成员: [发送与群组](references/writes.md)。
12
+ - 查找会话、搜索与导出消息、获取链接、下载资源,以及管理会话状态和标签: [会话与消息](references/chats.md)。
13
+ - 发送与管理消息、文件、图片、表情和收藏,管理群组及成员: [发送与群组](references/writes.md)。
14
14
  - 查找录制妙记、导出文字记录、查询或申请访问权限: [录制妙记](references/minutes.md)。
15
15
 
16
16
  命令输出 JSON:成功为 `ok: true`,失败为 `ok: false`,检查退出码和错误信息。飞书网页客户端数字 ID 与开放平台 ID 不同;按实际查询结果选定对象,名称相近时先消歧。列表和搜索有分页或扫描范围,无法读取的内容、缺失结果和权限错误应如实说明。
17
17
 
18
- `chat-open` 会打开或创建私聊,发送、群组、会话状态和妙记权限申请命令也会修改数据;按照用户的实际意图操作。写入返回 `EFFECT_UNKNOWN`、`submitted_unconfirmed` 或部分成功时,先查询实际状态,避免重复提交。不要将消息已发送当作对方已读。
18
+ `chat-open` 会打开或创建私聊;发送、修改消息、表情、收藏、群组、会话状态及妙记权限申请等命令也会修改数据,请按用户的实际意图操作。写入返回 `EFFECT_UNKNOWN`、`submitted_unconfirmed` 或部分成功时,先查询实际状态,避免重复提交。不要将消息已发送当作对方已读。
@@ -2,17 +2,24 @@
2
2
 
3
3
  ```sh
4
4
  larkmate search --query '名称或关键词'
5
+ larkmate search-messages --query '消息关键词' --limit 20
6
+ larkmate search-messages --query '消息关键词' --cursor "$NEXT_CURSOR"
5
7
  larkmate chats --limit 50
6
8
  larkmate chats --cursor "$NEXT_CURSOR"
7
9
  larkmate chats --parent "$BOX_ID"
8
10
  larkmate chat-info --chat "$CHAT_ID"
9
11
  larkmate history --chat "$CHAT_ID" --limit 50 --pages 3
12
+ larkmate message-link --chat "$CHAT_ID" --message "$MESSAGE_ID"
13
+ larkmate download-file --chat "$CHAT_ID" --message "$MESSAGE_ID" --key "$RESOURCE_KEY" --output ./attachment
14
+ larkmate favorites --limit 50
10
15
  larkmate messages-export --chat "$CHAT_ID" --output ./messages.md
11
16
  larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000000 --before 1800000000 --format jsonl --output ./messages.jsonl
12
17
  ```
13
18
 
14
19
  `chats` 默认读取收件箱的一页,不是全部历史会话。`--type`、`--state` 只过滤当前页,`--scope done` 查询已完成分组;`boxes` 用 `--parent` 单独读取,`nextCursor` 用于翻页。`history` 每页最多 100 个位置,`--pages` 最多 100 页;`--query`、`--sender`、`--after`、`--before` 只过滤已扫描的位置,不是全量搜索。`omittedPositions` 是没有返回的位置数,不是消息数;部分消息类型可能没有可解析正文。
15
20
 
21
+ `search-messages` 用于在当前用户可访问的会话范围内进行跨会话搜索,可使用 `nextCursor` 配合相同的查询条件继续翻页;具体搜索范围和结果由飞书服务决定。`message-link` 返回飞书生成的原生消息链接。`download-file` 根据 `history` 返回的资源键将文件或图片下载至新文件,不会覆盖已有文件;若下载中断,输出文件将不完整。`favorites` 用于读取收藏列表首页,其中 `hasMore` 表示可能仍有未返回的收藏。
22
+
16
23
  `messages-export` 会自动向前分页至会话最早位置,并按从新到旧的顺序输出 Markdown 或 JSON Lines。该命令支持 `--sender`、`--query`,以及以 Unix 秒为单位的 `--after` 和 `--before`;筛选范围仅限指定会话。可通过 `--max-pages` 限制页数,导出结束时需检查 `reachedBeginning`、`nextStart`、`nextLimit`、`omittedPositions` 和 `missingTimestamps`。
17
24
 
18
25
  输出文件不会覆盖已有文件;若导出中断,文件中不会包含完成统计,须视为不完整。继续导出时,请使用新的输出文件,并将 `nextStart` 和 `nextLimit` 分别传给 `--start` 和 `--limit`,以避免分页重叠。
@@ -7,9 +7,19 @@ larkmate send --chat "$CHAT_ID" --text '消息内容'
7
7
  larkmate send --chat "$CHAT_ID" --text '回复内容' --reply-to "$MESSAGE_ID"
8
8
  larkmate send --chat "$CHAT_ID" --text '@名称 消息内容' --mention "$MEMBER_ID:名称"
9
9
  larkmate send-file --chat "$CHAT_ID" --file ./report.pdf
10
+ larkmate send-image --chat "$CHAT_ID" --file ./image.png
11
+ larkmate message-edit --message "$MESSAGE_ID" --text '修改后的文本'
12
+ larkmate message-recall --message "$MESSAGE_ID"
13
+ larkmate message-forward --chat "$CHAT_ID" --message "$MESSAGE_ID" --to "$TARGET_CHAT_ID"
14
+ larkmate reaction-add --message "$MESSAGE_ID" --emoji DarkThumbsup
15
+ larkmate reaction-remove --message "$MESSAGE_ID" --emoji DarkThumbsup
16
+ larkmate favorite-add --chat "$CHAT_ID" --message "$MESSAGE_ID"
17
+ larkmate favorite-remove --favorite "$FAVORITE_ID"
10
18
  ```
11
19
 
12
- 文件须为非空普通文件且不超过 100 MiB。`accepted` 表示服务器返回消息 ID,`submitted_unconfirmed` 表示未可靠确认接收;不确定时先查历史再决定是否重试。
20
+ 文件须为非空普通文件且不超过 100 MiB。`accepted` 表示服务器返回相应 ID,`submitted_unconfirmed` 表示未可靠确认接收;不确定时先检查实际状态再决定是否重试。
21
+
22
+ 图片支持 PNG、JPEG、GIF 和 WebP 格式,大小不超过 10 MiB。`message-edit` 会以纯文本替换原消息内容,无法保留原有的富文本格式或提及。`--emoji` 需传入飞书表情名称,默认值为 `DarkThumbsup`。`favorite-add` 成功确认时会返回收藏 ID,供 `favorite-remove` 使用;该收藏 ID 也可从 `favorites` 首页获取。发送、编辑、撤回、转发、表情及收藏操作均须遵循用户的明确意图。
13
23
 
14
24
  回复已有回复时,需同时传入 `--reply-root`,其值取目标消息的 `rootId`;若目标消息是回复链的第一条,则只需传入 `--reply-to`。`history` 会返回每条消息的 `rootId` 和 `parentId`。
15
25
 
package/src/client.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { uploadFile } from './upload.js';
2
- import { FeishuError, requireNumericId, requireText } from './errors.js';
2
+ import { FeishuError, requireNumericId, requireInt64Id, requireText } from './errors.js';
3
3
  import { shortId } from './gateway.js';
4
+ import { downloadFile } from './download.js';
5
+ import { randomUUID } from 'node:crypto';
4
6
 
5
7
  function ids(values, label) {
6
8
  if (!Array.isArray(values)) throw new FeishuError('INVALID_ARGUMENT', `${label} must be a list.`);
@@ -49,6 +51,40 @@ export class LarkMateClient {
49
51
  })) };
50
52
  }
51
53
 
54
+ async searchMessages({ query, limit = 20, cursor } = {}) {
55
+ requireText(query, 'query');
56
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new FeishuError('INVALID_ARGUMENT', 'limit must be between 1 and 100.');
57
+ let state = { session: shortId(), seq: 1, token: '' };
58
+ if (cursor != null) {
59
+ try {
60
+ if (typeof cursor !== 'string' || cursor.length > 65536 || !/^[A-Za-z0-9_-]+$/.test(cursor)) throw new Error();
61
+ state = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
62
+ if (state.query !== query || typeof state.session !== 'string' || !/^[a-zA-Z0-9]{1,64}$/.test(state.session) || !Number.isSafeInteger(state.seq) || state.seq < 2 || typeof state.token !== 'string' || !state.token) throw new Error();
63
+ } catch { throw new FeishuError('INVALID_ARGUMENT', 'Invalid cursor or cursor does not match the query.'); }
64
+ }
65
+ const response = await this.gateway.call(11021, 'UniversalSearchRequest', { header: {
66
+ searchSession: state.session, sessionSeqId: state.seq, query, locale: 'zh_CN', pageSize: limit,
67
+ ...(state.token ? { paginationToken: state.token } : {}),
68
+ searchContext: { tagName: 'SEARCH_MESSAGES', entityItems: [{ type: 5 }], commonFilter: { includeOuterTenant: true }, sourceKey: 'messenger' },
69
+ } }, { operation: 'search-messages' });
70
+ let data;
71
+ try { data = this.gateway.decode('UniversalSearchResponse', response.packet.payload); }
72
+ catch { throw new FeishuError('INVALID_RESPONSE', 'The message search response was unreadable.'); }
73
+ if (data.header?.errorCode) throw new FeishuError('SEARCH_REJECTED', 'Feishu rejected the message search.', { status: data.header.errorCode });
74
+ if (!data.header || (data.header.hasMore && !data.header.paginationToken)) throw new FeishuError('INVALID_RESPONSE', 'The message search response did not include a usable cursor.');
75
+ const items = (data.results || []).filter(item => item.type === 5).map(item => {
76
+ const m = item.meta?.message;
77
+ return { id: String(item.id || ''), chatId: m?.chatId || null, senderId: m?.senderId || null,
78
+ position: m && Object.hasOwn(m, 'position') ? m.position : null,
79
+ createTime: m && Object.hasOwn(m, 'createTime') ? String(m.createTime) : null,
80
+ title: (item.titleHighlighted || '').replace(/<[^>]+>/g, ''),
81
+ snippet: (item.summaryHighlighted || '').replace(/<[^>]+>/g, '') };
82
+ });
83
+ const nextCursor = data.header.hasMore ? Buffer.from(JSON.stringify({ query, session: state.session, seq: state.seq + 1, token: data.header.paginationToken })).toString('base64url') : null;
84
+ return { items, total: Object.hasOwn(data.header, 'total') ? data.header.total : null, hasMore: !!data.header.hasMore, nextCursor,
85
+ secondaryStageSearchable: data.header.secondaryStageSearchable ?? null };
86
+ }
87
+
52
88
  async chats({ limit = 50, cursor, parent, scope = 'inbox' } = {}) {
53
89
  if (!['inbox', 'done'].includes(scope)) throw new FeishuError('INVALID_ARGUMENT', 'scope must be inbox or done.');
54
90
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new FeishuError('INVALID_ARGUMENT', 'limit must be between 1 and 100.');
@@ -247,6 +283,134 @@ export class LarkMateClient {
247
283
  return { status: id ? 'accepted' : 'submitted_unconfirmed', chatId, messageId: id, cid, requestId: response.requestId, fileName: file.name };
248
284
  }
249
285
 
286
+ async reaction({ messageId, emoji = 'DarkThumbsup', remove = false }) {
287
+ requireInt64Id(messageId, 'message ID');
288
+ if (typeof emoji !== 'string' || !/^[A-Za-z0-9_]{1,64}$/.test(emoji)) {
289
+ throw new FeishuError('INVALID_ARGUMENT', 'emoji must be a Feishu reaction name.');
290
+ }
291
+ if (typeof remove !== 'boolean') throw new FeishuError('INVALID_ARGUMENT', 'remove must be a boolean.');
292
+ const result = await this.gateway.call(remove ? 26 : 25, 'MessageReactionRequest', {
293
+ messageId, reactionType: emoji, reactionStrategyVersion: 1,
294
+ }, { version: '5.7.0', mutating: true, operation: remove ? 'remove-reaction' : 'add-reaction' });
295
+ return { status: 'submitted_unconfirmed', messageId, emoji, action: remove ? 'remove' : 'add', requestId: result.requestId };
296
+ }
297
+
298
+ async sendImage({ chatId, path }) {
299
+ requireInt64Id(chatId, 'chat ID');
300
+ requireText(path, 'image path');
301
+ const image = await uploadFile(this.gateway, path, { image: true });
302
+ const cid = shortId();
303
+ const response = await this.gateway.call(5, 'PutMessageRequest', {
304
+ type: 5, chatId, cid, isNotified: true, version: 1,
305
+ rootId: '', parentId: '', isReplyInThread: false, isShare: false, aiInfoContext: new Uint8Array(), syncToChat: false, observedField20: 0,
306
+ content: { thumbnailKey: image.key },
307
+ }, { version: '8.5.0', mutating: true, operation: 'send-image' });
308
+ let id = null;
309
+ try {
310
+ if (response.packet.payload?.length) {
311
+ const m = this.gateway.decode('PutMessageResponse', response.packet.payload).message;
312
+ if (m?.id && !String(m.id).startsWith('-') && (!m.chatId || m.chatId === chatId)) id = String(m.id);
313
+ }
314
+ } catch { /* Submission remains unconfirmed. */ }
315
+ return { status: id ? 'accepted' : 'submitted_unconfirmed', chatId, messageId: id, cid, requestId: response.requestId };
316
+ }
317
+
318
+ async downloadFile(options) { return downloadFile(this.gateway, options); }
319
+
320
+ async messageLink({ chatId, messageId }) {
321
+ requireInt64Id(chatId, 'chat ID');
322
+ requireInt64Id(messageId, 'message ID');
323
+ const response = await this.gateway.call(1150, 'MessageLinkRequest', { chatId, type: 1, messageId }, { operation: 'message-link' });
324
+ let result, url;
325
+ try {
326
+ result = this.gateway.decode('MessageLinkResponse', response.packet.payload);
327
+ url = new URL(result.url);
328
+ } catch { throw new FeishuError('INVALID_RESPONSE', 'No valid message link was returned.'); }
329
+ if (url.protocol !== 'https:' || url.hostname !== 'applink.feishu.cn' || url.pathname !== '/client/message/link/open' || !result.token || url.searchParams.get('token') !== result.token) {
330
+ throw new FeishuError('INVALID_RESPONSE', 'No valid message link was returned.');
331
+ }
332
+ return { chatId, messageId, url: url.href };
333
+ }
334
+
335
+ async editMessage({ messageId, text }) {
336
+ requireInt64Id(messageId, 'message ID');
337
+ requireText(text, 'text');
338
+ await this.gateway.authenticate();
339
+ const paragraph = '2', element = '3', cid = shortId();
340
+ const response = await this.gateway.call(900010, 'EditMessageRequest', {
341
+ messageId, cid, type: 4, content: { extra: new Uint8Array(), richText: {
342
+ elementIds: [paragraph], innerText: text, elements: { dictionary: {
343
+ [paragraph]: { tag: 3, property: new Uint8Array(), childIds: [element] },
344
+ [element]: { tag: 1, property: this.gateway.encode('TextProperty', { content: text }) },
345
+ } },
346
+ } },
347
+ }, { version: '8.5.0', mutating: true, operation: 'edit-message' });
348
+ return { status: 'submitted_unconfirmed', messageId, requestId: response.requestId };
349
+ }
350
+
351
+ async forwardMessage({ chatId, messageId, targetChatId }) {
352
+ requireInt64Id(chatId, 'source chat ID');
353
+ requireInt64Id(messageId, 'message ID');
354
+ requireInt64Id(targetChatId, 'target chat ID');
355
+ const cid = randomUUID();
356
+ const response = await this.gateway.call(51, 'ForwardMessageRequest', {
357
+ sourceChatId: chatId, messageId, targetCids: { [targetChatId]: cid }, type: 1,
358
+ targets: { [targetChatId]: { type: 1 } }, extra: new Uint8Array(),
359
+ }, { version: '8.5.0', mutating: true, operation: 'forward-message' });
360
+ return { status: 'submitted_unconfirmed', chatId, messageId, targetChatId, cid, requestId: response.requestId };
361
+ }
362
+
363
+ async recallMessage(messageId) {
364
+ requireInt64Id(messageId, 'message ID');
365
+ const response = await this.gateway.call(9, 'RecallMessageRequest', { messageId },
366
+ { version: '8.5.0', mutating: true, operation: 'recall-message' });
367
+ return { status: 'submitted_unconfirmed', messageId, requestId: response.requestId };
368
+ }
369
+
370
+ async favoriteMessage({ chatId, messageId }) {
371
+ requireInt64Id(chatId, 'chat ID');
372
+ requireInt64Id(messageId, 'message ID');
373
+ const response = await this.gateway.call(500, 'PutFavoriteRequest', { favs: [{ id: messageId, type: 1, chatId }] },
374
+ { version: '8.5.0', mutating: true, operation: 'favorite-message' });
375
+ let favoriteId = null;
376
+ try {
377
+ const ids = this.gateway.decode('PutFavoriteResponse', response.packet.payload).ids;
378
+ if (ids.length === 1 && /^\d+$/.test(String(ids[0])) && String(ids[0]) !== '0') favoriteId = String(ids[0]);
379
+ } catch { /* Submission remains unconfirmed. */ }
380
+ return { status: favoriteId ? 'accepted' : 'submitted_unconfirmed', chatId, messageId, favoriteId, requestId: response.requestId };
381
+ }
382
+
383
+ async removeFavorite(favoriteId) {
384
+ requireInt64Id(favoriteId, 'favorite ID');
385
+ const response = await this.gateway.call(502, 'DeleteFavoriteRequest', { ids: [favoriteId] },
386
+ { version: '8.5.0', mutating: true, operation: 'remove-favorite' });
387
+ return { status: 'submitted_unconfirmed', favoriteId, requestId: response.requestId };
388
+ }
389
+
390
+ async favorites({ limit = 50 } = {}) {
391
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new FeishuError('INVALID_ARGUMENT', 'limit must be between 1 and 100.');
392
+ const response = await this.gateway.call(503, 'PullAllFavoritesRequest', { lastId: '0', count: limit }, { operation: 'favorites' });
393
+ let result;
394
+ try { result = this.gateway.decode('PullAllFavoritesResponse', response.packet.payload); }
395
+ catch { throw new FeishuError('INVALID_RESPONSE', 'The favorites response was unreadable.'); }
396
+ const items = result.favs.map(fav => {
397
+ let message = null;
398
+ if (fav.type === 1 && fav.content?.length) {
399
+ try {
400
+ const m = this.gateway.decode('MessageEntity', fav.content);
401
+ let text = null;
402
+ if (m.content?.length && (m.type === 4 || m.type === 2)) {
403
+ const body = this.gateway.decode(m.type === 4 ? 'TextContent' : 'PostContent', m.content);
404
+ text = body.richText?.innerText || body.text || null;
405
+ }
406
+ message = { id: m.id || null, chatId: m.chatId || null, senderId: m.fromId || null, type: m.type, text };
407
+ } catch { /* Keep the favorite ID if its content type is not understood. */ }
408
+ }
409
+ return { id: String(fav.id), createTime: Object.hasOwn(fav, 'createTime') ? String(fav.createTime) : null, type: fav.type, message };
410
+ });
411
+ return { items, hasMore: !!result.hasMore };
412
+ }
413
+
250
414
  async send({ chatId, text, mentions = [], replyTo, replyRoot }) {
251
415
  requireNumericId(chatId, 'chat ID');
252
416
  requireText(text, 'text');
@@ -0,0 +1,37 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { FeishuError, requireInt64Id, requireText } from './errors.js';
3
+
4
+ // Uses the same message-scoped access check as the web client; never follows redirects with the Cookie.
5
+ export async function downloadFile(gateway, { chatId, messageId, key, output }) {
6
+ requireInt64Id(chatId, 'chat ID');
7
+ requireInt64Id(messageId, 'message ID');
8
+ requireText(output, 'output path');
9
+ if (typeof key !== 'string' || !/^[\w.-]{1,200}$/.test(key)) throw new FeishuError('INVALID_ARGUMENT', 'Invalid file key.');
10
+ await gateway.authenticate();
11
+ const url = new URL('/uni_api/download/file', gateway.endpoints.file);
12
+ url.searchParams.set('data', JSON.stringify({ file_key: key, src: {
13
+ scene_type: 1, entity_id: messageId, auth_file_key: '', im_ext: { chat_id: chatId }, ext: {},
14
+ }, ext: {} }));
15
+ const response = await gateway.request(url, { method: 'GET', redirect: 'manual', headers: gateway.baseHeaders() }, { operation: 'download-file' });
16
+ if (response.status !== 200) {
17
+ try { await response.body?.cancel(); } catch { /* The unexpected status is the important error. */ }
18
+ throw new FeishuError('DOWNLOAD_FAILED', 'Feishu did not return a complete file.', { httpStatus: response.status });
19
+ }
20
+ let handle;
21
+ try { handle = await open(output, 'wx', 0o600); }
22
+ catch (error) {
23
+ try { await response.body?.cancel(); } catch { /* Preserve the output error. */ }
24
+ throw new FeishuError('DOWNLOAD_WRITE_FAILED', error.code === 'EEXIST' ? 'Output file already exists; choose a new path.' : 'Could not create the output file.');
25
+ }
26
+ let bytes = 0;
27
+ try {
28
+ if (!response.body) throw new Error('empty response');
29
+ for await (const chunk of response.body) { await handle.writeFile(chunk); bytes += chunk.length; }
30
+ const length = response.headers.get('content-length');
31
+ const encoding = response.headers.get('content-encoding');
32
+ if (length && (!encoding || encoding === 'identity') && /^\d+$/.test(length) && BigInt(bytes) !== BigInt(length)) throw new Error('incomplete response');
33
+ return { output, bytes, messageId };
34
+ } catch {
35
+ throw new FeishuError('DOWNLOAD_INCOMPLETE', 'The download stopped; the output file is incomplete.', { output, bytes });
36
+ } finally { await handle.close(); }
37
+ }
package/src/errors.js CHANGED
@@ -14,6 +14,14 @@ export function requireNumericId(value, label) {
14
14
  return value;
15
15
  }
16
16
 
17
+ export function requireInt64Id(value, label) {
18
+ requireNumericId(value, label);
19
+ if (value.length > 19 || BigInt(value) < 1n || BigInt(value) > 9223372036854775807n) {
20
+ throw new FeishuError('INVALID_ARGUMENT', `${label} must be a positive 64-bit ID.`);
21
+ }
22
+ return value;
23
+ }
24
+
17
25
  export function requireText(value, label) {
18
26
  if (typeof value !== 'string' || !value.trim()) {
19
27
  throw new FeishuError('INVALID_ARGUMENT', `${label} must not be empty.`);
package/src/upload.js CHANGED
@@ -14,19 +14,31 @@ export function crc32(bytes) {
14
14
  return (crc ^ 0xffffffff) >>> 0;
15
15
  }
16
16
 
17
- export async function uploadFile(gateway, path) {
17
+ export async function uploadFile(gateway, path, { image = false } = {}) {
18
18
  let handle;
19
19
  try { handle = await open(path, 'r'); }
20
20
  catch { throw new FeishuError('FILE_UNAVAILABLE', 'Cannot open the file.'); }
21
21
  try {
22
22
  const stat = await handle.stat();
23
- if (!stat.isFile() || stat.size < 1 || stat.size > MAX_BYTES) {
24
- throw new FeishuError('FILE_INVALID', 'Use a regular, non-empty file up to 100 MiB.');
23
+ if (!stat.isFile() || stat.size < 1 || stat.size > (image ? 10 * 1024 * 1024 : MAX_BYTES)) {
24
+ throw new FeishuError('FILE_INVALID', image ? 'Use a regular, non-empty image up to 10 MiB.' : 'Use a regular, non-empty file up to 100 MiB.');
25
25
  }
26
+ let mime;
27
+ if (image) {
28
+ const header = Buffer.alloc(12);
29
+ const { bytesRead } = await handle.read(header, 0, header.length, 0);
30
+ const b = header.subarray(0, bytesRead);
31
+ if (b.length >= 8 && b.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))) mime = 'image/png';
32
+ else if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) mime = 'image/jpeg';
33
+ else if (b.length >= 6 && ['GIF87a', 'GIF89a'].includes(b.subarray(0, 6).toString('ascii'))) mime = 'image/gif';
34
+ else if (b.length >= 12 && b.subarray(0, 4).toString('ascii') === 'RIFF' && b.subarray(8, 12).toString('ascii') === 'WEBP') mime = 'image/webp';
35
+ else throw new FeishuError('FILE_INVALID', 'Image must be PNG, JPEG, GIF or WebP.');
36
+ }
37
+ const fileType = image ? 2 : 1;
26
38
  const name = basename(path);
27
39
  await gateway.authenticate();
28
40
  const created = gateway.decode('CreateFileUploadResponse', await gateway.uploadRequest('/upload/create',
29
- gateway.encode('CreateFileUploadRequest', { fileType: 1, fileName: name, fileSize: stat.size }), 'application/x-protobuf'));
41
+ gateway.encode('CreateFileUploadRequest', { fileType, fileName: name, fileSize: stat.size }), 'application/x-protobuf'));
30
42
  const key = created.uploadId;
31
43
  if (typeof key !== 'string' || !/^[\w.-]{1,200}$/.test(key)) {
32
44
  throw new FeishuError('UPLOAD_FAILED', 'File upload could not be initialized.');
@@ -53,9 +65,11 @@ export async function uploadFile(gateway, path) {
53
65
  throw new FeishuError('FILE_CHANGED', 'File changed during upload.');
54
66
  }
55
67
  const completed = gateway.decode('CompleteFileUploadResponse', await gateway.uploadRequest('/upload/complete',
56
- gateway.encode('CompleteFileUploadRequest', { uploadId: key, fileType: 1, partToCrc32: checksums, fileName: name }),
68
+ gateway.encode('CompleteFileUploadRequest', { uploadId: key, fileType, partToCrc32: checksums, fileName: name, ...(mime ? { mime } : {}) }),
57
69
  'application/x-protobuf'));
58
70
  if (completed.code !== 0) throw new FeishuError('UPLOAD_FAILED', 'File upload completion was rejected.');
59
- return { key, name, size: stat.size };
71
+ const finalKey = completed.fileKey || (image ? null : key);
72
+ if (typeof finalKey !== 'string' || !/^[\w.-]{1,200}$/.test(finalKey)) throw new FeishuError('UPLOAD_FAILED', 'File upload did not return a usable file key.');
73
+ return { key: finalKey, name, size: stat.size, ...(mime ? { mime } : {}) };
60
74
  } finally { await handle.close(); }
61
75
  }