larkmate 0.1.16 → 0.1.17
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 +1 -1
- package/bin/larkmate.js +7 -5
- package/docs/message-listening.md +6 -6
- package/package.json +1 -1
- package/skills/larkmate/SKILL.md +1 -1
- package/skills/larkmate/references/listen.md +3 -3
- package/src/listen-modes.js +6 -6
- package/src/listen.js +18 -11
package/README.md
CHANGED
|
@@ -57,7 +57,7 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
57
57
|
- [x] 发送图片消息、下载图片或附件
|
|
58
58
|
- [x] 给消息添加和取消表情回应
|
|
59
59
|
- [x] 获取消息链接
|
|
60
|
-
- [x]
|
|
60
|
+
- [x] 全局或按会话监听新消息,支持本地服务和规则触发脚本
|
|
61
61
|
- 群聊
|
|
62
62
|
- [x] 查询群信息、成员、管理员和入退群记录
|
|
63
63
|
- [x] 修改群名称、描述、头像和本人群昵称
|
package/bin/larkmate.js
CHANGED
|
@@ -20,7 +20,7 @@ import { createRuleOutput, loadListenRules, startListenService } from '../src/li
|
|
|
20
20
|
|
|
21
21
|
const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
|
|
22
22
|
const program = new Command();
|
|
23
|
-
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.
|
|
23
|
+
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.17');
|
|
24
24
|
program.option('--credentials-file <path>', 'read LarkMate credentials.json');
|
|
25
25
|
program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
|
|
26
26
|
program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
|
|
@@ -139,19 +139,21 @@ program.command('status').description('Check the current user login.')
|
|
|
139
139
|
program.command('search').description('Search users, bots and groups.')
|
|
140
140
|
.requiredOption('--query <text>', 'search text')
|
|
141
141
|
.action(async options => output(await (await client()).search(options.query)));
|
|
142
|
-
program.command('listen').description('Stream new messages
|
|
143
|
-
.
|
|
142
|
+
program.command('listen').description('Stream new messages as JSON lines; defaults to all chats.')
|
|
143
|
+
.option('--chat <id>', 'restrict to a numeric chat ID; repeatable', collect, []).option('--all', 'listen to all chats')
|
|
144
144
|
.action(async o => {
|
|
145
145
|
if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
|
|
146
|
+
if (o.all && o.chat.length) throw new FeishuError('INVALID_ARGUMENT', 'Use --all or --chat, not both.');
|
|
146
147
|
const controller = new AbortController(), stop = () => controller.abort();
|
|
147
148
|
process.once('SIGINT', stop); process.once('SIGTERM', stop);
|
|
148
149
|
try { await listen({ gateway: new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) }), chatIds: o.chat, signal: controller.signal }); }
|
|
149
150
|
finally { process.removeListener('SIGINT', stop); process.removeListener('SIGTERM', stop); }
|
|
150
151
|
});
|
|
151
|
-
program.command('listen-service').description('Serve
|
|
152
|
-
.
|
|
152
|
+
program.command('listen-service').description('Serve messages on a private Unix socket; defaults to all chats.')
|
|
153
|
+
.option('--chat <id>', 'restrict to a numeric chat ID; repeatable', collect, []).option('--all', 'listen to all chats').requiredOption('--socket <path>', 'absolute Unix socket path')
|
|
153
154
|
.action(async o => {
|
|
154
155
|
if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
|
|
156
|
+
if (o.all && o.chat.length) throw new FeishuError('INVALID_ARGUMENT', 'Use --all or --chat, not both.');
|
|
155
157
|
const service = await startListenService(o.socket), controller = new AbortController(), stop = () => controller.abort();
|
|
156
158
|
process.once('SIGINT', stop); process.once('SIGTERM', stop);
|
|
157
159
|
try { process.stderr.write(`LarkMate: event socket ${service.path}\n`); await listen({ gateway:new Gateway({cookie:await loadCookie({file:program.opts().credentialsFile})}),chatIds:o.chat,output:service.output,signal:controller.signal }); }
|
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
# 监听飞书消息
|
|
2
2
|
|
|
3
|
-
LarkMate 使用当前用户的飞书 Cookie
|
|
3
|
+
LarkMate 使用当前用户的飞书 Cookie 监听消息,默认覆盖全部会话,也可通过 `--chat` 限定监听范围,并用 `search` 或 `chats` 查询会话 ID。监听不会主动标记消息为已读。监听进程需要持续运行;退出后不会在后台继续收取消息。
|
|
4
4
|
|
|
5
5
|
## 本地事件服务
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
8
|
mkdir -p "$HOME/.larkmate/events"
|
|
9
9
|
chmod 700 "$HOME/.larkmate/events"
|
|
10
|
-
larkmate listen-service --socket "$HOME/.larkmate/events/messages.sock"
|
|
10
|
+
larkmate listen-service --socket "$HOME/.larkmate/events/messages.sock"
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
默认监听全部会话;传入 `--chat "$CHAT_ID"` 可限制范围,并可重复指定。也可用 `--all` 显式表示全局监听。其他本机程序通过 Unix socket 订阅 JSON Lines:
|
|
14
14
|
|
|
15
15
|
```sh
|
|
16
16
|
curl -N --unix-socket "$HOME/.larkmate/events/messages.sock" http://localhost/events
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
-
socket 为 `0600
|
|
19
|
+
socket 为 `0600`,父目录必须归当前用户所有且不能被其他用户写入。所有连接者接收服务配置范围内的消息;订阅者不在线时不保存事件。也可用 `larkmate listen` 直接向标准输出流式输出,不启动服务;该命令同样支持 `--chat` 限定会话。
|
|
20
20
|
|
|
21
21
|
## 规则与脚本
|
|
22
22
|
|
|
@@ -47,7 +47,7 @@ socket 为 `0600`,父目录必须归当前用户所有且不能被其他用户
|
|
|
47
47
|
larkmate listen-run --rules ./rules.json
|
|
48
48
|
```
|
|
49
49
|
|
|
50
|
-
`
|
|
50
|
+
`run` 必填;省略 `chatIds` 或传入空数组时匹配全部会话,填写会话 ID 时只匹配指定会话。其他筛选项可省略,填写的条件同时生效。`types` 使用消息类型数字,`4` 表示文本;`contains` 和 `excludeContains` 区分大小写。`excludeSelf` 为 `true` 时跳过当前账号发送的消息。
|
|
51
51
|
|
|
52
52
|
过滤器和目标脚本均为固定的绝对可执行文件路径,`args` 为固定参数;消息不会经由 shell 解析。每次调用时,通过标准输入传入一行消息 JSON。过滤器退出码 `0` 表示匹配,`1` 表示不匹配,其余退出码或超时均视为错误;仅在匹配成功时执行 `run`。过滤器和脚本的标准输出与标准错误不会被转发,失败信息写入监听进程的标准错误。脚本默认超时时间为 30 秒,可配置为 1–600 秒。规则按顺序执行,脚本执行失败不会自动重试。
|
|
53
53
|
|
|
@@ -57,4 +57,4 @@ larkmate listen-run --rules ./rules.json
|
|
|
57
57
|
|
|
58
58
|
`message` 事件包含 `id`、`chatId`、`senderId`、`position`、`type`、`text`、`createTime` 等字段。文本无法完整解析时 `textIncomplete` 为 `true`;其他消息类型的 `text` 可能为 `null`。规则模式仅对 `message` 执行脚本,`gap` 事件写到标准错误。
|
|
59
59
|
|
|
60
|
-
连接中断后会自动重连,并在进程保持运行期间按会话位置尽力补拉消息;补拉的消息带有 `backfill: true`
|
|
60
|
+
连接中断后会自动重连,并在进程保持运行期间按会话位置尽力补拉消息;补拉的消息带有 `backfill: true` 标记。全局模式仅能补拉当前进程已收到过消息的会话;中断期间新出现或此前未收到消息的会话可能遗漏,因此会发出 `global_coverage_unknown` 缺口事件。若出现补拉失败、位置不可读或超出补拉上限等情况,也会输出 `gap`,调用方应检查并按需通过 `history` 补查。去重状态与会话位置均保存在内存中,进程重启后不会恢复;不保证事件不丢失,也不保证脚本恰好执行一次。
|
package/package.json
CHANGED
package/skills/larkmate/SKILL.md
CHANGED
|
@@ -14,7 +14,7 @@ description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、
|
|
|
14
14
|
根据任务读取所需参考:
|
|
15
15
|
|
|
16
16
|
- 查找会话、搜索与导出消息、获取链接、下载资源,以及管理会话状态和标签: [会话与消息](references/chats.md)。
|
|
17
|
-
-
|
|
17
|
+
- 全局或按会话监听、本地事件服务及脚本触发规则: [消息监听](references/listen.md)。
|
|
18
18
|
- 发送与管理消息、文件、图片、表情和收藏,管理群组及成员: [发送与群组](references/writes.md)。
|
|
19
19
|
- 查询和管理飞书任务、任务视图及成员: [飞书任务](references/tasks.md)。
|
|
20
20
|
- 查询和管理日历、日程及邀请: [日历与日程](references/calendar.md)。
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# 消息监听
|
|
2
2
|
|
|
3
|
-
用 `larkmate listen
|
|
3
|
+
用 `larkmate listen` 输出全部会话的实时 JSON Lines;传入 `--chat "$CHAT_ID"` 可限定会话,且支持重复传入。`listen-service --socket <绝对路径>` 在私有 Unix socket 的 `/events` 提供事件流,`listen-run --rules <文件>` 按规则筛选消息并运行脚本。完整规则格式和示例见[消息监听指南](https://github.com/NWYLZW/larkmate/blob/main/docs/message-listening.md)。
|
|
4
4
|
|
|
5
|
-
`listen-run`
|
|
5
|
+
`listen-run` 的规则可省略 `chatIds` 以匹配全部会话,也可按会话、发送人、类型、文本和自定义过滤脚本筛选。过滤脚本和目标脚本通过标准输入接收消息 JSON,不通过 shell 传递消息。`excludeSelf: true` 可防止处理账号自身发出的消息。只有用户明确要求配置触发行为时才创建规则或启动脚本,不根据收到的消息自行扩大脚本权限。
|
|
6
6
|
|
|
7
|
-
自动重连时会尽力按会话位置补拉,补拉事件带 `backfill: true
|
|
7
|
+
自动重连时会尽力按会话位置补拉,补拉事件带 `backfill: true`;全局模式只能补拉本次进程已见过的会话,并在中断时发出 `global_coverage_unknown` 缺口事件。处理 `gap` 事件并按需查询历史。去重和补拉位置仅保存在当前进程内,重启后不恢复,不能保证不漏或恰好执行一次。服务订阅者不在线时不会缓存事件。监听目前不能通过 broker 或系统用户委托使用;保护 socket、Cookie、规则文件和脚本的访问由部署方负责。
|
package/src/listen-modes.js
CHANGED
|
@@ -22,11 +22,12 @@ function script(value, label) {
|
|
|
22
22
|
}
|
|
23
23
|
export function parseListenRules(raw) {
|
|
24
24
|
if (!only(raw,['version','rules']) || raw.version!==1 || !Array.isArray(raw.rules) || !raw.rules.length || raw.rules.length>100) invalid('Use version 1 and 1 to 100 rules.');
|
|
25
|
-
const names=new Set(), chats=new Set();
|
|
25
|
+
const names=new Set(), chats=new Set(); let allChats=false;
|
|
26
26
|
const rules=raw.rules.map(r=>{
|
|
27
27
|
if (!only(r,['name','chatIds','senderIds','types','contains','excludeContains','excludeSelf','filter','run']) || typeof r.name!=='string' || !r.name.trim() || r.name.length>100 || names.has(r.name)) invalid('Invalid or duplicate rule name.');
|
|
28
28
|
names.add(r.name);
|
|
29
|
-
const chatIds=
|
|
29
|
+
const chatIds=r.chatIds===undefined ? [] : stringArray(r.chatIds,'chat IDs',Infinity);
|
|
30
|
+
if (!chatIds.length) allChats=true;
|
|
30
31
|
for(const id of chatIds){requireInt64Id(id,'chat ID');chats.add(id);}
|
|
31
32
|
const senderIds=r.senderIds===undefined?null:stringArray(r.senderIds,'sender IDs'); if(senderIds)for(const id of senderIds)requireInt64Id(id,'sender ID');
|
|
32
33
|
const types=r.types===undefined?null:r.types;
|
|
@@ -35,8 +36,7 @@ export function parseListenRules(raw) {
|
|
|
35
36
|
if(r.excludeSelf!==undefined&&typeof r.excludeSelf!=='boolean')invalid('Invalid excludeSelf.');
|
|
36
37
|
return {name:r.name,chatIds,senderIds,types,contains:r.contains,excludeContains:r.excludeContains,excludeSelf:r.excludeSelf===true,filter:r.filter===undefined?null:script(r.filter,'filter'),run:script(r.run,'run')};
|
|
37
38
|
});
|
|
38
|
-
|
|
39
|
-
return {rules,chatIds:[...chats]};
|
|
39
|
+
return {rules,chatIds:allChats?[]:[...chats],allChats};
|
|
40
40
|
}
|
|
41
41
|
export async function loadListenRules(path) {
|
|
42
42
|
let f;
|
|
@@ -47,7 +47,7 @@ export async function loadListenRules(path) {
|
|
|
47
47
|
finally { await f?.close(); }
|
|
48
48
|
}
|
|
49
49
|
function matches(rule,event,selfId) {
|
|
50
|
-
return event.kind==='message'&&rule.chatIds.includes(event.chatId)&&(!rule.senderIds||rule.senderIds.includes(event.senderId))&&(!rule.types||rule.types.includes(event.type))
|
|
50
|
+
return event.kind==='message'&&(!rule.chatIds.length||rule.chatIds.includes(event.chatId))&&(!rule.senderIds||rule.senderIds.includes(event.senderId))&&(!rule.types||rule.types.includes(event.type))
|
|
51
51
|
&&(!rule.excludeSelf||(selfId&&event.senderId!==selfId))&&(rule.contains===undefined||(event.text||'').includes(rule.contains))&&(rule.excludeContains===undefined||!(event.text||'').includes(rule.excludeContains));
|
|
52
52
|
}
|
|
53
53
|
function runScript(config,event) {
|
|
@@ -73,7 +73,7 @@ export function createRuleOutput({rules,selfId,log=process.stderr}) {
|
|
|
73
73
|
})().then(()=>callback(),callback)}});
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
-
// Exposes
|
|
76
|
+
// Exposes the configured event stream, protected by the socket and parent directory permissions.
|
|
77
77
|
export async function startListenService(socketPath) {
|
|
78
78
|
if(typeof socketPath!=='string'||!isAbsolute(socketPath)||socketPath.endsWith('/'))throw new FeishuError('INVALID_ARGUMENT','Use an absolute socket path.');
|
|
79
79
|
let parent;try{parent=await realpath(dirname(socketPath));}catch{throw new FeishuError('LISTEN_SOCKET_INVALID','The socket directory must exist.');}
|
package/src/listen.js
CHANGED
|
@@ -87,24 +87,30 @@ function formatMessage(gateway, m) {
|
|
|
87
87
|
type:m.type, text, textIncomplete, createTime:asString(m.createTime), rootId:asString(m.rootId), parentId:asString(m.parentId) };
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
-
export async function listen({ gateway, chatIds, output = process.stdout, log = process.stderr, signal, WebSocketImpl = WebSocket }) {
|
|
91
|
-
if (!Array.isArray(chatIds)
|
|
90
|
+
export async function listen({ gateway, chatIds = [], output = process.stdout, log = process.stderr, signal, WebSocketImpl = WebSocket }) {
|
|
91
|
+
if (!Array.isArray(chatIds)) throw new FeishuError('INVALID_ARGUMENT', 'chat IDs must be a list.');
|
|
92
92
|
const selected = new Set(chatIds.map(id => requireInt64Id(id, 'chat ID')));
|
|
93
|
+
const global = selected.size === 0;
|
|
93
94
|
const client = new LarkMateClient(gateway), seen = new Set(), seenOrder = [], positions = new Map();
|
|
94
95
|
const emit = async value => { if (!output.write(`${JSON.stringify(value)}\n`)) await once(output, 'drain'); };
|
|
95
96
|
const remember = id => { if (!id || seen.has(id)) return false; seen.add(id); seenOrder.push(id); if (seenOrder.length > 10000) seen.delete(seenOrder.shift()); return true; };
|
|
96
|
-
const writeMessage = async message => { if (!selected.has(message.chatId) || !remember(message.id)) return;
|
|
97
|
-
if (Number.isInteger(message.position)) positions.set(message.chatId, Math.max(positions.get(message.chatId) ?? 0, message.position)); await emit(message); };
|
|
97
|
+
const writeMessage = async message => { if ((!global && !selected.has(message.chatId)) || !remember(message.id)) return;
|
|
98
|
+
if (typeof message.chatId === 'string' && /^[1-9]\d{0,18}$/.test(message.chatId) && Number.isInteger(message.position)) positions.set(message.chatId, Math.max(positions.get(message.chatId) ?? 0, message.position)); await emit(message); };
|
|
98
99
|
for (const chatId of selected) { const info = await client.chatInfo(chatId); if (!Number.isInteger(info.lastMessagePosition)) throw new FeishuError('POSITION_UNAVAILABLE', 'Cannot read the initial message position.'); positions.set(chatId, info.lastMessagePosition); }
|
|
99
|
-
const backfill = async () => { for (const chatId of selected) {
|
|
100
|
-
|
|
100
|
+
const backfill = async () => { for (const chatId of (global ? [...positions.keys()] : selected)) {
|
|
101
|
+
let latest;
|
|
102
|
+
try { latest = (await client.chatInfo(chatId)).lastMessagePosition; }
|
|
103
|
+
catch (error) { await emit({kind:'gap',chatId,reason:'position_unavailable',code:error.code || 'READ_FAILED'}); continue; }
|
|
104
|
+
const from = positions.get(chatId) + 1;
|
|
101
105
|
if (!Number.isInteger(latest)) { await emit({ kind:'gap', chatId, reason:'position_unavailable' }); continue; }
|
|
102
106
|
if (latest - from >= 10000) { await emit({ kind:'gap', chatId, reason:'backfill_limit', fromPosition:from, throughPosition:latest }); positions.set(chatId,latest); continue; }
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
107
|
+
try {
|
|
108
|
+
for (let start=from; start<=latest; start+=100) {
|
|
109
|
+
const page = await client.history({chatId,start,limit:Math.min(100,latest-start+1)});
|
|
110
|
+
for (const m of page.items) await writeMessage({kind:'message',chatId,...m,backfill:true});
|
|
111
|
+
if (page.omittedPositions) await emit({kind:'gap',chatId,reason:'positions_unavailable',start,count:page.omittedPositions});
|
|
112
|
+
}
|
|
113
|
+
} catch (error) { await emit({kind:'gap',chatId,reason:'backfill_failed',code:error.code || 'READ_FAILED'}); continue; }
|
|
108
114
|
positions.set(chatId, Math.max(positions.get(chatId), latest));
|
|
109
115
|
} };
|
|
110
116
|
let attempt = 0;
|
|
@@ -174,6 +180,7 @@ export async function listen({ gateway, chatIds, output = process.stdout, log =
|
|
|
174
180
|
} finally { clearInterval(heartbeat); if (socket && socket.readyState < 2) socket.close(); }
|
|
175
181
|
if (signal?.aborted) break;
|
|
176
182
|
if (connected && !reported) await emit({kind:'gap',reason:'connection_interrupted'});
|
|
183
|
+
if (global && connected) await emit({kind:'gap',reason:'global_coverage_unknown'});
|
|
177
184
|
try { await delay(Math.min(30000,1000 * 2**Math.min(attempt++,5)), undefined, { signal }); } catch (error) { if (!signal?.aborted) throw error; }
|
|
178
185
|
}
|
|
179
186
|
}
|