@zhin.js/adapter-napcat 1.0.1 → 1.1.2
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 +757 -0
- package/{skills/napcat/PERMITS.md → PERMITS.md} +3 -3
- package/README.md +63 -95
- package/adapters/napcat/index.js +47 -0
- package/adapters/napcat/index.ts +64 -0
- package/agents/napcat/agent.json +20 -0
- package/agents/napcat/boundaries.md +3 -0
- package/agents/napcat/conventions.md +3 -0
- package/agents/napcat/skills/napcat-account/SKILL.md +25 -0
- package/agents/napcat/skills/napcat-account/tools/delete_friend/index.js +18 -0
- package/agents/napcat/skills/napcat-account/tools/delete_friend/index.ts +18 -0
- package/agents/napcat/skills/napcat-account/tools/get_user_status/index.js +16 -0
- package/agents/napcat/skills/napcat-account/tools/get_user_status/index.ts +16 -0
- package/agents/napcat/skills/napcat-account/tools/send_like/index.js +18 -0
- package/agents/napcat/skills/napcat-account/tools/send_like/index.ts +18 -0
- package/agents/napcat/skills/napcat-account/tools/set_avatar/index.js +17 -0
- package/agents/napcat/skills/napcat-account/tools/set_avatar/index.ts +17 -0
- package/agents/napcat/skills/napcat-account/tools/set_online_status/index.js +18 -0
- package/agents/napcat/skills/napcat-account/tools/set_online_status/index.ts +18 -0
- package/agents/napcat/skills/napcat-account/tools/set_profile/index.js +21 -0
- package/agents/napcat/skills/napcat-account/tools/set_profile/index.ts +21 -0
- package/agents/napcat/skills/napcat-account/tools/set_signature/index.js +17 -0
- package/agents/napcat/skills/napcat-account/tools/set_signature/index.ts +17 -0
- package/agents/napcat/skills/napcat-files-history/SKILL.md +22 -0
- package/agents/napcat/skills/napcat-files-history/tools/download_file/index.js +17 -0
- package/agents/napcat/skills/napcat-files-history/tools/download_file/index.ts +17 -0
- package/agents/napcat/skills/napcat-files-history/tools/get_friend_msg_history/index.js +18 -0
- package/agents/napcat/skills/napcat-files-history/tools/get_friend_msg_history/index.ts +18 -0
- package/agents/napcat/skills/napcat-files-history/tools/get_group_file_url/index.js +19 -0
- package/agents/napcat/skills/napcat-files-history/tools/get_group_file_url/index.ts +19 -0
- package/agents/napcat/skills/napcat-files-history/tools/get_group_msg_history/index.js +19 -0
- package/agents/napcat/skills/napcat-files-history/tools/get_group_msg_history/index.ts +19 -0
- package/agents/napcat/skills/napcat-files-history/tools/get_group_root_files/index.js +17 -0
- package/agents/napcat/skills/napcat-files-history/tools/get_group_root_files/index.ts +17 -0
- package/agents/napcat/skills/napcat-files-history/tools/upload_group_file/index.js +21 -0
- package/agents/napcat/skills/napcat-files-history/tools/upload_group_file/index.ts +21 -0
- package/agents/napcat/skills/napcat-group-content/SKILL.md +21 -0
- package/agents/napcat/skills/napcat-group-content/tools/del_group_notice/index.js +20 -0
- package/agents/napcat/skills/napcat-group-content/tools/del_group_notice/index.ts +20 -0
- package/agents/napcat/skills/napcat-group-content/tools/delete_essence_msg/index.js +19 -0
- package/agents/napcat/skills/napcat-group-content/tools/delete_essence_msg/index.ts +19 -0
- package/agents/napcat/skills/napcat-group-content/tools/get_essence_list/index.js +17 -0
- package/agents/napcat/skills/napcat-group-content/tools/get_essence_list/index.ts +17 -0
- package/agents/napcat/skills/napcat-group-content/tools/get_group_notice/index.js +17 -0
- package/agents/napcat/skills/napcat-group-content/tools/get_group_notice/index.ts +17 -0
- package/agents/napcat/skills/napcat-group-content/tools/send_group_notice/index.js +21 -0
- package/agents/napcat/skills/napcat-group-content/tools/send_group_notice/index.ts +21 -0
- package/agents/napcat/skills/napcat-group-content/tools/set_essence_msg/index.js +19 -0
- package/agents/napcat/skills/napcat-group-content/tools/set_essence_msg/index.ts +19 -0
- package/agents/napcat/skills/napcat-group-settings/SKILL.md +23 -0
- package/agents/napcat/skills/napcat-group-settings/tools/get_group_info_ex/index.js +17 -0
- package/agents/napcat/skills/napcat-group-settings/tools/get_group_info_ex/index.ts +17 -0
- package/agents/napcat/skills/napcat-group-settings/tools/get_group_shut_list/index.js +17 -0
- package/agents/napcat/skills/napcat-group-settings/tools/get_group_shut_list/index.ts +17 -0
- package/agents/napcat/skills/napcat-group-settings/tools/group_sign/index.js +18 -0
- package/agents/napcat/skills/napcat-group-settings/tools/group_sign/index.ts +18 -0
- package/agents/napcat/skills/napcat-group-settings/tools/set_group_portrait/index.js +20 -0
- package/agents/napcat/skills/napcat-group-settings/tools/set_group_portrait/index.ts +20 -0
- package/agents/napcat/skills/napcat-group-settings/tools/set_title/index.js +21 -0
- package/agents/napcat/skills/napcat-group-settings/tools/set_title/index.ts +21 -0
- package/agents/napcat/skills/napcat-media/SKILL.md +23 -0
- package/agents/napcat/skills/napcat-media/tools/ai_tts/index.js +19 -0
- package/agents/napcat/skills/napcat-media/tools/ai_tts/index.ts +19 -0
- package/agents/napcat/skills/napcat-media/tools/get_ai_characters/index.js +17 -0
- package/agents/napcat/skills/napcat-media/tools/get_ai_characters/index.ts +17 -0
- package/agents/napcat/skills/napcat-media/tools/get_mini_app_ark/index.js +20 -0
- package/agents/napcat/skills/napcat-media/tools/get_mini_app_ark/index.ts +20 -0
- package/agents/napcat/skills/napcat-media/tools/ocr_image/index.js +16 -0
- package/agents/napcat/skills/napcat-media/tools/ocr_image/index.ts +16 -0
- package/agents/napcat/skills/napcat-media/tools/translate/index.js +16 -0
- package/agents/napcat/skills/napcat-media/tools/translate/index.ts +16 -0
- package/agents/napcat/skills/napcat-messaging/SKILL.md +22 -0
- package/agents/napcat/skills/napcat-messaging/tools/forward_single_msg/index.js +22 -0
- package/agents/napcat/skills/napcat-messaging/tools/forward_single_msg/index.ts +28 -0
- package/agents/napcat/skills/napcat-messaging/tools/mark_msg_as_read/index.js +17 -0
- package/agents/napcat/skills/napcat-messaging/tools/mark_msg_as_read/index.ts +17 -0
- package/agents/napcat/skills/napcat-messaging/tools/send_forward_msg/index.js +19 -0
- package/agents/napcat/skills/napcat-messaging/tools/send_forward_msg/index.ts +27 -0
- package/agents/napcat/skills/napcat-messaging/tools/send_poke/index.js +18 -0
- package/agents/napcat/skills/napcat-messaging/tools/send_poke/index.ts +18 -0
- package/agents/napcat/skills/napcat-messaging/tools/set_emoji_reaction/index.js +18 -0
- package/agents/napcat/skills/napcat-messaging/tools/set_emoji_reaction/index.ts +18 -0
- package/agents/napcat/system.md +3 -0
- package/commands/napcat/endpoint/add/[id]/index.js +3 -0
- package/commands/napcat/endpoint/add/[id]/index.ts +3 -0
- package/commands/napcat/endpoint/definition.js +29 -0
- package/commands/napcat/endpoint/definition.ts +26 -0
- package/commands/napcat/endpoint/list/index.js +3 -0
- package/commands/napcat/endpoint/list/index.ts +3 -0
- package/commands/napcat/endpoint/remove/[id]/index.js +3 -0
- package/commands/napcat/endpoint/remove/[id]/index.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-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 +147 -0
- package/lib/protocol.js +318 -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 +29 -0
- package/lib/wss-endpoint.js +196 -0
- package/package.json +76 -34
- package/plugin.js +18 -0
- package/schema.json +131 -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 +62 -87
- 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 +465 -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 +247 -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/skills/napcat/SKILL.md +0 -311
- 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/endpoint-base.ts
DELETED
|
@@ -1,376 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* NapCat Endpoint 抽象基类
|
|
3
|
-
* 子类只需实现 callApi / $connect / $disconnect,其余 API 方法和事件处理全部复用。
|
|
4
|
-
*/
|
|
5
|
-
import { EventEmitter } from 'events';
|
|
6
|
-
import {
|
|
7
|
-
Endpoint,
|
|
8
|
-
Message,
|
|
9
|
-
SendContent,
|
|
10
|
-
SendOptions,
|
|
11
|
-
segment,
|
|
12
|
-
Notice,
|
|
13
|
-
Request,
|
|
14
|
-
type QuotedMessagePayload,
|
|
15
|
-
} from 'zhin.js';
|
|
16
|
-
import { parseOneBotGetMsgResponse } from './onebot-get-msg.js';
|
|
17
|
-
import type { NapCatEndpointConfig, NapCatMessageEvent, MessageSegment, ApiResponse } from './types.js';
|
|
18
|
-
import type { NapCatAdapter } from './adapter.js';
|
|
19
|
-
import { InboundMessageDeduper, isSelfMessage, normalizeMessage, resolveSideEventDedupeKey } from './napcat-inbound.js';
|
|
20
|
-
|
|
21
|
-
export abstract class NapCatEndpointBase extends EventEmitter implements Endpoint<NapCatEndpointConfig, NapCatMessageEvent> {
|
|
22
|
-
$connected = false;
|
|
23
|
-
protected readonly inboundDeduper = new InboundMessageDeduper();
|
|
24
|
-
|
|
25
|
-
get logger() { return this.adapter.plugin.logger; }
|
|
26
|
-
get $id() { return this.$config.name; }
|
|
27
|
-
|
|
28
|
-
constructor(public adapter: NapCatAdapter, public $config: NapCatEndpointConfig) {
|
|
29
|
-
super();
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
abstract $connect(): Promise<void>;
|
|
33
|
-
abstract $disconnect(): Promise<void>;
|
|
34
|
-
abstract callApi<T = any>(action: string, params?: Record<string, any>): Promise<T>;
|
|
35
|
-
|
|
36
|
-
// ══════════════════════════════════════════════════════════════════
|
|
37
|
-
// 消息格式化
|
|
38
|
-
// ══════════════════════════════════════════════════════════════════
|
|
39
|
-
|
|
40
|
-
$formatMessage(ev: NapCatMessageEvent): Message<NapCatMessageEvent> {
|
|
41
|
-
const content = normalizeMessage(ev.message);
|
|
42
|
-
const quoteId = Message.quoteIdFromContent(content);
|
|
43
|
-
Message.alignReplySegments(content, quoteId);
|
|
44
|
-
|
|
45
|
-
const message = Message.from(ev, {
|
|
46
|
-
$id: ev.message_id.toString(),
|
|
47
|
-
$adapter: 'napcat',
|
|
48
|
-
$endpoint: this.$config.name,
|
|
49
|
-
$sender: {
|
|
50
|
-
id: ev.user_id.toString(),
|
|
51
|
-
name: ev.sender?.nickname || ev.user_id.toString(),
|
|
52
|
-
role: ev.sender?.role,
|
|
53
|
-
},
|
|
54
|
-
$channel: {
|
|
55
|
-
id: (ev.group_id || ev.user_id).toString(),
|
|
56
|
-
type: ev.group_id ? 'group' : 'private',
|
|
57
|
-
},
|
|
58
|
-
$content: content,
|
|
59
|
-
$quote_id: quoteId,
|
|
60
|
-
$raw: ev.raw_message,
|
|
61
|
-
$timestamp: ev.time,
|
|
62
|
-
$recall: async () => { await this.deleteMsg(ev.message_id); },
|
|
63
|
-
$reply: async (content: SendContent, quote?: boolean | string): Promise<string> => {
|
|
64
|
-
if (!Array.isArray(content)) content = [content];
|
|
65
|
-
if (quote) content.unshift({ type: 'reply', data: { message_id: ev.message_id.toString() } });
|
|
66
|
-
return await this.adapter.sendMessage({
|
|
67
|
-
id: (ev.group_id || ev.user_id).toString(),
|
|
68
|
-
type: ev.group_id ? 'group' : 'private',
|
|
69
|
-
context: 'napcat',
|
|
70
|
-
endpoint: this.$config.name,
|
|
71
|
-
content,
|
|
72
|
-
});
|
|
73
|
-
},
|
|
74
|
-
});
|
|
75
|
-
return message;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
async $sendMessage(options: SendOptions): Promise<string> {
|
|
79
|
-
const msg: any = { message: options.content };
|
|
80
|
-
if (options.type === 'group') {
|
|
81
|
-
const result = await this.callApi<{ message_id: number }>('send_group_msg', { group_id: parseInt(options.id), ...msg });
|
|
82
|
-
this.logger.debug(`${this.$id} send group(${options.id}):${segment.raw(options.content)}`);
|
|
83
|
-
return result.message_id.toString();
|
|
84
|
-
}
|
|
85
|
-
if (options.type === 'private') {
|
|
86
|
-
const result = await this.callApi<{ message_id: number }>('send_private_msg', { user_id: parseInt(options.id), ...msg });
|
|
87
|
-
this.logger.debug(`${this.$id} send private(${options.id}):${segment.raw(options.content)}`);
|
|
88
|
-
return result.message_id.toString();
|
|
89
|
-
}
|
|
90
|
-
throw new Error('Either group_id or user_id must be provided');
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
async $recallMessage(id: string): Promise<void> {
|
|
94
|
-
await this.deleteMsg(parseInt(id));
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
async $addReaction(messageId: string, emojiId: string): Promise<string> {
|
|
98
|
-
await this.setMsgEmojiLike(parseInt(messageId), emojiId);
|
|
99
|
-
return `reaction:${messageId}:${emojiId}`;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
async $removeReaction(messageId: string, _reactionId: string): Promise<void> {
|
|
103
|
-
// NapCat 的 set_msg_emoji_like 是 toggle 行为,再调一次即取消
|
|
104
|
-
const parts = _reactionId.split(':');
|
|
105
|
-
const emojiId = parts[2] || parts[0];
|
|
106
|
-
await this.setMsgEmojiLike(parseInt(messageId), emojiId);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// ══════════════════════════════════════════════════════════════════
|
|
110
|
-
// 事件分发
|
|
111
|
-
// ══════════════════════════════════════════════════════════════════
|
|
112
|
-
|
|
113
|
-
protected dispatchEvent(event: any): void {
|
|
114
|
-
switch (event.post_type) {
|
|
115
|
-
case 'message':
|
|
116
|
-
case 'message_sent':
|
|
117
|
-
return this.handleMessage(event);
|
|
118
|
-
case 'notice':
|
|
119
|
-
return this.handleNotice(event);
|
|
120
|
-
case 'request':
|
|
121
|
-
return this.handleRequest(event);
|
|
122
|
-
case 'meta_event':
|
|
123
|
-
return this.handleMeta(event);
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
private handleMessage(ev: NapCatMessageEvent): void {
|
|
128
|
-
if (isSelfMessage(ev)) return;
|
|
129
|
-
const msgId = ev.message_id.toString();
|
|
130
|
-
if (!this.inboundDeduper.shouldProcess(msgId)) return;
|
|
131
|
-
ev.message = normalizeMessage(ev.message);
|
|
132
|
-
const message = this.$formatMessage(ev);
|
|
133
|
-
this.adapter.emit('message.receive', message);
|
|
134
|
-
this.logger.debug(`${this.$id} recv ${message.$channel.type}(${message.$channel.id}):${segment.raw(message.$content)}`);
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
private handleNotice(event: any): void {
|
|
138
|
-
const dedupeKey = resolveSideEventDedupeKey(event, 'notice');
|
|
139
|
-
if (!this.inboundDeduper.shouldProcess(dedupeKey)) return;
|
|
140
|
-
const noticeTypeMap: Record<string, string> = {
|
|
141
|
-
group_increase: 'group_member_increase',
|
|
142
|
-
group_decrease: 'group_member_decrease',
|
|
143
|
-
group_admin: 'group_admin_change',
|
|
144
|
-
group_ban: 'group_ban',
|
|
145
|
-
group_recall: 'group_recall',
|
|
146
|
-
friend_recall: 'friend_recall',
|
|
147
|
-
friend_add: 'friend_add',
|
|
148
|
-
group_upload: 'group_upload',
|
|
149
|
-
group_card: 'group_card_change',
|
|
150
|
-
essence: event.sub_type === 'add' ? 'essence_add' : 'essence_delete',
|
|
151
|
-
notify: this.resolveNotifyType(event),
|
|
152
|
-
group_msg_emoji_like: 'group_emoji_reaction',
|
|
153
|
-
};
|
|
154
|
-
const $type = noticeTypeMap[event.notice_type] || event.notice_type;
|
|
155
|
-
const isGroup = !!event.group_id;
|
|
156
|
-
const notice = Notice.from(event, {
|
|
157
|
-
$id: `${event.time}_${event.notice_type}_${event.group_id || event.user_id}`,
|
|
158
|
-
$adapter: 'napcat',
|
|
159
|
-
$endpoint: this.$config.name,
|
|
160
|
-
$type,
|
|
161
|
-
$subType: event.sub_type,
|
|
162
|
-
$channel: {
|
|
163
|
-
id: (event.group_id || event.user_id)?.toString() || '',
|
|
164
|
-
type: isGroup ? 'group' : 'private',
|
|
165
|
-
},
|
|
166
|
-
$operator: event.operator_id ? { id: event.operator_id.toString(), name: event.operator_id.toString() } : undefined,
|
|
167
|
-
$target: event.user_id ? { id: event.user_id.toString(), name: event.user_id.toString() } : undefined,
|
|
168
|
-
$timestamp: event.time || Math.floor(Date.now() / 1000),
|
|
169
|
-
});
|
|
170
|
-
this.adapter.emit('notice.receive', notice);
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
private resolveNotifyType(event: any): string {
|
|
174
|
-
switch (event.sub_type) {
|
|
175
|
-
case 'poke': return event.group_id ? 'group_poke' : 'friend_poke';
|
|
176
|
-
case 'input_status': return 'input_status';
|
|
177
|
-
case 'title': return 'title_change';
|
|
178
|
-
case 'profile_like': return 'profile_like';
|
|
179
|
-
default: return `notify_${event.sub_type}`;
|
|
180
|
-
}
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
private handleRequest(event: any): void {
|
|
184
|
-
const dedupeKey = resolveSideEventDedupeKey(event, 'request');
|
|
185
|
-
if (!this.inboundDeduper.shouldProcess(dedupeKey)) return;
|
|
186
|
-
const typeMap: Record<string, string> = {
|
|
187
|
-
friend: 'friend_add',
|
|
188
|
-
group: event.sub_type === 'invite' ? 'group_invite' : 'group_add',
|
|
189
|
-
};
|
|
190
|
-
const $type = typeMap[event.request_type] || event.request_type;
|
|
191
|
-
const request = Request.from(event, {
|
|
192
|
-
$id: event.flag || `${event.time}_${event.request_type}_${event.user_id}`,
|
|
193
|
-
$adapter: 'napcat',
|
|
194
|
-
$endpoint: this.$config.name,
|
|
195
|
-
$type,
|
|
196
|
-
$subType: event.sub_type,
|
|
197
|
-
$channel: {
|
|
198
|
-
id: (event.group_id || event.user_id)?.toString() || '',
|
|
199
|
-
type: event.group_id ? 'group' : 'private',
|
|
200
|
-
},
|
|
201
|
-
$sender: { id: event.user_id?.toString() || '', name: event.user_id?.toString() || '' },
|
|
202
|
-
$comment: event.comment,
|
|
203
|
-
$timestamp: event.time || Math.floor(Date.now() / 1000),
|
|
204
|
-
$approve: async (remark?: string) => {
|
|
205
|
-
await this.callApi(
|
|
206
|
-
event.request_type === 'friend' ? 'set_friend_add_request' : 'set_group_add_request',
|
|
207
|
-
{ flag: event.flag, approve: true, remark },
|
|
208
|
-
);
|
|
209
|
-
},
|
|
210
|
-
$reject: async (reason?: string) => {
|
|
211
|
-
await this.callApi(
|
|
212
|
-
event.request_type === 'friend' ? 'set_friend_add_request' : 'set_group_add_request',
|
|
213
|
-
{ flag: event.flag, approve: false, reason },
|
|
214
|
-
);
|
|
215
|
-
},
|
|
216
|
-
});
|
|
217
|
-
this.adapter.emit('request.receive', request);
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
protected handleMeta(event: any): void {
|
|
221
|
-
// subclass may override for lifecycle handling
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// ══════════════════════════════════════════════════════════════════
|
|
225
|
-
// OneBot11 标准 API
|
|
226
|
-
// ══════════════════════════════════════════════════════════════════
|
|
227
|
-
|
|
228
|
-
async sendMsg(messageType: 'private' | 'group', id: number, message: MessageSegment[]) {
|
|
229
|
-
return this.callApi<{ message_id: number }>('send_msg', { message_type: messageType, [messageType === 'group' ? 'group_id' : 'user_id']: id, message });
|
|
230
|
-
}
|
|
231
|
-
async deleteMsg(messageId: number) { return this.callApi('delete_msg', { message_id: messageId }); }
|
|
232
|
-
async getMsg(messageId: number) { return this.callApi('get_msg', { message_id: messageId }); }
|
|
233
|
-
|
|
234
|
-
async $getMsg(messageId: string): Promise<QuotedMessagePayload> {
|
|
235
|
-
const idParam = /^\d+$/.test(messageId) ? Number(messageId) : messageId;
|
|
236
|
-
const data = await this.callApi('get_msg', { message_id: idParam });
|
|
237
|
-
return parseOneBotGetMsgResponse(messageId, data);
|
|
238
|
-
}
|
|
239
|
-
async getForwardMsg(id: string) { return this.callApi('get_forward_msg', { id }); }
|
|
240
|
-
async sendLike(userId: number, times = 1) { return this.callApi('send_like', { user_id: userId, times }); }
|
|
241
|
-
|
|
242
|
-
// 群管理
|
|
243
|
-
async setGroupKick(groupId: number, userId: number, rejectAddRequest = false) { return this.callApi('set_group_kick', { group_id: groupId, user_id: userId, reject_add_request: rejectAddRequest }); }
|
|
244
|
-
async setGroupBan(groupId: number, userId: number, duration = 600) { return this.callApi('set_group_ban', { group_id: groupId, user_id: userId, duration }); }
|
|
245
|
-
async setGroupWholeBan(groupId: number, enable = true) { return this.callApi('set_group_whole_ban', { group_id: groupId, enable }); }
|
|
246
|
-
async setGroupAdmin(groupId: number, userId: number, enable = true) { return this.callApi('set_group_admin', { group_id: groupId, user_id: userId, enable }); }
|
|
247
|
-
async setGroupCard(groupId: number, userId: number, card: string) { return this.callApi('set_group_card', { group_id: groupId, user_id: userId, card }); }
|
|
248
|
-
async setGroupName(groupId: number, groupName: string) { return this.callApi('set_group_name', { group_id: groupId, group_name: groupName }); }
|
|
249
|
-
async setGroupLeave(groupId: number, isDismiss = false) { return this.callApi('set_group_leave', { group_id: groupId, is_dismiss: isDismiss }); }
|
|
250
|
-
async setGroupSpecialTitle(groupId: number, userId: number, specialTitle: string, duration = -1) { return this.callApi('set_group_special_title', { group_id: groupId, user_id: userId, special_title: specialTitle, duration }); }
|
|
251
|
-
|
|
252
|
-
// 好友/群请求
|
|
253
|
-
async setFriendAddRequest(flag: string, approve = true, remark?: string) { return this.callApi('set_friend_add_request', { flag, approve, remark }); }
|
|
254
|
-
async setGroupAddRequest(flag: string, subType: string, approve = true, reason?: string) { return this.callApi('set_group_add_request', { flag, sub_type: subType, approve, reason }); }
|
|
255
|
-
|
|
256
|
-
// 信息查询
|
|
257
|
-
async getLoginInfo() { return this.callApi('get_login_info'); }
|
|
258
|
-
async getStrangerInfo(userId: number, noCache = false) { return this.callApi('get_stranger_info', { user_id: userId, no_cache: noCache }); }
|
|
259
|
-
async getFriendList() { return this.callApi('get_friend_list'); }
|
|
260
|
-
async getGroupInfo(groupId: number, noCache = false) { return this.callApi('get_group_info', { group_id: groupId, no_cache: noCache }); }
|
|
261
|
-
async getGroupList() { return this.callApi('get_group_list'); }
|
|
262
|
-
async getGroupMemberInfo(groupId: number, userId: number, noCache = false) { return this.callApi('get_group_member_info', { group_id: groupId, user_id: userId, no_cache: noCache }); }
|
|
263
|
-
async getGroupMemberList(groupId: number) { return this.callApi('get_group_member_list', { group_id: groupId }); }
|
|
264
|
-
async getGroupHonorInfo(groupId: number, type: string) { return this.callApi('get_group_honor_info', { group_id: groupId, type }); }
|
|
265
|
-
|
|
266
|
-
// 凭证
|
|
267
|
-
async getCookies(domain?: string) { return this.callApi('get_cookies', { domain }); }
|
|
268
|
-
async getCsrfToken() { return this.callApi('get_csrf_token'); }
|
|
269
|
-
async getCredentials(domain?: string) { return this.callApi('get_credentials', { domain }); }
|
|
270
|
-
|
|
271
|
-
// 媒体
|
|
272
|
-
async getRecord(file: string, outFormat: string) { return this.callApi('get_record', { file, out_format: outFormat }); }
|
|
273
|
-
async getImage(file: string) { return this.callApi('get_image', { file }); }
|
|
274
|
-
async canSendImage() { return this.callApi('can_send_image'); }
|
|
275
|
-
async canSendRecord() { return this.callApi('can_send_record'); }
|
|
276
|
-
|
|
277
|
-
// 系统
|
|
278
|
-
async getStatus() { return this.callApi('get_status'); }
|
|
279
|
-
async getVersionInfo() { return this.callApi('get_version_info'); }
|
|
280
|
-
async cleanCache() { return this.callApi('clean_cache'); }
|
|
281
|
-
|
|
282
|
-
// ══════════════════════════════════════════════════════════════════
|
|
283
|
-
// go-cqhttp 扩展 API
|
|
284
|
-
// ══════════════════════════════════════════════════════════════════
|
|
285
|
-
|
|
286
|
-
async setQQProfile(nickname: string, company?: string, email?: string, college?: string, personalNote?: string) {
|
|
287
|
-
return this.callApi('set_qq_profile', { nickname, company, email, college, personal_note: personalNote });
|
|
288
|
-
}
|
|
289
|
-
async getOnlineClients(noCache = false) { return this.callApi('get_online_clients', { no_cache: noCache }); }
|
|
290
|
-
async deleteFriend(userId: number) { return this.callApi('delete_friend', { user_id: userId }); }
|
|
291
|
-
async markMsgAsRead(messageId: number) { return this.callApi('mark_msg_as_read', { message_id: messageId }); }
|
|
292
|
-
async sendGroupForwardMsg(groupId: number, messages: any[]) { return this.callApi('send_group_forward_msg', { group_id: groupId, messages }); }
|
|
293
|
-
async sendPrivateForwardMsg(userId: number, messages: any[]) { return this.callApi('send_private_forward_msg', { user_id: userId, messages }); }
|
|
294
|
-
async getGroupMsgHistory(groupId: number, messageSeq?: number, count?: number) { return this.callApi('get_group_msg_history', { group_id: groupId, message_seq: messageSeq, count }); }
|
|
295
|
-
async ocrImage(image: string) { return this.callApi('ocr_image', { image }); }
|
|
296
|
-
async getGroupSystemMsg() { return this.callApi('get_group_system_msg'); }
|
|
297
|
-
async getEssenceMsgList(groupId: number) { return this.callApi('get_essence_msg_list', { group_id: groupId }); }
|
|
298
|
-
async getGroupAtAllRemain(groupId: number) { return this.callApi('get_group_at_all_remain', { group_id: groupId }); }
|
|
299
|
-
async setGroupPortrait(groupId: number, file: string) { return this.callApi('set_group_portrait', { group_id: groupId, file }); }
|
|
300
|
-
async setEssenceMsg(messageId: number) { return this.callApi('set_essence_msg', { message_id: messageId }); }
|
|
301
|
-
async deleteEssenceMsg(messageId: number) { return this.callApi('delete_essence_msg', { message_id: messageId }); }
|
|
302
|
-
async sendGroupSign(groupId: number) { return this.callApi('send_group_sign', { group_id: groupId }); }
|
|
303
|
-
async sendGroupNotice(groupId: number, content: string, image?: string) { return this.callApi('_send_group_notice', { group_id: groupId, content, image }); }
|
|
304
|
-
async getGroupNotice(groupId: number) { return this.callApi('_get_group_notice', { group_id: groupId }); }
|
|
305
|
-
async deleteGroupNotice(groupId: number, noticeId: string) { return this.callApi('_del_group_notice', { group_id: groupId, notice_id: noticeId }); }
|
|
306
|
-
async uploadGroupFile(groupId: number, file: string, name: string, folder?: string) { return this.callApi('upload_group_file', { group_id: groupId, file, name, folder }); }
|
|
307
|
-
async deleteGroupFile(groupId: number, fileId: string, busid: number) { return this.callApi('delete_group_file', { group_id: groupId, file_id: fileId, busid }); }
|
|
308
|
-
async createGroupFileFolder(groupId: number, name: string, parentId = '/') { return this.callApi('create_group_file_folder', { group_id: groupId, name, parent_id: parentId }); }
|
|
309
|
-
async deleteGroupFolder(groupId: number, folderId: string) { return this.callApi('delete_group_folder', { group_id: groupId, folder_id: folderId }); }
|
|
310
|
-
async getGroupFileSystemInfo(groupId: number) { return this.callApi('get_group_file_system_info', { group_id: groupId }); }
|
|
311
|
-
async getGroupRootFiles(groupId: number) { return this.callApi('get_group_root_files', { group_id: groupId }); }
|
|
312
|
-
async getGroupFilesByFolder(groupId: number, folderId: string) { return this.callApi('get_group_files_by_folder', { group_id: groupId, folder_id: folderId }); }
|
|
313
|
-
async getGroupFileUrl(groupId: number, fileId: string, busid: number) { return this.callApi('get_group_file_url', { group_id: groupId, file_id: fileId, busid }); }
|
|
314
|
-
async uploadPrivateFile(userId: number, file: string, name: string) { return this.callApi('upload_private_file', { user_id: userId, file, name }); }
|
|
315
|
-
async downloadFile(url: string, threadCount = 1, headers?: string[]) { return this.callApi('download_file', { url, thread_count: threadCount, headers }); }
|
|
316
|
-
async checkUrlSafely(url: string) { return this.callApi('check_url_safely', { url }); }
|
|
317
|
-
|
|
318
|
-
// ══════════════════════════════════════════════════════════════════
|
|
319
|
-
// NapCat 独有 API
|
|
320
|
-
// ══════════════════════════════════════════════════════════════════
|
|
321
|
-
|
|
322
|
-
async setGroupSign(groupId: number) { return this.callApi('set_group_sign', { group_id: groupId }); }
|
|
323
|
-
async arkSharePeer(userId: number) { return this.callApi('ArkSharePeer', { user_id: userId }); }
|
|
324
|
-
async arkShareGroup(groupId: number) { return this.callApi('ArkShareGroup', { group_id: groupId }); }
|
|
325
|
-
async getRobotUinRange() { return this.callApi('get_robot_uin_range'); }
|
|
326
|
-
async setOnlineStatus(status: number, extStatus: number) { return this.callApi('set_online_status', { status, ext_status: extStatus }); }
|
|
327
|
-
async getFriendsWithCategory() { return this.callApi('get_friends_with_category'); }
|
|
328
|
-
async setQQAvatar(file: string) { return this.callApi('set_qq_avatar', { file }); }
|
|
329
|
-
async getFile(fileId: string) { return this.callApi('get_file', { file_id: fileId }); }
|
|
330
|
-
async forwardFriendSingleMsg(userId: number, messageId: number) { return this.callApi('forward_friend_single_msg', { user_id: userId, message_id: messageId }); }
|
|
331
|
-
async forwardGroupSingleMsg(groupId: number, messageId: number) { return this.callApi('forward_group_single_msg', { group_id: groupId, message_id: messageId }); }
|
|
332
|
-
async translateEn2Zh(sourceText: string) { return this.callApi('translate_en2zh', { source_text: sourceText }); }
|
|
333
|
-
async setMsgEmojiLike(messageId: number, emojiId: string) { return this.callApi('set_msg_emoji_like', { message_id: messageId, emoji_id: emojiId }); }
|
|
334
|
-
async sendForwardMsg(messageType: 'private' | 'group', id: number, messages: any[]) {
|
|
335
|
-
return this.callApi('send_forward_msg', { message_type: messageType, [messageType === 'group' ? 'group_id' : 'user_id']: id, messages });
|
|
336
|
-
}
|
|
337
|
-
async markPrivateMsgAsRead(userId: number) { return this.callApi('mark_private_msg_as_read', { user_id: userId }); }
|
|
338
|
-
async markGroupMsgAsRead(groupId: number) { return this.callApi('mark_group_msg_as_read', { group_id: groupId }); }
|
|
339
|
-
async getFriendMsgHistory(userId: number, messageSeq?: number, count?: number) { return this.callApi('get_friend_msg_history', { user_id: userId, message_seq: messageSeq, count }); }
|
|
340
|
-
async createCollection(briefContent: string, rawData: string) { return this.callApi('create_collection', { brief: briefContent, rawData }); }
|
|
341
|
-
async getCollectionList(page = 0, limit = 20) { return this.callApi('get_collection_list', { page, limit }); }
|
|
342
|
-
async setSelfLongnick(longnick: string) { return this.callApi('set_self_longnick', { longNick: longnick }); }
|
|
343
|
-
async getRecentContact(count = 10) { return this.callApi('get_recent_contact', { count }); }
|
|
344
|
-
async markAllAsRead() { return this.callApi('_mark_all_as_read'); }
|
|
345
|
-
async getProfileLike() { return this.callApi('get_profile_like'); }
|
|
346
|
-
async fetchCustomFace() { return this.callApi('fetch_custom_face'); }
|
|
347
|
-
async fetchEmojiLike(messageId: number, emojiId: string, emojiType: string) { return this.callApi('fetch_emoji_like', { message_id: messageId, emoji_id: emojiId, emoji_type: emojiType }); }
|
|
348
|
-
async setInputStatus(userId: number, eventType: string) { return this.callApi('set_input_status', { user_id: userId, event_type: eventType }); }
|
|
349
|
-
async getGroupInfoEx(groupId: number) { return this.callApi('get_group_info_ex', { group_id: groupId }); }
|
|
350
|
-
async getGroupIgnoreAddRequest(groupId: number) { return this.callApi('get_group_ignore_add_request', { group_id: groupId }); }
|
|
351
|
-
async friendPoke(userId: number) { return this.callApi('friend_poke', { user_id: userId }); }
|
|
352
|
-
async groupPoke(groupId: number, userId: number) { return this.callApi('group_poke', { group_id: groupId, user_id: userId }); }
|
|
353
|
-
async sendPoke(userId: number, groupId?: number) { return this.callApi('send_poke', { user_id: userId, group_id: groupId }); }
|
|
354
|
-
async ncGetPacketStatus() { return this.callApi('nc_get_packet_status'); }
|
|
355
|
-
async ncGetUserStatus(userId: number) { return this.callApi('nc_get_user_status', { user_id: userId }); }
|
|
356
|
-
async ncGetRkey() { return this.callApi('nc_get_rkey'); }
|
|
357
|
-
async getGroupShutList(groupId: number) { return this.callApi('get_group_shut_list', { group_id: groupId }); }
|
|
358
|
-
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string) {
|
|
359
|
-
return this.callApi('get_mini_app_ark', { type, title, desc, picUrl, jumpUrl });
|
|
360
|
-
}
|
|
361
|
-
async getAiRecord(groupId: number, characterId: string, text: string) { return this.callApi('get_ai_record', { group_id: groupId, character: characterId, text }); }
|
|
362
|
-
async getAiCharacters(groupId: number) { return this.callApi('get_ai_characters', { group_id: groupId }); }
|
|
363
|
-
async sendGroupAiRecord(groupId: number, characterId: string, text: string) { return this.callApi('send_group_ai_record', { group_id: groupId, character: characterId, text }); }
|
|
364
|
-
|
|
365
|
-
// ══════════════════════════════════════════════════════════════════
|
|
366
|
-
// Adapter 群管理接口适配
|
|
367
|
-
// ══════════════════════════════════════════════════════════════════
|
|
368
|
-
|
|
369
|
-
async kickMember(groupId: number, userId: number, reject = false) { await this.setGroupKick(groupId, userId, reject); return true; }
|
|
370
|
-
async muteMember(groupId: number, userId: number, duration = 600) { await this.setGroupBan(groupId, userId, duration); return true; }
|
|
371
|
-
async muteAll(groupId: number, enable = true) { await this.setGroupWholeBan(groupId, enable); return true; }
|
|
372
|
-
async setAdmin(groupId: number, userId: number, enable = true) { await this.setGroupAdmin(groupId, userId, enable); return true; }
|
|
373
|
-
async setCard(groupId: number, userId: number, card: string) { await this.setGroupCard(groupId, userId, card); return true; }
|
|
374
|
-
async setTitle(groupId: number, userId: number, title: string, duration = -1) { await this.setGroupSpecialTitle(groupId, userId, title, duration); return true; }
|
|
375
|
-
async getMemberList(groupId: number) { return this.getGroupMemberList(groupId); }
|
|
376
|
-
}
|
package/src/endpoint-http.ts
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* NapCat HTTP 连接方式
|
|
3
|
-
* 出站:HTTP POST 调用 NapCat API
|
|
4
|
-
* 入站:挂载 webhook 路由接收 NapCat 的 HTTP POST 事件上报
|
|
5
|
-
*/
|
|
6
|
-
import { formatCompact } from 'zhin.js';
|
|
7
|
-
import { NapCatEndpointBase } from './endpoint-base.js';
|
|
8
|
-
import type { NapCatHttpConfig, ApiResponse } from './types.js';
|
|
9
|
-
import type { NapCatAdapter } from './adapter.js';
|
|
10
|
-
import { registerFetchRoute, type Router, type RouterContext } from '@zhin.js/host-router/router';
|
|
11
|
-
import * as crypto from 'crypto';
|
|
12
|
-
import { enableTypingIndicator } from './typing-indicator.js';
|
|
13
|
-
|
|
14
|
-
export class NapCatHttpEndpoint extends NapCatEndpointBase {
|
|
15
|
-
private pollTimer?: NodeJS.Timeout;
|
|
16
|
-
|
|
17
|
-
declare $config: NapCatHttpConfig;
|
|
18
|
-
|
|
19
|
-
constructor(adapter: NapCatAdapter, public router: Router, config: NapCatHttpConfig) {
|
|
20
|
-
super(adapter, config);
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
async $connect(): Promise<void> {
|
|
24
|
-
this.mountWebhook();
|
|
25
|
-
await this.checkConnection();
|
|
26
|
-
this.startPoll();
|
|
27
|
-
this.$connected = true;
|
|
28
|
-
this.initTypingIndicator();
|
|
29
|
-
this.logger.info(formatCompact({ endpoint: this.$id, mode: 'http' }));
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
async $disconnect(): Promise<void> {
|
|
33
|
-
if (this.pollTimer) { clearInterval(this.pollTimer); this.pollTimer = undefined; }
|
|
34
|
-
this.inboundDeduper.clear();
|
|
35
|
-
this.$connected = false;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
async callApi<T = any>(action: string, params: Record<string, any> = {}): Promise<T> {
|
|
39
|
-
const url = `${this.$config.http_url.replace(/\/$/, '')}/${action}`;
|
|
40
|
-
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
|
41
|
-
if (this.$config.access_token) headers['Authorization'] = `Bearer ${this.$config.access_token}`;
|
|
42
|
-
|
|
43
|
-
const resp = await fetch(url, { method: 'POST', headers, body: JSON.stringify(params) });
|
|
44
|
-
if (!resp.ok) throw new Error(`HTTP ${resp.status} ${resp.statusText} for ${action}`);
|
|
45
|
-
const json = await resp.json() as ApiResponse<T>;
|
|
46
|
-
if (json.status !== 'ok' && json.retcode !== 0) {
|
|
47
|
-
throw new Error(`API error [${json.retcode}]: ${json.message || json.wording || 'unknown'}`);
|
|
48
|
-
}
|
|
49
|
-
return json.data;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
private mountWebhook(): void {
|
|
53
|
-
const postPath = this.$config.post_path;
|
|
54
|
-
registerFetchRoute(this.router, 'POST', postPath, async (ctx: RouterContext) => {
|
|
55
|
-
const body = ctx.request.body;
|
|
56
|
-
if (!body || typeof body !== 'object') { ctx.status = 400; ctx.body = { error: 'invalid body' }; return; }
|
|
57
|
-
|
|
58
|
-
if (this.$config.access_token) {
|
|
59
|
-
const sig = ctx.get('x-signature');
|
|
60
|
-
const authHeader = ctx.get('authorization');
|
|
61
|
-
if (sig) {
|
|
62
|
-
const expected = 'sha1=' + crypto.createHmac('sha1', this.$config.access_token).update(JSON.stringify(body)).digest('hex');
|
|
63
|
-
if (sig !== expected) { ctx.status = 403; ctx.body = { error: 'signature mismatch' }; return; }
|
|
64
|
-
} else if (authHeader) {
|
|
65
|
-
if (authHeader !== `Bearer ${this.$config.access_token}`) { ctx.status = 403; ctx.body = { error: 'auth failed' }; return; }
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
ctx.status = 204;
|
|
70
|
-
ctx.body = '';
|
|
71
|
-
try { this.dispatchEvent(body); } catch (e) {
|
|
72
|
-
this.logger.warn(formatCompact( { op: 'recv', endpoint: this.$id, ok: false, error: String(e) }));
|
|
73
|
-
}
|
|
74
|
-
});
|
|
75
|
-
this.logger.info(formatCompact( { op: 'webhook', endpoint: this.$id, path: postPath }));
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
private async checkConnection(): Promise<void> {
|
|
79
|
-
try {
|
|
80
|
-
await this.callApi('get_login_info');
|
|
81
|
-
} catch (e) {
|
|
82
|
-
throw new Error(`${this.$id} cannot connect to NapCat HTTP API at ${this.$config.http_url}: ${e}`);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
private startPoll(): void {
|
|
87
|
-
const interval = this.$config.poll_interval || 30000;
|
|
88
|
-
this.pollTimer = setInterval(async () => {
|
|
89
|
-
try {
|
|
90
|
-
await this.callApi('get_status');
|
|
91
|
-
} catch {
|
|
92
|
-
this.$connected = false;
|
|
93
|
-
this.logger.warn(formatCompact( { op: 'heartbeat', endpoint: this.$id, ok: false }));
|
|
94
|
-
}
|
|
95
|
-
}, interval);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
private initTypingIndicator(): void {
|
|
99
|
-
const tiConfig = (this.$config as any).typingIndicator;
|
|
100
|
-
if (tiConfig && tiConfig.enabled !== false) {
|
|
101
|
-
enableTypingIndicator(this, {
|
|
102
|
-
enabled: true,
|
|
103
|
-
defaultEmoji: tiConfig.defaultEmoji || '128516',
|
|
104
|
-
autoRemove: true,
|
|
105
|
-
removeDelay: 5000,
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
}
|
|
@@ -1,164 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* NapCat 正向 WebSocket 连接
|
|
3
|
-
*/
|
|
4
|
-
import WebSocket from 'ws';
|
|
5
|
-
import { formatCompact } from 'zhin.js';
|
|
6
|
-
import { NapCatEndpointBase } from './endpoint-base.js';
|
|
7
|
-
import type { NapCatWsClientConfig, ApiResponse } from './types.js';
|
|
8
|
-
import type { NapCatAdapter } from './adapter.js';
|
|
9
|
-
import { enableTypingIndicator } from './typing-indicator.js';
|
|
10
|
-
|
|
11
|
-
export class NapCatWsClient extends NapCatEndpointBase {
|
|
12
|
-
private ws?: WebSocket;
|
|
13
|
-
private reconnectTimer?: NodeJS.Timeout;
|
|
14
|
-
private heartbeatTimer?: NodeJS.Timeout;
|
|
15
|
-
private requestId = 0;
|
|
16
|
-
private pendingRequests = new Map<string, {
|
|
17
|
-
resolve: (value: any) => void;
|
|
18
|
-
reject: (error: Error) => void;
|
|
19
|
-
timeout: NodeJS.Timeout;
|
|
20
|
-
}>();
|
|
21
|
-
|
|
22
|
-
declare $config: NapCatWsClientConfig;
|
|
23
|
-
|
|
24
|
-
constructor(adapter: NapCatAdapter, config: NapCatWsClientConfig) {
|
|
25
|
-
super(adapter, config);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
async $connect(): Promise<void> {
|
|
29
|
-
return new Promise((resolve, reject) => {
|
|
30
|
-
const headers: Record<string, string> = {};
|
|
31
|
-
let url = this.$config.url;
|
|
32
|
-
if (this.$config.access_token) {
|
|
33
|
-
headers['Authorization'] = `Bearer ${this.$config.access_token}`;
|
|
34
|
-
const u = new URL(url);
|
|
35
|
-
u.searchParams.set('access_token', this.$config.access_token);
|
|
36
|
-
url = u.toString();
|
|
37
|
-
}
|
|
38
|
-
this.ws = new WebSocket(url, { headers });
|
|
39
|
-
|
|
40
|
-
this.ws.on('open', () => {
|
|
41
|
-
this.$connected = true;
|
|
42
|
-
if (!this.$config.access_token) {
|
|
43
|
-
this.logger.warn(formatCompact({ endpoint: this.$id, ok: false, error: 'missing access_token' }));
|
|
44
|
-
}
|
|
45
|
-
this.logger.info(formatCompact({ endpoint: this.$id, mode: 'ws' }));
|
|
46
|
-
this.startHeartbeat();
|
|
47
|
-
this.initTypingIndicator();
|
|
48
|
-
resolve();
|
|
49
|
-
});
|
|
50
|
-
|
|
51
|
-
this.ws.on('message', (data) => {
|
|
52
|
-
try {
|
|
53
|
-
this.handleWsMessage(JSON.parse(data.toString()));
|
|
54
|
-
} catch (error) {
|
|
55
|
-
this.emit('error', error);
|
|
56
|
-
}
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
this.ws.on('close', (code, reason) => {
|
|
60
|
-
this.$connected = false;
|
|
61
|
-
const reasonStr = reason?.toString?.() || '';
|
|
62
|
-
const codeHint = code === 1005 ? ' [no status]' : code === 1006 ? ' [abnormal]' : '';
|
|
63
|
-
this.logger.warn(formatCompact( {
|
|
64
|
-
op: 'disconnect',
|
|
65
|
-
endpoint: this.$id,
|
|
66
|
-
code,
|
|
67
|
-
error: reasonStr || 'closed',
|
|
68
|
-
reconnect_ms: this.$config.reconnect_interval || 5000,
|
|
69
|
-
}));
|
|
70
|
-
reject({ code, reason });
|
|
71
|
-
this.scheduleReconnect();
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
this.ws.on('error', (error) => {
|
|
75
|
-
this.logger.warn(formatCompact( {
|
|
76
|
-
op: 'ws_error',
|
|
77
|
-
endpoint: this.$id,
|
|
78
|
-
ok: false,
|
|
79
|
-
error: error instanceof Error ? error.message : String(error),
|
|
80
|
-
}));
|
|
81
|
-
reject(error);
|
|
82
|
-
});
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
async $disconnect(): Promise<void> {
|
|
87
|
-
if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = undefined; }
|
|
88
|
-
if (this.heartbeatTimer) { clearInterval(this.heartbeatTimer); this.heartbeatTimer = undefined; }
|
|
89
|
-
for (const [, req] of this.pendingRequests) { clearTimeout(req.timeout); req.reject(new Error('Connection closed')); }
|
|
90
|
-
this.pendingRequests.clear();
|
|
91
|
-
if (this.ws) { this.ws.close(); this.ws = undefined; }
|
|
92
|
-
this.inboundDeduper.clear();
|
|
93
|
-
this.$connected = false;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
async callApi<T = any>(action: string, params: Record<string, any> = {}): Promise<T> {
|
|
97
|
-
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) throw new Error('WebSocket is not connected');
|
|
98
|
-
const echo = `req_${++this.requestId}`;
|
|
99
|
-
return new Promise((resolve, reject) => {
|
|
100
|
-
const timeout = setTimeout(() => { this.pendingRequests.delete(echo); reject(new Error(`API call timeout: ${action}`)); }, 30000);
|
|
101
|
-
this.pendingRequests.set(echo, { resolve, reject, timeout });
|
|
102
|
-
this.ws!.send(JSON.stringify({ action, params, echo }));
|
|
103
|
-
});
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
private handleWsMessage(message: any): void {
|
|
107
|
-
if (message.echo && this.pendingRequests.has(message.echo)) {
|
|
108
|
-
const req = this.pendingRequests.get(message.echo)!;
|
|
109
|
-
this.pendingRequests.delete(message.echo);
|
|
110
|
-
clearTimeout(req.timeout);
|
|
111
|
-
const resp = message as ApiResponse;
|
|
112
|
-
if (resp.status === 'ok') return req.resolve(resp.data);
|
|
113
|
-
return req.reject(new Error(`API error [${resp.retcode}]: ${resp.message || resp.wording || 'unknown'}`));
|
|
114
|
-
}
|
|
115
|
-
this.dispatchEvent(message);
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
private startHeartbeat(): void {
|
|
119
|
-
const interval = this.$config.heartbeat_interval || 30000;
|
|
120
|
-
this.heartbeatTimer = setInterval(() => {
|
|
121
|
-
if (this.ws && this.ws.readyState === WebSocket.OPEN) this.ws.ping();
|
|
122
|
-
}, interval);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
private scheduleReconnect(): void {
|
|
126
|
-
if (this.reconnectTimer) return;
|
|
127
|
-
const interval = this.$config.reconnect_interval || 5000;
|
|
128
|
-
this.reconnectTimer = setTimeout(async () => {
|
|
129
|
-
this.reconnectTimer = undefined;
|
|
130
|
-
try { await this.$connect(); } catch { this.scheduleReconnect(); }
|
|
131
|
-
}, interval);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
protected handleMeta(event: any): void {
|
|
135
|
-
if (event.meta_event_type === 'lifecycle' && event.sub_type === 'connect') {
|
|
136
|
-
this.logger.info(formatCompact({ endpoint: this.$id, lifecycle: 'connect', self_id: event.self_id }));
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
private initTypingIndicator(): void {
|
|
141
|
-
const tiConfig = this.$config.typingIndicator;
|
|
142
|
-
if (tiConfig && tiConfig.enabled !== false) {
|
|
143
|
-
enableTypingIndicator(this, {
|
|
144
|
-
enabled: tiConfig.enabled ?? true,
|
|
145
|
-
defaultEmoji: tiConfig.defaultEmoji || '128516',
|
|
146
|
-
autoRemove: true,
|
|
147
|
-
removeDelay: 5000,
|
|
148
|
-
privateConfig: tiConfig.privateConfig ? {
|
|
149
|
-
type: tiConfig.privateConfig.type || 'message',
|
|
150
|
-
message: tiConfig.privateConfig.message || '正在思考中...',
|
|
151
|
-
autoRemove: true,
|
|
152
|
-
removeDelay: 3000,
|
|
153
|
-
} : undefined,
|
|
154
|
-
groupConfig: tiConfig.groupConfig ? {
|
|
155
|
-
type: tiConfig.groupConfig.type || 'reaction',
|
|
156
|
-
emoji: tiConfig.groupConfig.emoji || '128516',
|
|
157
|
-
autoRemove: true,
|
|
158
|
-
removeDelay: 5000,
|
|
159
|
-
} : undefined,
|
|
160
|
-
});
|
|
161
|
-
this.logger.info(formatCompact({ endpoint: this.$id, typingIndicator: 'enabled' }));
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
}
|