larkmate 0.1.25 → 0.1.26

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
@@ -61,7 +61,7 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
61
61
  - [x] 按会话、发送者和时间范围分页导出消息到本地文件
62
62
  - [x] 读取文本、链接、提及及部分图片和文件元数据
63
63
  - [ ] 完整解析富文本中的图片、表情包和互动卡片
64
- - [x] 发送文本、链接和带标题的消息,引用回复、@ 用户或所有人
64
+ - [x] 发送文本、链接、飞书表情和带标题的消息,引用回复、@ 用户或所有人
65
65
  - [x] 发送文件
66
66
  - [x] 全局搜索消息(分页)
67
67
  - [x] 编辑文本消息或撤回消息
package/bin/larkmate.js CHANGED
@@ -456,6 +456,7 @@ program.command('send').description('Send text once as the user; delivery remain
456
456
  .requiredOption('--chat <id>', 'numeric chat ID')
457
457
  .requiredOption('--text <text>', 'message text')
458
458
  .option('--mention <id:name>', 'mention a numeric user or bot ID, or all for everyone; repeatable', collect, [])
459
+ .option('--emoji <key>', 'turn each :key: marker into a Feishu emoji; repeatable', collect, [])
459
460
  .option('--reply-to <id>', 'reply to a numeric message ID')
460
461
  .option('--reply-root <id>', 'root ID when replying to an existing reply')
461
462
  .action(async options => {
@@ -464,10 +465,14 @@ program.command('send').description('Send text once as the user; delivery remain
464
465
  if (colon < 1) throw new FeishuError('INVALID_ARGUMENT', 'A mention must use id:name.');
465
466
  return { id: value.slice(0, colon), name: value.slice(colon + 1) };
466
467
  });
467
- output(await (await client()).send({ chatId: options.chat, text: options.text, mentions, replyTo: options.replyTo, replyRoot: options.replyRoot }));
468
+ output(await (await client()).send({ chatId: options.chat, text: options.text, mentions, emojis: options.emoji, replyTo: options.replyTo, replyRoot: options.replyRoot }));
468
469
  });
469
470
 
470
- program.command('send-rich').description('Send structured text, links and mentions from JSON.')
471
+ program.command('emoji-list').description('List available Feishu emoji names and keys.')
472
+ .option('--query <text>', 'filter by emoji name or key')
473
+ .action(async options => output(await (await client()).emojiList({ query: options.query })));
474
+
475
+ program.command('send-rich').description('Send structured text, links, mentions and emoji from JSON.')
471
476
  .requiredOption('--chat <id>', 'numeric chat ID')
472
477
  .requiredOption('--json <path>', 'JSON file or - for standard input')
473
478
  .option('--reply-to <id>', 'reply to a numeric message ID')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "larkmate",
3
- "version": "0.1.25",
3
+ "version": "0.1.26",
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
@@ -199,6 +199,7 @@ message RichTextElement {
199
199
  FIGURE = 4;
200
200
  AT = 5;
201
201
  A = 6;
202
+ EMOTION = 10;
202
203
  }
203
204
  }
204
205
 
@@ -213,6 +214,34 @@ message AtProperty {
213
214
  optional string content = 2;
214
215
  }
215
216
 
217
+ message EmotionProperty {
218
+ optional string key = 1;
219
+ }
220
+
221
+ message PullEmojiResourcesV2Request {
222
+ map<string, int32> emojiSetId2version = 1;
223
+ optional bool needUserTenantResources = 2;
224
+ optional int32 accessType = 3;
225
+ }
226
+ message EmojiI18nText {
227
+ optional string defaultText = 1;
228
+ map<string, string> i18nTexts = 2;
229
+ }
230
+ message EmojiResource {
231
+ optional string key = 1;
232
+ optional EmojiI18nText i18nText = 2;
233
+ optional bool isDeleted = 4;
234
+ repeated string skinKeys = 5;
235
+ optional string emojiSetId = 7;
236
+ }
237
+ message EmojiResourceSet {
238
+ optional string setId = 1;
239
+ optional int32 setSource = 2;
240
+ repeated EmojiResource emojiResources = 3;
241
+ optional int32 version = 4;
242
+ }
243
+ message PullEmojiResourcesV2Response { repeated EmojiResourceSet emojiResourceSet = 1; }
244
+
216
245
  // For A (hyperlink) elements.
217
246
  message AnchorProperty {
218
247
  optional string href = 1;
@@ -22,7 +22,7 @@ larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000
22
22
 
23
23
  `chats` 默认读取收件箱的一页,不是全部历史会话。`--type`、`--state` 只过滤当前页,`--scope done` 查询已完成分组;`boxes` 用 `--parent` 单独读取,`nextCursor` 用于翻页。`history` 每页最多 100 个位置,`--pages` 最多 100 页;`--query`、`--sender`、`--after`、`--before` 只过滤已扫描的位置,不是全量搜索。`omittedPositions` 是没有返回的位置数,不是消息数;部分消息类型可能没有可解析正文。
24
24
 
25
- 历史消息的 `segments` 保留文本、提及用户和链接,`title` 是带标题消息的标题;`textIncomplete` 表示正文未能完整解析,汇总中的 `incompleteText` 是此类消息数。
25
+ 历史消息的 `segments` 保留文本、提及、链接和飞书表情代码,`title` 是带标题消息的标题;`textIncomplete` 表示正文未能完整解析,汇总中的 `incompleteText` 是此类消息数。飞书原生表情在纯文本中以 `:代码:` 表示。
26
26
 
27
27
  `search-messages` 用于在当前用户可访问的会话范围内进行跨会话搜索,可使用 `nextCursor` 配合相同的查询条件继续翻页;具体搜索范围和结果由飞书服务决定。`message-link` 返回飞书生成的原生消息链接。`download-file` 根据 `history` 返回的资源键将文件或图片下载至新文件,不会覆盖已有文件;若下载中断,输出文件将不完整。`favorites` 用于读取收藏列表首页,其中 `hasMore` 表示可能仍有未返回的收藏。
28
28
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  服务订阅支持会话及发送人的 ID、名称和正则,以及消息类型、正文包含/排除、正文正则和排除本人。相同维度的 ID、名称和正则是“或”,不同维度是“且”。大量条件或 `anyOf`、`allOf`、`not` 组合通过 `POST /events` JSON 传入;规则模式支持同样的条件。正则使用 RE2 语法,不支持部分 JavaScript 正则特性。名称解析失败且结果无法确定时会发出 `name_unavailable` 缺口,不猜测匹配;同名对象都会匹配,需要精确区分时使用 ID。
6
6
 
7
- 消息事件的 `segments` 包含解析出的文本、提及和链接;文本过滤也检查带标题消息的标题。`textIncomplete` 表示未能完整解析,无法安全判断的文本规则会产生缺口事件。
7
+ 消息事件的 `segments` 包含解析出的文本、提及、链接和飞书表情代码;文本过滤也检查带标题消息的标题。`textIncomplete` 表示未能完整解析,无法安全判断的文本规则会产生缺口事件。
8
8
 
9
9
  通过 `listen-service --policy <绝对路径>` 为每个 API key 限定会话、发送人和类型;订阅过滤条件只能缩小授权范围。未配置策略时依靠 socket 文件权限控制访问。授权配置及订阅示例见 [API 服务与授权](https://github.com/NWYLZW/larkmate/blob/main/docs/api-service.md)。限制范围内的 `gap` 会传递;无法定位会话的全局缺口只包含通用原因。
10
10
 
@@ -7,6 +7,8 @@ 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 --chat "$CHAT_ID" --text '@所有人 消息内容' --mention 'all:所有人'
10
+ larkmate emoji-list --query '大笑'
11
+ larkmate send --chat "$CHAT_ID" --text '你好 :LAUGH:' --emoji LAUGH
10
12
  larkmate send-rich --chat "$CHAT_ID" --json ./message.json
11
13
  larkmate send-file --chat "$CHAT_ID" --file ./report.pdf
12
14
  larkmate send-image --chat "$CHAT_ID" --file ./image.png
@@ -21,12 +23,16 @@ larkmate favorite-remove --favorite "$FAVORITE_ID"
21
23
 
22
24
  同一用户只需提供一次 `--mention`,正文中所有匹配的提及都会生效。
23
25
 
24
- `send-rich` 的 JSON 使用 `segments` 数组,支持文本、链接和用户提及;可选 `title` 用于发送带标题的消息:
26
+ 使用 `emoji-list` 按名称或代码查询可用的飞书原生表情;`send` 的 `--emoji` 可重复指定,每个 `:代码:` 会转成正文表情。普通 Unicode 表情直接写入文本即可。受限代理和 API key 调用 `emoji-list` 时需要允许该命令和全局访问。
27
+
28
+ `send-rich` 的 JSON 使用 `segments` 数组,支持文本、链接、用户提及和表情;可选 `title` 用于发送带标题的消息:
25
29
 
26
30
  ```json
27
31
  {"title":"标题","segments":[{"type":"text","text":"请查看 "},{"type":"link","text":"参考链接","url":"https://example.com/"},{"type":"text","text":" "},{"type":"mention","text":"@名称","userId":"123"}]}
28
32
  ```
29
33
 
34
+ 表情片段写作 `{"type":"emoji","key":"LAUGH"}`,代码可从 `emoji-list` 获取。
35
+
30
36
  `userId` 使用飞书网页数字 ID;`all` 表示 @所有人,受群权限限制。代理、系统用户委托或 API key 需允许 `send-rich`;在现有策略中,带提及或引用的发送还需要全部会话授权。
31
37
 
32
38
  文件须为非空普通文件且不超过 100 MiB。`accepted` 表示服务器返回相应 ID,`submitted_unconfirmed` 表示未可靠确认接收;不确定时先检查实际状态再决定是否重试。
@@ -10,7 +10,7 @@ import { handleFileRequest, brokerUpload, brokerDownload } from './agent-files.j
10
10
  // The socket policy is enforced in this process, never by the calling agent.
11
11
  // An explicit mapping prevents callers from reaching arbitrary object methods.
12
12
  const routes = {
13
- status: ['client', 'status', 'global'], search: ['client', 'search', 'global'],
13
+ status: ['client', 'status', 'global'], search: ['client', 'search', 'global'], 'emoji-list': ['client', 'emojiList', 'global'],
14
14
  'calendars': ['calendar','calendars','global'], 'calendar-search': ['calendar','searchCalendars','global'],
15
15
  'calendar-busy': ['calendar','busy','global'], 'calendar-suggest': ['calendar','suggest','global'],
16
16
  'calendar-events': ['calendar','events','global'], 'event-get': ['calendar','event','global'], 'calendar-rooms': ['calendar','rooms','global'],
@@ -159,7 +159,7 @@ export function authorize(policy, request) {
159
159
  }
160
160
  if (scope === 'chatObject' || scope === 'send') {
161
161
  if (args.length !== 1 || !object(args[0]) || !chatAllowed(args[0].chatId)) denied();
162
- const keys = scope === 'send' ? (method === 'sendRich' ? ['chatId', 'segments', 'title', 'replyTo', 'replyRoot'] : ['chatId', 'text', 'mentions', 'replyTo', 'replyRoot'])
162
+ const keys = scope === 'send' ? (method === 'sendRich' ? ['chatId', 'segments', 'title', 'replyTo', 'replyRoot'] : ['chatId', 'text', 'mentions', 'emojis', 'replyTo', 'replyRoot'])
163
163
  : method === 'historyPages' ? ['chatId', 'limit', 'start', 'pages', 'query', 'sender', 'after', 'before']
164
164
  : method === 'members' ? ['chatId', 'cursor', 'offset', 'limit']
165
165
  : method === 'updateGroup' ? ['chatId', 'name', 'description']
package/src/client.js CHANGED
@@ -4,7 +4,7 @@ import { shortId } from './gateway.js';
4
4
  import { downloadFile } from './download.js';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { open } from 'node:fs/promises';
7
- import { buildRichText, readRichText } from './rich-text.js';
7
+ import { buildRichText, readRichText, requireEmojiKey } from './rich-text.js';
8
8
 
9
9
  function ids(values, label) {
10
10
  if (!Array.isArray(values)) throw new FeishuError('INVALID_ARGUMENT', `${label} must be a list.`);
@@ -26,6 +26,26 @@ function decodedPayload(gateway, response, type, operation) {
26
26
  export class LarkMateClient {
27
27
  constructor(gateway) { this.gateway = gateway; }
28
28
 
29
+ async emojiList({ query } = {}) {
30
+ if (query != null && (typeof query !== 'string' || query.length > 200)) throw new FeishuError('INVALID_ARGUMENT', 'emoji query must be at most 200 characters.');
31
+ const response = await this.gateway.call(142, 'PullEmojiResourcesV2Request', { needUserTenantResources: true, accessType: 1 },
32
+ { version: '8.5.0', operation: 'emoji-list' });
33
+ if (!response.packet.payload?.length) throw new FeishuError('INVALID_RESPONSE', 'No emoji resources were returned.');
34
+ let data; try { data = this.gateway.decode('PullEmojiResourcesV2Response', response.packet.payload); }
35
+ catch { throw new FeishuError('INVALID_RESPONSE', 'The emoji resource list was unreadable.'); }
36
+ const needle = (query || '').trim().toLocaleLowerCase();
37
+ const items = [];
38
+ for (const set of data.emojiResourceSet || []) for (const emoji of set.emojiResources || []) {
39
+ if (!emoji.key || emoji.isDeleted) continue;
40
+ const names = emoji.i18nText?.i18nTexts || {};
41
+ const name = names['zh-CN'] || emoji.i18nText?.defaultText || emoji.key;
42
+ const englishName = names['en-US'] || emoji.i18nText?.defaultText || null;
43
+ if (needle && ![emoji.key, name, englishName, ...Object.values(names)].some(value => typeof value === 'string' && value.toLocaleLowerCase().includes(needle))) continue;
44
+ items.push({ key: emoji.key, name, englishName, source: ({ 1: 'default', 2: 'tenant', 3: 'other_tenant' })[set.setSource] || 'unknown', skinKeys: emoji.skinKeys || [] });
45
+ }
46
+ return { items };
47
+ }
48
+
29
49
  async contactAlias({ userId }) {
30
50
  requireInt64Id(userId, 'user ID');
31
51
  const r = await this.gateway.call(5031, 'PullContactProfileV2Request', { scene: 1, userId, useNewLayout: true }, { operation: 'contact-alias' });
@@ -508,13 +528,14 @@ export class LarkMateClient {
508
528
  return { items, hasMore: !!result.hasMore };
509
529
  }
510
530
 
511
- async send({ chatId, text, mentions = [], replyTo, replyRoot }) {
531
+ async send({ chatId, text, mentions = [], emojis = [], replyTo, replyRoot }) {
512
532
  requireNumericId(chatId, 'chat ID');
513
533
  requireText(text, 'text');
514
534
  if (replyTo) requireNumericId(replyTo, 'reply message ID');
515
535
  if (replyRoot) requireNumericId(replyRoot, 'reply root ID');
516
536
  if (replyRoot && !replyTo) throw new FeishuError('INVALID_ARGUMENT', 'reply-root requires reply-to.');
517
537
  if (!Array.isArray(mentions)) throw new FeishuError('INVALID_ARGUMENT', 'mentions must be a list.');
538
+ if (!Array.isArray(emojis)) throw new FeishuError('INVALID_ARGUMENT', 'emojis must be a list.');
518
539
  await this.gateway.authenticate();
519
540
  const elementIds = [];
520
541
  const atIds = [];
@@ -523,9 +544,10 @@ export class LarkMateClient {
523
544
  for (const mention of mentions) {
524
545
  if (mention.id !== 'all') requireNumericId(mention.id, 'mention ID');
525
546
  const marker = `@${requireText(mention.name, 'mention name')}`;
526
- if (markers.has(marker) && markers.get(marker) !== mention.id) throw new FeishuError('INVALID_ARGUMENT', 'A mention name cannot identify multiple users.');
527
- markers.set(marker, mention.id);
547
+ if (markers.has(marker) && markers.get(marker).userId !== mention.id) throw new FeishuError('INVALID_ARGUMENT', 'A mention name cannot identify multiple users.');
548
+ markers.set(marker, { type: 'mention', userId: mention.id });
528
549
  }
550
+ for (const key of emojis) markers.set(`:${requireEmojiKey(key)}:`, { type: 'emoji', key });
529
551
  const found = new Set();
530
552
  const addText = part => {
531
553
  if (!part) return;
@@ -536,20 +558,22 @@ export class LarkMateClient {
536
558
  let position = 0;
537
559
  while (position < text.length) {
538
560
  let next = null;
539
- for (const [marker, userId] of markers) {
561
+ for (const [marker, value] of markers) {
540
562
  const index = text.indexOf(marker, position);
541
- if (index >= 0 && (!next || index < next.index || index === next.index && marker.length > next.marker.length)) next = { marker, userId, index };
563
+ if (index >= 0 && (!next || index < next.index || index === next.index && marker.length > next.marker.length)) next = { marker, value, index };
542
564
  }
543
565
  if (!next) break;
544
566
  addText(text.slice(position, next.index));
545
567
  const id = shortId();
546
568
  elementIds.push(id);
547
- atIds.push(id);
548
- dictionary[id] = { tag: 5, property: this.gateway.encode('AtProperty', { userId: next.userId, content: next.marker }) };
569
+ if (next.value.type === 'mention') {
570
+ atIds.push(id);
571
+ dictionary[id] = { tag: 5, property: this.gateway.encode('AtProperty', { userId: next.value.userId, content: next.marker }) };
572
+ } else dictionary[id] = { tag: 10, property: this.gateway.encode('EmotionProperty', { key: next.value.key }) };
549
573
  found.add(next.marker);
550
574
  position = next.index + next.marker.length;
551
575
  }
552
- if (found.size !== markers.size) throw new FeishuError('INVALID_ARGUMENT', 'The mention marker is absent from the text.');
576
+ if (found.size !== markers.size) throw new FeishuError('INVALID_ARGUMENT', 'A mention or emoji marker is absent from the text.');
553
577
  addText(text.slice(position));
554
578
  const cid = shortId();
555
579
  const response = await this.gateway.call(5, 'PutMessageRequest', {
package/src/rich-text.js CHANGED
@@ -4,6 +4,11 @@ import { shortId } from './gateway.js';
4
4
  const ownKeys = (value, allowed) => value && typeof value === 'object' && !Array.isArray(value)
5
5
  && Object.keys(value).every(key => allowed.includes(key));
6
6
 
7
+ export function requireEmojiKey(key) {
8
+ if (typeof key !== 'string' || !/^[A-Za-z0-9_+.-]{1,128}$/.test(key)) throw new FeishuError('INVALID_ARGUMENT', 'emoji key must be a Feishu emoji name.');
9
+ return key;
10
+ }
11
+
7
12
  // RichText can contain nested paragraphs, and innerText can be empty even when
8
13
  // the element dictionary contains readable text, mentions, or links.
9
14
  export function readRichText(gateway, richText, fallback = null) {
@@ -22,6 +27,10 @@ export function readRichText(gateway, richText, fallback = null) {
22
27
  const start = segments.length;
23
28
  for (const child of element.childIds || []) visit(child);
24
29
  if (segments.length > start && !segments.at(-1).text?.endsWith('\n')) segments.push({ type: 'text', text: '\n' });
30
+ } else if (element.tag === 10) {
31
+ const property = gateway.decode('EmotionProperty', element.property || new Uint8Array());
32
+ if (!Object.hasOwn(property, 'key') || !property.key) { incomplete = true; return; }
33
+ segments.push({ type: 'emoji', key: property.key, text: `:${property.key}:` });
25
34
  } else if ([1, 5, 6].includes(element.tag)) {
26
35
  const type = element.tag === 1 ? 'TextProperty' : element.tag === 5 ? 'AtProperty' : 'AnchorProperty';
27
36
  const property = gateway.decode(type, element.property || new Uint8Array());
@@ -54,8 +63,8 @@ export function buildRichText(gateway, parts) {
54
63
  if (!Array.isArray(parts) || parts.length === 0 || parts.length > 1000) throw new FeishuError('INVALID_ARGUMENT', 'segments must contain 1 to 1000 items.');
55
64
  const elementIds = [], atIds = [], anchorIds = [], dictionary = {}, texts = [];
56
65
  for (const part of parts) {
57
- if (!ownKeys(part, ['type', 'text', 'userId', 'url'])) throw new FeishuError('INVALID_ARGUMENT', 'Invalid rich text segment.');
58
- const text = part.text;
66
+ if (!ownKeys(part, ['type', 'text', 'userId', 'url', 'key'])) throw new FeishuError('INVALID_ARGUMENT', 'Invalid rich text segment.');
67
+ const text = part.type === 'emoji' ? `:${requireEmojiKey(part.key)}:` : part.text;
59
68
  if (typeof text !== 'string' || text.length === 0) throw new FeishuError('INVALID_ARGUMENT', 'segment text must not be empty.');
60
69
  const id = shortId();
61
70
  let tag, property;
@@ -70,6 +79,8 @@ export function buildRichText(gateway, parts) {
70
79
  let url; try { url = new URL(part.url); } catch { throw new FeishuError('INVALID_ARGUMENT', 'A link must have an HTTP or HTTPS URL.'); }
71
80
  if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new FeishuError('INVALID_ARGUMENT', 'A link must have an HTTP or HTTPS URL without credentials.');
72
81
  tag = 6; property = gateway.encode('AnchorProperty', { href: part.url, content: text, textContent: text }); anchorIds.push(id);
82
+ } else if (part.type === 'emoji' && ownKeys(part, ['type', 'key'])) {
83
+ tag = 10; property = gateway.encode('EmotionProperty', { key: part.key });
73
84
  } else throw new FeishuError('INVALID_ARGUMENT', 'Unsupported rich text segment.');
74
85
  elementIds.push(id); dictionary[id] = { tag, property }; texts.push(text);
75
86
  }