@zhin.js/adapter-napcat 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +661 -0
- package/README.md +60 -95
- package/adapters/napcat.js +47 -0
- package/adapters/napcat.ts +64 -0
- package/{skills/napcat → agent}/PERMITS.md +3 -3
- package/{skills/napcat/SKILL.md → agent/skills/napcat.md} +2 -2
- package/agent/tools/ai_tts.ts +19 -0
- package/agent/tools/del_group_notice.ts +20 -0
- package/agent/tools/delete_essence_msg.ts +19 -0
- package/agent/tools/delete_friend.ts +18 -0
- package/agent/tools/download_file.ts +17 -0
- package/agent/tools/forward_single_msg.ts +28 -0
- package/agent/tools/get_ai_characters.ts +17 -0
- package/agent/tools/get_essence_list.ts +17 -0
- package/agent/tools/get_friend_msg_history.ts +18 -0
- package/agent/tools/get_group_file_url.ts +19 -0
- package/agent/tools/get_group_info_ex.ts +17 -0
- package/agent/tools/get_group_msg_history.ts +19 -0
- package/agent/tools/get_group_notice.ts +17 -0
- package/agent/tools/get_group_root_files.ts +17 -0
- package/agent/tools/get_group_shut_list.ts +17 -0
- package/agent/tools/get_mini_app_ark.ts +20 -0
- package/agent/tools/get_user_status.ts +16 -0
- package/agent/tools/group_sign.ts +18 -0
- package/agent/tools/mark_msg_as_read.ts +17 -0
- package/agent/tools/ocr_image.ts +16 -0
- package/agent/tools/send_forward_msg.ts +27 -0
- package/agent/tools/send_group_notice.ts +21 -0
- package/agent/tools/send_like.ts +18 -0
- package/agent/tools/send_poke.ts +18 -0
- package/agent/tools/set_avatar.ts +17 -0
- package/agent/tools/set_emoji_reaction.ts +18 -0
- package/agent/tools/set_essence_msg.ts +19 -0
- package/agent/tools/set_group_portrait.ts +20 -0
- package/agent/tools/set_online_status.ts +18 -0
- package/agent/tools/set_profile.ts +21 -0
- package/agent/tools/set_signature.ts +17 -0
- package/agent/tools/set_title.ts +21 -0
- package/agent/tools/translate.ts +16 -0
- package/agent/tools/upload_group_file.ts +21 -0
- package/commands/endpoint/add/[id].js +3 -0
- package/commands/endpoint/add/[id].ts +3 -0
- package/commands/endpoint/list.js +3 -0
- package/commands/endpoint/list.ts +3 -0
- package/commands/endpoint/remove/[id].js +3 -0
- package/commands/endpoint/remove/[id].ts +3 -0
- package/lib/client.d.ts +52 -0
- package/lib/client.js +62 -0
- package/lib/endpoint-management.d.ts +15 -0
- package/lib/endpoint-management.js +47 -0
- package/lib/http-endpoint.d.ts +27 -0
- package/lib/http-endpoint.js +177 -0
- package/lib/index.d.ts +11 -22
- package/lib/index.js +10 -59
- package/lib/napcat-endpoint-commands.d.ts +1 -0
- package/lib/napcat-endpoint-commands.js +28 -0
- package/lib/napcat-inbound.d.ts +12 -5
- package/lib/napcat-inbound.js +28 -13
- package/lib/napcat-runtime-state.d.ts +1 -0
- package/lib/napcat-runtime-state.js +6 -0
- package/lib/onebot-get-msg.d.ts +16 -3
- package/lib/onebot-get-msg.js +53 -1
- package/lib/protocol.d.ts +165 -0
- package/lib/protocol.js +305 -0
- package/lib/side-event-dispatch.d.ts +7 -0
- package/lib/side-event-dispatch.js +36 -0
- package/lib/webhook.d.ts +2 -0
- package/lib/webhook.js +14 -0
- package/lib/ws-endpoint.d.ts +27 -0
- package/lib/ws-endpoint.js +241 -0
- package/lib/ws-transport.d.ts +13 -0
- package/lib/ws-transport.js +75 -0
- package/lib/ws-types.d.ts +17 -0
- package/lib/ws-types.js +1 -0
- package/lib/wss-auth.d.ts +2 -0
- package/lib/wss-auth.js +16 -0
- package/lib/wss-endpoint.d.ts +26 -0
- package/lib/wss-endpoint.js +187 -0
- package/package.json +62 -32
- package/plugin.js +18 -0
- package/schema.json +110 -0
- package/src/client.ts +79 -0
- package/src/endpoint-management.ts +72 -0
- package/src/http-endpoint.ts +234 -0
- package/src/index.ts +63 -87
- package/src/napcat-endpoint-commands.ts +26 -0
- package/src/napcat-inbound.ts +34 -10
- package/src/napcat-runtime-state.ts +7 -0
- package/src/onebot-get-msg.ts +69 -5
- package/src/protocol.ts +468 -0
- package/src/side-event-dispatch.ts +48 -0
- package/src/webhook.ts +16 -0
- package/src/ws-endpoint.ts +301 -0
- package/src/ws-transport.ts +105 -0
- package/src/ws-types.ts +20 -0
- package/src/wss-auth.ts +17 -0
- package/src/wss-endpoint.ts +242 -0
- package/client/NapCatManagement.tsx +0 -113
- package/client/index.tsx +0 -11
- package/client/tsconfig.json +0 -7
- package/client/utils/api.ts +0 -30
- package/dist/index.js +0 -27
- package/lib/adapter.d.ts +0 -28
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -94
- package/lib/adapter.js.map +0 -1
- package/lib/agent-prompt.d.ts +0 -3
- package/lib/agent-prompt.d.ts.map +0 -1
- package/lib/agent-prompt.js +0 -105
- package/lib/agent-prompt.js.map +0 -1
- package/lib/endpoint-base.d.ts +0 -143
- package/lib/endpoint-base.d.ts.map +0 -1
- package/lib/endpoint-base.js +0 -334
- package/lib/endpoint-base.js.map +0 -1
- package/lib/endpoint-http.d.ts +0 -18
- package/lib/endpoint-http.d.ts.map +0 -1
- package/lib/endpoint-http.js +0 -119
- package/lib/endpoint-http.js.map +0 -1
- package/lib/endpoint-ws-client.d.ts +0 -21
- package/lib/endpoint-ws-client.d.ts.map +0 -1
- package/lib/endpoint-ws-client.js +0 -165
- package/lib/endpoint-ws-client.js.map +0 -1
- package/lib/endpoint-ws-server.d.ts +0 -21
- package/lib/endpoint-ws-server.d.ts.map +0 -1
- package/lib/endpoint-ws-server.js +0 -150
- package/lib/endpoint-ws-server.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/napcat-inbound.d.ts.map +0 -1
- package/lib/napcat-inbound.js.map +0 -1
- package/lib/onebot-get-msg.d.ts.map +0 -1
- package/lib/onebot-get-msg.js.map +0 -1
- package/lib/routes.d.ts +0 -4
- package/lib/routes.d.ts.map +0 -1
- package/lib/routes.js +0 -61
- package/lib/routes.js.map +0 -1
- package/lib/tools.d.ts +0 -8
- package/lib/tools.d.ts.map +0 -1
- package/lib/tools.js +0 -605
- package/lib/tools.js.map +0 -1
- package/lib/types.d.ts +0 -293
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js +0 -6
- package/lib/types.js.map +0 -1
- package/lib/typing-indicator.d.ts +0 -45
- package/lib/typing-indicator.d.ts.map +0 -1
- package/lib/typing-indicator.js +0 -132
- package/lib/typing-indicator.js.map +0 -1
- package/plugin.yml +0 -3
- package/src/adapter.ts +0 -101
- package/src/agent-prompt.ts +0 -114
- package/src/endpoint-base.ts +0 -376
- package/src/endpoint-http.ts +0 -109
- package/src/endpoint-ws-client.ts +0 -164
- package/src/endpoint-ws-server.ts +0 -150
- package/src/routes.ts +0 -61
- package/src/tools.ts +0 -632
- package/src/types.ts +0 -279
- package/src/typing-indicator.ts +0 -184
package/src/client.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { defineEndpointClient } from 'zhin.js/adapter';
|
|
2
|
+
import type { NapCatEvent } from './protocol.js';
|
|
3
|
+
|
|
4
|
+
export type NapcatApiCall = (
|
|
5
|
+
action: string,
|
|
6
|
+
params?: Record<string, unknown>,
|
|
7
|
+
) => Promise<unknown>;
|
|
8
|
+
|
|
9
|
+
/** Transport-independent NapCat protocol Client produced by every Endpoint mode. */
|
|
10
|
+
export class NapcatClient {
|
|
11
|
+
constructor(readonly callApi: NapcatApiCall) {}
|
|
12
|
+
|
|
13
|
+
async setTitle(groupId: number, userId: number, title: string, duration = -1): Promise<boolean> {
|
|
14
|
+
await this.callApi('set_group_special_title', {
|
|
15
|
+
group_id: groupId,
|
|
16
|
+
user_id: userId,
|
|
17
|
+
special_title: title,
|
|
18
|
+
duration,
|
|
19
|
+
});
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
sendLike(userId: number, times = 1) { return this.callApi('send_like', { user_id: userId, times }); }
|
|
24
|
+
deleteFriend(userId: number) { return this.callApi('delete_friend', { user_id: userId }); }
|
|
25
|
+
markMsgAsRead(messageId: number) { return this.callApi('mark_msg_as_read', { message_id: messageId }); }
|
|
26
|
+
ocrImage(image: string) { return this.callApi('ocr_image', { image }); }
|
|
27
|
+
setQQProfile(nickname: string, company?: string, email?: string, college?: string, personalNote?: string) {
|
|
28
|
+
return this.callApi('set_qq_profile', { nickname, company, email, college, personal_note: personalNote });
|
|
29
|
+
}
|
|
30
|
+
setGroupPortrait(groupId: number, file: string) { return this.callApi('set_group_portrait', { group_id: groupId, file }); }
|
|
31
|
+
setEssenceMsg(messageId: number) { return this.callApi('set_essence_msg', { message_id: messageId }); }
|
|
32
|
+
deleteEssenceMsg(messageId: number) { return this.callApi('delete_essence_msg', { message_id: messageId }); }
|
|
33
|
+
getEssenceMsgList(groupId: number) { return this.callApi('get_essence_msg_list', { group_id: groupId }); }
|
|
34
|
+
sendGroupSign(groupId: number) { return this.callApi('send_group_sign', { group_id: groupId }); }
|
|
35
|
+
sendGroupNotice(groupId: number, content: string, image?: string) { return this.callApi('_send_group_notice', { group_id: groupId, content, image }); }
|
|
36
|
+
getGroupNotice(groupId: number) { return this.callApi('_get_group_notice', { group_id: groupId }); }
|
|
37
|
+
deleteGroupNotice(groupId: number, noticeId: string) { return this.callApi('_del_group_notice', { group_id: groupId, notice_id: noticeId }); }
|
|
38
|
+
uploadGroupFile(groupId: number, file: string, name: string, folder?: string) { return this.callApi('upload_group_file', { group_id: groupId, file, name, folder }); }
|
|
39
|
+
getGroupRootFiles(groupId: number) { return this.callApi('get_group_root_files', { group_id: groupId }); }
|
|
40
|
+
getGroupFileUrl(groupId: number, fileId: string, busid: number) { return this.callApi('get_group_file_url', { group_id: groupId, file_id: fileId, busid }); }
|
|
41
|
+
downloadFile(url: string, threadCount = 1, headers?: string[]) { return this.callApi('download_file', { url, thread_count: threadCount, headers }); }
|
|
42
|
+
setOnlineStatus(status: number, extStatus: number) { return this.callApi('set_online_status', { status, ext_status: extStatus }); }
|
|
43
|
+
setQQAvatar(file: string) { return this.callApi('set_qq_avatar', { file }); }
|
|
44
|
+
forwardFriendSingleMsg(userId: number, messageId: number) { return this.callApi('forward_friend_single_msg', { user_id: userId, message_id: messageId }); }
|
|
45
|
+
forwardGroupSingleMsg(groupId: number, messageId: number) { return this.callApi('forward_group_single_msg', { group_id: groupId, message_id: messageId }); }
|
|
46
|
+
translateEn2Zh(sourceText: string) { return this.callApi('translate_en2zh', { source_text: sourceText }); }
|
|
47
|
+
setMsgEmojiLike(messageId: number, emojiId: string) { return this.callApi('set_msg_emoji_like', { message_id: messageId, emoji_id: emojiId }); }
|
|
48
|
+
sendForwardMsg(messageType: 'private' | 'group', id: number, messages: unknown[]) {
|
|
49
|
+
return this.callApi('send_forward_msg', {
|
|
50
|
+
message_type: messageType,
|
|
51
|
+
[messageType === 'group' ? 'group_id' : 'user_id']: id,
|
|
52
|
+
messages,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
getFriendMsgHistory(userId: number, messageSeq?: number, count?: number) { return this.callApi('get_friend_msg_history', { user_id: userId, message_seq: messageSeq, count }); }
|
|
56
|
+
getGroupMsgHistory(groupId: number, messageSeq?: number, count?: number) { return this.callApi('get_group_msg_history', { group_id: groupId, message_seq: messageSeq, count }); }
|
|
57
|
+
setSelfLongnick(longnick: string) { return this.callApi('set_self_longnick', { longNick: longnick }); }
|
|
58
|
+
getGroupInfoEx(groupId: number) { return this.callApi('get_group_info_ex', { group_id: groupId }); }
|
|
59
|
+
sendPoke(userId: number, groupId?: number) { return this.callApi('send_poke', { user_id: userId, group_id: groupId }); }
|
|
60
|
+
ncGetUserStatus(userId: number) { return this.callApi('nc_get_user_status', { user_id: userId }); }
|
|
61
|
+
getGroupShutList(groupId: number) { return this.callApi('get_group_shut_list', { group_id: groupId }); }
|
|
62
|
+
getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string) { return this.callApi('get_mini_app_ark', { type, title, desc, picUrl, jumpUrl }); }
|
|
63
|
+
getAiCharacters(groupId: number) { return this.callApi('get_ai_characters', { group_id: groupId }); }
|
|
64
|
+
sendGroupAiRecord(groupId: number, characterId: string, text: string) {
|
|
65
|
+
return this.callApi('send_group_ai_record', { group_id: groupId, character: characterId, text });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export type NapcatClientEventMap = Record<string, NapCatEvent>;
|
|
69
|
+
|
|
70
|
+
declare module '@zhin.js/feature-kit' {
|
|
71
|
+
interface AdapterClientRegistry {
|
|
72
|
+
readonly napcat: {
|
|
73
|
+
readonly client: NapcatClient;
|
|
74
|
+
readonly events: NapcatClientEventMap;
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export const napcatClient = defineEndpointClient<NapcatClient, NapcatClientEventMap>('napcat');
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NapCat endpoint management 语义端口(Console 社交面 RPC 消费,见
|
|
3
|
+
* packages/im/adapter/src/endpoint-management.ts)。
|
|
4
|
+
*
|
|
5
|
+
* 归一化取舍:
|
|
6
|
+
* - friend → {user_id:number, nickname, remark: remark ?? ''}
|
|
7
|
+
* - group → {group_id:number, name: group_name ?? name}
|
|
8
|
+
* - 群成员列表保持 OneBot11 原生形状,仅保证数组
|
|
9
|
+
*/
|
|
10
|
+
import type {
|
|
11
|
+
EndpointFriend,
|
|
12
|
+
EndpointGroup,
|
|
13
|
+
EndpointManagement,
|
|
14
|
+
} from 'zhin.js/adapter';
|
|
15
|
+
|
|
16
|
+
/** 管理面只依赖 endpoint 的 callApi(ws/wss/http 三种传输各自实现)。 */
|
|
17
|
+
export interface NapCatManagementCaller {
|
|
18
|
+
callApi(action: string, params?: Record<string, unknown>): Promise<unknown>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function createNapCatEndpointManagement(
|
|
22
|
+
endpoint: NapCatManagementCaller,
|
|
23
|
+
): EndpointManagement {
|
|
24
|
+
return Object.freeze<EndpointManagement>({
|
|
25
|
+
async listFriends(): Promise<readonly EndpointFriend[]> {
|
|
26
|
+
const data = await endpoint.callApi('get_friend_list');
|
|
27
|
+
return toArray(data).map((value) => {
|
|
28
|
+
const friend = asRecord(value);
|
|
29
|
+
return {
|
|
30
|
+
user_id: toNumberId(friend.user_id, 'user_id'),
|
|
31
|
+
nickname: String(friend.nickname ?? ''),
|
|
32
|
+
remark: String(friend.remark ?? ''),
|
|
33
|
+
};
|
|
34
|
+
});
|
|
35
|
+
},
|
|
36
|
+
async listGroups(): Promise<readonly EndpointGroup[]> {
|
|
37
|
+
const data = await endpoint.callApi('get_group_list');
|
|
38
|
+
return toArray(data).map((value) => {
|
|
39
|
+
const group = asRecord(value);
|
|
40
|
+
return {
|
|
41
|
+
group_id: toNumberId(group.group_id, 'group_id'),
|
|
42
|
+
name: String(group.group_name ?? group.name ?? ''),
|
|
43
|
+
};
|
|
44
|
+
});
|
|
45
|
+
},
|
|
46
|
+
async listGroupMembers(groupId: string): Promise<readonly unknown[]> {
|
|
47
|
+
const data = await endpoint.callApi('get_group_member_list', {
|
|
48
|
+
group_id: toNumberId(groupId, 'group_id'),
|
|
49
|
+
});
|
|
50
|
+
return toArray(data);
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function asRecord(value: unknown): Record<string, unknown> {
|
|
56
|
+
return value !== null && typeof value === 'object'
|
|
57
|
+
? value as Record<string, unknown>
|
|
58
|
+
: {};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function toArray(value: unknown): readonly unknown[] {
|
|
62
|
+
return Array.isArray(value) ? value : [];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** console RPC 传入的 gid/uid 可能是字符串,统一收敛为数字。 */
|
|
66
|
+
function toNumberId(value: unknown, label: string): number {
|
|
67
|
+
const n = Number(value);
|
|
68
|
+
if (!Number.isFinite(n) || String(value ?? '').trim() === '') {
|
|
69
|
+
throw new TypeError(`napcat ${label} 必须是数字: ${String(value)}`);
|
|
70
|
+
}
|
|
71
|
+
return n;
|
|
72
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { Endpoint } from 'zhin.js/adapter';
|
|
2
|
+
/**
|
|
3
|
+
* NapCat HTTP endpoint — POST inbound events + HTTP API outbound.
|
|
4
|
+
*/
|
|
5
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
6
|
+
import {
|
|
7
|
+
createRecallEndpointControl,
|
|
8
|
+
type EndpointControl,
|
|
9
|
+
type EndpointManagement,
|
|
10
|
+
type EndpointSendRequest,
|
|
11
|
+
} from 'zhin.js/adapter';
|
|
12
|
+
import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
|
|
13
|
+
import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
|
|
14
|
+
import type { CapabilityId } from 'zhin.js';
|
|
15
|
+
import { createNapCatEndpointManagement } from './endpoint-management.js';
|
|
16
|
+
import {
|
|
17
|
+
InboundMessageDeduper,
|
|
18
|
+
isNapCatBotMentioned,
|
|
19
|
+
isSelfMessage,
|
|
20
|
+
normalizeMessage,
|
|
21
|
+
} from './napcat-inbound.js';
|
|
22
|
+
import {
|
|
23
|
+
buildSendAction,
|
|
24
|
+
callNapCatHttpAction,
|
|
25
|
+
formatInboundContent,
|
|
26
|
+
formatOutboundSegments,
|
|
27
|
+
isMessageEvent,
|
|
28
|
+
napcatInboundConversation,
|
|
29
|
+
napcatOutboundTarget,
|
|
30
|
+
senderNickname,
|
|
31
|
+
senderUserId,
|
|
32
|
+
type NapCatEvent,
|
|
33
|
+
type NapCatHttpConfig,
|
|
34
|
+
} from './protocol.js';
|
|
35
|
+
import { receiveNapCatSideEvent } from './side-event-dispatch.js';
|
|
36
|
+
import { createNapCatContentPort } from './onebot-get-msg.js';
|
|
37
|
+
import { NapcatClient } from './client.js';
|
|
38
|
+
import { readRequestBody } from './webhook.js';
|
|
39
|
+
import { NapCatWsEndpoint } from './ws-endpoint.js';
|
|
40
|
+
import { verifyNapCatAccessToken } from './wss-auth.js';
|
|
41
|
+
|
|
42
|
+
export interface NapCatHttpEndpointOptions {
|
|
43
|
+
readonly id: CapabilityId;
|
|
44
|
+
readonly http: HttpHost;
|
|
45
|
+
readonly config: NapCatHttpConfig;
|
|
46
|
+
readonly callHttpAction?: typeof callNapCatHttpAction;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class NapCatHttpEndpoint extends Endpoint<NapcatClient> {
|
|
50
|
+
readonly client = new NapcatClient((action, params) => this.#callApi(action, params));
|
|
51
|
+
readonly #logger!: ReturnType<typeof getAdapterLogger>;
|
|
52
|
+
|
|
53
|
+
readonly #options: NapCatHttpEndpointOptions;
|
|
54
|
+
readonly #inboundDeduper = new InboundMessageDeduper();
|
|
55
|
+
readonly management: EndpointManagement = createNapCatEndpointManagement(this.client);
|
|
56
|
+
readonly control: EndpointControl = createRecallEndpointControl((id) => this.recallMessage(id));
|
|
57
|
+
readonly content = createNapCatContentPort((action, params) => this.client.callApi(action, params));
|
|
58
|
+
readonly #callHttpAction: typeof callNapCatHttpAction;
|
|
59
|
+
#routeReleases: HttpRouteRegistration[] = [];
|
|
60
|
+
#open = false;
|
|
61
|
+
#started = false;
|
|
62
|
+
|
|
63
|
+
constructor(options: NapCatHttpEndpointOptions) {
|
|
64
|
+
super();
|
|
65
|
+
this.#logger = getAdapterLogger('napcat', options.config.id);
|
|
66
|
+
this.#options = options;
|
|
67
|
+
this.#callHttpAction = options.callHttpAction ?? callNapCatHttpAction;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async start(): Promise<void> {
|
|
71
|
+
if (this.#started) return;
|
|
72
|
+
this.#started = true;
|
|
73
|
+
this.#setupRoutes();
|
|
74
|
+
this.#logger.info(formatCompact({
|
|
75
|
+
op: 'listen',
|
|
76
|
+
endpoint: this.#options.config.id,
|
|
77
|
+
mode: 'http',
|
|
78
|
+
path: this.#options.config.post_path,
|
|
79
|
+
}));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
open(): void {
|
|
83
|
+
this.#open = true;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
close(): void {
|
|
87
|
+
this.#open = false;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async stop(): Promise<void> {
|
|
91
|
+
this.#open = false;
|
|
92
|
+
for (const release of this.#routeReleases.splice(0)) release();
|
|
93
|
+
this.#inboundDeduper.clear();
|
|
94
|
+
this.#started = false;
|
|
95
|
+
this.#logger.debug(formatCompact({ op: 'disconnect' }));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async send({ conversation, payload }: EndpointSendRequest): Promise<string> {
|
|
99
|
+
const message = formatOutboundSegments(payload);
|
|
100
|
+
const { action, params } = buildSendAction(napcatOutboundTarget(conversation), message);
|
|
101
|
+
const resp = await this.#callHttpAction(
|
|
102
|
+
{
|
|
103
|
+
http_url: this.#options.config.http_url,
|
|
104
|
+
access_token: this.#options.config.access_token,
|
|
105
|
+
},
|
|
106
|
+
action,
|
|
107
|
+
params,
|
|
108
|
+
);
|
|
109
|
+
const data = resp.data as { message_id?: number | string } | undefined;
|
|
110
|
+
const messageId = data?.message_id != null ? String(data.message_id) : '';
|
|
111
|
+
this.#logger.debug(formatCompact({
|
|
112
|
+
op: 'napcat_send',
|
|
113
|
+
endpoint: this.#options.config.id,
|
|
114
|
+
target: `${conversation.kind}:${conversation.id}`,
|
|
115
|
+
messageId,
|
|
116
|
+
}));
|
|
117
|
+
return messageId;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async recallMessage(messageId: string): Promise<void> {
|
|
121
|
+
if (!messageId) return;
|
|
122
|
+
await this.client.callApi('delete_msg', { message_id: Number(messageId) });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
#callApi(action: string, params: Record<string, unknown> = {}): Promise<unknown> {
|
|
126
|
+
return this.#callHttpAction(
|
|
127
|
+
{
|
|
128
|
+
http_url: this.#options.config.http_url,
|
|
129
|
+
access_token: this.#options.config.access_token,
|
|
130
|
+
},
|
|
131
|
+
action,
|
|
132
|
+
params,
|
|
133
|
+
).then((resp) => resp.data);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
admit(ev: NapCatEvent): void {
|
|
137
|
+
if (!this.#open) return;
|
|
138
|
+
void this.emitPlatform(napCatPlatformEventName(ev), ev).catch((error) => {
|
|
139
|
+
this.#logger.warn(formatCompact({
|
|
140
|
+
op: 'napcat_platform_event_failed',
|
|
141
|
+
error: error instanceof Error ? error.message : String(error),
|
|
142
|
+
}));
|
|
143
|
+
});
|
|
144
|
+
if (!isMessageEvent(ev)) {
|
|
145
|
+
receiveNapCatSideEvent(
|
|
146
|
+
(name, payload) => this.emit(name, payload),
|
|
147
|
+
this.#options.config.id,
|
|
148
|
+
this.client,
|
|
149
|
+
ev,
|
|
150
|
+
this.#logger,
|
|
151
|
+
);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (isSelfMessage(ev)) return;
|
|
155
|
+
const msgId = String(ev.message_id);
|
|
156
|
+
if (!this.#inboundDeduper.shouldProcess(msgId)) return;
|
|
157
|
+
if (Array.isArray(ev.message) || typeof ev.message === 'string') {
|
|
158
|
+
ev = { ...ev, message: normalizeMessage(ev.message) };
|
|
159
|
+
}
|
|
160
|
+
const conversation = napcatInboundConversation(String(this.#options.id), ev);
|
|
161
|
+
const nickname = senderNickname(ev);
|
|
162
|
+
const mentioned = isNapCatBotMentioned(ev);
|
|
163
|
+
void this.emit('message.receive', {
|
|
164
|
+
conversation,
|
|
165
|
+
message: { conversation, id: msgId },
|
|
166
|
+
content: formatInboundContent(ev),
|
|
167
|
+
sender: {
|
|
168
|
+
id: senderUserId(ev),
|
|
169
|
+
name: nickname,
|
|
170
|
+
...(ev.sender?.role ? { roles: [ev.sender.role] } : {}),
|
|
171
|
+
},
|
|
172
|
+
endpointId: this.#options.config.id,
|
|
173
|
+
...(mentioned ? { mentioned: true } : {}),
|
|
174
|
+
metadata: Object.freeze({
|
|
175
|
+
message_type: ev.message_type,
|
|
176
|
+
user_id: ev.user_id != null ? String(ev.user_id) : undefined,
|
|
177
|
+
group_id: ev.group_id != null ? String(ev.group_id) : undefined,
|
|
178
|
+
time: ev.time,
|
|
179
|
+
self_id: ev.self_id != null ? String(ev.self_id) : undefined,
|
|
180
|
+
role: ev.sender?.role,
|
|
181
|
+
...(nickname ? { nickname } : {}),
|
|
182
|
+
}),
|
|
183
|
+
}).catch((err) => {
|
|
184
|
+
this.#logger.warn(formatCompact({
|
|
185
|
+
op: 'napcat_gateway_receive_failed',
|
|
186
|
+
target: `${conversation.kind}:${conversation.id}`,
|
|
187
|
+
error: err instanceof Error ? err.message : String(err),
|
|
188
|
+
}));
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
#setupRoutes(): void {
|
|
193
|
+
const path = this.#options.config.post_path;
|
|
194
|
+
this.#routeReleases.push(
|
|
195
|
+
this.#options.http.route('POST', path, async (request, response) => {
|
|
196
|
+
await this.#handlePost(request, response);
|
|
197
|
+
}, { summary: 'NapCat HTTP event callback', tags: ['napcat'] }),
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async #handlePost(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
|
202
|
+
try {
|
|
203
|
+
if (!verifyNapCatAccessToken(this.#options.config.access_token, request)) {
|
|
204
|
+
response.writeHead(403, { 'Content-Type': 'application/json' });
|
|
205
|
+
response.end(JSON.stringify({ message: 'Unauthorized' }));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const raw = await readRequestBody(request);
|
|
209
|
+
let ev: NapCatEvent;
|
|
210
|
+
try {
|
|
211
|
+
ev = JSON.parse(raw) as NapCatEvent;
|
|
212
|
+
} catch {
|
|
213
|
+
response.writeHead(400, { 'Content-Type': 'application/json' });
|
|
214
|
+
response.end(JSON.stringify({ message: 'Invalid JSON' }));
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (this.#open) this.admit(ev);
|
|
218
|
+
response.writeHead(200, { 'Content-Type': 'application/json' });
|
|
219
|
+
response.end(JSON.stringify({ status: 'ok' }));
|
|
220
|
+
} catch (error) {
|
|
221
|
+
this.#logger.error('NapCat HTTP webhook error:', error);
|
|
222
|
+
if (!response.headersSent) {
|
|
223
|
+
response.writeHead(500, { 'Content-Type': 'application/json' });
|
|
224
|
+
response.end(JSON.stringify({ message: 'Internal Server Error' }));
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function napCatPlatformEventName(ev: NapCatEvent): string {
|
|
231
|
+
return [ev.post_type, ev.message_type ?? ev.notice_type ?? ev.request_type, ev.sub_type]
|
|
232
|
+
.filter(Boolean)
|
|
233
|
+
.join('.');
|
|
234
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,98 +1,74 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
1
|
+
export {
|
|
2
|
+
buildSendAction,
|
|
3
|
+
buildWsConnectOptions,
|
|
4
|
+
callNapCatHttpAction,
|
|
5
|
+
formatInboundContent,
|
|
6
|
+
formatOutboundSegments,
|
|
7
|
+
getChannelId,
|
|
8
|
+
isMessageEvent,
|
|
9
|
+
mediaRefToOneBotFile,
|
|
10
|
+
napcatInboundConversation,
|
|
11
|
+
napcatOutboundTarget,
|
|
12
|
+
resolveNapCatConfig,
|
|
13
|
+
senderNickname,
|
|
14
|
+
senderUserId,
|
|
15
|
+
type MessageSegment,
|
|
16
|
+
type NapCatActionRequest,
|
|
17
|
+
type NapCatActionResponse,
|
|
18
|
+
type NapCatAdapterConfig,
|
|
19
|
+
type NapCatConfigBase,
|
|
20
|
+
type NapCatEndpointConfig,
|
|
21
|
+
type NapCatEvent,
|
|
22
|
+
type NapCatHttpConfig,
|
|
23
|
+
type NapCatMessageEvent,
|
|
24
|
+
type NapCatSender,
|
|
25
|
+
type NapCatWireSegment,
|
|
26
|
+
type NapCatWsConfig,
|
|
27
|
+
type NapCatWssConfig,
|
|
28
|
+
type ParsedSendTarget,
|
|
29
|
+
type ResolvedNapCatConfig,
|
|
30
|
+
} from './protocol.js';
|
|
24
31
|
|
|
25
|
-
export * from './types.js';
|
|
26
|
-
export { NapCatWsClient } from './endpoint-ws-client.js';
|
|
27
|
-
export { NapCatWsServer } from './endpoint-ws-server.js';
|
|
28
|
-
export { NapCatHttpEndpoint } from './endpoint-http.js';
|
|
29
|
-
export { NapCatAdapter, type NapCatEndpoint } from './adapter.js';
|
|
30
|
-
export { NapCatEndpointBase } from './endpoint-base.js';
|
|
31
32
|
export {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
33
|
+
InboundMessageDeduper,
|
|
34
|
+
isNapCatBotMentioned,
|
|
35
|
+
isSelfMessage,
|
|
36
|
+
normalizeMessage,
|
|
37
|
+
} from './napcat-inbound.js';
|
|
36
38
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
interface Adapters {
|
|
45
|
-
napcat: NapCatAdapter;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
39
|
+
export {
|
|
40
|
+
napcatClient,
|
|
41
|
+
type NapcatClient,
|
|
42
|
+
type NapcatClientEventMap,
|
|
43
|
+
} from './client.js';
|
|
48
44
|
|
|
49
|
-
|
|
50
|
-
const { provide, useContext } = plugin;
|
|
45
|
+
export { parseOneBotGetMsgResponse } from './onebot-get-msg.js';
|
|
51
46
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
mounted: async (p: Plugin) => {
|
|
57
|
-
registerAgentPromptContributor(createNapCatAgentPromptContributor());
|
|
58
|
-
const adapter = new NapCatAdapter(p);
|
|
59
|
-
await adapter.start();
|
|
60
|
-
return adapter;
|
|
61
|
-
},
|
|
62
|
-
dispose: async (adapter: NapCatAdapter) => {
|
|
63
|
-
unregisterAgentPromptContributor('napcat');
|
|
64
|
-
await adapter.stop();
|
|
65
|
-
},
|
|
66
|
-
} as unknown as Context<'napcat'>);
|
|
47
|
+
export {
|
|
48
|
+
NapCatWsEndpoint,
|
|
49
|
+
type NapCatWsEndpointOptions,
|
|
50
|
+
} from './ws-endpoint.js';
|
|
67
51
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
52
|
+
export {
|
|
53
|
+
NapCatWssEndpoint,
|
|
54
|
+
type NapCatWssEndpointOptions,
|
|
55
|
+
} from './wss-endpoint.js';
|
|
72
56
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
disposers.push(...groupTools.map(t => toolService.addTool(t, plugin.name)));
|
|
57
|
+
export {
|
|
58
|
+
NapCatHttpEndpoint,
|
|
59
|
+
type NapCatHttpEndpointOptions,
|
|
60
|
+
} from './http-endpoint.js';
|
|
78
61
|
|
|
79
|
-
|
|
80
|
-
disposers.push(...napcatTools.map(t => toolService.addTool(t, plugin.name)));
|
|
62
|
+
export type { NapCatWsSocket, NapCatWsCreateOptions } from './ws-types.js';
|
|
81
63
|
|
|
82
|
-
|
|
83
|
-
|
|
64
|
+
export {
|
|
65
|
+
callNapCatWsAction,
|
|
66
|
+
decodeWsPayload,
|
|
67
|
+
handleNapCatWsMessage,
|
|
68
|
+
rejectAllPending,
|
|
69
|
+
startNapCatHeartbeat,
|
|
70
|
+
} from './ws-transport.js';
|
|
84
71
|
|
|
85
|
-
|
|
86
|
-
useContext('web', (pageManager) => {
|
|
87
|
-
pageManager.addEntry({
|
|
88
|
-
id: 'napcat',
|
|
89
|
-
development: path.resolve(import.meta.dirname, '../client/index.tsx'),
|
|
90
|
-
production: path.resolve(import.meta.dirname, '../dist/index.js'),
|
|
91
|
-
meta: { name: 'NapCat' },
|
|
92
|
-
});
|
|
93
|
-
});
|
|
72
|
+
export { verifyNapCatAccessToken } from './wss-auth.js';
|
|
94
73
|
|
|
95
|
-
|
|
96
|
-
useContext('router', 'napcat', async (router: Router, napcat: NapCatAdapter) => {
|
|
97
|
-
registerRoutes(router, napcat);
|
|
98
|
-
});
|
|
74
|
+
export { readRequestBody } from './webhook.js';
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `napcat.endpoint` 命令族:由 @zhin.js/adapter 的 createEndpointCommands 套件生成。
|
|
3
|
+
* commands/endpoint/ 下的 list / add / remove 直接默认导出这三项。
|
|
4
|
+
*/
|
|
5
|
+
import { createEndpointCommands } from 'zhin.js/adapter';
|
|
6
|
+
import { defineCommand } from 'zhin.js/command';
|
|
7
|
+
import { napcatRuntimeStateToken } from './napcat-runtime-state.js';
|
|
8
|
+
|
|
9
|
+
export const napcatEndpointCommands = createEndpointCommands({
|
|
10
|
+
adapterKey: 'napcat',
|
|
11
|
+
adapterDisplayName: 'NapCat',
|
|
12
|
+
fields: [
|
|
13
|
+
{ key: 'url', description: 'NapCat WebSocket URL(connection: ws 必填)' },
|
|
14
|
+
{ key: 'path', description: 'reverse-wss 路径(connection: wss)' },
|
|
15
|
+
{ key: 'http_url', description: 'HTTP API base URL(connection: http 出站)' },
|
|
16
|
+
{ key: 'post_path', description: 'HTTP POST 事件路径(connection: http 入站)' },
|
|
17
|
+
{ key: 'access_token', env: true, description: 'NapCat access token' },
|
|
18
|
+
],
|
|
19
|
+
running: (use) => use(napcatRuntimeStateToken).endpoints.values(),
|
|
20
|
+
describeEntry: (entry) => {
|
|
21
|
+
if (entry.url) return `url: ${String(entry.url)}`;
|
|
22
|
+
if (entry.path) return `path: ${String(entry.path)}`;
|
|
23
|
+
if (entry.http_url) return `http_url: ${String(entry.http_url)}`;
|
|
24
|
+
return '';
|
|
25
|
+
},
|
|
26
|
+
}, defineCommand);
|
package/src/napcat-inbound.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* NapCat 入站消息治理:去重、自发过滤、消息归一化
|
|
3
3
|
*/
|
|
4
|
-
import type { NapCatMessageEvent, MessageSegment } from './
|
|
4
|
+
import type { NapCatMessageEvent, MessageSegment } from './protocol.js';
|
|
5
5
|
|
|
6
6
|
const DEDUPE_TTL_MS = 120_000;
|
|
7
7
|
|
|
@@ -24,7 +24,11 @@ export class InboundMessageDeduper {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
/** 判断是否为 bot 自身发出的消息 */
|
|
27
|
-
export function isSelfMessage(event: NapCatMessageEvent
|
|
27
|
+
export function isSelfMessage(event: NapCatMessageEvent | {
|
|
28
|
+
post_type?: string;
|
|
29
|
+
self_id?: number | string;
|
|
30
|
+
user_id?: number | string;
|
|
31
|
+
}): boolean {
|
|
28
32
|
if (event.post_type === 'message_sent') return true;
|
|
29
33
|
if (event.self_id != null && event.user_id != null) {
|
|
30
34
|
return Number(event.self_id) === Number(event.user_id);
|
|
@@ -44,14 +48,34 @@ export function normalizeMessage(message: MessageSegment[] | string): MessageSeg
|
|
|
44
48
|
return [];
|
|
45
49
|
}
|
|
46
50
|
|
|
51
|
+
const CQ_AT_RE = /\[CQ:at,qq=([^\],\s]+)\]/g;
|
|
52
|
+
|
|
53
|
+
function atTargetMatchesUin(target: unknown, uin: string): boolean {
|
|
54
|
+
const qq = String(target ?? '').trim();
|
|
55
|
+
return Boolean(qq) && qq !== 'all' && Number(qq) === Number(uin);
|
|
56
|
+
}
|
|
57
|
+
|
|
47
58
|
/**
|
|
48
|
-
*
|
|
59
|
+
* OneBot11 mentioned 判定:消息段 {type:'at', data:{qq}} 的 qq 等于本机 uin
|
|
60
|
+
* (事件 self_id)时为 true;`qq === 'all'` 不算。兼容 CQ 字符串形式。
|
|
49
61
|
*/
|
|
50
|
-
export function
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
if (
|
|
55
|
-
|
|
56
|
-
|
|
62
|
+
export function isNapCatBotMentioned(ev: {
|
|
63
|
+
self_id?: number | string;
|
|
64
|
+
message?: MessageSegment[] | string;
|
|
65
|
+
}): boolean {
|
|
66
|
+
if (ev.self_id == null) return false;
|
|
67
|
+
const uin = String(ev.self_id).trim();
|
|
68
|
+
if (!uin) return false;
|
|
69
|
+
const segments = normalizeMessage(ev.message ?? []);
|
|
70
|
+
for (const seg of segments) {
|
|
71
|
+
if (seg.type === 'at' && atTargetMatchesUin(seg.data?.qq, uin)) return true;
|
|
72
|
+
}
|
|
73
|
+
const text = segments
|
|
74
|
+
.map((seg) => (seg.type === 'text' ? String(seg.data?.text ?? '') : ''))
|
|
75
|
+
.join('');
|
|
76
|
+
if (!text) return false;
|
|
77
|
+
for (const match of text.matchAll(CQ_AT_RE)) {
|
|
78
|
+
if (atTargetMatchesUin(match[1], uin)) return true;
|
|
79
|
+
}
|
|
80
|
+
return false;
|
|
57
81
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NapCat 插件实例的运行时状态:adapter create() 注册的 endpoint 列表。
|
|
3
|
+
* 由 plugin.ts setup() provide,adapter create 与 `napcat.endpoint` 命令共享(同一 owner generation)。
|
|
4
|
+
*/
|
|
5
|
+
import { defineEndpointRuntimeStateToken } from 'zhin.js/adapter';
|
|
6
|
+
|
|
7
|
+
export const napcatRuntimeStateToken = defineEndpointRuntimeStateToken('napcat');
|