@zhin.js/adapter-lark 1.0.96 → 1.1.0

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.
Files changed (68) hide show
  1. package/CHANGELOG.md +641 -0
  2. package/README.md +70 -83
  3. package/adapters/lark.js +36 -0
  4. package/adapters/lark.ts +41 -0
  5. package/agent/PERMITS.md +22 -0
  6. package/agent/tools/add_members.ts +20 -0
  7. package/agent/tools/create_chat.ts +18 -0
  8. package/agent/tools/dissolve_chat.ts +16 -0
  9. package/agent/tools/get_user.ts +16 -0
  10. package/agent/tools/remove_managers.ts +20 -0
  11. package/agent/tools/set_managers.ts +20 -0
  12. package/agent/tools/update_chat.ts +21 -0
  13. package/agent/tools/upload_file.ts +23 -0
  14. package/commands/endpoint/add/[id].js +3 -0
  15. package/commands/endpoint/add/[id].ts +3 -0
  16. package/commands/endpoint/list.js +3 -0
  17. package/commands/endpoint/list.ts +3 -0
  18. package/commands/endpoint/remove/[id].js +3 -0
  19. package/commands/endpoint/remove/[id].ts +3 -0
  20. package/lib/client.d.ts +12 -0
  21. package/lib/client.js +2 -0
  22. package/lib/endpoint.d.ts +100 -0
  23. package/lib/endpoint.js +497 -0
  24. package/lib/index.d.ts +6 -15
  25. package/lib/index.js +6 -209
  26. package/lib/lark-endpoint-commands.d.ts +1 -0
  27. package/lib/lark-endpoint-commands.js +19 -0
  28. package/lib/lark-runtime-state.d.ts +1 -0
  29. package/lib/lark-runtime-state.js +6 -0
  30. package/lib/media-upload.d.ts +15 -0
  31. package/lib/media-upload.js +58 -0
  32. package/lib/platform-permit.d.ts +14 -0
  33. package/lib/platform-permit.js +35 -0
  34. package/lib/protocol.d.ts +123 -0
  35. package/lib/protocol.js +273 -0
  36. package/lib/webhook.d.ts +14 -0
  37. package/lib/webhook.js +73 -0
  38. package/package.json +63 -20
  39. package/plugin.js +19 -0
  40. package/schema.json +97 -0
  41. package/src/client.ts +16 -0
  42. package/src/endpoint.ts +590 -0
  43. package/src/index.ts +51 -227
  44. package/src/lark-endpoint-commands.ts +20 -0
  45. package/src/lark-runtime-state.ts +7 -0
  46. package/src/media-upload.ts +69 -0
  47. package/src/platform-permit.ts +50 -0
  48. package/src/protocol.ts +402 -0
  49. package/src/webhook.ts +110 -0
  50. package/lib/adapter.d.ts +0 -17
  51. package/lib/adapter.d.ts.map +0 -1
  52. package/lib/adapter.js +0 -45
  53. package/lib/adapter.js.map +0 -1
  54. package/lib/bot.d.ts +0 -82
  55. package/lib/bot.d.ts.map +0 -1
  56. package/lib/bot.js +0 -638
  57. package/lib/bot.js.map +0 -1
  58. package/lib/index.d.ts.map +0 -1
  59. package/lib/index.js.map +0 -1
  60. package/lib/types.d.ts +0 -63
  61. package/lib/types.d.ts.map +0 -1
  62. package/lib/types.js +0 -2
  63. package/lib/types.js.map +0 -1
  64. package/plugin.yml +0 -3
  65. package/src/adapter.ts +0 -55
  66. package/src/bot.ts +0 -712
  67. package/src/types.ts +0 -58
  68. /package/{skills/lark/SKILL.md → agent/skills/lark.md} +0 -0
package/src/bot.ts DELETED
@@ -1,712 +0,0 @@
1
- /**
2
- * 飞书/Lark Bot 实现
3
- */
4
- import { registerFetchRoute, type Router, type RouterContext } from "@zhin.js/host-router/router";
5
- import axios, { type AxiosInstance } from "axios";
6
- import { createHash } from "crypto";
7
- import { formatCompact, Bot, Message, MessageSegment, segment, SendContent, SendOptions } from 'zhin.js';
8
- import type { LarkBotConfig, LarkMessage, LarkEvent, AccessToken } from "./types.js";
9
- import type { LarkAdapter } from "./adapter.js";
10
-
11
- export class LarkBot implements Bot<LarkBotConfig, LarkMessage> {
12
- $connected: boolean
13
- private router: any
14
- private accessToken: AccessToken
15
- private axiosInstance: AxiosInstance
16
-
17
- get logger() {
18
- return this.adapter.plugin.logger;
19
- }
20
-
21
- get $id() {
22
- return this.$config.name;
23
- }
24
-
25
- constructor(public adapter: LarkAdapter, router: any, public $config: LarkBotConfig) {
26
- this.router = router;
27
- this.$connected = false;
28
- this.accessToken = { token: '', expires_in: 0, timestamp: 0 };
29
-
30
- // 设置 API 基础 URL
31
- const baseURL = $config.apiBaseUrl || ($config.isFeishu ?
32
- 'https://open.feishu.cn/open-apis' :
33
- 'https://open.larksuite.com/open-apis'
34
- );
35
-
36
- this.axiosInstance = axios.create({
37
- baseURL,
38
- timeout: 30000,
39
- headers: {
40
- 'Content-Type': 'application/json; charset=utf-8'
41
- }
42
- });
43
-
44
- // 设置请求拦截器,自动添加 access_token
45
- this.axiosInstance.interceptors.request.use(async (config) => {
46
- await this.ensureAccessToken();
47
- config.headers = config.headers;
48
- config.headers['Authorization'] = `Bearer ${this.accessToken.token}`;
49
- return config;
50
- });
51
-
52
- // 设置 webhook 路由
53
- this.setupWebhookRoute();
54
- }
55
-
56
- private setupWebhookRoute(): void {
57
- registerFetchRoute(this.router, "POST", this.$config.webhookPath, (ctx: RouterContext) => {
58
- void this.handleWebhook(ctx);
59
- });
60
- }
61
-
62
- private async handleWebhook(ctx: RouterContext): Promise<void> {
63
- try {
64
- const body = ctx.request.body;
65
-
66
- // 验证请求(如果配置了验证令牌)
67
- if (this.$config.verificationToken) {
68
- const token = ctx.get('x-lark-request-token');
69
- if (token !== this.$config.verificationToken) {
70
- this.logger.warn(formatCompact( { op: 'webhook', ok: false, error: 'invalid verification token' }));
71
- ctx.status = 403;
72
- ctx.body = 'Forbidden';
73
- return;
74
- }
75
- }
76
-
77
- // 签名验证(如果配置了加密密钥)
78
- if (this.$config.encryptKey) {
79
- const timestamp = ctx.get('x-lark-request-timestamp');
80
- const nonce = ctx.get('x-lark-request-nonce');
81
- const signature = ctx.get('x-lark-signature');
82
- const bodyStr = JSON.stringify(body);
83
-
84
- if (!timestamp || !nonce || !signature || !this.verifySignature(timestamp, nonce, bodyStr, signature)) {
85
- this.logger.warn(formatCompact( { op: 'webhook', ok: false, error: 'invalid signature' }));
86
- ctx.status = 403;
87
- ctx.body = 'Forbidden';
88
- return;
89
- }
90
- }
91
-
92
- const event = body as LarkEvent;
93
-
94
- // URL 验证挑战(首次配置 webhook 时)
95
- if (event.type === 'url_verification') {
96
- ctx.body = { challenge: (event as any).challenge };
97
- return;
98
- }
99
-
100
- // 处理消息事件
101
- if (event.type === 'event_callback' && event.event) {
102
- await this.handleEvent(event.event);
103
- }
104
-
105
- ctx.status = 200;
106
- ctx.body = { code: 0, msg: 'success' };
107
-
108
- } catch (error) {
109
- this.logger.error('Webhook error:', error);
110
- ctx.status = 500;
111
- ctx.body = { code: -1, msg: 'Internal Server Error' };
112
- }
113
- }
114
-
115
- private verifySignature(timestamp: string, nonce: string, body: string, signature: string): boolean {
116
- if (!this.$config.encryptKey) return true;
117
-
118
- try {
119
- const stringToSign = `${timestamp}${nonce}${this.$config.encryptKey}${body}`;
120
- const calculatedSignature = createHash('sha256').update(stringToSign).digest('hex');
121
- return calculatedSignature === signature;
122
- } catch (error) {
123
- this.logger.error('Signature verification error:', error);
124
- return false;
125
- }
126
- }
127
-
128
- private async handleEvent(event: any): Promise<void> {
129
- // 处理消息事件
130
- if (event.message) {
131
- const message = this.$formatMessage(event.message, event);
132
- this.adapter.emit('message.receive', message);
133
- this.logger.debug(formatCompact( {
134
- op: 'recv',
135
- bot: this.$config.name,
136
- channel: message.$channel.type,
137
- id: message.$channel.id,
138
- len: segment.raw(message.$content).length,
139
- }));
140
- }
141
- }
142
-
143
- // ================================================================================================
144
- // Token 管理
145
- // ================================================================================================
146
-
147
- private async ensureAccessToken(): Promise<void> {
148
- const now = Date.now();
149
- // 提前 5 分钟刷新 token
150
- if (this.accessToken.token && now < (this.accessToken.timestamp + (this.accessToken.expires_in - 300) * 1000)) {
151
- return;
152
- }
153
-
154
- await this.refreshAccessToken();
155
- }
156
-
157
- private async refreshAccessToken(): Promise<void> {
158
- try {
159
- const response = await axios.post(
160
- `${this.$config.apiBaseUrl || (this.$config.isFeishu ?
161
- 'https://open.feishu.cn/open-apis' :
162
- 'https://open.larksuite.com/open-apis'
163
- )}/auth/v3/tenant_access_token/internal`,
164
- {
165
- app_id: this.$config.appId,
166
- app_secret: this.$config.appSecret
167
- }
168
- );
169
-
170
- if (response.data.code === 0) {
171
- this.accessToken = {
172
- token: response.data.tenant_access_token,
173
- expires_in: response.data.expire,
174
- timestamp: Date.now()
175
- };
176
- this.logger.debug('Access token refreshed successfully');
177
- } else {
178
- throw new Error(`Failed to get access token: ${response.data.msg}`);
179
- }
180
- } catch (error) {
181
- this.logger.error('Failed to refresh access token:', error);
182
- throw error;
183
- }
184
- }
185
-
186
- // ================================================================================================
187
- // 消息格式化
188
- // ================================================================================================
189
-
190
- $formatMessage(msg: LarkMessage, event?: any): Message<LarkMessage> {
191
- const content = this.parseMessageContent(msg);
192
-
193
- // 确定聊天类型
194
- const chatType = msg.chat_id?.startsWith('oc_') ? 'group' : 'private';
195
-
196
- return Message.from(msg, {
197
- $id: msg.message_id || Date.now().toString(),
198
- $adapter: 'lark',
199
- $bot: this.$config.name,
200
- $sender: {
201
- id: msg.sender?.sender_id?.open_id || 'unknown',
202
- name: msg.sender?.sender_id?.user_id || msg.sender?.sender_id?.open_id || 'Unknown User'
203
- },
204
- $channel: {
205
- id: msg.chat_id || 'unknown',
206
- type: chatType as any
207
- },
208
- $content: content,
209
- $raw: JSON.stringify(msg),
210
- $timestamp: msg.create_time ? parseInt(msg.create_time) : Date.now(),
211
- $recall: async () => {
212
- await this.$recallMessage(msg.message_id || '');
213
- },
214
- $reply: async (content: SendContent): Promise<string> => {
215
- return await this.adapter.sendMessage({
216
- context: 'lark',
217
- bot: this.$config.name,
218
- id: msg.chat_id || 'unknown',
219
- type: chatType,
220
- content: content
221
- });
222
- }
223
- });
224
- }
225
-
226
- private parseMessageContent(msg: LarkMessage): MessageSegment[] {
227
- const content: MessageSegment[] = [];
228
-
229
- if (!msg.content || !msg.message_type) {
230
- return content;
231
- }
232
-
233
- try {
234
- const messageContent = JSON.parse(msg.content);
235
-
236
- switch (msg.message_type) {
237
- case 'text':
238
- if (messageContent.text) {
239
- content.push(segment('text', { content: messageContent.text }));
240
-
241
- // 处理 @提及
242
- if (msg.mentions) {
243
- for (const mention of msg.mentions) {
244
- if (mention.key && messageContent.text.includes(mention.key)) {
245
- content.push(segment('at', {
246
- id: mention.id?.open_id,
247
- name: mention.name
248
- }));
249
- }
250
- }
251
- }
252
- }
253
- break;
254
-
255
- case 'image':
256
- content.push(segment('image', {
257
- file_key: messageContent.image_key,
258
- url: `https://open.feishu.cn/open-apis/im/v1/messages/${msg.message_id}/resources/${messageContent.image_key}`
259
- }));
260
- break;
261
-
262
- case 'file':
263
- content.push(segment('file', {
264
- file_key: messageContent.file_key,
265
- file_name: messageContent.file_name,
266
- file_size: messageContent.file_size
267
- }));
268
- break;
269
-
270
- case 'audio':
271
- content.push(segment('audio', {
272
- file_key: messageContent.file_key,
273
- duration: messageContent.duration
274
- }));
275
- break;
276
-
277
- case 'video':
278
- content.push(segment('video', {
279
- file_key: messageContent.file_key,
280
- duration: messageContent.duration,
281
- width: messageContent.width,
282
- height: messageContent.height
283
- }));
284
- break;
285
-
286
- case 'sticker':
287
- content.push(segment('sticker', {
288
- file_key: messageContent.file_key
289
- }));
290
- break;
291
-
292
- case 'rich_text':
293
- // 富文本消息处理(简化)
294
- if (messageContent.content) {
295
- this.parseRichTextContent(messageContent.content, content);
296
- }
297
- break;
298
-
299
- case 'post':
300
- // 卡片消息处理
301
- content.push(segment('card', messageContent));
302
- break;
303
-
304
- default:
305
- content.push(segment('text', { content: `[不支持的消息类型: ${msg.message_type}]` }));
306
- break;
307
- }
308
- } catch (error) {
309
- this.logger.error('Failed to parse message content:', error);
310
- content.push(segment('text', { content: '[消息解析失败]' }));
311
- }
312
-
313
- return content;
314
- }
315
-
316
- private parseRichTextContent(richContent: any, content: MessageSegment[]): void {
317
- // 简化的富文本解析
318
- if (Array.isArray(richContent)) {
319
- for (const block of richContent) {
320
- if (block.tag === 'text' && block.text) {
321
- content.push(segment('text', { content: block.text }));
322
- } else if (block.tag === 'a' && block.href) {
323
- content.push(segment('link', {
324
- url: block.href,
325
- text: block.text || block.href
326
- }));
327
- } else if (block.tag === 'at' && block.user_id) {
328
- content.push(segment('at', {
329
- id: block.user_id,
330
- name: block.user_name
331
- }));
332
- }
333
- }
334
- }
335
- }
336
-
337
- // ================================================================================================
338
- // 消息发送
339
- // ================================================================================================
340
-
341
- async $sendMessage(options: SendOptions): Promise<string> {
342
- const chatId = options.id;
343
- const content = this.formatSendContent(options.content);
344
-
345
- try {
346
- const response = await this.axiosInstance.post('/im/v1/messages', {
347
- receive_id: chatId,
348
- receive_id_type: 'chat_id',
349
- msg_type: content.msg_type,
350
- content: content.content
351
- });
352
-
353
- if (response.data.code !== 0) {
354
- throw new Error(`Failed to send message: ${response.data.msg}`);
355
- }
356
-
357
- this.logger.debug('Message sent successfully:', response.data.data?.message_id);
358
- return response.data.data?.message_id || '';
359
- } catch (error) {
360
- this.logger.error('Failed to send message:', error);
361
- throw error;
362
- }
363
- }
364
- async $recallMessage(id:string):Promise<void> {
365
- await this.axiosInstance.post('/im/v1/messages/recall', {
366
- message_id: id
367
- });
368
- }
369
-
370
- private formatSendContent(content: SendContent): { msg_type: string, content: string } {
371
- if (typeof content === 'string') {
372
- return {
373
- msg_type: 'text',
374
- content: JSON.stringify({ text: content })
375
- };
376
- }
377
-
378
- if (Array.isArray(content)) {
379
- const textParts: string[] = [];
380
- let hasMedia = false;
381
- let mediaContent: any = null;
382
-
383
- for (const item of content) {
384
- if (typeof item === 'string') {
385
- textParts.push(item);
386
- } else {
387
- const segment = item as MessageSegment;
388
- switch (segment.type) {
389
- case 'text':
390
- textParts.push(segment.data.content || segment.data.text || '');
391
- break;
392
-
393
- case 'at':
394
- textParts.push(`<at user_id="${segment.data.id}">${segment.data.name || segment.data.id}</at>`);
395
- break;
396
-
397
- case 'image':
398
- if (!hasMedia) {
399
- hasMedia = true;
400
- mediaContent = {
401
- msg_type: 'image',
402
- content: JSON.stringify({
403
- image_key: segment.data.file_key || segment.data.key
404
- })
405
- };
406
- }
407
- break;
408
-
409
- case 'file':
410
- if (!hasMedia) {
411
- hasMedia = true;
412
- mediaContent = {
413
- msg_type: 'file',
414
- content: JSON.stringify({
415
- file_key: segment.data.file_key || segment.data.key
416
- })
417
- };
418
- }
419
- break;
420
-
421
- case 'card':
422
- if (!hasMedia) {
423
- hasMedia = true;
424
- mediaContent = {
425
- msg_type: 'interactive',
426
- content: JSON.stringify(segment.data)
427
- };
428
- }
429
- break;
430
- }
431
- }
432
- }
433
-
434
- // 优先发送媒体内容
435
- if (hasMedia && mediaContent) {
436
- return mediaContent;
437
- }
438
-
439
- // 否则发送文本内容
440
- return {
441
- msg_type: 'text',
442
- content: JSON.stringify({ text: textParts.join('') })
443
- };
444
- }
445
-
446
- return {
447
- msg_type: 'text',
448
- content: JSON.stringify({ text: String(content) })
449
- };
450
- }
451
-
452
- // ================================================================================================
453
- // Bot 生命周期
454
- // ================================================================================================
455
-
456
- async $connect(): Promise<void> {
457
- try {
458
- // 获取 access token
459
- await this.refreshAccessToken();
460
-
461
- this.$connected = true;
462
- this.logger.info(formatCompact({ bot: this.$config.name }));
463
- this.logger.info(formatCompact( { op: 'webhook', path: this.$config.webhookPath }));
464
-
465
- } catch (error) {
466
- this.logger.error('Failed to connect Lark bot:', error);
467
- throw error;
468
- }
469
- }
470
-
471
- async $disconnect(): Promise<void> {
472
- try {
473
- this.$connected = false;
474
- this.logger.info(formatCompact( { op: 'disconnect', bot: this.$config.name }));
475
- } catch (error) {
476
- this.logger.error('Error disconnecting Lark bot:', error);
477
- }
478
- }
479
-
480
- // ================================================================================================
481
- // 工具方法
482
- // ================================================================================================
483
-
484
- // 获取用户信息
485
- async getUserInfo(userId: string, userIdType: 'open_id' | 'user_id' | 'union_id' = 'open_id'): Promise<any> {
486
- try {
487
- const response = await this.axiosInstance.get(`/contact/v3/users/${userId}`, {
488
- params: { user_id_type: userIdType }
489
- });
490
-
491
- return response.data.data?.user;
492
- } catch (error) {
493
- this.logger.error('Failed to get user info:', error);
494
- return null;
495
- }
496
- }
497
-
498
- // 获取群聊信息
499
- async getChatInfo(chatId: string): Promise<any> {
500
- try {
501
- const response = await this.axiosInstance.get(`/im/v1/chats/${chatId}`);
502
- return response.data.data;
503
- } catch (error) {
504
- this.logger.error('Failed to get chat info:', error);
505
- return null;
506
- }
507
- }
508
-
509
- // 上传文件
510
- async uploadFile(filePath: string, fileType: 'image' | 'file' | 'video' | 'audio' = 'file'): Promise<string | null> {
511
- try {
512
- const FormData = require('form-data');
513
- const fs = require('fs');
514
-
515
- const form = new FormData();
516
- form.append('file', fs.createReadStream(filePath));
517
- form.append('file_type', fileType);
518
-
519
- const response = await this.axiosInstance.post('/im/v1/files', form, {
520
- headers: {
521
- ...form.getHeaders()
522
- }
523
- });
524
-
525
- if (response.data.code === 0) {
526
- return response.data.data.file_key;
527
- }
528
-
529
- throw new Error(`Upload failed: ${response.data.msg}`);
530
- } catch (error) {
531
- this.logger.error('Failed to upload file:', error);
532
- return null;
533
- }
534
- }
535
-
536
- // ==================== 群组管理 API ====================
537
-
538
- /**
539
- * 创建群聊
540
- * @param name 群名
541
- * @param userIds 成员 open_id 列表
542
- * @param ownerId 群主 open_id
543
- */
544
- async createChat(name: string, userIds: string[], ownerId?: string): Promise<string | null> {
545
- try {
546
- const response = await this.axiosInstance.post('/im/v1/chats', {
547
- name,
548
- user_id_list: userIds,
549
- owner_id: ownerId
550
- });
551
-
552
- if (response.data.code === 0) {
553
- this.logger.debug(formatCompact( { op: 'create_chat', chat: response.data.data.chat_id }));
554
- return response.data.data.chat_id;
555
- }
556
- throw new Error(`Failed to create chat: ${response.data.msg}`);
557
- } catch (error) {
558
- this.logger.error('Failed to create chat:', error);
559
- return null;
560
- }
561
- }
562
-
563
- /**
564
- * 更新群信息
565
- * @param chatId 群聊 ID
566
- * @param options 更新选项
567
- */
568
- async updateChatInfo(chatId: string, options: {
569
- name?: string;
570
- description?: string;
571
- }): Promise<boolean> {
572
- try {
573
- const response = await this.axiosInstance.put(`/im/v1/chats/${chatId}`, options);
574
-
575
- if (response.data.code === 0) {
576
- this.logger.debug(formatCompact( { op: 'update_chat', chat: chatId }));
577
- return true;
578
- }
579
- throw new Error(`Failed to update chat: ${response.data.msg}`);
580
- } catch (error) {
581
- this.logger.error('Failed to update chat:', error);
582
- return false;
583
- }
584
- }
585
-
586
- /**
587
- * 添加群成员
588
- * @param chatId 群聊 ID
589
- * @param userIds 用户 ID 列表
590
- */
591
- async addChatMembers(chatId: string, userIds: string[]): Promise<boolean> {
592
- try {
593
- const response = await this.axiosInstance.post(`/im/v1/chats/${chatId}/members`, {
594
- id_list: userIds
595
- });
596
-
597
- if (response.data.code === 0) {
598
- this.logger.debug(formatCompact( { op: 'add_member', chat: chatId }));
599
- return true;
600
- }
601
- throw new Error(`Failed to add members: ${response.data.msg}`);
602
- } catch (error) {
603
- this.logger.error('Failed to add chat members:', error);
604
- return false;
605
- }
606
- }
607
-
608
- /**
609
- * 移除群成员
610
- * @param chatId 群聊 ID
611
- * @param userIds 用户 ID 列表
612
- */
613
- async removeChatMembers(chatId: string, userIds: string[]): Promise<boolean> {
614
- try {
615
- const response = await this.axiosInstance.delete(`/im/v1/chats/${chatId}/members`, {
616
- data: { id_list: userIds }
617
- });
618
-
619
- if (response.data.code === 0) {
620
- this.logger.debug(formatCompact( { op: 'remove_member', chat: chatId }));
621
- return true;
622
- }
623
- throw new Error(`Failed to remove members: ${response.data.msg}`);
624
- } catch (error) {
625
- this.logger.error('Failed to remove chat members:', error);
626
- return false;
627
- }
628
- }
629
-
630
- /**
631
- * 获取群成员列表
632
- * @param chatId 群聊 ID
633
- */
634
- async getChatMembers(chatId: string): Promise<any[]> {
635
- try {
636
- const response = await this.axiosInstance.get(`/im/v1/chats/${chatId}/members`);
637
-
638
- if (response.data.code === 0) {
639
- return response.data.data.items || [];
640
- }
641
- throw new Error(`Failed to get members: ${response.data.msg}`);
642
- } catch (error) {
643
- this.logger.error('Failed to get chat members:', error);
644
- return [];
645
- }
646
- }
647
-
648
- /**
649
- * 解散群聊
650
- * @param chatId 群聊 ID
651
- */
652
- async dissolveChat(chatId: string): Promise<boolean> {
653
- try {
654
- const response = await this.axiosInstance.delete(`/im/v1/chats/${chatId}`);
655
-
656
- if (response.data.code === 0) {
657
- this.logger.debug(formatCompact( { op: 'delete_chat', chat: chatId }));
658
- return true;
659
- }
660
- throw new Error(`Failed to dissolve chat: ${response.data.msg}`);
661
- } catch (error) {
662
- this.logger.error('Failed to dissolve chat:', error);
663
- return false;
664
- }
665
- }
666
-
667
- /**
668
- * 设置群管理员
669
- * @param chatId 群聊 ID
670
- * @param userIds 用户 ID 列表
671
- */
672
- async setChatManagers(chatId: string, userIds: string[]): Promise<boolean> {
673
- try {
674
- const response = await this.axiosInstance.post(`/im/v1/chats/${chatId}/managers/add_managers`, {
675
- manager_ids: userIds
676
- });
677
-
678
- if (response.data.code === 0) {
679
- this.logger.debug(formatCompact( { op: 'set_admin', chat: chatId }));
680
- return true;
681
- }
682
- throw new Error(`Failed to set managers: ${response.data.msg}`);
683
- } catch (error) {
684
- this.logger.error('Failed to set chat managers:', error);
685
- return false;
686
- }
687
- }
688
-
689
- /**
690
- * 移除群管理员
691
- * @param chatId 群聊 ID
692
- * @param userIds 用户 ID 列表
693
- */
694
- async removeChatManagers(chatId: string, userIds: string[]): Promise<boolean> {
695
- try {
696
- const response = await this.axiosInstance.post(`/im/v1/chats/${chatId}/managers/delete_managers`, {
697
- manager_ids: userIds
698
- });
699
-
700
- if (response.data.code === 0) {
701
- this.logger.debug(formatCompact( { op: 'remove_admin', chat: chatId }));
702
- return true;
703
- }
704
- throw new Error(`Failed to remove managers: ${response.data.msg}`);
705
- } catch (error) {
706
- this.logger.error('Failed to remove chat managers:', error);
707
- return false;
708
- }
709
- }
710
- }
711
-
712
- // 定义 Adapter 类