larkmate 0.1.5 → 0.1.6
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 +4 -2
- package/bin/larkmate.js +24 -2
- package/package.json +1 -1
- package/skills/larkmate/references/chats.md +6 -0
- package/skills/larkmate/references/writes.md +3 -0
- package/src/client.js +6 -2
- package/src/export-messages.js +49 -0
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
|
+
- [x] 发送文本、引用回复、@ 用户或机器人、发送文件
|
|
46
47
|
- [ ] 全局搜索历史消息
|
|
47
|
-
- [ ]
|
|
48
|
+
- [ ] 编辑或撤回消息
|
|
48
49
|
- [ ] 转发或收藏消息
|
|
49
50
|
- [ ] 发送图片消息、下载图片或附件
|
|
50
51
|
- [ ] 给消息添加表情回应
|
|
52
|
+
- [ ] 获取消息链接
|
|
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.6');
|
|
13
14
|
program.option('--credentials-file <path>', 'read LarkMate credentials.json');
|
|
14
15
|
program.exitOverride();
|
|
15
16
|
|
|
@@ -141,17 +142,38 @@ program.command('history').description('Read a bounded page of chat messages as
|
|
|
141
142
|
...(options.start != null ? { start: Number(options.start) } : {}),
|
|
142
143
|
})));
|
|
143
144
|
|
|
145
|
+
program.command('messages-export').description('Export a conversation to a local file, paging through history.')
|
|
146
|
+
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
147
|
+
.requiredOption('--output <path>', 'new local output file')
|
|
148
|
+
.option('--format <format>', 'markdown or jsonl', 'markdown')
|
|
149
|
+
.option('--sender <id>', 'only messages from this numeric sender ID')
|
|
150
|
+
.option('--query <text>', 'only messages containing this text')
|
|
151
|
+
.option('--after <seconds>', 'inclusive Unix time in seconds')
|
|
152
|
+
.option('--before <seconds>', 'inclusive Unix time in seconds')
|
|
153
|
+
.option('--start <number>', 'first position of the initial page')
|
|
154
|
+
.option('--limit <number>', 'positions per page, 1 to 100', '100')
|
|
155
|
+
.option('--max-pages <number>', 'stop after this many pages; default scans to the beginning')
|
|
156
|
+
.action(async o => output(await exportMessages(await client(), {
|
|
157
|
+
chatId: o.chat, output: o.output, format: o.format, sender: o.sender, query: o.query, limit: Number(o.limit),
|
|
158
|
+
...(o.after != null ? { after: Number(o.after) } : {}),
|
|
159
|
+
...(o.before != null ? { before: Number(o.before) } : {}),
|
|
160
|
+
...(o.start != null ? { start: Number(o.start) } : {}),
|
|
161
|
+
...(o.maxPages != null ? { maxPages: Number(o.maxPages) } : {}),
|
|
162
|
+
})));
|
|
163
|
+
|
|
144
164
|
program.command('send').description('Send text once as the user; delivery remains unconfirmed.')
|
|
145
165
|
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
146
166
|
.requiredOption('--text <text>', 'message text')
|
|
147
167
|
.option('--mention <id:name>', 'mention a numeric user or bot ID; repeatable', collect, [])
|
|
168
|
+
.option('--reply-to <id>', 'reply to a numeric message ID')
|
|
169
|
+
.option('--reply-root <id>', 'root ID when replying to an existing reply')
|
|
148
170
|
.action(async options => {
|
|
149
171
|
const mentions = options.mention.map(value => {
|
|
150
172
|
const colon = value.indexOf(':');
|
|
151
173
|
if (colon < 1) throw new FeishuError('INVALID_ARGUMENT', 'A mention must use id:name.');
|
|
152
174
|
return { id: value.slice(0, colon), name: value.slice(colon + 1) };
|
|
153
175
|
});
|
|
154
|
-
output(await (await client()).send({ chatId: options.chat, text: options.text, mentions }));
|
|
176
|
+
output(await (await client()).send({ chatId: options.chat, text: options.text, mentions, replyTo: options.replyTo, replyRoot: options.replyRoot }));
|
|
155
177
|
});
|
|
156
178
|
|
|
157
179
|
program.command('send-file').description('Upload and send a local file as the user.')
|
package/package.json
CHANGED
|
@@ -7,10 +7,16 @@ larkmate chats --cursor "$NEXT_CURSOR"
|
|
|
7
7
|
larkmate chats --parent "$BOX_ID"
|
|
8
8
|
larkmate chat-info --chat "$CHAT_ID"
|
|
9
9
|
larkmate history --chat "$CHAT_ID" --limit 50 --pages 3
|
|
10
|
+
larkmate messages-export --chat "$CHAT_ID" --output ./messages.md
|
|
11
|
+
larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000000 --before 1800000000 --format jsonl --output ./messages.jsonl
|
|
10
12
|
```
|
|
11
13
|
|
|
12
14
|
`chats` 默认读取收件箱的一页,不是全部历史会话。`--type`、`--state` 只过滤当前页,`--scope done` 查询已完成分组;`boxes` 用 `--parent` 单独读取,`nextCursor` 用于翻页。`history` 每页最多 100 个位置,`--pages` 最多 100 页;`--query`、`--sender`、`--after`、`--before` 只过滤已扫描的位置,不是全量搜索。`omittedPositions` 是没有返回的位置数,不是消息数;部分消息类型可能没有可解析正文。
|
|
13
15
|
|
|
16
|
+
`messages-export` 会自动向前分页至会话最早位置,并按从新到旧的顺序输出 Markdown 或 JSON Lines。该命令支持 `--sender`、`--query`,以及以 Unix 秒为单位的 `--after` 和 `--before`;筛选范围仅限指定会话。可通过 `--max-pages` 限制页数,导出结束时需检查 `reachedBeginning`、`nextStart`、`nextLimit`、`omittedPositions` 和 `missingTimestamps`。
|
|
17
|
+
|
|
18
|
+
输出文件不会覆盖已有文件;若导出中断,文件中不会包含完成统计,须视为不完整。继续导出时,请使用新的输出文件,并将 `nextStart` 和 `nextLimit` 分别传给 `--start` 和 `--limit`,以避免分页重叠。
|
|
19
|
+
|
|
14
20
|
```sh
|
|
15
21
|
larkmate pinned
|
|
16
22
|
larkmate marked
|
|
@@ -4,12 +4,15 @@
|
|
|
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
|
|
9
10
|
```
|
|
10
11
|
|
|
11
12
|
文件须为非空普通文件且不超过 100 MiB。`accepted` 表示服务器返回消息 ID,`submitted_unconfirmed` 表示未可靠确认接收;不确定时先查历史再决定是否重试。
|
|
12
13
|
|
|
14
|
+
回复已有回复时,需同时传入 `--reply-root`,其值取目标消息的 `rootId`;若目标消息是回复链的第一条,则只需传入 `--reply-to`。`history` 会返回每条消息的 `rootId` 和 `parentId`。
|
|
15
|
+
|
|
13
16
|
```sh
|
|
14
17
|
larkmate group-members --chat "$CHAT_ID"
|
|
15
18
|
larkmate group-create --name '群名称' --member "$MEMBER_ID"
|
package/src/client.js
CHANGED
|
@@ -186,7 +186,7 @@ export class LarkMateClient {
|
|
|
186
186
|
: { key: content.imageV2?.imageKey || content.image?.imageKey || content.image?.key || null };
|
|
187
187
|
} catch { /* Leave unknown resources unparsed. */ }
|
|
188
188
|
}
|
|
189
|
-
return { id: String(message.id || ''), position: Number(position),
|
|
189
|
+
return { id: String(message.id || ''), position: Number(position), rootId: message.rootId || null, parentId: message.parentId || null,
|
|
190
190
|
senderId: message.fromId || '', type: message.type, text,
|
|
191
191
|
createTime: Object.hasOwn(message, 'createTime') ? String(message.createTime) : null, resource };
|
|
192
192
|
}).sort((a, b) => a.position - b.position);
|
|
@@ -247,9 +247,12 @@ export class LarkMateClient {
|
|
|
247
247
|
return { status: id ? 'accepted' : 'submitted_unconfirmed', chatId, messageId: id, cid, requestId: response.requestId, fileName: file.name };
|
|
248
248
|
}
|
|
249
249
|
|
|
250
|
-
async send({ chatId, text, mentions = [] }) {
|
|
250
|
+
async send({ chatId, text, mentions = [], replyTo, replyRoot }) {
|
|
251
251
|
requireNumericId(chatId, 'chat ID');
|
|
252
252
|
requireText(text, 'text');
|
|
253
|
+
if (replyTo) requireNumericId(replyTo, 'reply message ID');
|
|
254
|
+
if (replyRoot) requireNumericId(replyRoot, 'reply root ID');
|
|
255
|
+
if (replyRoot && !replyTo) throw new FeishuError('INVALID_ARGUMENT', 'reply-root requires reply-to.');
|
|
253
256
|
if (!Array.isArray(mentions)) throw new FeishuError('INVALID_ARGUMENT', 'mentions must be a list.');
|
|
254
257
|
await this.gateway.authenticate();
|
|
255
258
|
const elementIds = [];
|
|
@@ -278,6 +281,7 @@ export class LarkMateClient {
|
|
|
278
281
|
const cid = shortId();
|
|
279
282
|
const response = await this.gateway.call(5, 'PutMessageRequest', {
|
|
280
283
|
type: 4, chatId, cid, isNotified: true, version: 1,
|
|
284
|
+
...(replyTo ? { parentId: replyTo, rootId: replyRoot || replyTo } : {}),
|
|
281
285
|
content: { richText: { elementIds, innerText: text, elements: { dictionary }, atIds } },
|
|
282
286
|
}, { version: '5.7.0', mutating: true, operation: 'send' });
|
|
283
287
|
return { status: 'submitted_unconfirmed', chatId, cid, requestId: response.requestId };
|
|
@@ -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
|
+
}
|