larkmate 0.1.5 → 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 +8 -6
- package/bin/larkmate.js +72 -2
- package/package.json +1 -1
- package/proto/lark.proto +62 -1
- package/skills/larkmate/SKILL.md +4 -4
- package/skills/larkmate/references/chats.md +13 -0
- package/skills/larkmate/references/writes.md +14 -1
- package/src/client.js +171 -3
- package/src/download.js +37 -0
- package/src/errors.js +8 -0
- package/src/export-messages.js +49 -0
- package/src/upload.js +20 -6
package/README.md
CHANGED
|
@@ -41,13 +41,15 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
41
41
|
- 消息
|
|
42
42
|
- [x] 分页读取指定会话的历史消息
|
|
43
43
|
- [x] 在已扫描的历史消息中按关键词、发送者和时间筛选
|
|
44
|
+
- [x] 按会话、发送者和时间范围分页导出消息到本地文件
|
|
44
45
|
- [x] 读取文本、富文本及部分图片和文件元数据
|
|
45
|
-
- [x]
|
|
46
|
-
- [
|
|
47
|
-
- [
|
|
48
|
-
- [
|
|
49
|
-
- [
|
|
50
|
-
- [
|
|
46
|
+
- [x] 发送文本、引用回复、@ 用户或机器人、发送文件
|
|
47
|
+
- [x] 全局搜索消息(分页)
|
|
48
|
+
- [x] 编辑文本消息或撤回消息
|
|
49
|
+
- [x] 转发或收藏消息
|
|
50
|
+
- [x] 发送图片消息、下载图片或附件
|
|
51
|
+
- [x] 给消息添加和取消表情回应
|
|
52
|
+
- [x] 获取消息链接
|
|
51
53
|
- 群聊
|
|
52
54
|
- [x] 查询群信息和成员
|
|
53
55
|
- [x] 修改群名称和介绍、解散群聊
|
package/bin/larkmate.js
CHANGED
|
@@ -7,9 +7,10 @@ import { SessionControls } from '../src/session-controls.js';
|
|
|
7
7
|
import { Minutes, formatTranscript } from '../src/minutes.js';
|
|
8
8
|
import { writeFile } from 'node:fs/promises';
|
|
9
9
|
import { FeishuError } from '../src/errors.js';
|
|
10
|
+
import { exportMessages } from '../src/export-messages.js';
|
|
10
11
|
|
|
11
12
|
const program = new Command();
|
|
12
|
-
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.
|
|
13
|
+
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.7');
|
|
13
14
|
program.option('--credentials-file <path>', 'read LarkMate credentials.json');
|
|
14
15
|
program.exitOverride();
|
|
15
16
|
|
|
@@ -35,6 +36,11 @@ program.command('status').description('Check the current user login.')
|
|
|
35
36
|
program.command('search').description('Search users, bots and groups.')
|
|
36
37
|
.requiredOption('--query <text>', 'search text')
|
|
37
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 })));
|
|
38
44
|
|
|
39
45
|
program.command('chats').description('List a page of inbox chats without opening them.')
|
|
40
46
|
.option('--limit <number>', 'inbox cards per page, 1 to 100', '50')
|
|
@@ -141,23 +147,87 @@ program.command('history').description('Read a bounded page of chat messages as
|
|
|
141
147
|
...(options.start != null ? { start: Number(options.start) } : {}),
|
|
142
148
|
})));
|
|
143
149
|
|
|
150
|
+
program.command('messages-export').description('Export a conversation to a local file, paging through history.')
|
|
151
|
+
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
152
|
+
.requiredOption('--output <path>', 'new local output file')
|
|
153
|
+
.option('--format <format>', 'markdown or jsonl', 'markdown')
|
|
154
|
+
.option('--sender <id>', 'only messages from this numeric sender ID')
|
|
155
|
+
.option('--query <text>', 'only messages containing this text')
|
|
156
|
+
.option('--after <seconds>', 'inclusive Unix time in seconds')
|
|
157
|
+
.option('--before <seconds>', 'inclusive Unix time in seconds')
|
|
158
|
+
.option('--start <number>', 'first position of the initial page')
|
|
159
|
+
.option('--limit <number>', 'positions per page, 1 to 100', '100')
|
|
160
|
+
.option('--max-pages <number>', 'stop after this many pages; default scans to the beginning')
|
|
161
|
+
.action(async o => output(await exportMessages(await client(), {
|
|
162
|
+
chatId: o.chat, output: o.output, format: o.format, sender: o.sender, query: o.query, limit: Number(o.limit),
|
|
163
|
+
...(o.after != null ? { after: Number(o.after) } : {}),
|
|
164
|
+
...(o.before != null ? { before: Number(o.before) } : {}),
|
|
165
|
+
...(o.start != null ? { start: Number(o.start) } : {}),
|
|
166
|
+
...(o.maxPages != null ? { maxPages: Number(o.maxPages) } : {}),
|
|
167
|
+
})));
|
|
168
|
+
|
|
144
169
|
program.command('send').description('Send text once as the user; delivery remains unconfirmed.')
|
|
145
170
|
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
146
171
|
.requiredOption('--text <text>', 'message text')
|
|
147
172
|
.option('--mention <id:name>', 'mention a numeric user or bot ID; repeatable', collect, [])
|
|
173
|
+
.option('--reply-to <id>', 'reply to a numeric message ID')
|
|
174
|
+
.option('--reply-root <id>', 'root ID when replying to an existing reply')
|
|
148
175
|
.action(async options => {
|
|
149
176
|
const mentions = options.mention.map(value => {
|
|
150
177
|
const colon = value.indexOf(':');
|
|
151
178
|
if (colon < 1) throw new FeishuError('INVALID_ARGUMENT', 'A mention must use id:name.');
|
|
152
179
|
return { id: value.slice(0, colon), name: value.slice(colon + 1) };
|
|
153
180
|
});
|
|
154
|
-
output(await (await client()).send({ chatId: options.chat, text: options.text, mentions }));
|
|
181
|
+
output(await (await client()).send({ chatId: options.chat, text: options.text, mentions, replyTo: options.replyTo, replyRoot: options.replyRoot }));
|
|
155
182
|
});
|
|
156
183
|
|
|
157
184
|
program.command('send-file').description('Upload and send a local file as the user.')
|
|
158
185
|
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
159
186
|
.requiredOption('--file <path>', 'local file path')
|
|
160
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) })));
|
|
161
231
|
|
|
162
232
|
program.command('group-create').description('Create a group as the user.')
|
|
163
233
|
.requiredOption('--name <name>', 'group name')
|
package/package.json
CHANGED
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;
|
package/skills/larkmate/SKILL.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: larkmate
|
|
3
|
-
description: 使用 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
|
-
-
|
|
13
|
-
-
|
|
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`
|
|
18
|
+
`chat-open` 会打开或创建私聊;发送、修改消息、表情、收藏、群组、会话状态及妙记权限申请等命令也会修改数据,请按用户的实际意图操作。写入返回 `EFFECT_UNKNOWN`、`submitted_unconfirmed` 或部分成功时,先查询实际状态,避免重复提交。不要将消息已发送当作对方已读。
|
|
@@ -2,15 +2,28 @@
|
|
|
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
|
|
15
|
+
larkmate messages-export --chat "$CHAT_ID" --output ./messages.md
|
|
16
|
+
larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000000 --before 1800000000 --format jsonl --output ./messages.jsonl
|
|
10
17
|
```
|
|
11
18
|
|
|
12
19
|
`chats` 默认读取收件箱的一页,不是全部历史会话。`--type`、`--state` 只过滤当前页,`--scope done` 查询已完成分组;`boxes` 用 `--parent` 单独读取,`nextCursor` 用于翻页。`history` 每页最多 100 个位置,`--pages` 最多 100 页;`--query`、`--sender`、`--after`、`--before` 只过滤已扫描的位置,不是全量搜索。`omittedPositions` 是没有返回的位置数,不是消息数;部分消息类型可能没有可解析正文。
|
|
13
20
|
|
|
21
|
+
`search-messages` 用于在当前用户可访问的会话范围内进行跨会话搜索,可使用 `nextCursor` 配合相同的查询条件继续翻页;具体搜索范围和结果由飞书服务决定。`message-link` 返回飞书生成的原生消息链接。`download-file` 根据 `history` 返回的资源键将文件或图片下载至新文件,不会覆盖已有文件;若下载中断,输出文件将不完整。`favorites` 用于读取收藏列表首页,其中 `hasMore` 表示可能仍有未返回的收藏。
|
|
22
|
+
|
|
23
|
+
`messages-export` 会自动向前分页至会话最早位置,并按从新到旧的顺序输出 Markdown 或 JSON Lines。该命令支持 `--sender`、`--query`,以及以 Unix 秒为单位的 `--after` 和 `--before`;筛选范围仅限指定会话。可通过 `--max-pages` 限制页数,导出结束时需检查 `reachedBeginning`、`nextStart`、`nextLimit`、`omittedPositions` 和 `missingTimestamps`。
|
|
24
|
+
|
|
25
|
+
输出文件不会覆盖已有文件;若导出中断,文件中不会包含完成统计,须视为不完整。继续导出时,请使用新的输出文件,并将 `nextStart` 和 `nextLimit` 分别传给 `--start` 和 `--limit`,以避免分页重叠。
|
|
26
|
+
|
|
14
27
|
```sh
|
|
15
28
|
larkmate pinned
|
|
16
29
|
larkmate marked
|
|
@@ -4,11 +4,24 @@
|
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
larkmate send --chat "$CHAT_ID" --text '消息内容'
|
|
7
|
+
larkmate send --chat "$CHAT_ID" --text '回复内容' --reply-to "$MESSAGE_ID"
|
|
7
8
|
larkmate send --chat "$CHAT_ID" --text '@名称 消息内容' --mention "$MEMBER_ID:名称"
|
|
8
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"
|
|
9
18
|
```
|
|
10
19
|
|
|
11
|
-
文件须为非空普通文件且不超过 100 MiB。`accepted`
|
|
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` 首页获取。发送、编辑、撤回、转发、表情及收藏操作均须遵循用户的明确意图。
|
|
23
|
+
|
|
24
|
+
回复已有回复时,需同时传入 `--reply-root`,其值取目标消息的 `rootId`;若目标消息是回复链的第一条,则只需传入 `--reply-to`。`history` 会返回每条消息的 `rootId` 和 `parentId`。
|
|
12
25
|
|
|
13
26
|
```sh
|
|
14
27
|
larkmate group-members --chat "$CHAT_ID"
|
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.');
|
|
@@ -186,7 +222,7 @@ export class LarkMateClient {
|
|
|
186
222
|
: { key: content.imageV2?.imageKey || content.image?.imageKey || content.image?.key || null };
|
|
187
223
|
} catch { /* Leave unknown resources unparsed. */ }
|
|
188
224
|
}
|
|
189
|
-
return { id: String(message.id || ''), position: Number(position),
|
|
225
|
+
return { id: String(message.id || ''), position: Number(position), rootId: message.rootId || null, parentId: message.parentId || null,
|
|
190
226
|
senderId: message.fromId || '', type: message.type, text,
|
|
191
227
|
createTime: Object.hasOwn(message, 'createTime') ? String(message.createTime) : null, resource };
|
|
192
228
|
}).sort((a, b) => a.position - b.position);
|
|
@@ -247,9 +283,140 @@ 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
|
|
|
250
|
-
async
|
|
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
|
+
|
|
414
|
+
async send({ chatId, text, mentions = [], replyTo, replyRoot }) {
|
|
251
415
|
requireNumericId(chatId, 'chat ID');
|
|
252
416
|
requireText(text, 'text');
|
|
417
|
+
if (replyTo) requireNumericId(replyTo, 'reply message ID');
|
|
418
|
+
if (replyRoot) requireNumericId(replyRoot, 'reply root ID');
|
|
419
|
+
if (replyRoot && !replyTo) throw new FeishuError('INVALID_ARGUMENT', 'reply-root requires reply-to.');
|
|
253
420
|
if (!Array.isArray(mentions)) throw new FeishuError('INVALID_ARGUMENT', 'mentions must be a list.');
|
|
254
421
|
await this.gateway.authenticate();
|
|
255
422
|
const elementIds = [];
|
|
@@ -278,6 +445,7 @@ export class LarkMateClient {
|
|
|
278
445
|
const cid = shortId();
|
|
279
446
|
const response = await this.gateway.call(5, 'PutMessageRequest', {
|
|
280
447
|
type: 4, chatId, cid, isNotified: true, version: 1,
|
|
448
|
+
...(replyTo ? { parentId: replyTo, rootId: replyRoot || replyTo } : {}),
|
|
281
449
|
content: { richText: { elementIds, innerText: text, elements: { dictionary }, atIds } },
|
|
282
450
|
}, { version: '5.7.0', mutating: true, operation: 'send' });
|
|
283
451
|
return { status: 'submitted_unconfirmed', chatId, cid, requestId: response.requestId };
|
package/src/download.js
ADDED
|
@@ -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.`);
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { open } from 'node:fs/promises';
|
|
2
|
+
import { FeishuError } from './errors.js';
|
|
3
|
+
|
|
4
|
+
// Stream newest pages first, so even very large conversations need only one page in memory.
|
|
5
|
+
export async function exportMessages(client, { chatId, output, format = 'markdown', sender, query, after, before, start, maxPages, limit = 100 } = {}) {
|
|
6
|
+
if (typeof output !== 'string' || !output) throw new FeishuError('INVALID_ARGUMENT', 'An output path is required.');
|
|
7
|
+
if (!['markdown', 'jsonl'].includes(format)) throw new FeishuError('INVALID_ARGUMENT', 'Format must be markdown or jsonl.');
|
|
8
|
+
if (maxPages != null && (!Number.isSafeInteger(maxPages) || maxPages < 1)) throw new FeishuError('INVALID_ARGUMENT', 'max-pages must be a positive integer.');
|
|
9
|
+
// Validate all scan parameters before creating an output file.
|
|
10
|
+
if (!/^\d+$/.test(chatId || '') || (sender && !/^\d+$/.test(sender))) throw new FeishuError('INVALID_ARGUMENT', 'Chat and sender IDs must be numeric.');
|
|
11
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new FeishuError('INVALID_ARGUMENT', 'limit must be between 1 and 100.');
|
|
12
|
+
if (start != null && (!Number.isInteger(start) || start < 1 || start + limit - 1 > 2147483647)) throw new FeishuError('INVALID_ARGUMENT', 'start and limit must fit the position range.');
|
|
13
|
+
if ([after, before].some(value => value != null && (!Number.isSafeInteger(value) || value < 0)) || (after != null && before != null && after > before)) throw new FeishuError('INVALID_ARGUMENT', 'Invalid time range.');
|
|
14
|
+
let handle;
|
|
15
|
+
try { handle = await open(output, 'wx', 0o600); }
|
|
16
|
+
catch (error) { throw new FeishuError('EXPORT_WRITE_FAILED', error.code === 'EEXIST' ? 'Output file already exists; choose a new path.' : 'Could not create the output file.'); }
|
|
17
|
+
const metadata = { chatId, sender: sender || null, query: query || null, after: after ?? null, before: before ?? null, start: start ?? null, order: 'newest_first' };
|
|
18
|
+
let next = start, pages = 0, count = 0, scannedPositions = 0, omittedPositions = 0, missingTimestamps = 0;
|
|
19
|
+
try {
|
|
20
|
+
await handle.writeFile(format === 'jsonl' ? `${JSON.stringify({ kind: 'metadata', ...metadata })}\n` : `# 消息导出\n\n筛选条件:\`${JSON.stringify(metadata)}\`\n\n`);
|
|
21
|
+
do {
|
|
22
|
+
const page = await client.historyPages({ chatId, limit, start: next, pages: 1, sender, query, after, before });
|
|
23
|
+
pages++;
|
|
24
|
+
scannedPositions += page.scannedPositions;
|
|
25
|
+
omittedPositions += page.omittedPositions;
|
|
26
|
+
missingTimestamps += page.missingTimestamps;
|
|
27
|
+
const chunks = [];
|
|
28
|
+
for (const item of page.items.reverse()) {
|
|
29
|
+
count++;
|
|
30
|
+
if (format === 'jsonl') chunks.push(`${JSON.stringify({ kind: 'message', ...item })}\n`);
|
|
31
|
+
else {
|
|
32
|
+
const timestamp = item.createTime != null && Number.isFinite(Number(item.createTime)) && Math.abs(Number(item.createTime)) < 8640000000000
|
|
33
|
+
? new Date(Number(item.createTime) * 1000).toISOString() : '时间未知';
|
|
34
|
+
const body = item.text ?? (item.resource ? JSON.stringify(item.resource) : `[无法解析的消息类型 ${item.type}]`);
|
|
35
|
+
chunks.push(`## ${timestamp} · 发送者 ${item.senderId || '未知'}\n\n消息 ID:${item.id || '未知'} · 位置:${item.position}\n\n${String(body).split('\n').map(line => `> ${line}`).join('\n')}\n\n`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (chunks.length) await handle.writeFile(chunks.join(''));
|
|
39
|
+
next = page.nextStart;
|
|
40
|
+
limit = page.nextLimit;
|
|
41
|
+
} while (next != null && (maxPages == null || pages < maxPages));
|
|
42
|
+
const summary = { output, format, count, pages, scannedPositions, omittedPositions, missingTimestamps, reachedBeginning: next == null, nextStart: next ?? null, nextLimit: limit ?? null };
|
|
43
|
+
await handle.writeFile(format === 'jsonl' ? `${JSON.stringify({ kind: 'summary', ...summary })}\n` : `---\n\n导出统计:\`${JSON.stringify(summary)}\`\n`);
|
|
44
|
+
return summary;
|
|
45
|
+
} catch (error) {
|
|
46
|
+
// Keep the partial file so users do not lose a lengthy export; it has no completion footer.
|
|
47
|
+
throw new FeishuError('EXPORT_INCOMPLETE', 'Export stopped; the output file is incomplete.', { output, pages, cause: error.code || 'WRITE_FAILED' });
|
|
48
|
+
} finally { await handle.close(); }
|
|
49
|
+
}
|
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
|
|
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
|
|
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
|
-
|
|
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
|
}
|