@asabot/core 0.1.0 → 0.2.1
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/CHANGELOG.md +17 -0
- package/README.md +93 -14
- package/asabot.config.example.yaml +47 -29
- package/dist/adapters/feishu/adapter.d.ts +19 -0
- package/dist/adapters/feishu/adapter.js +621 -0
- package/dist/adapters/feishu/api.d.ts +142 -0
- package/dist/adapters/feishu/api.js +306 -0
- package/dist/adapters/feishu/bot.d.ts +95 -0
- package/dist/adapters/feishu/bot.js +539 -0
- package/dist/adapters/feishu/cards.d.ts +93 -0
- package/dist/adapters/feishu/cards.js +106 -0
- package/dist/adapters/feishu/config.d.ts +13 -0
- package/dist/adapters/feishu/config.js +36 -0
- package/dist/adapters/feishu/events.d.ts +33 -0
- package/dist/adapters/feishu/events.js +14 -0
- package/dist/adapters/feishu/index.d.ts +8 -0
- package/dist/adapters/feishu/index.js +5 -0
- package/dist/adapters/feishu/message.d.ts +64 -0
- package/dist/adapters/feishu/message.js +197 -0
- package/dist/adapters/feishu/transport.d.ts +34 -0
- package/dist/adapters/feishu/transport.js +110 -0
- package/dist/adapters/index.d.ts +1 -7
- package/dist/adapters/index.js +75 -6
- package/dist/adapters/loader.d.ts +6 -0
- package/dist/adapters/loader.js +73 -0
- package/dist/adapters/media-source.d.ts +7 -0
- package/dist/adapters/media-source.js +137 -0
- package/dist/adapters/onebot11/adapter.d.ts +5 -0
- package/dist/adapters/onebot11/adapter.js +23 -11
- package/dist/adapters/onebot11/api.d.ts +4 -1
- package/dist/adapters/onebot11/api.js +21 -8
- package/dist/adapters/onebot11/errors.d.ts +3 -0
- package/dist/adapters/onebot11/errors.js +6 -0
- package/dist/adapters/virtual/index.js +7 -1
- package/dist/adapters/wecom/adapter.d.ts +14 -0
- package/dist/adapters/wecom/adapter.js +220 -0
- package/dist/adapters/wecom/bot.d.ts +71 -0
- package/dist/adapters/wecom/bot.js +312 -0
- package/dist/adapters/wecom/cards.d.ts +37 -0
- package/dist/adapters/wecom/cards.js +30 -0
- package/dist/adapters/wecom/config.d.ts +8 -0
- package/dist/adapters/wecom/config.js +10 -0
- package/dist/adapters/wecom/events.d.ts +93 -0
- package/dist/adapters/wecom/events.js +46 -0
- package/dist/adapters/wecom/index.d.ts +7 -0
- package/dist/adapters/wecom/index.js +21 -0
- package/dist/adapters/wecom/media.d.ts +50 -0
- package/dist/adapters/wecom/media.js +149 -0
- package/dist/adapters/wecom/message.d.ts +151 -0
- package/dist/adapters/wecom/message.js +116 -0
- package/dist/adapters/wecom/transport.d.ts +39 -0
- package/dist/adapters/wecom/transport.js +116 -0
- package/dist/adapters/weixin-clawbot/adapter.d.ts +16 -0
- package/dist/adapters/weixin-clawbot/adapter.js +173 -0
- package/dist/adapters/weixin-clawbot/bot.d.ts +41 -0
- package/dist/adapters/weixin-clawbot/bot.js +254 -0
- package/dist/adapters/weixin-clawbot/index.d.ts +2 -0
- package/dist/adapters/weixin-clawbot/index.js +19 -0
- package/dist/adapters/weixin-clawbot/media.d.ts +57 -0
- package/dist/adapters/weixin-clawbot/media.js +196 -0
- package/dist/adapters/weixin-clawbot/message.d.ts +12 -0
- package/dist/adapters/weixin-clawbot/message.js +79 -0
- package/dist/adapters/weixin-clawbot/protocol.d.ts +145 -0
- package/dist/adapters/weixin-clawbot/protocol.js +178 -0
- package/dist/adapters/weixin-clawbot/setup.d.ts +2 -0
- package/dist/adapters/weixin-clawbot/setup.js +121 -0
- package/dist/bootstrap.d.ts +5 -0
- package/dist/bootstrap.js +5 -20
- package/dist/cli.js +9 -3
- package/dist/core/adapter.d.ts +69 -3
- package/dist/core/adapter.js +11 -1
- package/dist/core/app.d.ts +12 -9
- package/dist/core/app.js +50 -51
- package/dist/core/bot-accounts.d.ts +28 -0
- package/dist/core/bot-accounts.js +78 -0
- package/dist/core/bot-policies.d.ts +30 -0
- package/dist/core/bot-policies.js +112 -0
- package/dist/core/bot.d.ts +19 -1
- package/dist/core/bot.js +13 -0
- package/dist/core/capabilities.d.ts +54 -0
- package/dist/core/capabilities.js +25 -0
- package/dist/core/config/schema.d.ts +61 -8
- package/dist/core/config/schema.js +15 -3
- package/dist/core/config/write.js +5 -1
- package/dist/core/connections.d.ts +84 -0
- package/dist/core/connections.js +326 -0
- package/dist/core/delivery.d.ts +53 -0
- package/dist/core/delivery.js +115 -0
- package/dist/core/dispatch/api.d.ts +3 -1
- package/dist/core/dispatch/api.js +12 -5
- package/dist/core/dispatch/dispatcher.d.ts +1 -0
- package/dist/core/dispatch/dispatcher.js +35 -15
- package/dist/core/dispatch/outgoing.d.ts +1 -0
- package/dist/core/dispatch/outgoing.js +5 -3
- package/dist/core/dispatch/trace.d.ts +2 -0
- package/dist/core/dispatch/types.d.ts +6 -0
- package/dist/core/dispatch/types.js +1 -2
- package/dist/core/errors.d.ts +4 -1
- package/dist/core/errors.js +7 -1
- package/dist/core/event/session.d.ts +3 -1
- package/dist/core/event/session.js +7 -4
- package/dist/core/event/types.d.ts +5 -1
- package/dist/core/identity.d.ts +18 -0
- package/dist/core/identity.js +31 -0
- package/dist/core/logger.js +9 -2
- package/dist/core/message/segment.js +3 -13
- package/dist/core/message/types.d.ts +2 -0
- package/dist/core/permission.d.ts +2 -1
- package/dist/core/permission.js +7 -2
- package/dist/core/plugin/context.d.ts +17 -11
- package/dist/core/plugin/context.js +48 -21
- package/dist/core/plugin/definition.d.ts +7 -0
- package/dist/core/plugin/execution.d.ts +3 -0
- package/dist/core/plugin/execution.js +3 -0
- package/dist/core/plugin/icon.d.ts +2 -0
- package/dist/core/plugin/icon.js +14 -0
- package/dist/core/plugin/manager.d.ts +26 -7
- package/dist/core/plugin/manager.js +179 -56
- package/dist/core/plugin/packages.d.ts +4 -0
- package/dist/core/plugin/packages.js +39 -9
- package/dist/core/plugin/tasks.d.ts +131 -24
- package/dist/core/plugin/tasks.js +517 -117
- package/dist/core/plugin/types.d.ts +14 -0
- package/dist/core/ratelimit.js +6 -1
- package/dist/core/storage/index.d.ts +3 -1
- package/dist/core/storage/index.js +52 -2
- package/dist/core/target.d.ts +24 -6
- package/dist/core/target.js +26 -6
- package/dist/core/utils/merge.d.ts +3 -0
- package/dist/core/utils/merge.js +18 -0
- package/dist/core/utils/redact.d.ts +6 -0
- package/dist/core/utils/redact.js +76 -0
- package/dist/index.d.ts +14 -6
- package/dist/index.js +7 -2
- package/dist/plugins/admin.js +30 -3
- package/dist/plugins/help.js +1 -0
- package/dist/plugins/history.d.ts +4 -0
- package/dist/plugins/history.js +13 -3
- package/dist/plugins/http.js +1 -0
- package/dist/plugins/long-message.js +20 -12
- package/dist/plugins/status.js +1 -0
- package/dist/server/auth.d.ts +5 -1
- package/dist/server/auth.js +11 -7
- package/dist/server/connection-setups.d.ts +126 -0
- package/dist/server/connection-setups.js +188 -0
- package/dist/server/groups.d.ts +1 -0
- package/dist/server/groups.js +8 -8
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +230 -29
- package/dist/server/schemas.d.ts +6 -2
- package/dist/server/settings.d.ts +66 -20
- package/dist/server/settings.js +158 -61
- package/dist/server/views.d.ts +97 -17
- package/dist/server/views.js +48 -13
- package/dist/testing/create-test-app.js +2 -2
- package/dist/testing/dispatch-fixture.js +2 -1
- package/dist/testing/fake-bot.d.ts +2 -1
- package/dist/testing/fake-bot.js +4 -1
- package/docs/DEPLOY.md +211 -0
- package/docs/FEISHU.md +170 -0
- package/docs/WECOM.md +107 -0
- package/docs/WEIXIN-CLAWBOT.md +56 -0
- package/package.json +29 -3
- package/web/dist/assets/index-ogXTSYEt.css +2 -0
- package/web/dist/assets/index-r9XycpMd.js +51 -0
- package/web/dist/assets/{markdown-CDlgpI7K.js → markdown-CIohfKSa.js} +3 -3
- package/web/dist/index.html +2 -2
- package/web/dist/plugin-pages/_sdk.js +26 -1
- package/web/dist/assets/index-BI5GCpiI.css +0 -2
- package/web/dist/assets/index-C-rshHwD.js +0 -51
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { createSession } from '../../core/event/index.js';
|
|
3
|
+
import { LruSet } from '../../core/utils/lru.js';
|
|
4
|
+
import { WecomBotImpl } from './bot.js';
|
|
5
|
+
import { platform, wecomSchema } from './config.js';
|
|
6
|
+
import { eventFrame, } from './events.js';
|
|
7
|
+
import { incoming, messageFrame } from './message.js';
|
|
8
|
+
import { SDKTransport } from './transport.js';
|
|
9
|
+
const messageWindow = 24 * 60 * 60_000;
|
|
10
|
+
const eventWindow = 5_000;
|
|
11
|
+
export class WecomAdapter {
|
|
12
|
+
platform = platform;
|
|
13
|
+
#host;
|
|
14
|
+
#options;
|
|
15
|
+
#config;
|
|
16
|
+
#running;
|
|
17
|
+
constructor(config, host, options = {}) {
|
|
18
|
+
this.#config = config;
|
|
19
|
+
this.#host = host;
|
|
20
|
+
this.#options = options;
|
|
21
|
+
}
|
|
22
|
+
async start() {
|
|
23
|
+
if (this.#running)
|
|
24
|
+
return;
|
|
25
|
+
const config = this.#config;
|
|
26
|
+
const host = this.#host;
|
|
27
|
+
const transport = this.#options.createTransport?.(config) ?? new SDKTransport(config);
|
|
28
|
+
const shutdown = new AbortController();
|
|
29
|
+
const bot = new WecomBotImpl(config, host, transport, shutdown.signal);
|
|
30
|
+
const running = { bot, transport, shutdown, seen: new LruSet(8192) };
|
|
31
|
+
const current = () => this.#running === running && !shutdown.signal.aborted;
|
|
32
|
+
const log = host.logger.child({ platform, selfId: bot.selfId });
|
|
33
|
+
host.registerBot(bot);
|
|
34
|
+
this.#running = running;
|
|
35
|
+
host.setBotInfo(bot, { connection: '企业微信 WebSocket 长连接' });
|
|
36
|
+
host.connection?.update({ state: 'connecting', nextRetryAt: undefined });
|
|
37
|
+
transport.start({
|
|
38
|
+
connecting: () => {
|
|
39
|
+
if (!current())
|
|
40
|
+
return;
|
|
41
|
+
bot.setStatus('connecting');
|
|
42
|
+
host.connection?.update({ state: 'connecting', nextRetryAt: undefined });
|
|
43
|
+
},
|
|
44
|
+
ready: () => {
|
|
45
|
+
if (!current())
|
|
46
|
+
return;
|
|
47
|
+
bot.setStatus('online');
|
|
48
|
+
host.connection?.update({ state: 'online' });
|
|
49
|
+
log.info('企业微信认证成功');
|
|
50
|
+
},
|
|
51
|
+
disconnected: () => {
|
|
52
|
+
if (current())
|
|
53
|
+
bot.setStatus('offline');
|
|
54
|
+
},
|
|
55
|
+
retrying: (delay) => {
|
|
56
|
+
if (!current())
|
|
57
|
+
return;
|
|
58
|
+
const reason = '企业微信长连接中断,正在重连';
|
|
59
|
+
host.connection?.update({ state: 'retrying', error: reason, nextRetryAt: Date.now() + delay });
|
|
60
|
+
log.warn({ retryIn: delay }, reason);
|
|
61
|
+
},
|
|
62
|
+
failed: (reason) => {
|
|
63
|
+
if (!current())
|
|
64
|
+
return;
|
|
65
|
+
shutdown.abort();
|
|
66
|
+
transport.close();
|
|
67
|
+
bot.setStatus('offline');
|
|
68
|
+
host.connection?.update({ state: 'error', error: reason, nextRetryAt: undefined });
|
|
69
|
+
log.warn(reason);
|
|
70
|
+
},
|
|
71
|
+
message: (frame) => {
|
|
72
|
+
if (current() && bot.status === 'online')
|
|
73
|
+
this.#message(running, frame, config.botName);
|
|
74
|
+
},
|
|
75
|
+
event: (frame) => {
|
|
76
|
+
if (current() && bot.status === 'online')
|
|
77
|
+
this.#event(running, frame);
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
async stop() {
|
|
82
|
+
const running = this.#running;
|
|
83
|
+
if (!running)
|
|
84
|
+
return;
|
|
85
|
+
this.#running = undefined;
|
|
86
|
+
running.shutdown.abort();
|
|
87
|
+
running.transport.close();
|
|
88
|
+
running.bot.setStatus('offline');
|
|
89
|
+
this.#host.unregisterBot(running.bot);
|
|
90
|
+
}
|
|
91
|
+
async reconfigure(config) {
|
|
92
|
+
const next = wecomSchema.parse(config);
|
|
93
|
+
await this.stop();
|
|
94
|
+
this.#config = next;
|
|
95
|
+
await this.start();
|
|
96
|
+
}
|
|
97
|
+
#message(running, frame, botName) {
|
|
98
|
+
const receivedAt = Date.now();
|
|
99
|
+
const parsed = messageFrame.safeParse(frame);
|
|
100
|
+
if (!parsed.success) {
|
|
101
|
+
this.#host.logger.debug({ platform }, '忽略无效或不支持的企业微信消息');
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const { body, headers } = parsed.data;
|
|
105
|
+
if (!this.#accept(running, body))
|
|
106
|
+
return;
|
|
107
|
+
const { bot } = running;
|
|
108
|
+
const actor = { platform, selfId: bot.selfId, userId: body.from.userid };
|
|
109
|
+
const channel = body.chattype === 'group'
|
|
110
|
+
? { messageType: 'group', groupId: body.chatid }
|
|
111
|
+
: { messageType: 'private' };
|
|
112
|
+
const message = incoming(body, bot.media, receivedAt, botName);
|
|
113
|
+
if (!message.length)
|
|
114
|
+
return;
|
|
115
|
+
const session = createSession({
|
|
116
|
+
...actor,
|
|
117
|
+
...channel,
|
|
118
|
+
id: randomUUID(),
|
|
119
|
+
bot,
|
|
120
|
+
time: body.create_time ? body.create_time * 1000 : receivedAt,
|
|
121
|
+
raw: undefined,
|
|
122
|
+
messageId: body.msgid,
|
|
123
|
+
message,
|
|
124
|
+
sender: { userId: actor.userId, nickname: actor.userId },
|
|
125
|
+
isSuperuser: this.#host.isSuperuser(actor),
|
|
126
|
+
isBotAdmin: this.#host.isBotAdmin(actor),
|
|
127
|
+
}, this.#host.sessionServices);
|
|
128
|
+
const target = { type: session.messageType, id: session.groupId ?? session.userId };
|
|
129
|
+
this.#host.emit(bot.bindSession(session, { target, reqId: headers.req_id, deadline: receivedAt + messageWindow }));
|
|
130
|
+
}
|
|
131
|
+
#event(running, frame) {
|
|
132
|
+
const receivedAt = Date.now();
|
|
133
|
+
const parsed = eventFrame.safeParse(frame);
|
|
134
|
+
if (!parsed.success) {
|
|
135
|
+
this.#host.logger.debug({ platform }, '忽略无效或不支持的企业微信事件');
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const { body, headers } = parsed.data;
|
|
139
|
+
if (!this.#accept(running, body))
|
|
140
|
+
return;
|
|
141
|
+
const { event, from } = body;
|
|
142
|
+
const { bot } = running;
|
|
143
|
+
const group = body.chattype === 'group';
|
|
144
|
+
const target = {
|
|
145
|
+
platform,
|
|
146
|
+
selfId: bot.selfId,
|
|
147
|
+
type: group ? 'group' : 'private',
|
|
148
|
+
id: group ? body.chatid : from.userid,
|
|
149
|
+
};
|
|
150
|
+
const callback = { target, reqId: headers.req_id, deadline: receivedAt + eventWindow };
|
|
151
|
+
const common = {
|
|
152
|
+
id: randomUUID(),
|
|
153
|
+
platform,
|
|
154
|
+
selfId: bot.selfId,
|
|
155
|
+
bot,
|
|
156
|
+
raw: undefined,
|
|
157
|
+
kind: 'notice',
|
|
158
|
+
target,
|
|
159
|
+
time: body.create_time ? body.create_time * 1000 : receivedAt,
|
|
160
|
+
userId: from.userid,
|
|
161
|
+
corpId: from.corpid,
|
|
162
|
+
...(group && { groupId: body.chatid }),
|
|
163
|
+
messageId: body.msgid,
|
|
164
|
+
};
|
|
165
|
+
switch (event.eventtype) {
|
|
166
|
+
case 'enter_chat': {
|
|
167
|
+
if (group)
|
|
168
|
+
return;
|
|
169
|
+
const notice = {
|
|
170
|
+
...common,
|
|
171
|
+
name: 'notice.wecom.enter_chat',
|
|
172
|
+
platformType: event.eventtype,
|
|
173
|
+
replyWelcome: bot.welcome(callback),
|
|
174
|
+
};
|
|
175
|
+
this.#host.emit(notice);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
case 'template_card_event': {
|
|
179
|
+
const data = event.template_card_event;
|
|
180
|
+
const notice = {
|
|
181
|
+
...common,
|
|
182
|
+
name: 'notice.wecom.card.action',
|
|
183
|
+
platformType: event.eventtype,
|
|
184
|
+
cardType: data.card_type,
|
|
185
|
+
eventKey: data.event_key,
|
|
186
|
+
taskId: data.task_id,
|
|
187
|
+
selectedItems: (data.selected_items?.selected_item ?? []).map((item) => ({
|
|
188
|
+
questionKey: item.question_key,
|
|
189
|
+
optionIds: item.option_ids.option_id,
|
|
190
|
+
})),
|
|
191
|
+
updateCard: bot.cardUpdate(callback, data.task_id),
|
|
192
|
+
};
|
|
193
|
+
this.#host.emit(notice);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
case 'feedback_event': {
|
|
197
|
+
const data = event.feedback_event;
|
|
198
|
+
const notice = {
|
|
199
|
+
...common,
|
|
200
|
+
name: 'notice.wecom.feedback',
|
|
201
|
+
platformType: event.eventtype,
|
|
202
|
+
feedbackId: data.id,
|
|
203
|
+
feedbackType: data.type,
|
|
204
|
+
content: data.content,
|
|
205
|
+
inaccurateReasons: data.inaccurate_reason_list,
|
|
206
|
+
};
|
|
207
|
+
this.#host.emit(notice);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
#accept({ bot, seen }, body) {
|
|
212
|
+
if (body.aibotid !== bot.selfId ||
|
|
213
|
+
body.compat_info !== undefined ||
|
|
214
|
+
(this.#host.ignoreSelf && body.from.userid === bot.selfId) ||
|
|
215
|
+
seen.has(body.msgid))
|
|
216
|
+
return false;
|
|
217
|
+
seen.add(body.msgid);
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { AdapterHost } from '../../core/adapter.ts';
|
|
2
|
+
import type { Bot, BotCapabilities, MessageTarget, SendResult } from '../../core/bot.ts';
|
|
3
|
+
import type { Session } from '../../core/event/index.ts';
|
|
4
|
+
import { type Sendable } from '../../core/message/index.ts';
|
|
5
|
+
import { type WecomTemplateCard } from './cards.ts';
|
|
6
|
+
import { platform, type WecomConfig } from './config.ts';
|
|
7
|
+
import { WecomMedia } from './media.ts';
|
|
8
|
+
import { type WecomTransport } from './transport.ts';
|
|
9
|
+
export declare const wecomCapabilities: BotCapabilities;
|
|
10
|
+
export interface WecomStream {
|
|
11
|
+
readonly id: string;
|
|
12
|
+
update(content: string): Promise<void>;
|
|
13
|
+
finish(content: string): Promise<SendResult>;
|
|
14
|
+
}
|
|
15
|
+
export interface WecomBot extends Bot {
|
|
16
|
+
readonly platform: typeof platform;
|
|
17
|
+
readonly wecom: {
|
|
18
|
+
downloadMedia(handle: string): Promise<Buffer>;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
export interface WecomSession extends Session {
|
|
22
|
+
readonly platform: typeof platform;
|
|
23
|
+
readonly bot: WecomBot;
|
|
24
|
+
readonly wecom: {
|
|
25
|
+
createStream(options?: {
|
|
26
|
+
feedbackId?: string;
|
|
27
|
+
}): WecomStream;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export interface WecomCallback {
|
|
31
|
+
reqId: string;
|
|
32
|
+
target: MessageTarget;
|
|
33
|
+
deadline: number;
|
|
34
|
+
}
|
|
35
|
+
export declare class WecomBotImpl implements WecomBot {
|
|
36
|
+
#private;
|
|
37
|
+
readonly platform = "wecom";
|
|
38
|
+
readonly capabilities: BotCapabilities;
|
|
39
|
+
readonly selfId: string;
|
|
40
|
+
readonly nickname?: string;
|
|
41
|
+
constructor(config: WecomConfig, host: AdapterHost, transport: WecomTransport, shutdown: AbortSignal);
|
|
42
|
+
get media(): WecomMedia;
|
|
43
|
+
readonly wecom: {
|
|
44
|
+
downloadMedia: (handle: string) => Promise<Buffer>;
|
|
45
|
+
};
|
|
46
|
+
get status(): Bot['status'];
|
|
47
|
+
setStatus(status: Bot['status']): void;
|
|
48
|
+
bindSession(session: Session, callback: WecomCallback): WecomSession;
|
|
49
|
+
welcome(callback: WecomCallback): (content: string | WecomTemplateCard) => Promise<SendResult>;
|
|
50
|
+
cardUpdate(callback: WecomCallback, taskId: string): (card: WecomTemplateCard, userIds?: string[]) => Promise<SendResult>;
|
|
51
|
+
sendPrivate(userId: string, content: Sendable): Promise<SendResult>;
|
|
52
|
+
sendGroup(groupId: string, content: Sendable): Promise<SendResult>;
|
|
53
|
+
getSelf(): Promise<{
|
|
54
|
+
userId: string;
|
|
55
|
+
nickname: string;
|
|
56
|
+
}>;
|
|
57
|
+
sendForward(): Promise<never>;
|
|
58
|
+
getForward(): Promise<never>;
|
|
59
|
+
deleteMessage(): Promise<never>;
|
|
60
|
+
getMessage(): Promise<never>;
|
|
61
|
+
getGroupList(): Promise<never>;
|
|
62
|
+
getGroupMember(): Promise<never>;
|
|
63
|
+
getGroupMembers(): Promise<never>;
|
|
64
|
+
muteMember(): Promise<never>;
|
|
65
|
+
kickMember(): Promise<never>;
|
|
66
|
+
setMemberCard(): Promise<never>;
|
|
67
|
+
getFriendList(): Promise<never>;
|
|
68
|
+
call(action: string): Promise<never>;
|
|
69
|
+
}
|
|
70
|
+
export declare function isWecomBot(bot: Bot): bot is WecomBot;
|
|
71
|
+
export declare function isWecomSession(session: Session): session is WecomSession;
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { WsCmd } from '@wecom/aibot-node-sdk';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { DeliveryAttempt, DeliveryError } from '../../core/delivery.js';
|
|
5
|
+
import { dispatchContext } from '../../core/dispatch/trace.js';
|
|
6
|
+
import { NotConnectedError, UnsupportedError } from '../../core/errors.js';
|
|
7
|
+
import { normalizeSendable, seg } from '../../core/message/index.js';
|
|
8
|
+
import { cardForSend, cardSchema, feedbackIdSchema, wecom } from './cards.js';
|
|
9
|
+
import { platform } from './config.js';
|
|
10
|
+
import { WecomMedia } from './media.js';
|
|
11
|
+
import { contentText, outgoing } from './message.js';
|
|
12
|
+
import { classifyWecomSend } from './transport.js';
|
|
13
|
+
export const wecomCapabilities = {
|
|
14
|
+
segments: ['text', 'markdown', 'image', 'audio', 'video', 'file', 'wecom:card'],
|
|
15
|
+
textStyles: [],
|
|
16
|
+
actions: [
|
|
17
|
+
'sendPrivate',
|
|
18
|
+
'sendGroup',
|
|
19
|
+
'getSelf',
|
|
20
|
+
'wecom.reply',
|
|
21
|
+
'wecom.downloadMedia',
|
|
22
|
+
'wecom.stream.update',
|
|
23
|
+
'wecom.stream.finish',
|
|
24
|
+
'wecom.replyWelcome',
|
|
25
|
+
'wecom.updateCard',
|
|
26
|
+
],
|
|
27
|
+
};
|
|
28
|
+
const segment = z.object({ type: z.string().min(1), data: z.record(z.string(), z.unknown()) });
|
|
29
|
+
const sendable = z.union([z.string(), segment, z.array(segment)]);
|
|
30
|
+
const sendResult = z.object({ messageId: z.string().min(1) });
|
|
31
|
+
const welcome = z.union([contentText, cardSchema]);
|
|
32
|
+
const cardUpdate = z.tuple([cardSchema, z.array(z.string().min(1)).optional()]);
|
|
33
|
+
export class WecomBotImpl {
|
|
34
|
+
platform = platform;
|
|
35
|
+
capabilities = wecomCapabilities;
|
|
36
|
+
selfId;
|
|
37
|
+
nickname;
|
|
38
|
+
#host;
|
|
39
|
+
#transport;
|
|
40
|
+
#media;
|
|
41
|
+
#status = 'connecting';
|
|
42
|
+
constructor(config, host, transport, shutdown) {
|
|
43
|
+
this.selfId = config.botId;
|
|
44
|
+
this.nickname = config.botName;
|
|
45
|
+
this.#host = host;
|
|
46
|
+
this.#transport = transport;
|
|
47
|
+
this.#media = new WecomMedia(shutdown);
|
|
48
|
+
}
|
|
49
|
+
get media() {
|
|
50
|
+
return this.#media;
|
|
51
|
+
}
|
|
52
|
+
wecom = {
|
|
53
|
+
downloadMedia: async (handle) => {
|
|
54
|
+
const output = await this.#host.invokeApi({ bot: this, method: 'wecom.downloadMedia', args: [handle] }, async ([value]) => this.#media.download(z.string().min(1).parse(value)));
|
|
55
|
+
if (!Buffer.isBuffer(output))
|
|
56
|
+
throw new TypeError('媒体下载必须返回 Buffer');
|
|
57
|
+
return output;
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
get status() {
|
|
61
|
+
return this.#status;
|
|
62
|
+
}
|
|
63
|
+
setStatus(status) {
|
|
64
|
+
if (status === this.#status)
|
|
65
|
+
return;
|
|
66
|
+
const previous = this.#status;
|
|
67
|
+
this.#status = status;
|
|
68
|
+
if (status !== 'online' && previous !== 'online')
|
|
69
|
+
return;
|
|
70
|
+
const event = {
|
|
71
|
+
id: randomUUID(),
|
|
72
|
+
kind: 'internal',
|
|
73
|
+
platform,
|
|
74
|
+
selfId: this.selfId,
|
|
75
|
+
time: Date.now(),
|
|
76
|
+
raw: undefined,
|
|
77
|
+
bot: this,
|
|
78
|
+
};
|
|
79
|
+
this.#host.emit(status === 'online'
|
|
80
|
+
? { ...event, name: 'bot.online', status }
|
|
81
|
+
: { ...event, name: 'bot.offline', status: 'offline' });
|
|
82
|
+
}
|
|
83
|
+
bindSession(session, callback) {
|
|
84
|
+
const proactiveReply = session.reply;
|
|
85
|
+
const binding = {
|
|
86
|
+
platform: this.platform,
|
|
87
|
+
bot: this,
|
|
88
|
+
wecom: {
|
|
89
|
+
createStream: (options) => this.#createStream(callback, options?.feedbackId),
|
|
90
|
+
},
|
|
91
|
+
reply: (content, options = {}) => {
|
|
92
|
+
if (options.quote === false)
|
|
93
|
+
return proactiveReply(content, options);
|
|
94
|
+
const message = normalizeSendable(content);
|
|
95
|
+
if (options.at && session.groupId)
|
|
96
|
+
message.unshift(seg.at(session.userId));
|
|
97
|
+
return this.#reply(callback, message);
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
return Object.assign(session, binding);
|
|
101
|
+
}
|
|
102
|
+
welcome(callback) {
|
|
103
|
+
const consume = this.#oneShot(callback);
|
|
104
|
+
return (content) => this.#invokeSend(callback.target, 'wecom.replyWelcome', [content], async ([value]) => {
|
|
105
|
+
const parsed = welcome.parse(value);
|
|
106
|
+
const input = typeof parsed === 'string' ? parsed : cardForSend(parsed);
|
|
107
|
+
const body = typeof input === 'string'
|
|
108
|
+
? { msgtype: 'text', text: { content: input } }
|
|
109
|
+
: { msgtype: 'template_card', template_card: input };
|
|
110
|
+
consume();
|
|
111
|
+
const id = await this.#respond(callback, body, WsCmd.RESPONSE_WELCOME);
|
|
112
|
+
return this.#record(callback.target, [typeof input === 'string' ? seg.text(input) : wecom.card(input)], id);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
cardUpdate(callback, taskId) {
|
|
116
|
+
const consume = this.#oneShot(callback);
|
|
117
|
+
return (card, userIds) => this.#invokeSend(callback.target, 'wecom.updateCard', [card, userIds], async (args) => {
|
|
118
|
+
const [input, users] = cardUpdate.parse(args);
|
|
119
|
+
const template = { ...input, task_id: taskId };
|
|
120
|
+
consume();
|
|
121
|
+
const id = await this.#respond(callback, {
|
|
122
|
+
response_type: 'update_template_card',
|
|
123
|
+
template_card: template,
|
|
124
|
+
...(users?.length ? { userids: users } : {}),
|
|
125
|
+
}, WsCmd.RESPONSE_UPDATE);
|
|
126
|
+
return this.#record(callback.target, [wecom.card(template)], id);
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
sendPrivate(userId, content) {
|
|
130
|
+
return this.#send({ type: 'private', id: userId }, content);
|
|
131
|
+
}
|
|
132
|
+
sendGroup(groupId, content) {
|
|
133
|
+
return this.#send({ type: 'group', id: groupId }, content);
|
|
134
|
+
}
|
|
135
|
+
async getSelf() {
|
|
136
|
+
return { userId: this.selfId, nickname: this.nickname ?? this.selfId };
|
|
137
|
+
}
|
|
138
|
+
#reply(callback, content) {
|
|
139
|
+
return this.#invokeSend(callback.target, 'wecom.reply', [content], async ([value]) => this.#send(callback.target, sendable.parse(value), callback));
|
|
140
|
+
}
|
|
141
|
+
async #invokeSend(target, method, args, execute) {
|
|
142
|
+
return new DeliveryAttempt(this, target).run(async () => sendResult.parse(await this.#host.invokeApi({ bot: this, method, args }, execute)));
|
|
143
|
+
}
|
|
144
|
+
#send(target, content, callback) {
|
|
145
|
+
const attempt = new DeliveryAttempt(this, target);
|
|
146
|
+
return attempt.run(() => this.#deliver(attempt, target, content, callback));
|
|
147
|
+
}
|
|
148
|
+
async #deliver(attempt, target, content, callback) {
|
|
149
|
+
this.#assertOnline();
|
|
150
|
+
if (callback)
|
|
151
|
+
this.#assertCallback(callback);
|
|
152
|
+
const prepared = await this.#host.prepareOutgoing({
|
|
153
|
+
bot: this,
|
|
154
|
+
target,
|
|
155
|
+
message: normalizeSendable(content),
|
|
156
|
+
...(callback && { sendPart: (part) => this.#reply(callback, part) }),
|
|
157
|
+
});
|
|
158
|
+
if (!Array.isArray(prepared))
|
|
159
|
+
return prepared.sent;
|
|
160
|
+
let sent;
|
|
161
|
+
for (const part of outgoing(prepared)) {
|
|
162
|
+
this.#assertOnline();
|
|
163
|
+
if (callback)
|
|
164
|
+
this.#assertCallback(callback);
|
|
165
|
+
const { body, message } = 'media' in part ? await this.#media.upload(part.media, this.#transport) : part;
|
|
166
|
+
this.#assertOnline();
|
|
167
|
+
const id = callback
|
|
168
|
+
? await this.#respond(callback, body)
|
|
169
|
+
: await attempt.request(() => this.#transport.send(target, body), classifyWecomSend);
|
|
170
|
+
sent = attempt.confirm(this.#record(target, message, id));
|
|
171
|
+
}
|
|
172
|
+
if (!sent)
|
|
173
|
+
throw new Error('没有可发送的企业微信消息内容');
|
|
174
|
+
return sent;
|
|
175
|
+
}
|
|
176
|
+
#createStream(callback, feedbackId) {
|
|
177
|
+
this.#assertOnline();
|
|
178
|
+
this.#assertCallback(callback);
|
|
179
|
+
const id = randomUUID();
|
|
180
|
+
const feedback = feedbackId === undefined ? undefined : { id: feedbackIdSchema.parse(feedbackId) };
|
|
181
|
+
let startedAt;
|
|
182
|
+
let busy = false;
|
|
183
|
+
let finished = false;
|
|
184
|
+
const send = async (content, finish) => {
|
|
185
|
+
const text = contentText.parse(content);
|
|
186
|
+
if (busy)
|
|
187
|
+
throw new Error('请等待企业微信上一帧流式回复完成');
|
|
188
|
+
if (finished)
|
|
189
|
+
throw this.#unavailable(callback.target, '企业微信流式回复已结束');
|
|
190
|
+
const now = Date.now();
|
|
191
|
+
if (startedAt !== undefined && now >= startedAt + 10 * 60_000)
|
|
192
|
+
throw this.#unavailable(callback.target, '企业微信流式回复已超过 10 分钟');
|
|
193
|
+
this.#assertOnline();
|
|
194
|
+
this.#assertCallback(callback);
|
|
195
|
+
const body = {
|
|
196
|
+
msgtype: 'stream',
|
|
197
|
+
stream: { id, content: text, finish, ...(startedAt === undefined && feedback && { feedback }) },
|
|
198
|
+
};
|
|
199
|
+
busy = true;
|
|
200
|
+
startedAt ??= now;
|
|
201
|
+
try {
|
|
202
|
+
const messageId = await this.#respond(callback, body);
|
|
203
|
+
if (finish)
|
|
204
|
+
finished = true;
|
|
205
|
+
return { text, messageId };
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
busy = false;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
return {
|
|
212
|
+
id,
|
|
213
|
+
update: async (content) => {
|
|
214
|
+
await new DeliveryAttempt(this, callback.target).run(() => this.#host.invokeApi({ bot: this, method: 'wecom.stream.update', args: [content] }, ([value]) => send(value, false)));
|
|
215
|
+
},
|
|
216
|
+
finish: (content) => this.#invokeSend(callback.target, 'wecom.stream.finish', [content], async ([value]) => {
|
|
217
|
+
const { text, messageId } = await send(value, true);
|
|
218
|
+
return this.#record(callback.target, [seg.markdown(text)], messageId);
|
|
219
|
+
}),
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
#oneShot(callback) {
|
|
223
|
+
let used = false;
|
|
224
|
+
return () => {
|
|
225
|
+
this.#assertOnline();
|
|
226
|
+
this.#assertCallback(callback);
|
|
227
|
+
if (used)
|
|
228
|
+
throw this.#unavailable(callback.target, '此企业微信事件已回复');
|
|
229
|
+
used = true;
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
#respond(callback, body, command) {
|
|
233
|
+
this.#assertOnline();
|
|
234
|
+
this.#assertCallback(callback);
|
|
235
|
+
return new DeliveryAttempt(this, callback.target).request(() => this.#transport.reply(callback.reqId, body, command), classifyWecomSend);
|
|
236
|
+
}
|
|
237
|
+
#assertCallback(callback) {
|
|
238
|
+
if (Date.now() >= callback.deadline)
|
|
239
|
+
throw this.#unavailable(callback.target, '企业微信回调回复已超时');
|
|
240
|
+
}
|
|
241
|
+
#unavailable(target, message) {
|
|
242
|
+
return new DeliveryError({ ...target, platform, selfId: this.selfId }, { code: 'CONVERSATION_UNAVAILABLE', message });
|
|
243
|
+
}
|
|
244
|
+
#assertOnline() {
|
|
245
|
+
if (this.#status !== 'online')
|
|
246
|
+
throw new NotConnectedError('企业微信未上线');
|
|
247
|
+
}
|
|
248
|
+
#record(target, message, messageId = `wecom-local:${randomUUID()}`) {
|
|
249
|
+
const context = dispatchContext.getStore();
|
|
250
|
+
this.#host.emit({
|
|
251
|
+
id: randomUUID(),
|
|
252
|
+
kind: 'internal',
|
|
253
|
+
name: 'bot.message.sent',
|
|
254
|
+
time: Date.now(),
|
|
255
|
+
raw: undefined,
|
|
256
|
+
bot: this,
|
|
257
|
+
platform,
|
|
258
|
+
selfId: this.selfId,
|
|
259
|
+
messageId,
|
|
260
|
+
messageType: target.type,
|
|
261
|
+
...(target.type === 'group' ? { groupId: target.id } : { userId: target.id }),
|
|
262
|
+
...(context?.active.value && { eventId: context.eventId }),
|
|
263
|
+
message,
|
|
264
|
+
});
|
|
265
|
+
return { messageId };
|
|
266
|
+
}
|
|
267
|
+
async sendForward() {
|
|
268
|
+
return this.#unsupported('sendForward');
|
|
269
|
+
}
|
|
270
|
+
async getForward() {
|
|
271
|
+
return this.#unsupported('getForward');
|
|
272
|
+
}
|
|
273
|
+
async deleteMessage() {
|
|
274
|
+
return this.#unsupported('deleteMessage');
|
|
275
|
+
}
|
|
276
|
+
async getMessage() {
|
|
277
|
+
return this.#unsupported('getMessage');
|
|
278
|
+
}
|
|
279
|
+
async getGroupList() {
|
|
280
|
+
return this.#unsupported('getGroupList');
|
|
281
|
+
}
|
|
282
|
+
async getGroupMember() {
|
|
283
|
+
return this.#unsupported('getGroupMember');
|
|
284
|
+
}
|
|
285
|
+
async getGroupMembers() {
|
|
286
|
+
return this.#unsupported('getGroupMembers');
|
|
287
|
+
}
|
|
288
|
+
async muteMember() {
|
|
289
|
+
return this.#unsupported('muteMember');
|
|
290
|
+
}
|
|
291
|
+
async kickMember() {
|
|
292
|
+
return this.#unsupported('kickMember');
|
|
293
|
+
}
|
|
294
|
+
async setMemberCard() {
|
|
295
|
+
return this.#unsupported('setMemberCard');
|
|
296
|
+
}
|
|
297
|
+
async getFriendList() {
|
|
298
|
+
return this.#unsupported('getFriendList');
|
|
299
|
+
}
|
|
300
|
+
async call(action) {
|
|
301
|
+
return this.#unsupported(action);
|
|
302
|
+
}
|
|
303
|
+
#unsupported(action) {
|
|
304
|
+
throw new UnsupportedError(platform, action);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
export function isWecomBot(bot) {
|
|
308
|
+
return bot instanceof WecomBotImpl;
|
|
309
|
+
}
|
|
310
|
+
export function isWecomSession(session) {
|
|
311
|
+
return isWecomBot(session.bot) && 'wecom' in session;
|
|
312
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { TemplateCard } from '@wecom/aibot-node-sdk';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
declare const cardType: z.ZodEnum<{
|
|
4
|
+
button_interaction: "button_interaction";
|
|
5
|
+
multiple_interaction: "multiple_interaction";
|
|
6
|
+
news_notice: "news_notice";
|
|
7
|
+
text_notice: "text_notice";
|
|
8
|
+
vote_interaction: "vote_interaction";
|
|
9
|
+
}>;
|
|
10
|
+
export declare const feedbackIdSchema: z.ZodString;
|
|
11
|
+
export declare const cardSchema: z.ZodObject<{
|
|
12
|
+
card_type: z.ZodEnum<{
|
|
13
|
+
button_interaction: "button_interaction";
|
|
14
|
+
multiple_interaction: "multiple_interaction";
|
|
15
|
+
news_notice: "news_notice";
|
|
16
|
+
text_notice: "text_notice";
|
|
17
|
+
vote_interaction: "vote_interaction";
|
|
18
|
+
}>;
|
|
19
|
+
task_id: z.ZodOptional<z.ZodString>;
|
|
20
|
+
feedback: z.ZodOptional<z.ZodObject<{
|
|
21
|
+
id: z.ZodString;
|
|
22
|
+
}, z.core.$strip>>;
|
|
23
|
+
}, z.core.$loose>;
|
|
24
|
+
export type WecomTemplateCard = Omit<TemplateCard, 'card_type'> & {
|
|
25
|
+
card_type: z.output<typeof cardType>;
|
|
26
|
+
};
|
|
27
|
+
export type WecomCardSegment = {
|
|
28
|
+
type: 'wecom:card';
|
|
29
|
+
data: {
|
|
30
|
+
card: z.output<typeof cardSchema>;
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
export declare function cardForSend(card: z.output<typeof cardSchema>): z.output<typeof cardSchema>;
|
|
34
|
+
export declare const wecom: {
|
|
35
|
+
card(card: WecomTemplateCard): WecomCardSegment;
|
|
36
|
+
};
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
const cardType = z.enum([
|
|
4
|
+
'text_notice',
|
|
5
|
+
'news_notice',
|
|
6
|
+
'button_interaction',
|
|
7
|
+
'vote_interaction',
|
|
8
|
+
'multiple_interaction',
|
|
9
|
+
]);
|
|
10
|
+
export const feedbackIdSchema = z
|
|
11
|
+
.string()
|
|
12
|
+
.min(1)
|
|
13
|
+
.refine((value) => Buffer.byteLength(value) <= 256, '反馈 ID 不能超过 256 字节');
|
|
14
|
+
export const cardSchema = z.looseObject({
|
|
15
|
+
card_type: cardType,
|
|
16
|
+
task_id: z
|
|
17
|
+
.string()
|
|
18
|
+
.regex(/^[\w@-]{1,128}$/)
|
|
19
|
+
.optional(),
|
|
20
|
+
feedback: z.object({ id: feedbackIdSchema }).optional(),
|
|
21
|
+
});
|
|
22
|
+
export function cardForSend(card) {
|
|
23
|
+
const interactive = card.card_type !== 'text_notice' && card.card_type !== 'news_notice';
|
|
24
|
+
return !card.task_id && (interactive || card.action_menu) ? { ...card, task_id: randomUUID() } : card;
|
|
25
|
+
}
|
|
26
|
+
export const wecom = {
|
|
27
|
+
card(card) {
|
|
28
|
+
return { type: 'wecom:card', data: { card: cardSchema.parse(card) } };
|
|
29
|
+
},
|
|
30
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const platform = "wecom";
|
|
3
|
+
export declare const wecomSchema: z.ZodObject<{
|
|
4
|
+
botId: z.ZodString;
|
|
5
|
+
secret: z.ZodString;
|
|
6
|
+
botName: z.ZodOptional<z.ZodString>;
|
|
7
|
+
}, z.core.$strict>;
|
|
8
|
+
export type WecomConfig = z.output<typeof wecomSchema>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { botIdentitySchema } from '../../core/identity.js';
|
|
3
|
+
export const platform = 'wecom';
|
|
4
|
+
export const wecomSchema = z
|
|
5
|
+
.object({
|
|
6
|
+
botId: botIdentitySchema.shape.selfId.meta({ title: 'BotID' }),
|
|
7
|
+
secret: z.string().regex(/^\S+$/).meta({ title: 'Secret', writeOnly: true }),
|
|
8
|
+
botName: z.string().trim().min(1).max(120).optional().meta({ title: '机器人显示名' }),
|
|
9
|
+
})
|
|
10
|
+
.strict();
|