Skip to content

Commit a485bfd

Browse files
author
linyuan.yang
committed
lark 增加 获取群组列表
1 parent bd4519a commit a485bfd

3 files changed

Lines changed: 80 additions & 0 deletions

File tree

‎packages/channel.lark/src/LarkService.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,19 @@ export interface LarkHistoryMessage {
9696
content: MessageContent;
9797
}
9898

99+
export interface LarkChatListItem {
100+
chat_id: string;
101+
avatar?: string;
102+
name?: string;
103+
description?: string;
104+
owner_id?: string;
105+
owner_id_type?: string;
106+
external?: boolean;
107+
tenant_key?: string;
108+
labels?: string[];
109+
chat_status?: 'normal' | 'dissolved' | 'dissolved_save';
110+
}
111+
99112
export interface LarkServiceOptions {
100113
appId: string;
101114
appSecret: string;
@@ -327,6 +340,51 @@ export class LarkService implements IChannelService {
327340
}
328341
}
329342

343+
/** https://open.feishu.cn/document/server-docs/group/chat/list */
344+
async getChatList(options?: {
345+
limit?: number;
346+
sortType?: 'ByCreateTimeAsc' | 'ByActiveTimeDesc';
347+
filter?: (chat: any) => boolean;
348+
}): Promise<{ items: LarkChatListItem[]; hasMore: boolean }> {
349+
const limit = options?.limit ?? 100;
350+
let currentPage: any;
351+
let currentItem: any;
352+
try {
353+
const iter = await this.larkClient.im.v1.chat.listWithIterator({
354+
params: {
355+
user_id_type: this.userIdType as any,
356+
sort_type: options?.sortType ?? 'ByActiveTimeDesc',
357+
},
358+
});
359+
const items: LarkChatListItem[] = [];
360+
for await (const page of iter) {
361+
currentPage = page;
362+
for (const item of page?.items ?? []) {
363+
currentItem = item;
364+
if (item.chat_status && item.chat_status !== 'normal') continue;
365+
if (options?.filter && !options.filter(item)) continue;
366+
items.push({
367+
chat_id: item.chat_id ?? '',
368+
avatar: item.avatar,
369+
name: item.name,
370+
description: item.description,
371+
owner_id: item.owner_id,
372+
owner_id_type: item.owner_id_type,
373+
external: item.external,
374+
tenant_key: item.tenant_key,
375+
labels: item.labels,
376+
chat_status: item.chat_status,
377+
});
378+
if (items.length >= limit) return { items, hasMore: true };
379+
}
380+
}
381+
return { items, hasMore: false };
382+
} catch (error: any) {
383+
this.logger?.error(`Error getting chat list: ${error.message}\n${error.stack}\ncurrentItem: ${JSON.stringify(currentItem, null, 2)}\ncurrentPage: ${JSON.stringify(currentPage, null, 2)}`);
384+
return { items: [], hasMore: false };
385+
}
386+
}
387+
330388
private async getTenantAccessToken(): Promise<string> {
331389
if (this.tenantAccessToken && NowDate() < this.tokenExpireTime) {
332390
return this.tenantAccessToken;

‎packages/channel.lark/src/LarkSessionHandler.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,27 @@ Returns a map of question label → answer (string for radio/input, string[] for
248248
return `Message sent successfully.`;
249249
},
250250
}),
251+
new DynamicStructuredTool({
252+
name: '_get_chat_list',
253+
description: 'List all Lark groups the bot has joined. Returns chat_id, name, description, and other metadata for each group. Useful for broadcasting or for the user to pick a target chat.',
254+
schema: z.object({
255+
limit: z.number().optional().describe('Max number of chats to return (default 100).'),
256+
sort_type: z.enum(['ByCreateTimeAsc', 'ByActiveTimeDesc']).optional().describe('Sort order. Defaults to "ByActiveTimeDesc".'),
257+
name_keyword: z.string().optional().describe('If set, only return chats whose name contains this substring (case-insensitive).'),
258+
}),
259+
func: async ({ limit, sort_type, name_keyword }) => {
260+
const kw = name_keyword?.toLowerCase();
261+
const { items, hasMore } = await this.larkService.getChatList({
262+
limit,
263+
sortType: sort_type,
264+
filter: kw ? (c) => (c.name ?? '').toLowerCase().includes(kw) : undefined,
265+
});
266+
const lines = items.map((c) =>
267+
`<chat id="${c.chat_id}" name="${c.name ?? ''}" external="${c.external ?? false}">${c.description ?? ''}</chat>`
268+
);
269+
return `<chat-list count="${items.length}" has_more="${hasMore}">\n${lines.join('\n')}\n</chat-list>`;
270+
},
271+
}),
251272
new DynamicStructuredTool({
252273
name: '_get_message_history',
253274
description: 'Retrieve message history from the current Lark chat in reverse chronological order (newest first). To paginate older messages, pass the previous response\'s "oldest_time" attribute as the next call\'s "end_time".',

‎packages/channel.lark/src/plugin.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export const larkPlugin: ChannelPlugin = {
2929
{ name: '_send_file', label: '发送文件' },
3030
{ name: '_send_message', label: '发送消息' },
3131
{ name: '_get_message_history', label: '获取消息历史' },
32+
{ name: '_get_chat_list', label: '获取群组列表' },
3233
],
3334

3435
async init(ctx: ChannelPluginContext): Promise<IChannelService | undefined> {

0 commit comments

Comments
 (0)