@zhin.js/adapter-dingtalk 1.0.80 → 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 (65) hide show
  1. package/CHANGELOG.md +621 -0
  2. package/README.md +67 -333
  3. package/adapters/dingtalk.js +33 -0
  4. package/adapters/dingtalk.ts +38 -0
  5. package/agent/PERMITS.md +19 -0
  6. package/agent/tools/add_chat_members.ts +20 -0
  7. package/agent/tools/create_chat.ts +21 -0
  8. package/agent/tools/dept_info.ts +15 -0
  9. package/agent/tools/get_dept_users.ts +16 -0
  10. package/agent/tools/get_user.ts +15 -0
  11. package/agent/tools/list_departments.ts +16 -0
  12. package/agent/tools/send_work_notice.ts +18 -0
  13. package/agent/tools/update_chat.ts +25 -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/dingtalk-endpoint-commands.d.ts +1 -0
  23. package/lib/dingtalk-endpoint-commands.js +18 -0
  24. package/lib/dingtalk-runtime-state.d.ts +1 -0
  25. package/lib/dingtalk-runtime-state.js +6 -0
  26. package/lib/endpoint.d.ts +72 -0
  27. package/lib/endpoint.js +353 -0
  28. package/lib/index.d.ts +5 -15
  29. package/lib/index.js +5 -214
  30. package/lib/platform-permit.d.ts +14 -0
  31. package/lib/platform-permit.js +33 -0
  32. package/lib/protocol.d.ts +134 -0
  33. package/lib/protocol.js +265 -0
  34. package/lib/webhook.d.ts +13 -0
  35. package/lib/webhook.js +47 -0
  36. package/package.json +64 -18
  37. package/plugin.js +19 -0
  38. package/schema.json +92 -0
  39. package/src/client.ts +16 -0
  40. package/src/dingtalk-endpoint-commands.ts +19 -0
  41. package/src/dingtalk-runtime-state.ts +7 -0
  42. package/src/endpoint.ts +439 -0
  43. package/src/index.ts +44 -228
  44. package/src/platform-permit.ts +48 -0
  45. package/src/protocol.ts +385 -0
  46. package/src/webhook.ts +75 -0
  47. package/lib/adapter.d.ts +0 -16
  48. package/lib/adapter.d.ts.map +0 -1
  49. package/lib/adapter.js +0 -37
  50. package/lib/adapter.js.map +0 -1
  51. package/lib/bot.d.ts +0 -46
  52. package/lib/bot.d.ts.map +0 -1
  53. package/lib/bot.js +0 -539
  54. package/lib/bot.js.map +0 -1
  55. package/lib/index.d.ts.map +0 -1
  56. package/lib/index.js.map +0 -1
  57. package/lib/types.d.ts +0 -58
  58. package/lib/types.d.ts.map +0 -1
  59. package/lib/types.js +0 -5
  60. package/lib/types.js.map +0 -1
  61. package/plugin.yml +0 -3
  62. package/src/adapter.ts +0 -44
  63. package/src/bot.ts +0 -590
  64. package/src/types.ts +0 -56
  65. /package/{skills/dingtalk/SKILL.md → agent/skills/dingtalk.md} +0 -0
@@ -0,0 +1,385 @@
1
+ /**
2
+ * DingTalk protocol helpers — no legacy Adapter/Endpoint / segment-mapper.
3
+ * Canonicalization is owned by gateway/core before endpoint.send.
4
+ */
5
+
6
+ import { createHmac, timingSafeEqual } from 'node:crypto';
7
+ import type { IncomingMessage } from 'node:http';
8
+
9
+ import { isMediaRef } from '@zhin.js/core';
10
+ import type { ConversationRef } from '@zhin.js/im-contract';
11
+ import { formatCompact, getLogger } from '@zhin.js/logger';
12
+
13
+ const logger = getLogger('dingtalk');
14
+
15
+ /** Plugin Runtime owner config (`plugins.<instanceKey>` / schema.json). */
16
+ export interface DingTalkAdapterConfig {
17
+ readonly id?: string;
18
+ readonly appKey?: string;
19
+ readonly appSecret?: string;
20
+ readonly webhookPath?: string;
21
+ readonly robotCode?: string;
22
+ readonly apiBaseUrl?: string;
23
+ /** Transitional: legacy root `endpoints[]` with `context: dingtalk`. */
24
+ readonly endpoints?: ReadonlyArray<Partial<ResolvedDingTalkConfig> & {
25
+ readonly context?: string;
26
+ }>;
27
+ }
28
+
29
+ export interface ResolvedDingTalkConfig {
30
+ readonly context: 'dingtalk';
31
+ readonly id: string;
32
+ readonly appKey: string;
33
+ readonly appSecret: string;
34
+ readonly webhookPath: string;
35
+ readonly robotCode?: string;
36
+ readonly apiBaseUrl: string;
37
+ }
38
+
39
+ export interface DingTalkMessage {
40
+ readonly msgtype?: string;
41
+ readonly text?: { readonly content?: string };
42
+ readonly msgId?: string;
43
+ readonly createAt?: number;
44
+ readonly conversationType?: string;
45
+ readonly conversationId?: string;
46
+ readonly senderId?: string;
47
+ readonly senderNick?: string;
48
+ readonly senderCorpId?: string;
49
+ readonly sessionWebhook?: string;
50
+ readonly chatbotCorpId?: string;
51
+ readonly chatbotUserId?: string;
52
+ readonly isAdmin?: boolean;
53
+ readonly senderStaffId?: string;
54
+ readonly atUsers?: ReadonlyArray<{ readonly dingtalkId?: string; readonly staffId?: string }>;
55
+ readonly content?: Record<string, unknown>;
56
+ }
57
+
58
+ export interface DingTalkEvent extends DingTalkMessage {
59
+ readonly [key: string]: unknown;
60
+ }
61
+
62
+ /**
63
+ * 钉钉回调消息 @ 机器人判定:机器人被 @ 时回调带 `isInAtList: true`;
64
+ * 部分回调形态的 `atUserIds` / `atUsers[].dingtalkId` 会包含机器人 robotCode(来自配置)。
65
+ * 两者都不满足则不标注。
66
+ */
67
+ export function isDingtalkBotMentioned(event: DingTalkMessage, robotCode?: string): boolean {
68
+ const extra = event as DingTalkMessage & {
69
+ readonly isInAtList?: unknown;
70
+ readonly atUserIds?: unknown;
71
+ };
72
+ if (extra.isInAtList === true) return true;
73
+ if (!robotCode) return false;
74
+ if (Array.isArray(extra.atUserIds) && extra.atUserIds.some((id) => String(id) === robotCode)) {
75
+ return true;
76
+ }
77
+ return (event.atUsers ?? []).some((user) => user.dingtalkId === robotCode);
78
+ }
79
+
80
+ export interface AccessToken {
81
+ token: string;
82
+ expires_in: number;
83
+ timestamp: number;
84
+ }
85
+
86
+ export interface DingTalkApiResponse {
87
+ readonly errcode: number;
88
+ readonly errmsg?: string;
89
+ readonly access_token?: string;
90
+ readonly expires_in?: number;
91
+ readonly msgId?: string;
92
+ readonly chatid?: string;
93
+ readonly result?: unknown;
94
+ readonly chat_info?: unknown;
95
+ readonly [key: string]: unknown;
96
+ }
97
+
98
+ export interface DingTalkWireSegment {
99
+ readonly type: string;
100
+ readonly data?: Record<string, unknown>;
101
+ }
102
+
103
+ export interface DingTalkSendBody {
104
+ readonly msgtype: string;
105
+ readonly text?: { readonly content: string };
106
+ readonly picture?: { readonly picURL: string };
107
+ readonly markdown?: { readonly title: string; readonly text: string };
108
+ readonly link?: {
109
+ readonly title: string;
110
+ readonly text: string;
111
+ readonly messageUrl?: string;
112
+ readonly picUrl?: string;
113
+ };
114
+ readonly at?: { readonly atUserIds: string[]; readonly isAtAll: boolean };
115
+ readonly robotCode?: string;
116
+ }
117
+
118
+ export function resolveDingTalkConfig(config: DingTalkAdapterConfig = {}): ResolvedDingTalkConfig {
119
+ const entry = config.endpoints?.find((item) => item.context === 'dingtalk');
120
+ const appKey = config.appKey ?? entry?.appKey ?? process.env.DINGTALK_APP_KEY;
121
+ const appSecret = config.appSecret ?? entry?.appSecret ?? process.env.DINGTALK_APP_SECRET;
122
+ if (!appKey || !appSecret) {
123
+ throw new TypeError(
124
+ 'DingTalk adapter requires appKey + appSecret (plugins.<key> or endpoints with context: dingtalk)',
125
+ );
126
+ }
127
+ const id = (typeof config.id === 'string' && config.id)
128
+ || (typeof entry?.id === 'string' && entry.id)
129
+ || process.env.DINGTALK_BOT_NAME
130
+ || 'dingtalk-bot';
131
+ const webhookPath = normalizeWebhookPath(
132
+ config.webhookPath ?? entry?.webhookPath ?? '/dingtalk/webhook',
133
+ );
134
+ const apiBaseUrl = (
135
+ config.apiBaseUrl ?? entry?.apiBaseUrl ?? 'https://oapi.dingtalk.com'
136
+ ).replace(/\/$/, '');
137
+ const robotCode = config.robotCode ?? entry?.robotCode;
138
+ return {
139
+ context: 'dingtalk',
140
+ id,
141
+ appKey,
142
+ appSecret,
143
+ webhookPath,
144
+ ...(robotCode ? { robotCode } : {}),
145
+ apiBaseUrl,
146
+ };
147
+ }
148
+
149
+ export function normalizeWebhookPath(path: string): string {
150
+ const trimmed = path.trim() || '/dingtalk/webhook';
151
+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
152
+ }
153
+
154
+ export function resolveChatType(conversationType?: string): 'group' | 'private' {
155
+ return conversationType === '2' ? 'group' : 'private';
156
+ }
157
+
158
+ /**
159
+ * 入站归一化 → ConversationRef:`conversationType: '2'` 为群会话(kind 'group'),
160
+ * 其余为单聊(kind 'private');会话原生 id 取 conversationId,缺省回退 senderId。
161
+ * 钉钉无 guild/频道容器概念,不产生 parent。
162
+ */
163
+ export function dingtalkInboundConversation(endpointKey: string, msg: DingTalkMessage): ConversationRef {
164
+ return {
165
+ endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey },
166
+ kind: resolveChatType(msg.conversationType),
167
+ id: msg.conversationId || msg.senderId || 'unknown',
168
+ };
169
+ }
170
+
171
+ export function resolveSender(msg: DingTalkMessage): string {
172
+ return msg.senderId || msg.senderStaffId || 'unknown';
173
+ }
174
+
175
+ export function generateMessageId(msg: DingTalkMessage): string {
176
+ return msg.msgId || `${msg.createAt ?? Date.now()}`;
177
+ }
178
+
179
+ /** Build inbound text for OutboundMessageService.receive. */
180
+ export function formatInboundContent(msg: DingTalkMessage): string {
181
+ if (!msg.msgtype) return '';
182
+ switch (msg.msgtype) {
183
+ case 'text':
184
+ return msg.text?.content || '';
185
+ case 'picture':
186
+ return '[image]';
187
+ case 'file': {
188
+ const name = typeof msg.content?.fileName === 'string' ? msg.content.fileName : '';
189
+ return name ? `[file: ${name}]` : '[file]';
190
+ }
191
+ case 'audio':
192
+ return '[audio]';
193
+ case 'video':
194
+ return '[video]';
195
+ case 'richText': {
196
+ const rich = msg.content?.richText;
197
+ if (Array.isArray(rich)) {
198
+ return rich
199
+ .map((item) => (item && typeof item === 'object' && 'text' in item
200
+ ? String((item as { text?: string }).text || '')
201
+ : ''))
202
+ .join('');
203
+ }
204
+ return '[richText]';
205
+ }
206
+ case 'markdown':
207
+ return typeof msg.content?.text === 'string' ? msg.content.text : '[markdown]';
208
+ default:
209
+ return `[${msg.msgtype}]`;
210
+ }
211
+ }
212
+
213
+ /** DingTalk timestamps are epoch milliseconds; reject replays outside ±1 hour. */
214
+ export const MAX_TIMESTAMP_DRIFT_MS = 60 * 60 * 1000;
215
+
216
+ export function verifySignature(
217
+ appSecret: string,
218
+ timestamp: string,
219
+ sign: string,
220
+ ): boolean {
221
+ try {
222
+ const ts = Number(timestamp);
223
+ if (!Number.isFinite(ts) || Math.abs(Date.now() - ts) > MAX_TIMESTAMP_DRIFT_MS) {
224
+ return false;
225
+ }
226
+ const stringToSign = `${timestamp}\n${appSecret}`;
227
+ const hmac = createHmac('sha256', appSecret);
228
+ hmac.update(stringToSign);
229
+ const calculated = hmac.digest('base64');
230
+ const a = Buffer.from(calculated);
231
+ const b = Buffer.from(sign);
232
+ if (a.length !== b.length) return false;
233
+ return timingSafeEqual(a, b);
234
+ } catch {
235
+ return false;
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Wire-encode an already-rendered outbound payload into DingTalk robot body.
241
+ * Segment canonicalization is intentionally not done here: media segments carry
242
+ * the canonical `data.media` MediaRef and nothing else is consulted.
243
+ *
244
+ * 钉钉机器人媒体消息仅支持远程 URL(picture.picURL):
245
+ * - image 段 kind=url → 直发 picture;
246
+ * - 其余 kind / audio / video / file 段无投递面,warn + 丢弃。
247
+ */
248
+ export function formatOutboundBody(payload: unknown): DingTalkSendBody {
249
+ if (typeof payload === 'string') {
250
+ return { msgtype: 'text', text: { content: payload } };
251
+ }
252
+
253
+ const items: Array<string | DingTalkWireSegment> = Array.isArray(payload)
254
+ ? payload as Array<string | DingTalkWireSegment>
255
+ : payload && typeof payload === 'object' && 'type' in (payload as object)
256
+ ? [payload as DingTalkWireSegment]
257
+ : [];
258
+
259
+ if (items.length === 0) {
260
+ const text = payload == null
261
+ ? ''
262
+ : typeof payload === 'object'
263
+ ? JSON.stringify(payload)
264
+ : String(payload);
265
+ return { msgtype: 'text', text: { content: text } };
266
+ }
267
+
268
+ const textParts: string[] = [];
269
+ const atUserIds: string[] = [];
270
+ let media: DingTalkSendBody | null = null;
271
+ let markdownTitle: string | undefined;
272
+
273
+ for (const item of items) {
274
+ if (typeof item === 'string') {
275
+ textParts.push(item);
276
+ continue;
277
+ }
278
+ const data = item.data ?? {};
279
+ switch (item.type) {
280
+ case 'text':
281
+ textParts.push(String(data.content ?? data.text ?? ''));
282
+ break;
283
+ case 'at': {
284
+ const userId = data.id ?? data.userId;
285
+ if (userId) {
286
+ atUserIds.push(String(userId));
287
+ textParts.push(`@${String(data.name || userId)} `);
288
+ }
289
+ break;
290
+ }
291
+ case 'image': {
292
+ if (media) break;
293
+ const ref = data.media;
294
+ if (isMediaRef(ref) && ref.kind === 'url') {
295
+ media = {
296
+ msgtype: 'picture',
297
+ picture: { picURL: ref.value },
298
+ };
299
+ break;
300
+ }
301
+ logger.warn(formatCompact({
302
+ op: 'dingtalk_outbound_media_dropped',
303
+ type: item.type,
304
+ reason: isMediaRef(ref) ? `unsupported_kind:${ref.kind}` : 'missing_media_ref',
305
+ }));
306
+ break;
307
+ }
308
+ case 'audio':
309
+ case 'video':
310
+ case 'file':
311
+ // 钉钉机器人无音频/视频/文件投递面,warn + 丢弃
312
+ logger.warn(formatCompact({
313
+ op: 'dingtalk_outbound_media_dropped',
314
+ type: item.type,
315
+ reason: 'undeliverable_msgtype',
316
+ }));
317
+ break;
318
+ case 'markdown':
319
+ markdownTitle ??= String(data.title || '消息');
320
+ textParts.push(String(data.content ?? data.text ?? ''));
321
+ break;
322
+ case 'link':
323
+ if (!media) {
324
+ media = {
325
+ msgtype: 'link',
326
+ link: {
327
+ title: String(data.title || '链接'),
328
+ text: String(data.text ?? data.content ?? ''),
329
+ messageUrl: typeof data.url === 'string' ? data.url : undefined,
330
+ picUrl: typeof data.picUrl === 'string' ? data.picUrl : undefined,
331
+ },
332
+ };
333
+ }
334
+ break;
335
+ default:
336
+ textParts.push(`[${item.type}]`);
337
+ }
338
+ }
339
+
340
+ if (media) return media;
341
+ if (markdownTitle !== undefined) {
342
+ return {
343
+ msgtype: 'markdown',
344
+ markdown: { title: markdownTitle, text: textParts.join('') },
345
+ ...(atUserIds.length > 0 ? { at: { atUserIds, isAtAll: false } } : {}),
346
+ };
347
+ }
348
+
349
+ const result: DingTalkSendBody = {
350
+ msgtype: 'text',
351
+ text: { content: textParts.join('') },
352
+ };
353
+ if (atUserIds.length > 0) {
354
+ return { ...result, at: { atUserIds, isAtAll: false } };
355
+ }
356
+ return result;
357
+ }
358
+
359
+ export function headerValue(
360
+ headers: IncomingMessage['headers'],
361
+ name: string,
362
+ ): string {
363
+ const value = headers[name] ?? headers[name.toLowerCase()];
364
+ if (Array.isArray(value)) return value[0] ?? '';
365
+ return value ?? '';
366
+ }
367
+
368
+ export async function readTextBody(
369
+ request: IncomingMessage,
370
+ options: { readonly limit?: number } = {},
371
+ ): Promise<string> {
372
+ const limit = options.limit ?? 1_048_576;
373
+ const chunks: Buffer[] = [];
374
+ let size = 0;
375
+ for await (const chunk of request) {
376
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
377
+ size += buffer.length;
378
+ if (size > limit) {
379
+ request.destroy();
380
+ throw new Error(`Request body exceeds ${limit} bytes`);
381
+ }
382
+ chunks.push(buffer);
383
+ }
384
+ return Buffer.concat(chunks).toString('utf8');
385
+ }
package/src/webhook.ts ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * DingTalk webhook HTTP: signature → parse → admit.
3
+ */
4
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
+ import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
6
+ import { formatCompact, getLogger } from '@zhin.js/logger';
7
+ import {
8
+ headerValue,
9
+ readTextBody,
10
+ verifySignature,
11
+ type DingTalkEvent,
12
+ type ResolvedDingTalkConfig,
13
+ } from './protocol.js';
14
+
15
+ const logger = getLogger('dingtalk');
16
+
17
+ export interface DingTalkWebhookHandler {
18
+ readonly config: ResolvedDingTalkConfig;
19
+ readonly isOpen: boolean;
20
+ admit(event: DingTalkEvent): void;
21
+ }
22
+
23
+ export function registerDingTalkWebhookRoutes(
24
+ http: HttpHost,
25
+ handler: DingTalkWebhookHandler,
26
+ ): HttpRouteRegistration[] {
27
+ const path = handler.config.webhookPath;
28
+ return [
29
+ http.route('POST', path, async (request, response) => {
30
+ await handleDingTalkWebhookRequest(request, response, handler);
31
+ }, { summary: 'DingTalk robot webhook', tags: ['dingtalk'] }),
32
+ ];
33
+ }
34
+
35
+ export async function handleDingTalkWebhookRequest(
36
+ request: IncomingMessage,
37
+ response: ServerResponse,
38
+ handler: DingTalkWebhookHandler,
39
+ ): Promise<void> {
40
+ try {
41
+ // DingTalk outgoing callbacks put timestamp/sign on the URL query;
42
+ // headers are accepted as a fallback for legacy senders.
43
+ const query = new URL(request.url ?? '/', 'http://localhost').searchParams;
44
+ const timestamp = query.get('timestamp') || headerValue(request.headers, 'timestamp');
45
+ const sign = query.get('sign') || headerValue(request.headers, 'sign');
46
+ // Missing credentials must never be admitted: verify unconditionally.
47
+ if (!timestamp || !sign || !verifySignature(handler.config.appSecret, timestamp, sign)) {
48
+ logger.warn(formatCompact({ op: 'webhook', ok: false, error: 'invalid signature' }));
49
+ response.writeHead(403, { 'Content-Type': 'application/json' });
50
+ response.end(JSON.stringify({ code: -1, msg: 'Forbidden' }));
51
+ return;
52
+ }
53
+
54
+ const rawBody = await readTextBody(request);
55
+ let event: DingTalkEvent;
56
+ try {
57
+ event = JSON.parse(rawBody) as DingTalkEvent;
58
+ } catch {
59
+ response.writeHead(200, { 'Content-Type': 'application/json' });
60
+ response.end(JSON.stringify({ code: 0, msg: 'success' }));
61
+ return;
62
+ }
63
+
64
+ if (event.msgtype && handler.isOpen) {
65
+ handler.admit(event);
66
+ }
67
+
68
+ response.writeHead(200, { 'Content-Type': 'application/json' });
69
+ response.end(JSON.stringify({ code: 0, msg: 'success' }));
70
+ } catch (error) {
71
+ logger.error('Webhook error:', error);
72
+ response.writeHead(500, { 'Content-Type': 'application/json' });
73
+ response.end(JSON.stringify({ code: -1, msg: 'Internal Server Error' }));
74
+ }
75
+ }
package/lib/adapter.d.ts DELETED
@@ -1,16 +0,0 @@
1
- /**
2
- * 钉钉适配器
3
- */
4
- import { Adapter, Plugin } from "zhin.js";
5
- import { DingTalkBot } from "./bot.js";
6
- import type { DingTalkBotConfig } from "./types.js";
7
- export declare class DingTalkAdapter extends Adapter<DingTalkBot> {
8
- #private;
9
- constructor(plugin: Plugin, router: any);
10
- createBot(config: DingTalkBotConfig): DingTalkBot;
11
- kickMember(botId: string, sceneId: string, userId: string): Promise<boolean>;
12
- setGroupName(botId: string, sceneId: string, name: string): Promise<boolean>;
13
- getGroupInfo(botId: string, sceneId: string): Promise<any>;
14
- start(): Promise<void>;
15
- }
16
- //# sourceMappingURL=adapter.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EACL,OAAO,EACP,MAAM,EACP,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,qBAAa,eAAgB,SAAQ,OAAO,CAAC,WAAW,CAAC;;gBAG3C,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG;IAKvC,SAAS,CAAC,MAAM,EAAE,iBAAiB,GAAG,WAAW;IAI3C,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAMzD,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;IAMzD,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;IAM3C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAG7B"}
package/lib/adapter.js DELETED
@@ -1,37 +0,0 @@
1
- /**
2
- * 钉钉适配器
3
- */
4
- import { Adapter, } from "zhin.js";
5
- import { DingTalkBot } from "./bot.js";
6
- export class DingTalkAdapter extends Adapter {
7
- #router;
8
- constructor(plugin, router) {
9
- super(plugin, "dingtalk", []);
10
- this.#router = router;
11
- }
12
- createBot(config) {
13
- return new DingTalkBot(this, this.#router, config);
14
- }
15
- async kickMember(botId, sceneId, userId) {
16
- const bot = this.bots.get(botId);
17
- if (!bot)
18
- throw new Error(`Bot ${botId} 不存在`);
19
- return bot.updateChat(sceneId, { del_useridlist: [userId] });
20
- }
21
- async setGroupName(botId, sceneId, name) {
22
- const bot = this.bots.get(botId);
23
- if (!bot)
24
- throw new Error(`Bot ${botId} 不存在`);
25
- return bot.updateChat(sceneId, { name });
26
- }
27
- async getGroupInfo(botId, sceneId) {
28
- const bot = this.bots.get(botId);
29
- if (!bot)
30
- throw new Error(`Bot ${botId} 不存在`);
31
- return bot.getChatInfo(sceneId);
32
- }
33
- async start() {
34
- await super.start();
35
- }
36
- }
37
- //# sourceMappingURL=adapter.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EACL,OAAO,GAER,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAGvC,MAAM,OAAO,eAAgB,SAAQ,OAAoB;IACvD,OAAO,CAAM;IAEb,YAAY,MAAc,EAAE,MAAW;QACrC,KAAK,CAAC,MAAM,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC;QAC9B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;IAED,SAAS,CAAC,MAAy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alkBotConfig, DingTalkMessage } from "./types.js";
6
- import type { DingTalkAdapter } from "./adapter.js";
7
- export declare class DingTalkBot implements Bot<DingTalkBotConfig, DingTalkMessage> {
8
- adapter: DingTalkAdapter;
9
- $config: DingTalkBotConfig;
10
- $connected: boolean;
11
- private router;
12
- private accessToken;
13
- private baseURL;
14
- private sessionWebhooks;
15
- get $id(): string;
16
- get logger(): import("zhin.js").Logger;
17
- constructor(adapter: DingTalkAdapter, router: any, $config: DingTalkBotConfig);
18
- private request;
19
- private setupWebhookRoute;
20
- private handleWebhook;
21
- private verifySignature;
22
- private handleEvent;
23
- private ensureAccessToken;
24
- private refreshAccessToken;
25
- $formatMessage(msg: DingTalkMessage): Message<DingTalkMessage>;
26
- private parseMessageContent;
27
- $sendMessage(options: SendOptions): Promise<string>;
28
- $recallMessage(id: string): Promise<void>;
29
- private formatSendContent;
30
- $connect(): Promise<void>;
31
- $disconnect(): Promise<void>;
32
- getUserInfo(userId: string): Promise<any>;
33
- getDepartmentUsers(deptId: number): Promise<any[]>;
34
- sendWorkNotice(userIdList: string[], content: any): Promise<boolean>;
35
- getDepartmentList(deptId?: number): Promise<any[]>;
36
- getDepartmentInfo(deptId: number): Promise<any>;
37
- createChat(name: string, ownerUserId: string, userIdList: string[]): Promise<string | null>;
38
- getChatInfo(chatId: string): Promise<any>;
39
- updateChat(chatId: string, options: {
40
- name?: string;
41
- owner?: string;
42
- add_useridlist?: string[];
43
- del_useridlist?: string[];
44
- }): Promise<boolean>;
45
- }
46
- //# sourceMappingURL=bot.d.ts.map
package/lib/bot.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"bot.d.ts","sourceRoot":"","sources":["../src/bot.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAiB,GAAG,EAAE,OAAO,EAAwC,WAAW,EAAE,MAAM,SAAS,CAAC;AAGzG,OAAO,KAAK,EACV,iBAAiB,EACjB,eAAe,EAGhB,MAAM,YAAY,CAAC;AACpB,OAAO,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