@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,142 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { AdapterHost } from '../../core/adapter.ts';
|
|
3
|
+
import type { Bot, MessageTarget, MessageThread, SendResult } from '../../core/bot.ts';
|
|
4
|
+
import { type DeliveryCode } from '../../core/delivery.ts';
|
|
5
|
+
import type { Sendable } from '../../core/message/index.ts';
|
|
6
|
+
import type { FeishuCard, FeishuElement } from './cards.ts';
|
|
7
|
+
import type { FeishuConfig } from './config.ts';
|
|
8
|
+
import { type FeishuMessageInfo } from './message.ts';
|
|
9
|
+
import type { FeishuRequest, FeishuTransport, FeishuUploadKind } from './transport.ts';
|
|
10
|
+
export interface FeishuApi {
|
|
11
|
+
sendCard(target: MessageTarget, card: FeishuCard): Promise<SendResult>;
|
|
12
|
+
updateCard(messageId: string, card: FeishuCard): Promise<void>;
|
|
13
|
+
/** 以指定消息开启话题;传入现有话题时,messageId 必须是该话题的根消息。 */
|
|
14
|
+
replyInThread(target: MessageTarget, messageId: string, content: Sendable): Promise<SendResult & {
|
|
15
|
+
thread: MessageThread;
|
|
16
|
+
}>;
|
|
17
|
+
listMessages(container: FeishuMessageContainer, options?: FeishuListMessagesOptions): Promise<FeishuMessagePage>;
|
|
18
|
+
forwardMessage(messageId: string, target: MessageTarget): Promise<SendResult>;
|
|
19
|
+
forwardThread(threadId: string, target: MessageTarget): Promise<SendResult>;
|
|
20
|
+
mergeForward(messageIds: string[], target: MessageTarget): Promise<FeishuMergeForwardResult>;
|
|
21
|
+
editMessage(messageId: string, text: string): Promise<void>;
|
|
22
|
+
addReaction(messageId: string, emoji: string): Promise<string>;
|
|
23
|
+
removeReaction(messageId: string, reactionId: string): Promise<void>;
|
|
24
|
+
listReactions(messageId: string, options?: FeishuListReactionsOptions): Promise<FeishuPage<FeishuReaction>>;
|
|
25
|
+
pinMessage(messageId: string): Promise<void>;
|
|
26
|
+
unpinMessage(messageId: string): Promise<void>;
|
|
27
|
+
listPins(chatId: string, options?: FeishuPageOptions): Promise<FeishuPage<FeishuPin>>;
|
|
28
|
+
listReadUsers(messageId: string, options?: FeishuPageOptions): Promise<FeishuPage<FeishuReadUser>>;
|
|
29
|
+
getChat(chatId: string): Promise<FeishuChatInfo>;
|
|
30
|
+
setChatMessageMode(chatId: string, mode: 'chat' | 'thread'): Promise<void>;
|
|
31
|
+
addChatMembers(chatId: string, openIds: string[]): Promise<FeishuAddMembersResult>;
|
|
32
|
+
urgentApp(messageId: string, openIds: string[]): Promise<{
|
|
33
|
+
invalidUserIds: string[];
|
|
34
|
+
}>;
|
|
35
|
+
commandButton(label: string, command: string): FeishuElement;
|
|
36
|
+
downloadResource(messageId: string, key: string, type: 'image' | 'file'): Promise<Buffer>;
|
|
37
|
+
}
|
|
38
|
+
export interface FeishuMessageContainer {
|
|
39
|
+
type: 'chat' | 'thread';
|
|
40
|
+
id: string;
|
|
41
|
+
}
|
|
42
|
+
export interface FeishuPageOptions {
|
|
43
|
+
pageSize?: number;
|
|
44
|
+
pageToken?: string;
|
|
45
|
+
}
|
|
46
|
+
export interface FeishuListMessagesOptions extends FeishuPageOptions {
|
|
47
|
+
order?: 'asc' | 'desc';
|
|
48
|
+
/** 毫秒级 Unix 时间戳,仅适用于 chat 容器。 */
|
|
49
|
+
startTime?: number;
|
|
50
|
+
endTime?: number;
|
|
51
|
+
}
|
|
52
|
+
export interface FeishuListReactionsOptions extends FeishuPageOptions {
|
|
53
|
+
emoji?: string;
|
|
54
|
+
}
|
|
55
|
+
export interface FeishuPage<T> {
|
|
56
|
+
items: T[];
|
|
57
|
+
pageToken?: string;
|
|
58
|
+
}
|
|
59
|
+
export interface FeishuReaction {
|
|
60
|
+
reactionId: string;
|
|
61
|
+
emoji: string;
|
|
62
|
+
operatorId: string;
|
|
63
|
+
operatorType: 'user' | 'app';
|
|
64
|
+
time: number;
|
|
65
|
+
}
|
|
66
|
+
export interface FeishuPin {
|
|
67
|
+
messageId: string;
|
|
68
|
+
chatId: string;
|
|
69
|
+
operatorId: string;
|
|
70
|
+
time: number;
|
|
71
|
+
}
|
|
72
|
+
export interface FeishuReadUser {
|
|
73
|
+
userId: string;
|
|
74
|
+
time: number;
|
|
75
|
+
}
|
|
76
|
+
export interface FeishuChatInfo {
|
|
77
|
+
chatId: string;
|
|
78
|
+
mode: 'p2p' | 'group' | 'topic';
|
|
79
|
+
messageMode?: 'chat' | 'thread';
|
|
80
|
+
name?: string;
|
|
81
|
+
description?: string;
|
|
82
|
+
avatar?: string;
|
|
83
|
+
ownerId?: string;
|
|
84
|
+
adminIds: string[];
|
|
85
|
+
botAdminIds: string[];
|
|
86
|
+
memberCount?: number;
|
|
87
|
+
}
|
|
88
|
+
export interface FeishuAddMembersResult {
|
|
89
|
+
invalidIds: string[];
|
|
90
|
+
missingIds: string[];
|
|
91
|
+
pendingApprovalIds: string[];
|
|
92
|
+
}
|
|
93
|
+
export interface FeishuMergeForwardResult extends SendResult {
|
|
94
|
+
invalidMessageIds: string[];
|
|
95
|
+
}
|
|
96
|
+
export type FeishuMessagePage = FeishuPage<FeishuMessageInfo>;
|
|
97
|
+
declare const envelope: z.ZodObject<{
|
|
98
|
+
code: z.ZodNumber;
|
|
99
|
+
msg: z.ZodOptional<z.ZodString>;
|
|
100
|
+
}, z.core.$loose>;
|
|
101
|
+
export declare function classifyFeishuSend(error: unknown): {
|
|
102
|
+
code: DeliveryCode;
|
|
103
|
+
platformCode?: number;
|
|
104
|
+
} | undefined;
|
|
105
|
+
export declare const idSchema: z.ZodString;
|
|
106
|
+
export declare const chatMode: z.ZodEnum<{
|
|
107
|
+
group: "group";
|
|
108
|
+
p2p: "p2p";
|
|
109
|
+
topic: "topic";
|
|
110
|
+
}>;
|
|
111
|
+
export declare const chatRolesSchema: z.ZodObject<{
|
|
112
|
+
chat_mode: z.ZodOptional<z.ZodEnum<{
|
|
113
|
+
group: "group";
|
|
114
|
+
p2p: "p2p";
|
|
115
|
+
topic: "topic";
|
|
116
|
+
}>>;
|
|
117
|
+
owner_id: z.ZodOptional<z.ZodString>;
|
|
118
|
+
user_manager_id_list: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
119
|
+
}, z.core.$strip>;
|
|
120
|
+
export declare const messagePath: (id: string) => string;
|
|
121
|
+
export declare const chatPath: (id: string) => string;
|
|
122
|
+
export declare class FeishuClient {
|
|
123
|
+
private readonly host;
|
|
124
|
+
private readonly bot;
|
|
125
|
+
private readonly transport;
|
|
126
|
+
private readonly config;
|
|
127
|
+
constructor(host: AdapterHost, bot: Bot, transport: FeishuTransport, config: FeishuConfig);
|
|
128
|
+
invoke<T>(method: keyof FeishuApi, args: unknown[], run: (args: unknown[]) => Promise<T>): Promise<T>;
|
|
129
|
+
invokeSend<T>(target: MessageTarget, method: keyof FeishuApi, args: unknown[], run: (args: unknown[]) => Promise<T>): Promise<T>;
|
|
130
|
+
private checked;
|
|
131
|
+
raw(method: string, path: string, input?: FeishuRequest): Promise<z.output<typeof envelope>>;
|
|
132
|
+
data<T>(method: string, path: string, schema: z.ZodType<T>, input?: FeishuRequest): Promise<T>;
|
|
133
|
+
upload(kind: FeishuUploadKind, bytes: Buffer, name: string): Promise<string>;
|
|
134
|
+
download(messageId: string, key: string, type: 'image' | 'file'): Promise<Buffer>;
|
|
135
|
+
page<T>(path: string, schema: z.ZodType<T>, params: Record<string, string | number>, { pageSize, pageToken }: {
|
|
136
|
+
pageSize: number;
|
|
137
|
+
pageToken?: string;
|
|
138
|
+
}): Promise<FeishuPage<T>>;
|
|
139
|
+
allPages<T>(path: string, schema: z.ZodType<T>, params: Record<string, string | number>): Promise<T[]>;
|
|
140
|
+
}
|
|
141
|
+
export declare function feishuOperations(client: FeishuClient, messageType: (chatId: string) => Promise<'private' | 'group'>, invalidateChat: (chatId: string) => void): Omit<FeishuApi, 'sendCard' | 'updateCard' | 'replyInThread' | 'forwardMessage' | 'forwardThread' | 'mergeForward' | 'commandButton' | 'downloadResource'>;
|
|
142
|
+
export {};
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { DeliveryAttempt } from '../../core/delivery.js';
|
|
3
|
+
import { NotConnectedError } from '../../core/errors.js';
|
|
4
|
+
import { redactText } from '../../core/utils/redact.js';
|
|
5
|
+
import { decodeMessageResource, messageResource } from './message.js';
|
|
6
|
+
const envelope = z.object({ code: z.number(), msg: z.string().optional() }).passthrough();
|
|
7
|
+
const transportFailure = z.object({
|
|
8
|
+
code: z.string().optional(),
|
|
9
|
+
name: z.string().optional(),
|
|
10
|
+
response: z.object({ status: z.number(), data: z.unknown().optional() }).optional(),
|
|
11
|
+
});
|
|
12
|
+
class FeishuRequestError extends Error {
|
|
13
|
+
platformCode;
|
|
14
|
+
status;
|
|
15
|
+
timeout;
|
|
16
|
+
constructor(message, platformCode, status, timeout = false) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'FeishuRequestError';
|
|
19
|
+
this.platformCode = platformCode;
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.timeout = timeout;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function classifyFeishuSend(error) {
|
|
25
|
+
if (!(error instanceof FeishuRequestError))
|
|
26
|
+
return undefined;
|
|
27
|
+
const { platformCode, status } = error;
|
|
28
|
+
if (status === 429 || platformCode === 99991400)
|
|
29
|
+
return { code: 'RATE_LIMITED', platformCode };
|
|
30
|
+
if (error.timeout || status === 408 || status === 504)
|
|
31
|
+
return { code: 'DELIVERY_TIMEOUT', platformCode };
|
|
32
|
+
if (status === 404 || platformCode === 230003)
|
|
33
|
+
return { code: 'CONVERSATION_UNAVAILABLE', platformCode };
|
|
34
|
+
if (status !== undefined && status >= 500)
|
|
35
|
+
return { code: 'DELIVERY_UNCONFIRMED', platformCode };
|
|
36
|
+
if (platformCode || (status !== undefined && status >= 400))
|
|
37
|
+
return { code: 'DELIVERY_REJECTED', platformCode };
|
|
38
|
+
}
|
|
39
|
+
export const idSchema = z.string().min(1);
|
|
40
|
+
const timeSchema = z.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
41
|
+
const ids = z.array(idSchema).default([]);
|
|
42
|
+
export const chatMode = z.enum(['group', 'p2p', 'topic']);
|
|
43
|
+
const messageMode = z.enum(['chat', 'thread']);
|
|
44
|
+
export const chatRolesSchema = z.object({
|
|
45
|
+
chat_mode: chatMode.optional(),
|
|
46
|
+
owner_id: z.string().optional(),
|
|
47
|
+
user_manager_id_list: ids,
|
|
48
|
+
});
|
|
49
|
+
const fullChat = chatRolesSchema.extend({
|
|
50
|
+
chat_mode: chatMode,
|
|
51
|
+
group_message_type: messageMode.optional(),
|
|
52
|
+
name: z.string().optional(),
|
|
53
|
+
description: z.string().optional(),
|
|
54
|
+
avatar: z.string().optional(),
|
|
55
|
+
bot_manager_id_list: ids,
|
|
56
|
+
user_count: z.coerce.number().int().nonnegative().optional(),
|
|
57
|
+
});
|
|
58
|
+
const container = z.object({ type: z.enum(['chat', 'thread']), id: idSchema });
|
|
59
|
+
const pageOptions = z.object({
|
|
60
|
+
pageSize: z.number().int().min(1).max(50).default(20),
|
|
61
|
+
pageToken: idSchema.optional(),
|
|
62
|
+
});
|
|
63
|
+
const messageListOptions = pageOptions.extend({
|
|
64
|
+
order: z.enum(['asc', 'desc']).default('desc'),
|
|
65
|
+
startTime: z.number().int().nonnegative().optional(),
|
|
66
|
+
endTime: z.number().int().nonnegative().optional(),
|
|
67
|
+
});
|
|
68
|
+
const messageListArgs = z.tuple([container, messageListOptions.prefault({})]).refine(([source, options]) => {
|
|
69
|
+
const { startTime, endTime } = options;
|
|
70
|
+
if (startTime === undefined && endTime === undefined)
|
|
71
|
+
return true;
|
|
72
|
+
return source.type === 'chat' && (startTime === undefined || endTime === undefined || startTime < endTime);
|
|
73
|
+
}, 'Message time filters require a chat and startTime before endTime');
|
|
74
|
+
const reactionListOptions = pageOptions.extend({ emoji: idSchema.optional() });
|
|
75
|
+
const readUserListOptions = pageOptions.extend({ pageSize: z.number().int().min(1).max(100).default(20) });
|
|
76
|
+
const reaction = z
|
|
77
|
+
.object({
|
|
78
|
+
reaction_id: idSchema,
|
|
79
|
+
reaction_type: z.object({ emoji_type: idSchema }),
|
|
80
|
+
operator: z.object({ operator_id: idSchema, operator_type: z.enum(['user', 'app']) }),
|
|
81
|
+
action_time: timeSchema,
|
|
82
|
+
})
|
|
83
|
+
.transform((item) => ({
|
|
84
|
+
reactionId: item.reaction_id,
|
|
85
|
+
emoji: item.reaction_type.emoji_type,
|
|
86
|
+
operatorId: item.operator.operator_id,
|
|
87
|
+
operatorType: item.operator.operator_type,
|
|
88
|
+
time: item.action_time,
|
|
89
|
+
}));
|
|
90
|
+
const pin = z
|
|
91
|
+
.object({
|
|
92
|
+
message_id: idSchema,
|
|
93
|
+
chat_id: idSchema,
|
|
94
|
+
operator_id: idSchema,
|
|
95
|
+
create_time: timeSchema,
|
|
96
|
+
})
|
|
97
|
+
.transform((item) => ({
|
|
98
|
+
messageId: item.message_id,
|
|
99
|
+
chatId: item.chat_id,
|
|
100
|
+
operatorId: item.operator_id,
|
|
101
|
+
time: item.create_time,
|
|
102
|
+
}));
|
|
103
|
+
const readUser = z
|
|
104
|
+
.object({ user_id: idSchema, timestamp: timeSchema })
|
|
105
|
+
.transform((item) => ({ userId: item.user_id, time: item.timestamp }));
|
|
106
|
+
const addedMembers = z.object({
|
|
107
|
+
invalid_id_list: ids,
|
|
108
|
+
not_existed_id_list: ids,
|
|
109
|
+
pending_approval_id_list: ids,
|
|
110
|
+
});
|
|
111
|
+
export const messagePath = (id) => `/im/v1/messages/${encodeURIComponent(id)}`;
|
|
112
|
+
export const chatPath = (id) => `/im/v1/chats/${encodeURIComponent(id)}`;
|
|
113
|
+
export class FeishuClient {
|
|
114
|
+
host;
|
|
115
|
+
bot;
|
|
116
|
+
transport;
|
|
117
|
+
config;
|
|
118
|
+
constructor(host, bot, transport, config) {
|
|
119
|
+
this.host = host;
|
|
120
|
+
this.bot = bot;
|
|
121
|
+
this.transport = transport;
|
|
122
|
+
this.config = config;
|
|
123
|
+
}
|
|
124
|
+
async invoke(method, args, run) {
|
|
125
|
+
const result = await this.host.invokeApi({ bot: this.bot, method: `feishu.${method}`, args }, (actualArgs) => {
|
|
126
|
+
if (this.bot.status !== 'online')
|
|
127
|
+
throw new NotConnectedError();
|
|
128
|
+
return run(actualArgs);
|
|
129
|
+
});
|
|
130
|
+
// In-process interceptors may replace the result and are responsible for preserving the method's return type.
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
133
|
+
invokeSend(target, method, args, run) {
|
|
134
|
+
return new DeliveryAttempt(this.bot, target).request(() => this.invoke(method, args, run));
|
|
135
|
+
}
|
|
136
|
+
async checked(work) {
|
|
137
|
+
let raw;
|
|
138
|
+
try {
|
|
139
|
+
raw = await work();
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
const failure = transportFailure.safeParse(error).data;
|
|
143
|
+
const response = failure?.response;
|
|
144
|
+
const code = envelope.safeParse(response?.data).data?.code;
|
|
145
|
+
throw new FeishuRequestError(redactText(error instanceof Error ? error.message : String(error), this.config), code, response?.status, failure?.name === 'TimeoutError' || failure?.code === 'ECONNABORTED' || failure?.code === 'ETIMEDOUT');
|
|
146
|
+
}
|
|
147
|
+
const result = envelope.parse(raw);
|
|
148
|
+
if (result.code !== 0)
|
|
149
|
+
throw new FeishuRequestError(redactText(`Feishu API ${result.code}: ${result.msg ?? 'request failed'}`, this.config), result.code);
|
|
150
|
+
return result;
|
|
151
|
+
}
|
|
152
|
+
raw(method, path, input) {
|
|
153
|
+
return this.checked(() => this.transport.request(method, path, input));
|
|
154
|
+
}
|
|
155
|
+
async data(method, path, schema, input) {
|
|
156
|
+
const result = await this.raw(method, path, input);
|
|
157
|
+
return schema.parse(result.data);
|
|
158
|
+
}
|
|
159
|
+
async upload(kind, bytes, name) {
|
|
160
|
+
const result = await this.checked(() => this.transport.upload(kind, bytes, name));
|
|
161
|
+
if (kind === 'image')
|
|
162
|
+
return z.object({ image_key: idSchema }).parse(result.data).image_key;
|
|
163
|
+
return z.object({ file_key: idSchema }).parse(result.data).file_key;
|
|
164
|
+
}
|
|
165
|
+
async download(messageId, key, type) {
|
|
166
|
+
try {
|
|
167
|
+
return await this.transport.download(messageId, key, type);
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
throw new Error(redactText(error instanceof Error ? error.message : String(error), this.config));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
async page(path, schema, params, { pageSize, pageToken }) {
|
|
174
|
+
const page = await this.data('GET', path, z.object({
|
|
175
|
+
items: z.array(schema).default([]),
|
|
176
|
+
has_more: z.boolean().default(false),
|
|
177
|
+
page_token: z.string().optional(),
|
|
178
|
+
}), { params: { ...params, page_size: pageSize, ...(pageToken ? { page_token: pageToken } : {}) } });
|
|
179
|
+
if (!page.has_more)
|
|
180
|
+
return { items: page.items };
|
|
181
|
+
if (!page.page_token || page.page_token === pageToken)
|
|
182
|
+
throw new Error('Feishu returned an invalid pagination token');
|
|
183
|
+
return { items: page.items, pageToken: page.page_token };
|
|
184
|
+
}
|
|
185
|
+
async allPages(path, schema, params) {
|
|
186
|
+
const items = [];
|
|
187
|
+
const seen = new Set();
|
|
188
|
+
let pageToken;
|
|
189
|
+
do {
|
|
190
|
+
const page = await this.page(path, schema, params, { pageSize: 100, pageToken });
|
|
191
|
+
items.push(...page.items);
|
|
192
|
+
pageToken = page.pageToken;
|
|
193
|
+
if (pageToken) {
|
|
194
|
+
if (seen.has(pageToken))
|
|
195
|
+
throw new Error('Feishu returned an invalid pagination token');
|
|
196
|
+
seen.add(pageToken);
|
|
197
|
+
}
|
|
198
|
+
} while (pageToken);
|
|
199
|
+
return items;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
export function feishuOperations(client, messageType, invalidateChat) {
|
|
203
|
+
return {
|
|
204
|
+
listMessages: (container, options) => client.invoke('listMessages', [container, options], async (args) => {
|
|
205
|
+
const [source, settings] = messageListArgs.parse(args);
|
|
206
|
+
const page = await client.page('/im/v1/messages', messageResource, {
|
|
207
|
+
container_id_type: source.type,
|
|
208
|
+
container_id: source.id,
|
|
209
|
+
sort_type: settings.order === 'asc' ? 'ByCreateTimeAsc' : 'ByCreateTimeDesc',
|
|
210
|
+
...(settings.startTime === undefined
|
|
211
|
+
? {}
|
|
212
|
+
: { start_time: Math.floor(settings.startTime / 1000) }),
|
|
213
|
+
...(settings.endTime === undefined ? {} : { end_time: Math.ceil(settings.endTime / 1000) }),
|
|
214
|
+
}, settings);
|
|
215
|
+
const first = page.items[0];
|
|
216
|
+
if (!first)
|
|
217
|
+
return { items: [], pageToken: page.pageToken };
|
|
218
|
+
const type = await messageType(first.chat_id);
|
|
219
|
+
return {
|
|
220
|
+
items: page.items.map((item) => decodeMessageResource(item, type)),
|
|
221
|
+
pageToken: page.pageToken,
|
|
222
|
+
};
|
|
223
|
+
}),
|
|
224
|
+
editMessage: (messageId, text) => client.invoke('editMessage', [messageId, text], async (args) => {
|
|
225
|
+
const [id, value] = z.tuple([idSchema, z.string()]).parse(args);
|
|
226
|
+
await client.raw('PUT', messagePath(id), {
|
|
227
|
+
data: { msg_type: 'text', content: JSON.stringify({ text: value }) },
|
|
228
|
+
});
|
|
229
|
+
}),
|
|
230
|
+
addReaction: (messageId, emoji) => client.invoke('addReaction', [messageId, emoji], async (args) => {
|
|
231
|
+
const [id, kind] = z.tuple([idSchema, idSchema]).parse(args);
|
|
232
|
+
const result = await client.data('POST', `${messagePath(id)}/reactions`, z.object({ reaction_id: idSchema }), {
|
|
233
|
+
data: { reaction_type: { emoji_type: kind } },
|
|
234
|
+
});
|
|
235
|
+
return result.reaction_id;
|
|
236
|
+
}),
|
|
237
|
+
removeReaction: (messageId, reactionId) => client.invoke('removeReaction', [messageId, reactionId], async (args) => {
|
|
238
|
+
const [id, reactionId] = z.tuple([idSchema, idSchema]).parse(args);
|
|
239
|
+
await client.raw('DELETE', `${messagePath(id)}/reactions/${encodeURIComponent(reactionId)}`);
|
|
240
|
+
}),
|
|
241
|
+
listReactions: (messageId, options) => client.invoke('listReactions', [messageId, options], (args) => {
|
|
242
|
+
const [id, settings] = z.tuple([idSchema, reactionListOptions.prefault({})]).parse(args);
|
|
243
|
+
return client.page(`${messagePath(id)}/reactions`, reaction, {
|
|
244
|
+
user_id_type: 'open_id',
|
|
245
|
+
...(settings.emoji ? { reaction_type: settings.emoji } : {}),
|
|
246
|
+
}, settings);
|
|
247
|
+
}),
|
|
248
|
+
pinMessage: (messageId) => client.invoke('pinMessage', [messageId], async (args) => {
|
|
249
|
+
const [id] = z.tuple([idSchema]).parse(args);
|
|
250
|
+
await client.raw('POST', '/im/v1/pins', { data: { message_id: id } });
|
|
251
|
+
}),
|
|
252
|
+
unpinMessage: (messageId) => client.invoke('unpinMessage', [messageId], async (args) => {
|
|
253
|
+
const [id] = z.tuple([idSchema]).parse(args);
|
|
254
|
+
await client.raw('DELETE', `/im/v1/pins/${encodeURIComponent(id)}`);
|
|
255
|
+
}),
|
|
256
|
+
listPins: (chatId, options) => client.invoke('listPins', [chatId, options], (args) => {
|
|
257
|
+
const [id, settings] = z.tuple([idSchema, pageOptions.prefault({})]).parse(args);
|
|
258
|
+
return client.page('/im/v1/pins', pin, { chat_id: id }, settings);
|
|
259
|
+
}),
|
|
260
|
+
listReadUsers: (messageId, options) => client.invoke('listReadUsers', [messageId, options], (args) => {
|
|
261
|
+
const [id, settings] = z.tuple([idSchema, readUserListOptions.prefault({})]).parse(args);
|
|
262
|
+
return client.page(`${messagePath(id)}/read_users`, readUser, { user_id_type: 'open_id' }, settings);
|
|
263
|
+
}),
|
|
264
|
+
getChat: (chatId) => client.invoke('getChat', [chatId], async (args) => {
|
|
265
|
+
const [id] = z.tuple([idSchema]).parse(args);
|
|
266
|
+
const chat = await client.data('GET', chatPath(id), fullChat, { params: { user_id_type: 'open_id' } });
|
|
267
|
+
return {
|
|
268
|
+
chatId: id,
|
|
269
|
+
mode: chat.chat_mode,
|
|
270
|
+
messageMode: chat.group_message_type,
|
|
271
|
+
name: chat.name,
|
|
272
|
+
description: chat.description,
|
|
273
|
+
avatar: chat.avatar,
|
|
274
|
+
ownerId: chat.owner_id,
|
|
275
|
+
adminIds: chat.user_manager_id_list,
|
|
276
|
+
botAdminIds: chat.bot_manager_id_list,
|
|
277
|
+
memberCount: chat.user_count,
|
|
278
|
+
};
|
|
279
|
+
}),
|
|
280
|
+
setChatMessageMode: (chatId, mode) => client.invoke('setChatMessageMode', [chatId, mode], async (args) => {
|
|
281
|
+
const [id, value] = z.tuple([idSchema, messageMode]).parse(args);
|
|
282
|
+
await client.raw('PUT', chatPath(id), { data: { group_message_type: value } });
|
|
283
|
+
invalidateChat(id);
|
|
284
|
+
}),
|
|
285
|
+
addChatMembers: (chatId, openIds) => client.invoke('addChatMembers', [chatId, openIds], async (args) => {
|
|
286
|
+
const [id, members] = z.tuple([idSchema, z.array(idSchema).min(1).max(50)]).parse(args);
|
|
287
|
+
const added = await client.data('POST', `${chatPath(id)}/members`, addedMembers, {
|
|
288
|
+
params: { member_id_type: 'open_id', succeed_type: 1 },
|
|
289
|
+
data: { id_list: members },
|
|
290
|
+
});
|
|
291
|
+
return {
|
|
292
|
+
invalidIds: added.invalid_id_list,
|
|
293
|
+
missingIds: added.not_existed_id_list,
|
|
294
|
+
pendingApprovalIds: added.pending_approval_id_list,
|
|
295
|
+
};
|
|
296
|
+
}),
|
|
297
|
+
urgentApp: (messageId, openIds) => client.invoke('urgentApp', [messageId, openIds], async (args) => {
|
|
298
|
+
const [id, users] = z.tuple([idSchema, z.array(idSchema).min(1).max(200)]).parse(args);
|
|
299
|
+
const result = await client.data('PATCH', `${messagePath(id)}/urgent_app`, z.object({ invalid_user_id_list: ids }), {
|
|
300
|
+
params: { user_id_type: 'open_id' },
|
|
301
|
+
data: { user_id_list: users },
|
|
302
|
+
});
|
|
303
|
+
return { invalidUserIds: result.invalid_user_id_list };
|
|
304
|
+
}),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { AdapterHost } from '../../core/adapter.ts';
|
|
3
|
+
import { type Bot, type ForwardMessage, type ForwardNode, type GroupInfo, type GroupMemberInfo, type MessageTarget, type MessageThread, type SendResult, type ThreadTarget, type UserInfo } from '../../core/bot.ts';
|
|
4
|
+
import type { Session } from '../../core/event/index.ts';
|
|
5
|
+
import { type Sendable } from '../../core/message/index.ts';
|
|
6
|
+
import { LruSet } from '../../core/utils/lru.ts';
|
|
7
|
+
import { type FeishuApi } from './api.ts';
|
|
8
|
+
import type { FeishuConfig } from './config.ts';
|
|
9
|
+
import { type FeishuMessageInfo, messageResource } from './message.ts';
|
|
10
|
+
import type { FeishuTransport } from './transport.ts';
|
|
11
|
+
export interface FeishuBot extends Bot {
|
|
12
|
+
readonly feishu: FeishuApi;
|
|
13
|
+
sendThread(target: ThreadTarget, content: Sendable): Promise<SendResult>;
|
|
14
|
+
getMessage(messageId: string): Promise<FeishuMessageInfo>;
|
|
15
|
+
}
|
|
16
|
+
export declare function isFeishu(bot: Bot): bot is FeishuBot;
|
|
17
|
+
type Conversation = {
|
|
18
|
+
messageType: 'private';
|
|
19
|
+
groupId?: undefined;
|
|
20
|
+
thread?: MessageThread;
|
|
21
|
+
} | {
|
|
22
|
+
messageType: 'group';
|
|
23
|
+
groupId: string;
|
|
24
|
+
thread?: MessageThread;
|
|
25
|
+
};
|
|
26
|
+
export declare const feishuCapabilities: {
|
|
27
|
+
segments: string[];
|
|
28
|
+
textStyles: readonly ['bold', 'italic', 'underline', 'strike', 'code'];
|
|
29
|
+
actions: string[];
|
|
30
|
+
};
|
|
31
|
+
export declare class FeishuBotImpl implements FeishuBot {
|
|
32
|
+
readonly platform = "feishu";
|
|
33
|
+
readonly capabilities: {
|
|
34
|
+
segments: string[];
|
|
35
|
+
textStyles: readonly ['bold', 'italic', 'underline', 'strike', 'code'];
|
|
36
|
+
actions: string[];
|
|
37
|
+
};
|
|
38
|
+
status: Bot['status'];
|
|
39
|
+
readonly selfId: string;
|
|
40
|
+
readonly nickname: string;
|
|
41
|
+
readonly avatar?: string;
|
|
42
|
+
readonly feishu: FeishuApi;
|
|
43
|
+
readonly sentMessageIds: LruSet<string>;
|
|
44
|
+
readonly shutdown: AbortController;
|
|
45
|
+
private readonly host;
|
|
46
|
+
private readonly client;
|
|
47
|
+
private readonly config;
|
|
48
|
+
private readonly buttonSecret;
|
|
49
|
+
private readonly roles;
|
|
50
|
+
private readonly conversations;
|
|
51
|
+
constructor(host: AdapterHost, transport: FeishuTransport, self: UserInfo, config: FeishuConfig, buttonSecret: string);
|
|
52
|
+
private signature;
|
|
53
|
+
private commandButton;
|
|
54
|
+
commandFrom(value: Record<string, unknown>): string | undefined;
|
|
55
|
+
resolveChannel(chatId: string): Promise<{
|
|
56
|
+
messageType: 'private';
|
|
57
|
+
} | {
|
|
58
|
+
messageType: 'group';
|
|
59
|
+
groupId: string;
|
|
60
|
+
}>;
|
|
61
|
+
rememberConversation(messageId: string, target: MessageTarget, thread?: MessageThread | undefined): void;
|
|
62
|
+
private cacheConversation;
|
|
63
|
+
knownConversation(messageId: string): Conversation | undefined;
|
|
64
|
+
resolveConversation(messageId: string): Promise<Conversation>;
|
|
65
|
+
private assertOnline;
|
|
66
|
+
resolveSender(userId: string, groupId?: string): Promise<Session['sender']>;
|
|
67
|
+
invalidateChat(chatId: string): void;
|
|
68
|
+
sendPrivate(userId: string, content: Sendable): Promise<SendResult>;
|
|
69
|
+
sendGroup(groupId: string, content: Sendable): Promise<SendResult>;
|
|
70
|
+
sendThread(target: ThreadTarget, content: Sendable): Promise<SendResult>;
|
|
71
|
+
private media;
|
|
72
|
+
private send;
|
|
73
|
+
private deliver;
|
|
74
|
+
private sentThread;
|
|
75
|
+
private recordSent;
|
|
76
|
+
private forward;
|
|
77
|
+
getSelf(): Promise<UserInfo>;
|
|
78
|
+
deleteMessage(messageId: string): Promise<void>;
|
|
79
|
+
getGroupList(): Promise<GroupInfo[]>;
|
|
80
|
+
getGroupMembers(groupId: string): Promise<GroupMemberInfo[]>;
|
|
81
|
+
getGroupMember(groupId: string, userId: string): Promise<GroupMemberInfo>;
|
|
82
|
+
getMessage(messageId: string): Promise<FeishuMessageInfo>;
|
|
83
|
+
getMessageResource(messageId: string): Promise<z.output<typeof messageResource>>;
|
|
84
|
+
private getMessageResources;
|
|
85
|
+
call(action: string, params?: Record<string, unknown>): Promise<unknown>;
|
|
86
|
+
sendForward(_target: MessageTarget, _nodes: ForwardNode[]): Promise<SendResult>;
|
|
87
|
+
getForward(id: string): Promise<ForwardMessage[]>;
|
|
88
|
+
muteMember(_group: string, _user: string, _duration: number): Promise<void>;
|
|
89
|
+
kickMember(groupId: string, userId: string, options?: {
|
|
90
|
+
rejectRequest?: boolean;
|
|
91
|
+
}): Promise<void>;
|
|
92
|
+
setMemberCard(_group: string, _user: string, _card: string): Promise<void>;
|
|
93
|
+
getFriendList(): Promise<UserInfo[]>;
|
|
94
|
+
}
|
|
95
|
+
export {};
|