@asabot/core 0.1.0 → 0.2.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.
- package/CHANGELOG.md +17 -0
- package/README.md +78 -13
- 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 +5 -1
- 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 +10 -10
- package/dist/core/plugin/context.js +20 -18
- package/dist/core/plugin/definition.d.ts +5 -0
- package/dist/core/plugin/execution.d.ts +3 -0
- package/dist/core/plugin/execution.js +3 -0
- package/dist/core/plugin/manager.d.ts +18 -4
- package/dist/core/plugin/manager.js +137 -45
- package/dist/core/plugin/tasks.d.ts +131 -24
- package/dist/core/plugin/tasks.js +517 -117
- package/dist/core/plugin/types.d.ts +3 -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 +13 -5
- 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 +229 -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 +95 -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 +190 -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-BAbj8e7E.css +2 -0
- package/web/dist/assets/index-CMuBy6y5.js +51 -0
- package/web/dist/assets/{markdown-CDlgpI7K.js → markdown-MEN1AImu.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,539 @@
|
|
|
1
|
+
import { createHmac, randomUUID } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { sendTo, } from '../../core/bot.js';
|
|
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 { isSegment, normalizeSendable, seg } from '../../core/message/index.js';
|
|
8
|
+
import { messageTargetSchema, threadSchema } from '../../core/target.js';
|
|
9
|
+
import { LruSet } from '../../core/utils/lru.js';
|
|
10
|
+
import { redactText } from '../../core/utils/redact.js';
|
|
11
|
+
import { constantTimeEqual } from '../../core/utils/security.js';
|
|
12
|
+
import { chatMode, chatPath, chatRolesSchema, classifyFeishuSend, FeishuClient, feishuOperations, idSchema, messagePath, } from './api.js';
|
|
13
|
+
import { cardSchema, feishu } from './cards.js';
|
|
14
|
+
import { decodeMessageResource, messageResource, readMedia, threadFields, threadOf, } from './message.js';
|
|
15
|
+
export function isFeishu(bot) {
|
|
16
|
+
return bot.platform === 'feishu' && 'feishu' in bot;
|
|
17
|
+
}
|
|
18
|
+
const sentSchema = threadFields;
|
|
19
|
+
const forwardedSchema = sentSchema.extend({
|
|
20
|
+
msg_type: z.string().optional(),
|
|
21
|
+
invalid_message_id_list: z.array(idSchema).default([]),
|
|
22
|
+
});
|
|
23
|
+
const threadTargetSchema = messageTargetSchema.extend({ thread: threadSchema });
|
|
24
|
+
const threadSendResult = z.object({ messageId: idSchema, thread: threadSchema });
|
|
25
|
+
const segmentSchema = z.object({ type: z.string().min(1), data: z.record(z.string(), z.unknown()) });
|
|
26
|
+
const sendableSchema = z.union([z.string(), segmentSchema, z.array(segmentSchema)]);
|
|
27
|
+
const forwardMessageArgs = z.tuple([idSchema, messageTargetSchema]);
|
|
28
|
+
const memberSchema = z.object({ member_id: z.string(), name: z.string().default('') });
|
|
29
|
+
export const feishuCapabilities = {
|
|
30
|
+
segments: [
|
|
31
|
+
'text',
|
|
32
|
+
'at',
|
|
33
|
+
'reply',
|
|
34
|
+
'image',
|
|
35
|
+
'audio',
|
|
36
|
+
'video',
|
|
37
|
+
'file',
|
|
38
|
+
'markdown',
|
|
39
|
+
'button',
|
|
40
|
+
'feishu:card',
|
|
41
|
+
'feishu:sticker',
|
|
42
|
+
'feishu:emoji',
|
|
43
|
+
'feishu:share_chat',
|
|
44
|
+
'feishu:share_user',
|
|
45
|
+
],
|
|
46
|
+
textStyles: ['bold', 'italic', 'underline', 'strike', 'code'],
|
|
47
|
+
actions: [
|
|
48
|
+
'sendPrivate',
|
|
49
|
+
'sendGroup',
|
|
50
|
+
'sendThread',
|
|
51
|
+
'getSelf',
|
|
52
|
+
'getGroupList',
|
|
53
|
+
'getGroupMember',
|
|
54
|
+
'getGroupMembers',
|
|
55
|
+
'getMessage',
|
|
56
|
+
'getForward',
|
|
57
|
+
'kickMember',
|
|
58
|
+
'deleteMessage',
|
|
59
|
+
'call',
|
|
60
|
+
'feishu.sendCard',
|
|
61
|
+
'feishu.updateCard',
|
|
62
|
+
'feishu.downloadResource',
|
|
63
|
+
'feishu.replyInThread',
|
|
64
|
+
'feishu.listMessages',
|
|
65
|
+
'feishu.forwardMessage',
|
|
66
|
+
'feishu.forwardThread',
|
|
67
|
+
'feishu.mergeForward',
|
|
68
|
+
'feishu.editMessage',
|
|
69
|
+
'feishu.addReaction',
|
|
70
|
+
'feishu.removeReaction',
|
|
71
|
+
'feishu.listReactions',
|
|
72
|
+
'feishu.pinMessage',
|
|
73
|
+
'feishu.unpinMessage',
|
|
74
|
+
'feishu.listPins',
|
|
75
|
+
'feishu.listReadUsers',
|
|
76
|
+
'feishu.getChat',
|
|
77
|
+
'feishu.setChatMessageMode',
|
|
78
|
+
'feishu.addChatMembers',
|
|
79
|
+
'feishu.urgentApp',
|
|
80
|
+
],
|
|
81
|
+
};
|
|
82
|
+
export class FeishuBotImpl {
|
|
83
|
+
platform = 'feishu';
|
|
84
|
+
capabilities = feishuCapabilities;
|
|
85
|
+
status = 'connecting';
|
|
86
|
+
selfId;
|
|
87
|
+
nickname;
|
|
88
|
+
avatar;
|
|
89
|
+
feishu;
|
|
90
|
+
sentMessageIds = new LruSet(1000);
|
|
91
|
+
shutdown = new AbortController();
|
|
92
|
+
host;
|
|
93
|
+
client;
|
|
94
|
+
config;
|
|
95
|
+
buttonSecret;
|
|
96
|
+
roles = new Map();
|
|
97
|
+
conversations = new Map();
|
|
98
|
+
constructor(host, transport, self, config, buttonSecret) {
|
|
99
|
+
this.host = host;
|
|
100
|
+
this.client = new FeishuClient(host, this, transport, config);
|
|
101
|
+
this.selfId = self.userId;
|
|
102
|
+
this.nickname = self.nickname;
|
|
103
|
+
this.avatar = self.avatar;
|
|
104
|
+
this.config = config;
|
|
105
|
+
this.buttonSecret = buttonSecret;
|
|
106
|
+
this.feishu = {
|
|
107
|
+
sendCard: (target, card) => sendTo(this, target, feishu.card(card)),
|
|
108
|
+
...feishuOperations(this.client, async (chatId) => (await this.resolveChannel(chatId)).messageType, (chatId) => this.invalidateChat(chatId)),
|
|
109
|
+
replyInThread: async (target, messageId, content) => threadSendResult.parse(await this.client.invokeSend(target, 'replyInThread', [target, messageId, content], async (args) => {
|
|
110
|
+
const [destination, root, message] = z
|
|
111
|
+
.tuple([messageTargetSchema, idSchema, sendableSchema])
|
|
112
|
+
.parse(args);
|
|
113
|
+
if (destination.thread) {
|
|
114
|
+
if (destination.thread.rootMessageId !== root)
|
|
115
|
+
throw new DeliveryError({ ...destination, platform: this.platform, selfId: this.selfId }, { code: 'CONVERSATION_UNAVAILABLE', message: '指定的消息不是目标话题的根消息' });
|
|
116
|
+
return this.send(destination, message);
|
|
117
|
+
}
|
|
118
|
+
return this.send(destination, message, root);
|
|
119
|
+
})),
|
|
120
|
+
forwardMessage: (messageId, target) => this.client.invokeSend(target, 'forwardMessage', [messageId, target], async (args) => {
|
|
121
|
+
const [id, destination] = forwardMessageArgs.parse(args);
|
|
122
|
+
return (await this.forward(`${messagePath(id)}/forward`, destination, false)).sent;
|
|
123
|
+
}),
|
|
124
|
+
forwardThread: (threadId, target) => this.client.invokeSend(target, 'forwardThread', [threadId, target], async (args) => {
|
|
125
|
+
const [id, destination] = forwardMessageArgs.parse(args);
|
|
126
|
+
return (await this.forward(`/im/v1/threads/${encodeURIComponent(id)}/forward`, destination, true))
|
|
127
|
+
.sent;
|
|
128
|
+
}),
|
|
129
|
+
mergeForward: (messageIds, target) => this.client.invokeSend(target, 'mergeForward', [messageIds, target], async (args) => {
|
|
130
|
+
const [ids, destination] = z
|
|
131
|
+
.tuple([z.array(idSchema).min(1).max(100), messageTargetSchema])
|
|
132
|
+
.parse(args);
|
|
133
|
+
const { sent, invalidMessageIds } = await this.forward('/im/v1/messages/merge_forward', destination, true, { message_id_list: ids });
|
|
134
|
+
return { ...sent, invalidMessageIds };
|
|
135
|
+
}),
|
|
136
|
+
commandButton: (label, command) => this.commandButton(label, command),
|
|
137
|
+
updateCard: (messageId, card) => this.client.invoke('updateCard', [messageId, card], async (args) => {
|
|
138
|
+
const [id, value] = z.tuple([idSchema, cardSchema]).parse(args);
|
|
139
|
+
await this.client.raw('PATCH', messagePath(id), { data: { content: JSON.stringify(value) } });
|
|
140
|
+
}),
|
|
141
|
+
downloadResource: async (messageId, key, type) => z.instanceof(Buffer).parse(await this.client.invoke('downloadResource', [messageId, key, type], (args) => {
|
|
142
|
+
const [id, fileKey, kind] = z.tuple([idSchema, idSchema, z.enum(['image', 'file'])]).parse(args);
|
|
143
|
+
return this.client.download(id, fileKey, kind);
|
|
144
|
+
})),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
signature(command) {
|
|
148
|
+
return createHmac('sha256', this.buttonSecret)
|
|
149
|
+
.update(JSON.stringify([this.selfId, command]))
|
|
150
|
+
.digest('base64url');
|
|
151
|
+
}
|
|
152
|
+
commandButton(label, command) {
|
|
153
|
+
z.string().min(1).max(2000).parse(command);
|
|
154
|
+
return feishu.button(label, {
|
|
155
|
+
value: { __asabot_command: { command, signature: this.signature(command) } },
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
commandFrom(value) {
|
|
159
|
+
const result = z
|
|
160
|
+
.object({ command: z.string().min(1).max(2000), signature: z.string() })
|
|
161
|
+
.safeParse(value.__asabot_command);
|
|
162
|
+
if (!result.success || !constantTimeEqual(result.data.signature, this.signature(result.data.command)))
|
|
163
|
+
return undefined;
|
|
164
|
+
return result.data.command;
|
|
165
|
+
}
|
|
166
|
+
async resolveChannel(chatId) {
|
|
167
|
+
const cached = this.roles.get(chatId);
|
|
168
|
+
const chat = cached && cached.expires > Date.now() ? await cached.value : undefined;
|
|
169
|
+
const mode = chat?.chat_mode ??
|
|
170
|
+
(await this.client.data('GET', chatPath(chatId), z.object({ chat_mode: chatMode }), {
|
|
171
|
+
params: { user_id_type: 'open_id' },
|
|
172
|
+
})).chat_mode;
|
|
173
|
+
return mode === 'p2p' ? { messageType: 'private' } : { messageType: 'group', groupId: chatId };
|
|
174
|
+
}
|
|
175
|
+
rememberConversation(messageId, target, thread = target.thread) {
|
|
176
|
+
this.cacheConversation(messageId, target.type === 'group'
|
|
177
|
+
? { messageType: 'group', groupId: target.id, thread }
|
|
178
|
+
: { messageType: 'private', thread });
|
|
179
|
+
}
|
|
180
|
+
cacheConversation(messageId, conversation) {
|
|
181
|
+
this.conversations.delete(messageId);
|
|
182
|
+
this.conversations.set(messageId, conversation);
|
|
183
|
+
if (this.conversations.size > 1000) {
|
|
184
|
+
const oldest = this.conversations.keys().next();
|
|
185
|
+
if (!oldest.done)
|
|
186
|
+
this.conversations.delete(oldest.value);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
knownConversation(messageId) {
|
|
190
|
+
return this.conversations.get(messageId);
|
|
191
|
+
}
|
|
192
|
+
async resolveConversation(messageId) {
|
|
193
|
+
const known = this.conversations.get(messageId);
|
|
194
|
+
if (known)
|
|
195
|
+
return known;
|
|
196
|
+
const message = await this.getMessageResource(messageId);
|
|
197
|
+
const conversation = { ...(await this.resolveChannel(message.chat_id)), thread: threadOf(message) };
|
|
198
|
+
this.cacheConversation(messageId, conversation);
|
|
199
|
+
return conversation;
|
|
200
|
+
}
|
|
201
|
+
assertOnline() {
|
|
202
|
+
if (this.status !== 'online')
|
|
203
|
+
throw new NotConnectedError();
|
|
204
|
+
}
|
|
205
|
+
async resolveSender(userId, groupId) {
|
|
206
|
+
const sender = { userId, nickname: userId };
|
|
207
|
+
if (!groupId)
|
|
208
|
+
return sender;
|
|
209
|
+
let cached = this.roles.get(groupId);
|
|
210
|
+
if (!cached || cached.expires < Date.now()) {
|
|
211
|
+
const value = this.client
|
|
212
|
+
.data('GET', chatPath(groupId), chatRolesSchema, {
|
|
213
|
+
params: { user_id_type: 'open_id' },
|
|
214
|
+
})
|
|
215
|
+
.catch((error) => {
|
|
216
|
+
this.host.logger.warn({
|
|
217
|
+
platform: 'feishu',
|
|
218
|
+
groupId,
|
|
219
|
+
reason: redactText(error instanceof Error ? error.message : String(error), this.config),
|
|
220
|
+
}, 'Cannot resolve Feishu group roles');
|
|
221
|
+
return undefined;
|
|
222
|
+
});
|
|
223
|
+
cached = { expires: Date.now() + 30_000, value };
|
|
224
|
+
this.roles.delete(groupId);
|
|
225
|
+
this.roles.set(groupId, cached);
|
|
226
|
+
while (this.roles.size > 500)
|
|
227
|
+
this.roles.delete(this.roles.keys().next().value);
|
|
228
|
+
}
|
|
229
|
+
const chat = await cached.value;
|
|
230
|
+
if (!chat)
|
|
231
|
+
return sender;
|
|
232
|
+
return {
|
|
233
|
+
...sender,
|
|
234
|
+
role: userId === chat.owner_id ? 'owner' : chat.user_manager_id_list.includes(userId) ? 'admin' : 'member',
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
invalidateChat(chatId) {
|
|
238
|
+
this.roles.delete(chatId);
|
|
239
|
+
}
|
|
240
|
+
sendPrivate(userId, content) {
|
|
241
|
+
return this.send({ type: 'private', id: userId }, content);
|
|
242
|
+
}
|
|
243
|
+
sendGroup(groupId, content) {
|
|
244
|
+
return this.send({ type: 'group', id: groupId }, content);
|
|
245
|
+
}
|
|
246
|
+
sendThread(target, content) {
|
|
247
|
+
return new DeliveryAttempt(this, target).run(() => this.send(threadTargetSchema.parse(target), content));
|
|
248
|
+
}
|
|
249
|
+
async media(type, source, name = 'file') {
|
|
250
|
+
const bytes = await readMedia(source, Math.min(this.config.mediaMaxBytes, type === 'image' ? 10 * 1024 * 1024 : 30 * 1024 * 1024), this.config.apiTimeout, this.shutdown.signal);
|
|
251
|
+
if (bytes === undefined)
|
|
252
|
+
return source;
|
|
253
|
+
return this.client.upload(type, bytes, name);
|
|
254
|
+
}
|
|
255
|
+
send(target, content, openThreadAt) {
|
|
256
|
+
const attempt = new DeliveryAttempt(this, target);
|
|
257
|
+
return attempt.run(() => this.deliver(attempt, target, content, openThreadAt));
|
|
258
|
+
}
|
|
259
|
+
async deliver(attempt, target, content, openThreadAt) {
|
|
260
|
+
this.assertOnline();
|
|
261
|
+
const prepared = await this.host.prepareOutgoing({
|
|
262
|
+
bot: this,
|
|
263
|
+
target,
|
|
264
|
+
message: normalizeSendable(content),
|
|
265
|
+
...(openThreadAt
|
|
266
|
+
? { sendFirst: (part) => this.feishu.replyInThread(target, openThreadAt, part) }
|
|
267
|
+
: {}),
|
|
268
|
+
});
|
|
269
|
+
if (!Array.isArray(prepared))
|
|
270
|
+
return prepared.sent;
|
|
271
|
+
let replyId;
|
|
272
|
+
let thread = target.thread;
|
|
273
|
+
let post = [];
|
|
274
|
+
let original = [];
|
|
275
|
+
let last;
|
|
276
|
+
const deliver = async (type, body, message) => {
|
|
277
|
+
this.assertOnline();
|
|
278
|
+
const reference = thread?.rootMessageId ?? openThreadAt ?? replyId;
|
|
279
|
+
const request = new DeliveryAttempt(this, { ...target, thread });
|
|
280
|
+
const response = await request.request(() => this.client.data('POST', reference ? `${messagePath(reference)}/reply` : '/im/v1/messages', sentSchema, {
|
|
281
|
+
...(reference
|
|
282
|
+
? {}
|
|
283
|
+
: { params: { receive_id_type: target.type === 'group' ? 'chat_id' : 'open_id' } }),
|
|
284
|
+
data: {
|
|
285
|
+
...(reference ? {} : { receive_id: target.id }),
|
|
286
|
+
...(reference && (thread || openThreadAt) ? { reply_in_thread: true } : {}),
|
|
287
|
+
msg_type: type,
|
|
288
|
+
content: JSON.stringify(body),
|
|
289
|
+
uuid: randomUUID(),
|
|
290
|
+
},
|
|
291
|
+
}), classifyFeishuSend);
|
|
292
|
+
const deliveredThread = this.sentThread(response, thread, openThreadAt);
|
|
293
|
+
thread = deliveredThread;
|
|
294
|
+
last = attempt.confirm(this.recordSent(target, response, message, deliveredThread));
|
|
295
|
+
if (openThreadAt && !thread)
|
|
296
|
+
throw new DeliveryError(attempt.target, {
|
|
297
|
+
code: 'DELIVERY_UNCONFIRMED',
|
|
298
|
+
message: '消息已发送,但飞书没有返回新话题的 ID',
|
|
299
|
+
});
|
|
300
|
+
};
|
|
301
|
+
const flush = async () => {
|
|
302
|
+
const text = post.length === 1 ? post[0] : undefined;
|
|
303
|
+
if (text?.tag === 'text' && !text.style)
|
|
304
|
+
await deliver('text', { text: text.text }, original);
|
|
305
|
+
else if (post.length)
|
|
306
|
+
await deliver('post', { zh_cn: { title: '', content: [post] } }, original);
|
|
307
|
+
post = [];
|
|
308
|
+
original = [];
|
|
309
|
+
};
|
|
310
|
+
for (const segment of prepared) {
|
|
311
|
+
if (isSegment(segment, 'reply')) {
|
|
312
|
+
await flush();
|
|
313
|
+
replyId = segment.data.id;
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
if (isSegment(segment, 'text')) {
|
|
317
|
+
post.push({
|
|
318
|
+
tag: 'text',
|
|
319
|
+
text: segment.data.text,
|
|
320
|
+
...(segment.data.style ? { style: segment.data.style } : {}),
|
|
321
|
+
});
|
|
322
|
+
original.push(segment);
|
|
323
|
+
}
|
|
324
|
+
else if (isSegment(segment, 'at')) {
|
|
325
|
+
post.push({ tag: 'at', user_id: segment.data.id });
|
|
326
|
+
original.push(segment);
|
|
327
|
+
}
|
|
328
|
+
else if (isSegment(segment, 'image')) {
|
|
329
|
+
post.push({ tag: 'img', image_key: await this.media('image', segment.data.file) });
|
|
330
|
+
original.push(segment);
|
|
331
|
+
}
|
|
332
|
+
else if (isSegment(segment, 'audio') || isSegment(segment, 'video')) {
|
|
333
|
+
await flush();
|
|
334
|
+
const type = segment.type;
|
|
335
|
+
await deliver(type === 'audio' ? 'audio' : 'media', {
|
|
336
|
+
file_key: await this.media(type, segment.data.file, type === 'audio' ? 'audio.opus' : 'video.mp4'),
|
|
337
|
+
}, [segment]);
|
|
338
|
+
}
|
|
339
|
+
else if (isSegment(segment, 'file')) {
|
|
340
|
+
await flush();
|
|
341
|
+
await deliver('file', { file_key: await this.media('file', segment.data.file, segment.data.name) }, [
|
|
342
|
+
segment,
|
|
343
|
+
]);
|
|
344
|
+
}
|
|
345
|
+
else if (isSegment(segment, 'markdown')) {
|
|
346
|
+
await flush();
|
|
347
|
+
await deliver('interactive', feishu.message([feishu.markdown(segment.data.content)]), [segment]);
|
|
348
|
+
}
|
|
349
|
+
else if (isSegment(segment, 'button')) {
|
|
350
|
+
await flush();
|
|
351
|
+
const button = segment.data.kind === 'link'
|
|
352
|
+
? feishu.button(segment.data.label, { link: segment.data.value })
|
|
353
|
+
: this.commandButton(segment.data.label, segment.data.value);
|
|
354
|
+
await deliver('interactive', feishu.message([button]), [segment]);
|
|
355
|
+
}
|
|
356
|
+
else if (segment.type === 'feishu:card') {
|
|
357
|
+
await flush();
|
|
358
|
+
await deliver('interactive', cardSchema.parse(segment.data.card), [segment]);
|
|
359
|
+
}
|
|
360
|
+
else if (segment.type === 'feishu:emoji') {
|
|
361
|
+
post.push({ tag: 'emotion', emoji_type: z.string().min(1).parse(segment.data.emoji_type) });
|
|
362
|
+
original.push(segment);
|
|
363
|
+
}
|
|
364
|
+
else if (segment.type === 'feishu:sticker') {
|
|
365
|
+
await flush();
|
|
366
|
+
await deliver('sticker', z.object({ file_key: z.string().min(1) }).parse(segment.data), [segment]);
|
|
367
|
+
}
|
|
368
|
+
else if (segment.type === 'feishu:share_chat') {
|
|
369
|
+
await flush();
|
|
370
|
+
await deliver('share_chat', z.object({ chat_id: z.string().min(1) }).parse(segment.data), [segment]);
|
|
371
|
+
}
|
|
372
|
+
else if (segment.type === 'feishu:share_user') {
|
|
373
|
+
await flush();
|
|
374
|
+
await deliver('share_user', z.object({ user_id: z.string().min(1) }).parse(segment.data), [segment]);
|
|
375
|
+
}
|
|
376
|
+
else
|
|
377
|
+
throw new UnsupportedError('feishu', segment.type);
|
|
378
|
+
}
|
|
379
|
+
await flush();
|
|
380
|
+
if (!last)
|
|
381
|
+
throw new UnsupportedError('feishu', '空消息');
|
|
382
|
+
return last;
|
|
383
|
+
}
|
|
384
|
+
sentThread(response, known, root) {
|
|
385
|
+
return (threadOf({
|
|
386
|
+
...response,
|
|
387
|
+
root_id: response.root_id || response.parent_id || known?.rootMessageId || root,
|
|
388
|
+
}) ?? known);
|
|
389
|
+
}
|
|
390
|
+
recordSent(target, response, message, thread) {
|
|
391
|
+
const messageId = response.message_id;
|
|
392
|
+
this.sentMessageIds.add(messageId);
|
|
393
|
+
this.rememberConversation(messageId, { ...target, thread });
|
|
394
|
+
const context = dispatchContext.getStore();
|
|
395
|
+
const fields = {
|
|
396
|
+
platform: this.platform,
|
|
397
|
+
selfId: this.selfId,
|
|
398
|
+
messageId,
|
|
399
|
+
messageType: target.type,
|
|
400
|
+
...(target.type === 'group' ? { groupId: target.id } : { userId: target.id }),
|
|
401
|
+
...(context?.active.value ? { eventId: context.eventId } : {}),
|
|
402
|
+
};
|
|
403
|
+
this.host.logger.info({ ...fields, ...(thread ? { threadId: thread.id } : {}) }, 'Feishu message sent');
|
|
404
|
+
this.host.emit({
|
|
405
|
+
...fields,
|
|
406
|
+
id: randomUUID(),
|
|
407
|
+
time: Date.now(),
|
|
408
|
+
kind: 'internal',
|
|
409
|
+
name: 'bot.message.sent',
|
|
410
|
+
raw: response,
|
|
411
|
+
bot: this,
|
|
412
|
+
...(thread ? { thread } : {}),
|
|
413
|
+
message,
|
|
414
|
+
});
|
|
415
|
+
return { messageId, ...(thread ? { thread } : {}) };
|
|
416
|
+
}
|
|
417
|
+
async forward(path, target, merged, data = {}) {
|
|
418
|
+
const response = await new DeliveryAttempt(this, target).request(() => this.client.data('POST', path, forwardedSchema, {
|
|
419
|
+
params: {
|
|
420
|
+
receive_id_type: target.thread ? 'thread_id' : target.type === 'group' ? 'chat_id' : 'open_id',
|
|
421
|
+
},
|
|
422
|
+
data: { ...data, receive_id: target.thread?.id ?? target.id, uuid: randomUUID() },
|
|
423
|
+
}), classifyFeishuSend);
|
|
424
|
+
const message = merged || response.msg_type === 'merge_forward'
|
|
425
|
+
? seg.forward(response.message_id)
|
|
426
|
+
: seg.text('[转发消息]');
|
|
427
|
+
const sent = this.recordSent(target, response, [message], this.sentThread(response, target.thread));
|
|
428
|
+
return { sent, invalidMessageIds: response.invalid_message_id_list };
|
|
429
|
+
}
|
|
430
|
+
async getSelf() {
|
|
431
|
+
return { userId: this.selfId, nickname: this.nickname, avatar: this.avatar };
|
|
432
|
+
}
|
|
433
|
+
async deleteMessage(messageId) {
|
|
434
|
+
this.assertOnline();
|
|
435
|
+
await this.client.raw('DELETE', messagePath(messageId));
|
|
436
|
+
}
|
|
437
|
+
async getGroupList() {
|
|
438
|
+
this.assertOnline();
|
|
439
|
+
return (await this.client.allPages('/im/v1/chats', z.object({ chat_id: z.string(), name: z.string().default('') }), {
|
|
440
|
+
user_id_type: 'open_id',
|
|
441
|
+
})).map((chat) => ({ groupId: chat.chat_id, groupName: chat.name }));
|
|
442
|
+
}
|
|
443
|
+
async getGroupMembers(groupId) {
|
|
444
|
+
this.assertOnline();
|
|
445
|
+
const path = chatPath(groupId);
|
|
446
|
+
const [members, chat] = await Promise.all([
|
|
447
|
+
this.client.allPages(`${path}/members`, memberSchema, { member_id_type: 'open_id' }),
|
|
448
|
+
this.client.data('GET', path, chatRolesSchema, { params: { user_id_type: 'open_id' } }),
|
|
449
|
+
]);
|
|
450
|
+
return members.map((member) => ({
|
|
451
|
+
groupId,
|
|
452
|
+
userId: member.member_id,
|
|
453
|
+
nickname: member.name,
|
|
454
|
+
role: member.member_id === chat.owner_id
|
|
455
|
+
? 'owner'
|
|
456
|
+
: chat.user_manager_id_list.includes(member.member_id)
|
|
457
|
+
? 'admin'
|
|
458
|
+
: 'member',
|
|
459
|
+
}));
|
|
460
|
+
}
|
|
461
|
+
async getGroupMember(groupId, userId) {
|
|
462
|
+
const member = (await this.getGroupMembers(groupId)).find((m) => m.userId === userId);
|
|
463
|
+
if (!member)
|
|
464
|
+
throw new Error('Feishu group member not found');
|
|
465
|
+
return member;
|
|
466
|
+
}
|
|
467
|
+
async getMessage(messageId) {
|
|
468
|
+
this.assertOnline();
|
|
469
|
+
const message = await this.getMessageResource(messageId);
|
|
470
|
+
const channel = await this.resolveChannel(message.chat_id);
|
|
471
|
+
return decodeMessageResource(message, channel.messageType);
|
|
472
|
+
}
|
|
473
|
+
async getMessageResource(messageId) {
|
|
474
|
+
const items = await this.getMessageResources(messageId);
|
|
475
|
+
const message = items.find((item) => item.message_id === messageId);
|
|
476
|
+
if (!message)
|
|
477
|
+
throw new Error('Feishu message not found');
|
|
478
|
+
return message;
|
|
479
|
+
}
|
|
480
|
+
async getMessageResources(messageId) {
|
|
481
|
+
const { items } = await this.client.data('GET', messagePath(messageId), z.object({ items: z.array(messageResource) }), { params: { user_id_type: 'open_id' } });
|
|
482
|
+
return items;
|
|
483
|
+
}
|
|
484
|
+
async call(action, params = {}) {
|
|
485
|
+
this.assertOnline();
|
|
486
|
+
const [method, path, extra] = action.split(' ');
|
|
487
|
+
if (!method ||
|
|
488
|
+
!['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(method) ||
|
|
489
|
+
!path?.startsWith('/') ||
|
|
490
|
+
path.includes('..') ||
|
|
491
|
+
extra)
|
|
492
|
+
throw new TypeError('Expected METHOD /open-api-path');
|
|
493
|
+
const input = z
|
|
494
|
+
.object({
|
|
495
|
+
data: z.record(z.string(), z.unknown()).optional(),
|
|
496
|
+
params: z.record(z.string(), z.union([z.string(), z.number()])).optional(),
|
|
497
|
+
})
|
|
498
|
+
.strict()
|
|
499
|
+
.parse(params);
|
|
500
|
+
return this.client.raw(method, path, input);
|
|
501
|
+
}
|
|
502
|
+
async sendForward(_target, _nodes) {
|
|
503
|
+
throw new UnsupportedError('feishu', 'sendForward');
|
|
504
|
+
}
|
|
505
|
+
async getForward(id) {
|
|
506
|
+
this.assertOnline();
|
|
507
|
+
const items = await this.getMessageResources(id);
|
|
508
|
+
const root = items.find((item) => item.message_id === id && item.msg_type === 'merge_forward');
|
|
509
|
+
if (!root || root.deleted)
|
|
510
|
+
throw new Error('Feishu merged message is unavailable');
|
|
511
|
+
const channel = await this.resolveChannel(root.chat_id);
|
|
512
|
+
return items
|
|
513
|
+
.filter((item) => item.upper_message_id === id && !item.deleted)
|
|
514
|
+
.map((item) => {
|
|
515
|
+
const { userId, sender, time, message } = decodeMessageResource(item, channel.messageType);
|
|
516
|
+
return { userId, nickname: sender.nickname, time, message };
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
async muteMember(_group, _user, _duration) {
|
|
520
|
+
throw new UnsupportedError('feishu', 'muteMember');
|
|
521
|
+
}
|
|
522
|
+
async kickMember(groupId, userId, options) {
|
|
523
|
+
this.assertOnline();
|
|
524
|
+
if (options?.rejectRequest)
|
|
525
|
+
throw new UnsupportedError('feishu', 'kickMember.rejectRequest');
|
|
526
|
+
const result = await this.client.data('DELETE', `${chatPath(groupId)}/members`, z.object({ invalid_id_list: z.array(z.string()).default([]) }), {
|
|
527
|
+
params: { member_id_type: 'open_id' },
|
|
528
|
+
data: { id_list: [userId] },
|
|
529
|
+
});
|
|
530
|
+
if (result.invalid_id_list.length)
|
|
531
|
+
throw new Error('Feishu could not remove the requested member');
|
|
532
|
+
}
|
|
533
|
+
async setMemberCard(_group, _user, _card) {
|
|
534
|
+
throw new UnsupportedError('feishu', 'setMemberCard');
|
|
535
|
+
}
|
|
536
|
+
async getFriendList() {
|
|
537
|
+
throw new UnsupportedError('feishu', 'getFriendList');
|
|
538
|
+
}
|
|
539
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { MessageThread } from '../../core/bot.ts';
|
|
3
|
+
import type { AnyEvent, PlatformNoticeEvent, Session } from '../../core/event/index.ts';
|
|
4
|
+
import type { Segment } from '../../core/message/index.ts';
|
|
5
|
+
import type { Target } from '../../core/target.ts';
|
|
6
|
+
export interface FeishuElement {
|
|
7
|
+
tag: string;
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
export interface FeishuCard {
|
|
11
|
+
schema: '2.0';
|
|
12
|
+
body: {
|
|
13
|
+
elements: FeishuElement[];
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
};
|
|
16
|
+
header?: Record<string, unknown>;
|
|
17
|
+
config?: Record<string, unknown>;
|
|
18
|
+
[key: string]: unknown;
|
|
19
|
+
}
|
|
20
|
+
export interface FeishuCardResponse {
|
|
21
|
+
toast?: {
|
|
22
|
+
type: 'success' | 'info' | 'warning' | 'error';
|
|
23
|
+
content: string;
|
|
24
|
+
i18n?: Record<string, string>;
|
|
25
|
+
};
|
|
26
|
+
card?: {
|
|
27
|
+
type: 'raw';
|
|
28
|
+
data: FeishuCard;
|
|
29
|
+
} | {
|
|
30
|
+
type: 'template';
|
|
31
|
+
data: Record<string, unknown>;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export interface FeishuCardActionEvent extends PlatformNoticeEvent {
|
|
35
|
+
readonly name: 'notice.feishu.card.action';
|
|
36
|
+
readonly platformType: 'card.action.trigger';
|
|
37
|
+
readonly userId: string;
|
|
38
|
+
readonly chatId: string;
|
|
39
|
+
readonly messageId: string;
|
|
40
|
+
readonly thread?: MessageThread;
|
|
41
|
+
readonly target?: Target;
|
|
42
|
+
readonly sender: Session['sender'];
|
|
43
|
+
readonly action: {
|
|
44
|
+
tag: string;
|
|
45
|
+
name?: string;
|
|
46
|
+
value: Record<string, unknown>;
|
|
47
|
+
inputValue?: string;
|
|
48
|
+
option?: string;
|
|
49
|
+
options?: string[];
|
|
50
|
+
formValue?: Record<string, unknown>;
|
|
51
|
+
timezone?: string;
|
|
52
|
+
raw: Record<string, unknown>;
|
|
53
|
+
};
|
|
54
|
+
/** Accept the first response within two seconds; returns false after the deadline or shutdown. */
|
|
55
|
+
respond(response: FeishuCardResponse): boolean;
|
|
56
|
+
}
|
|
57
|
+
export declare const cardSchema: z.ZodType<FeishuCard>;
|
|
58
|
+
export declare const cardResponseSchema: z.ZodType<FeishuCardResponse>;
|
|
59
|
+
export declare function isFeishuCardAction(event: AnyEvent): event is FeishuCardActionEvent;
|
|
60
|
+
/** 飞书消息段及 JSON 2.0 卡片构造器。 */
|
|
61
|
+
export declare const feishu: {
|
|
62
|
+
card(card: FeishuCard): Segment;
|
|
63
|
+
emoji(emoji: string): Segment;
|
|
64
|
+
sticker(fileKey: string): Segment;
|
|
65
|
+
shareChat(chatId: string): Segment;
|
|
66
|
+
shareUser(openId: string): Segment;
|
|
67
|
+
message(elements: FeishuElement[], title?: string): FeishuCard;
|
|
68
|
+
markdown(content: string): FeishuElement;
|
|
69
|
+
button(label: string, options?: {
|
|
70
|
+
name?: string;
|
|
71
|
+
value?: Record<string, unknown>;
|
|
72
|
+
link?: string;
|
|
73
|
+
type?: 'default' | 'primary' | 'danger';
|
|
74
|
+
}): FeishuElement;
|
|
75
|
+
input(name: string, options?: {
|
|
76
|
+
placeholder?: string;
|
|
77
|
+
required?: boolean;
|
|
78
|
+
defaultValue?: string;
|
|
79
|
+
multiline?: boolean;
|
|
80
|
+
value?: Record<string, unknown>;
|
|
81
|
+
}): FeishuElement;
|
|
82
|
+
select(name: string, choices: {
|
|
83
|
+
label: string;
|
|
84
|
+
value: string;
|
|
85
|
+
}[], options?: {
|
|
86
|
+
placeholder?: string;
|
|
87
|
+
required?: boolean;
|
|
88
|
+
multiple?: boolean;
|
|
89
|
+
value?: Record<string, unknown>;
|
|
90
|
+
}): FeishuElement;
|
|
91
|
+
form(name: string, elements: FeishuElement[]): FeishuElement;
|
|
92
|
+
submit(label: string, name: string, value?: Record<string, unknown>): FeishuElement;
|
|
93
|
+
};
|