@zhin.js/adapter-napcat 3.0.2 → 5.0.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.
Files changed (183) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +47 -98
  3. package/adapters/napcat.ts +39 -0
  4. package/agent/tools/ai_tts.ts +2 -2
  5. package/agent/tools/del_group_notice.ts +2 -2
  6. package/agent/tools/delete_essence_msg.ts +2 -2
  7. package/agent/tools/delete_friend.ts +2 -2
  8. package/agent/tools/download_file.ts +2 -2
  9. package/agent/tools/forward_single_msg.ts +2 -2
  10. package/agent/tools/get_ai_characters.ts +2 -2
  11. package/agent/tools/get_essence_list.ts +2 -2
  12. package/agent/tools/get_friend_msg_history.ts +2 -2
  13. package/agent/tools/get_group_file_url.ts +2 -2
  14. package/agent/tools/get_group_info_ex.ts +2 -2
  15. package/agent/tools/get_group_msg_history.ts +2 -2
  16. package/agent/tools/get_group_notice.ts +2 -2
  17. package/agent/tools/get_group_root_files.ts +2 -2
  18. package/agent/tools/get_group_shut_list.ts +2 -2
  19. package/agent/tools/get_mini_app_ark.ts +2 -2
  20. package/agent/tools/get_user_status.ts +2 -2
  21. package/agent/tools/group_sign.ts +2 -2
  22. package/agent/tools/mark_msg_as_read.ts +2 -2
  23. package/agent/tools/ocr_image.ts +2 -2
  24. package/agent/tools/send_forward_msg.ts +2 -2
  25. package/agent/tools/send_group_notice.ts +2 -2
  26. package/agent/tools/send_like.ts +2 -2
  27. package/agent/tools/send_poke.ts +2 -2
  28. package/agent/tools/set_avatar.ts +2 -2
  29. package/agent/tools/set_emoji_reaction.ts +2 -2
  30. package/agent/tools/set_essence_msg.ts +2 -2
  31. package/agent/tools/set_group_portrait.ts +2 -2
  32. package/agent/tools/set_online_status.ts +2 -2
  33. package/agent/tools/set_profile.ts +2 -2
  34. package/agent/tools/set_signature.ts +2 -2
  35. package/agent/tools/set_title.ts +2 -2
  36. package/agent/tools/translate.ts +2 -2
  37. package/agent/tools/upload_group_file.ts +2 -2
  38. package/lib/http-endpoint.d.ts +26 -0
  39. package/lib/http-endpoint.js +147 -0
  40. package/lib/index.d.ts +11 -0
  41. package/lib/index.js +10 -0
  42. package/lib/napcat-agent-deps.d.ts +51 -0
  43. package/lib/napcat-agent-deps.js +33 -0
  44. package/lib/napcat-inbound.d.ts +28 -0
  45. package/lib/{src/napcat-inbound.js → napcat-inbound.js} +28 -13
  46. package/lib/onebot-get-msg.d.ts +14 -0
  47. package/lib/{src/onebot-get-msg.js → onebot-get-msg.js} +0 -1
  48. package/lib/protocol.d.ts +151 -0
  49. package/lib/protocol.js +217 -0
  50. package/lib/webhook.d.ts +2 -0
  51. package/lib/webhook.js +14 -0
  52. package/lib/ws-endpoint.d.ts +61 -0
  53. package/lib/ws-endpoint.js +357 -0
  54. package/lib/ws-transport.d.ts +13 -0
  55. package/lib/ws-transport.js +75 -0
  56. package/lib/ws-types.d.ts +17 -0
  57. package/lib/ws-types.js +1 -0
  58. package/lib/wss-auth.d.ts +2 -0
  59. package/lib/wss-auth.js +16 -0
  60. package/lib/wss-endpoint.d.ts +25 -0
  61. package/lib/wss-endpoint.js +157 -0
  62. package/package.json +44 -33
  63. package/plugin.ts +13 -0
  64. package/schema.json +74 -0
  65. package/src/http-endpoint.ts +197 -0
  66. package/src/index.ts +66 -81
  67. package/src/napcat-agent-deps.ts +81 -15
  68. package/src/napcat-inbound.ts +34 -10
  69. package/src/onebot-get-msg.ts +8 -2
  70. package/src/protocol.ts +373 -0
  71. package/src/webhook.ts +16 -0
  72. package/src/ws-endpoint.ts +452 -0
  73. package/src/ws-transport.ts +105 -0
  74. package/src/ws-types.ts +20 -0
  75. package/src/wss-auth.ts +17 -0
  76. package/src/wss-endpoint.ts +205 -0
  77. package/client/NapCatManagement.tsx +0 -113
  78. package/client/index.tsx +0 -11
  79. package/client/tsconfig.json +0 -7
  80. package/client/utils/api.ts +0 -30
  81. package/dist/index.js +0 -27
  82. package/lib/agent/tools/ai_tts.js +0 -21
  83. package/lib/agent/tools/ai_tts.js.map +0 -1
  84. package/lib/agent/tools/del_group_notice.js +0 -22
  85. package/lib/agent/tools/del_group_notice.js.map +0 -1
  86. package/lib/agent/tools/delete_essence_msg.js +0 -21
  87. package/lib/agent/tools/delete_essence_msg.js.map +0 -1
  88. package/lib/agent/tools/delete_friend.js +0 -20
  89. package/lib/agent/tools/delete_friend.js.map +0 -1
  90. package/lib/agent/tools/download_file.js +0 -19
  91. package/lib/agent/tools/download_file.js.map +0 -1
  92. package/lib/agent/tools/forward_single_msg.js +0 -24
  93. package/lib/agent/tools/forward_single_msg.js.map +0 -1
  94. package/lib/agent/tools/get_ai_characters.js +0 -19
  95. package/lib/agent/tools/get_ai_characters.js.map +0 -1
  96. package/lib/agent/tools/get_essence_list.js +0 -19
  97. package/lib/agent/tools/get_essence_list.js.map +0 -1
  98. package/lib/agent/tools/get_friend_msg_history.js +0 -20
  99. package/lib/agent/tools/get_friend_msg_history.js.map +0 -1
  100. package/lib/agent/tools/get_group_file_url.js +0 -21
  101. package/lib/agent/tools/get_group_file_url.js.map +0 -1
  102. package/lib/agent/tools/get_group_info_ex.js +0 -19
  103. package/lib/agent/tools/get_group_info_ex.js.map +0 -1
  104. package/lib/agent/tools/get_group_msg_history.js +0 -21
  105. package/lib/agent/tools/get_group_msg_history.js.map +0 -1
  106. package/lib/agent/tools/get_group_notice.js +0 -19
  107. package/lib/agent/tools/get_group_notice.js.map +0 -1
  108. package/lib/agent/tools/get_group_root_files.js +0 -19
  109. package/lib/agent/tools/get_group_root_files.js.map +0 -1
  110. package/lib/agent/tools/get_group_shut_list.js +0 -19
  111. package/lib/agent/tools/get_group_shut_list.js.map +0 -1
  112. package/lib/agent/tools/get_mini_app_ark.js +0 -22
  113. package/lib/agent/tools/get_mini_app_ark.js.map +0 -1
  114. package/lib/agent/tools/get_user_status.js +0 -18
  115. package/lib/agent/tools/get_user_status.js.map +0 -1
  116. package/lib/agent/tools/group_sign.js +0 -20
  117. package/lib/agent/tools/group_sign.js.map +0 -1
  118. package/lib/agent/tools/mark_msg_as_read.js +0 -19
  119. package/lib/agent/tools/mark_msg_as_read.js.map +0 -1
  120. package/lib/agent/tools/ocr_image.js +0 -18
  121. package/lib/agent/tools/ocr_image.js.map +0 -1
  122. package/lib/agent/tools/send_forward_msg.js +0 -21
  123. package/lib/agent/tools/send_forward_msg.js.map +0 -1
  124. package/lib/agent/tools/send_group_notice.js +0 -23
  125. package/lib/agent/tools/send_group_notice.js.map +0 -1
  126. package/lib/agent/tools/send_like.js +0 -20
  127. package/lib/agent/tools/send_like.js.map +0 -1
  128. package/lib/agent/tools/send_poke.js +0 -20
  129. package/lib/agent/tools/send_poke.js.map +0 -1
  130. package/lib/agent/tools/set_avatar.js +0 -19
  131. package/lib/agent/tools/set_avatar.js.map +0 -1
  132. package/lib/agent/tools/set_emoji_reaction.js +0 -20
  133. package/lib/agent/tools/set_emoji_reaction.js.map +0 -1
  134. package/lib/agent/tools/set_essence_msg.js +0 -21
  135. package/lib/agent/tools/set_essence_msg.js.map +0 -1
  136. package/lib/agent/tools/set_group_portrait.js +0 -22
  137. package/lib/agent/tools/set_group_portrait.js.map +0 -1
  138. package/lib/agent/tools/set_online_status.js +0 -20
  139. package/lib/agent/tools/set_online_status.js.map +0 -1
  140. package/lib/agent/tools/set_profile.js +0 -23
  141. package/lib/agent/tools/set_profile.js.map +0 -1
  142. package/lib/agent/tools/set_signature.js +0 -19
  143. package/lib/agent/tools/set_signature.js.map +0 -1
  144. package/lib/agent/tools/set_title.js +0 -23
  145. package/lib/agent/tools/set_title.js.map +0 -1
  146. package/lib/agent/tools/translate.js +0 -18
  147. package/lib/agent/tools/translate.js.map +0 -1
  148. package/lib/agent/tools/upload_group_file.js +0 -23
  149. package/lib/agent/tools/upload_group_file.js.map +0 -1
  150. package/lib/src/adapter.js +0 -102
  151. package/lib/src/adapter.js.map +0 -1
  152. package/lib/src/agent-prompt.js +0 -106
  153. package/lib/src/agent-prompt.js.map +0 -1
  154. package/lib/src/endpoint-base.js +0 -315
  155. package/lib/src/endpoint-base.js.map +0 -1
  156. package/lib/src/endpoint-http.js +0 -106
  157. package/lib/src/endpoint-http.js.map +0 -1
  158. package/lib/src/endpoint-ws-client.js +0 -139
  159. package/lib/src/endpoint-ws-client.js.map +0 -1
  160. package/lib/src/endpoint-ws-server.js +0 -137
  161. package/lib/src/endpoint-ws-server.js.map +0 -1
  162. package/lib/src/index.js +0 -58
  163. package/lib/src/index.js.map +0 -1
  164. package/lib/src/napcat-agent-deps.js +0 -19
  165. package/lib/src/napcat-agent-deps.js.map +0 -1
  166. package/lib/src/napcat-inbound.js.map +0 -1
  167. package/lib/src/onebot-get-msg.js.map +0 -1
  168. package/lib/src/routes.js +0 -61
  169. package/lib/src/routes.js.map +0 -1
  170. package/lib/src/segment-mapper.js +0 -2
  171. package/lib/src/segment-mapper.js.map +0 -1
  172. package/lib/src/types.js +0 -6
  173. package/lib/src/types.js.map +0 -1
  174. package/plugin.yml +0 -3
  175. package/src/adapter.ts +0 -109
  176. package/src/agent-prompt.ts +0 -115
  177. package/src/endpoint-base.ts +0 -362
  178. package/src/endpoint-http.ts +0 -95
  179. package/src/endpoint-ws-client.ts +0 -137
  180. package/src/endpoint-ws-server.ts +0 -136
  181. package/src/routes.ts +0 -61
  182. package/src/segment-mapper.ts +0 -1
  183. package/src/types.ts +0 -266
@@ -1 +0,0 @@
1
- {"version":3,"file":"segment-mapper.js","sourceRoot":"","sources":["../../src/segment-mapper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC"}
package/lib/src/types.js DELETED
@@ -1,6 +0,0 @@
1
- /**
2
- * NapCat 适配器类型定义
3
- * 覆盖 OneBot11 标准 + go-cqhttp 扩展 + NapCat 独有 API
4
- */
5
- export {};
6
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG"}
package/plugin.yml DELETED
@@ -1,3 +0,0 @@
1
- name: adapter-napcat
2
- description: NapCatQQ 适配器:OneBot11 + go-cqhttp 扩展 + NapCat 独有 API(戳一戳、表情回应、AI语音、群文件、精华消息、群公告等)
3
- version: 0.1.13
package/src/adapter.ts DELETED
@@ -1,109 +0,0 @@
1
- /**
2
- * NapCat 适配器:支持正向 WS / 反向 WS / HTTP
3
- */
4
- import { formatCompact, Adapter, Plugin, OUTBOUND_RICH_SEGMENT_POLICY_IM_FULL, ONEBOT_KEYBOARD_AI_OUTBOUND_EXTENSION } from 'zhin.js';
5
- import type { Router } from '@zhin.js/host-router';
6
- import { NapCatWsClient } from './endpoint-ws-client.js';
7
- import { NapCatWsServer } from './endpoint-ws-server.js';
8
- import { NapCatHttpEndpoint } from './endpoint-http.js';
9
- import type { NapCatEndpointConfig, NapCatWsClientConfig, NapCatWsServerConfig, NapCatHttpConfig } from './types.js';
10
-
11
- export type NapCatEndpoint = NapCatWsClient | NapCatWsServer | NapCatHttpEndpoint;
12
-
13
- export class NapCatAdapter extends Adapter<NapCatEndpoint> {
14
- static override readonly capabilities = ['inbound', 'outbound'] as const;
15
- static override outboundRichSegmentPolicy = OUTBOUND_RICH_SEGMENT_POLICY_IM_FULL;
16
- static override interactivePolicy = 'text' as const;
17
- static override aiOutboundCapabilities = {
18
- mentions: true,
19
- richSegments: ['qrcode', 'html', 'markdown', 'tts'],
20
- interactive: 'text' as const,
21
- };
22
- static override aiOutboundExtensions = [ONEBOT_KEYBOARD_AI_OUTBOUND_EXTENSION];
23
-
24
- #router?: Router;
25
-
26
- constructor(plugin: Plugin) {
27
- super(plugin, 'napcat', []);
28
- }
29
-
30
- createEndpoint(config: NapCatEndpointConfig): NapCatEndpoint {
31
- const connection = config.connection ?? 'ws';
32
- switch (connection) {
33
- case 'ws':
34
- return new NapCatWsClient(this, config as NapCatWsClientConfig);
35
- case 'wss':
36
- if (!this.#router) throw new Error('NapCat connection: wss requires router. Enable @zhin.js/host-router first.');
37
- return new NapCatWsServer(this, this.#router, config as NapCatWsServerConfig);
38
- case 'http':
39
- if (!this.#router) throw new Error('NapCat connection: http requires router. Enable @zhin.js/host-router first.');
40
- return new NapCatHttpEndpoint(this, this.#router, config as NapCatHttpConfig);
41
- default:
42
- throw new Error(`Unknown NapCat connection: ${connection}`);
43
- }
44
- }
45
-
46
- // ── 群管理接口(ISceneManagement 适配)──────────────────────────
47
-
48
- async removeMember(endpointId: string, sceneId: string, userId: string) {
49
- const endpoint = this.endpoints.get(endpointId);
50
- if (!endpoint) throw new Error(`Endpoint ${endpointId} not found`);
51
- return endpoint.kickMember(Number(sceneId), Number(userId));
52
- }
53
-
54
- async muteMember(endpointId: string, sceneId: string, userId: string, duration = 600) {
55
- const endpoint = this.endpoints.get(endpointId);
56
- if (!endpoint) throw new Error(`Endpoint ${endpointId} not found`);
57
- return endpoint.muteMember(Number(sceneId), Number(userId), duration);
58
- }
59
-
60
- async setSceneMuted(endpointId: string, sceneId: string, enable = true) {
61
- const endpoint = this.endpoints.get(endpointId);
62
- if (!endpoint) throw new Error(`Endpoint ${endpointId} not found`);
63
- return endpoint.muteAll(Number(sceneId), enable);
64
- }
65
-
66
- async setModerator(endpointId: string, sceneId: string, userId: string, enable = true) {
67
- const endpoint = this.endpoints.get(endpointId);
68
- if (!endpoint) throw new Error(`Endpoint ${endpointId} not found`);
69
- return endpoint.setAdmin(Number(sceneId), Number(userId), enable);
70
- }
71
-
72
- async setMemberNickname(endpointId: string, sceneId: string, userId: string, nickname: string) {
73
- const endpoint = this.endpoints.get(endpointId);
74
- if (!endpoint) throw new Error(`Endpoint ${endpointId} not found`);
75
- return endpoint.setCard(Number(sceneId), Number(userId), nickname);
76
- }
77
-
78
- async renameScene(endpointId: string, sceneId: string, name: string) {
79
- const endpoint = this.endpoints.get(endpointId);
80
- if (!endpoint) throw new Error(`Endpoint ${endpointId} not found`);
81
- return endpoint.setGroupName(Number(sceneId), name);
82
- }
83
-
84
- async listMembers(endpointId: string, sceneId: string) {
85
- const endpoint = this.endpoints.get(endpointId);
86
- if (!endpoint) throw new Error(`Endpoint ${endpointId} not found`);
87
- const members = await endpoint.getMemberList(Number(sceneId));
88
- return {
89
- members: members.map((m: any) => ({
90
- user_id: m.user_id, nickname: m.nickname, card: m.card, role: m.role, title: m.title,
91
- })),
92
- count: members.length,
93
- };
94
- }
95
-
96
- async getSceneInfo(endpointId: string, sceneId: string) {
97
- const endpoint = this.endpoints.get(endpointId);
98
- if (!endpoint) throw new Error(`Endpoint ${endpointId} not found`);
99
- return endpoint.getGroupInfo(Number(sceneId));
100
- }
101
-
102
- async start(): Promise<void> {
103
- this.#router = (this.plugin.inject as (key: string) => Router | undefined)('router');
104
- (this.plugin.useContext as (key: string, fn: (router: Router) => void) => void)('router', (router: Router) => {
105
- this.#router = router;
106
- });
107
- await super.start();
108
- }
109
- }
@@ -1,115 +0,0 @@
1
- import type {
2
- AgentPromptBuildContext,
3
- AgentPromptContributor,
4
- AgentPromptSection,
5
- DeferredToolCatalogItem,
6
- } from 'zhin.js';
7
- import { filterTools, type AgentTool } from 'zhin.js/ai';
8
-
9
- function isNapCatDelegatedTask(query: string, goal: string): boolean {
10
- const text = `${query} ${goal}`;
11
- if (/\bnapcat\b|napcat_|mcp_napcat/i.test(text)) return true;
12
- if (/戳一戳|poke|表情回应|emoji.*reaction/i.test(text)) return true;
13
- if (/精华消息|essence|群公告|group.*notice/i.test(text)) return true;
14
- if (/AI语音|ai.*record|tts|文字转语音/i.test(text)) return true;
15
- if (/群文件|upload.*file|群签到|group.*sign/i.test(text)) return true;
16
- if (/合并转发|forward.*msg|转发消息/i.test(text)) return true;
17
- if (/点赞/.test(text) && /qq|好友|\d{5,}/i.test(text)) return true;
18
- return false;
19
- }
20
-
21
- function selectNapCatDeferredTools(
22
- query: string,
23
- goal: string,
24
- deferredCatalog: DeferredToolCatalogItem[],
25
- maxTools: number,
26
- ): DeferredToolCatalogItem[] {
27
- const pool = deferredCatalog.filter(
28
- t => !t.name.startsWith('mcp_filesystem') && !t.name.startsWith('mcp_memory_'),
29
- );
30
- const napcatTools = pool.filter(t => t.name.startsWith('napcat_'));
31
- const pinned: DeferredToolCatalogItem[] = [];
32
- const preferOrder = [
33
- 'napcat_send_poke',
34
- 'napcat_set_emoji_reaction',
35
- 'napcat_send_like',
36
- 'napcat_set_essence_msg',
37
- 'napcat_send_group_notice',
38
- 'napcat_ai_tts',
39
- ];
40
- for (const name of preferOrder) {
41
- const t = napcatTools.find(x => x.name === name);
42
- if (t) pinned.push(t);
43
- }
44
- for (const t of napcatTools) {
45
- if (pinned.length >= maxTools) break;
46
- if (!pinned.some(p => p.name === t.name)) pinned.push(t);
47
- }
48
-
49
- const extra = filterTools(query, pool as AgentTool[], { maxTools, minScore: 0.08 })
50
- .map((t) => ({ name: t.name, description: t.description }))
51
- .filter(t => !pinned.some(p => p.name === t.name));
52
-
53
- const merged: DeferredToolCatalogItem[] = [...pinned];
54
- for (const t of extra) {
55
- if (merged.length >= maxTools) break;
56
- merged.push(t);
57
- }
58
- return merged.slice(0, maxTools);
59
- }
60
-
61
- const ORCHESTRATOR_NAPCAT = [
62
- 'On napcat/QQ: use run_deferred_task with tool_query "napcat_send_poke" or "napcat_set_emoji_reaction".',
63
- 'NapCat supports: poke, emoji reaction, forward msg, essence, group notice, AI TTS, OCR, group files.',
64
- 'Skip tool_search when the user clearly asks for QQ-specific features like poke, reaction, or group management.',
65
- ].join('\n');
66
-
67
- const WORKER_NAPCAT = [
68
- '- Use `napcat_send_poke` for poke/戳一戳.',
69
- '- Use `napcat_set_emoji_reaction` for emoji reaction/表情回应.',
70
- '- Use `napcat_send_like` for friend like/点赞.',
71
- '- Use `napcat_ai_tts` for AI voice/AI语音.',
72
- '- Use `napcat_set_essence_msg` / `napcat_delete_essence_msg` for essence messages.',
73
- '- Use `napcat_send_group_notice` for group announcements.',
74
- '- Do NOT use mcp_filesystem_* or explore node_modules for QQ tasks.',
75
- ].join('\n');
76
-
77
- export function createNapCatAgentPromptContributor(): AgentPromptContributor {
78
- return {
79
- platform: 'napcat',
80
-
81
- async buildSections(ctx: AgentPromptBuildContext): Promise<AgentPromptSection[] | null> {
82
- if (ctx.slot === 'orchestrator') {
83
- return [{
84
- id: 'platform.napcat.orchestrator',
85
- title: '## napcat / QQ',
86
- body: ORCHESTRATOR_NAPCAT,
87
- priority: 50,
88
- }];
89
- }
90
- if (ctx.slot === 'deferred_worker') {
91
- const query = ctx.deferred?.toolQuery ?? ctx.deferred?.goal ?? '';
92
- const goal = ctx.deferred?.goal ?? '';
93
- if (!isNapCatDelegatedTask(query, goal)) return null;
94
- return [{
95
- id: 'platform.napcat.deferred_worker',
96
- title: '## napcat / QQ(本任务)',
97
- body: WORKER_NAPCAT,
98
- priority: 50,
99
- }];
100
- }
101
- return null;
102
- },
103
-
104
- matchesDeferredTask(ctx: AgentPromptBuildContext): boolean {
105
- const query = ctx.deferred?.toolQuery ?? ctx.deferred?.goal ?? ctx.userMessagePreview ?? '';
106
- const goal = ctx.deferred?.goal ?? ctx.userMessagePreview ?? '';
107
- return isNapCatDelegatedTask(query, goal);
108
- },
109
-
110
- selectDeferredTools(query, goal, catalog, maxTools) {
111
- if (!isNapCatDelegatedTask(query, goal)) return null;
112
- return selectNapCatDeferredTools(query, goal, catalog, maxTools);
113
- },
114
- };
115
- }
@@ -1,362 +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
- expandInteractiveSegmentsInContent,
13
- mapNoticeParts,
14
- mapRequestParts,
15
- buildNotice,
16
- buildRequest,
17
- senderFromId,
18
- type QuotedMessagePayload,} from 'zhin.js';
19
- import { parseOneBotGetMsgResponse } from './onebot-get-msg.js';
20
- import type { NapCatEndpointConfig, NapCatMessageEvent, MessageSegment, ApiResponse } from './types.js';
21
- import type { NapCatAdapter } from './adapter.js';
22
- import { InboundMessageDeduper, isSelfMessage, normalizeMessage, resolveSideEventDedupeKey } from './napcat-inbound.js';
23
- import { fromCanonicalSegments, toCanonicalSegments } from './segment-mapper.js';
24
-
25
- export abstract class NapCatEndpointBase extends EventEmitter implements Endpoint<NapCatEndpointConfig, NapCatMessageEvent> {
26
- $connected = false;
27
- protected readonly inboundDeduper = new InboundMessageDeduper();
28
-
29
- get logger() { return this.adapter.plugin.logger; }
30
- get $id() { return this.$config.name; }
31
-
32
- constructor(public adapter: NapCatAdapter, public $config: NapCatEndpointConfig) {
33
- super();
34
- }
35
-
36
- abstract $connect(): Promise<void>;
37
- abstract $disconnect(): Promise<void>;
38
- abstract callApi<T = any>(action: string, params?: Record<string, any>): Promise<T>;
39
-
40
- // ══════════════════════════════════════════════════════════════════
41
- // 消息格式化
42
- // ══════════════════════════════════════════════════════════════════
43
-
44
- private toWireSendContent(content: SendContent): MessageSegment[] {
45
- const items = (Array.isArray(content) ? content : [content]).map((item) =>
46
- typeof item === 'string' ? { type: 'text', data: { text: item } } : item as MessageSegment,
47
- );
48
- return fromCanonicalSegments(toCanonicalSegments(items)) as MessageSegment[];
49
- }
50
-
51
- $formatMessage(ev: NapCatMessageEvent): Message<NapCatMessageEvent> {
52
- const wire = normalizeMessage(ev.message);
53
- const quoteId = Message.quoteIdFromContent(wire);
54
- Message.alignReplySegments(wire, quoteId);
55
- const content = toCanonicalSegments(wire);
56
-
57
- const message = Message.from(ev, {
58
- $id: ev.message_id.toString(),
59
- $adapter: 'napcat',
60
- $endpoint: this.$config.name,
61
- $sender: {
62
- id: ev.user_id.toString(),
63
- name: ev.sender?.nickname || ev.user_id.toString(),
64
- role: ev.sender?.role,
65
- },
66
- $channel: {
67
- id: (ev.group_id || ev.user_id).toString(),
68
- type: ev.group_id ? 'group' : 'private',
69
- },
70
- $content: content,
71
- $quote_id: quoteId,
72
- $raw: ev.raw_message,
73
- $timestamp: ev.time,
74
- $recall: async () => { await this.deleteMsg(ev.message_id); },
75
- $reply: async (content: SendContent, quote?: boolean | string): Promise<string> => {
76
- if (!Array.isArray(content)) content = [content];
77
- if (quote) content.unshift({ type: 'reply', data: { message_id: ev.message_id.toString() } });
78
- return await this.adapter.sendMessage({
79
- id: (ev.group_id || ev.user_id).toString(),
80
- type: ev.group_id ? 'group' : 'private',
81
- context: 'napcat',
82
- endpoint: this.$config.name,
83
- content,
84
- });
85
- },
86
- });
87
- return message;
88
- }
89
-
90
- async $sendMessage(options: SendOptions): Promise<string> {
91
- const content = this.toWireSendContent(expandInteractiveSegmentsInContent(options.content));
92
- const msg: any = { message: content };
93
- if (options.type === 'group') {
94
- const result = await this.callApi<{ message_id: number }>('send_group_msg', { group_id: parseInt(options.id), ...msg });
95
- this.logger.debug(`${this.$id} send group(${options.id}):${segment.raw(options.content)}`);
96
- return result.message_id.toString();
97
- }
98
- if (options.type === 'private') {
99
- const result = await this.callApi<{ message_id: number }>('send_private_msg', { user_id: parseInt(options.id), ...msg });
100
- this.logger.debug(`${this.$id} send private(${options.id}):${segment.raw(options.content)}`);
101
- return result.message_id.toString();
102
- }
103
- throw new Error('Either group_id or user_id must be provided');
104
- }
105
-
106
- async $recallMessage(id: string): Promise<void> {
107
- await this.deleteMsg(parseInt(id));
108
- }
109
-
110
- async $addReaction(messageId: string, emojiId: string): Promise<string> {
111
- await this.setMsgEmojiLike(parseInt(messageId), emojiId);
112
- return `reaction:${messageId}:${emojiId}`;
113
- }
114
-
115
- async $removeReaction(messageId: string, _reactionId: string): Promise<void> {
116
- // NapCat 的 set_msg_emoji_like 是 toggle 行为,再调一次即取消
117
- const parts = _reactionId.split(':');
118
- const emojiId = parts[2] || parts[0];
119
- await this.setMsgEmojiLike(parseInt(messageId), emojiId);
120
- }
121
-
122
- // ══════════════════════════════════════════════════════════════════
123
- // 事件分发
124
- // ══════════════════════════════════════════════════════════════════
125
-
126
- protected dispatchEvent(event: any): void {
127
- switch (event.post_type) {
128
- case 'message':
129
- case 'message_sent':
130
- return this.handleMessage(event);
131
- case 'notice':
132
- return this.handleNotice(event);
133
- case 'request':
134
- return this.handleRequest(event);
135
- case 'meta_event':
136
- return this.handleMeta(event);
137
- }
138
- }
139
-
140
- private handleMessage(ev: NapCatMessageEvent): void {
141
- if (isSelfMessage(ev)) return;
142
- const msgId = ev.message_id.toString();
143
- if (!this.inboundDeduper.shouldProcess(msgId)) return;
144
- ev.message = normalizeMessage(ev.message);
145
- const message = this.$formatMessage(ev);
146
- this.adapter.emit('message.receive', message);
147
- this.logger.debug(`${this.$id} recv ${message.$channel.type}(${message.$channel.id}):${segment.raw(message.$content)}`);
148
- }
149
-
150
- private handleNotice(event: any): void {
151
- const dedupeKey = resolveSideEventDedupeKey(event, 'notice');
152
- if (!this.inboundDeduper.shouldProcess(dedupeKey)) return;
153
- const isGroup = !!event.group_id;
154
- const { scene_type, sub_type } = mapNoticeParts('napcat', event.notice_type ?? '', {
155
- sub_type: event.sub_type,
156
- is_group: isGroup,
157
- });
158
- const sceneId = String((event.group_id || event.user_id) ?? '');
159
- const notice = buildNotice(event, {
160
- $id: `${event.time}_${event.notice_type}_${event.group_id || event.user_id}`,
161
- $adapter: 'napcat',
162
- $endpoint: this.$config.name,
163
- $type: 'notice',
164
- $scene_id: sceneId,
165
- $scene_type: scene_type,
166
- $sub_type: sub_type,
167
- $actor: senderFromId(event.operator_id),
168
- $target: senderFromId(event.user_id),
169
- $timestamp: (event.time || Math.floor(Date.now() / 1000)) * 1000,
170
- });
171
- this.adapter.emit('notice.receive', notice);
172
- }
173
-
174
- private handleRequest(event: any): void {
175
- const dedupeKey = resolveSideEventDedupeKey(event, 'request');
176
- if (!this.inboundDeduper.shouldProcess(dedupeKey)) return;
177
- const { scene_type, sub_type } = mapRequestParts('napcat', event.request_type ?? '', event.sub_type);
178
- const sceneId = String((event.group_id || event.user_id) ?? '');
179
- const request = buildRequest(event, {
180
- $id: event.flag || `${event.time}_${event.request_type}_${event.user_id}`,
181
- $adapter: 'napcat',
182
- $endpoint: this.$config.name,
183
- $type: 'request',
184
- $scene_id: sceneId,
185
- $scene_type: scene_type,
186
- $sub_type: sub_type,
187
- $actor: senderFromId(event.user_id) ?? { id: '', name: '' },
188
- $comment: event.comment,
189
- $timestamp: (event.time || Math.floor(Date.now() / 1000)) * 1000,
190
- $approve: async (remark?: string) => {
191
- await this.callApi(
192
- event.request_type === 'friend' ? 'set_friend_add_request' : 'set_group_add_request',
193
- { flag: event.flag, approve: true, remark },
194
- );
195
- },
196
- $reject: async (reason?: string) => {
197
- await this.callApi(
198
- event.request_type === 'friend' ? 'set_friend_add_request' : 'set_group_add_request',
199
- { flag: event.flag, approve: false, reason },
200
- );
201
- },
202
- });
203
- this.adapter.emit('request.receive', request);
204
- }
205
-
206
- protected handleMeta(event: any): void {
207
- // subclass may override for lifecycle handling
208
- }
209
-
210
- // ══════════════════════════════════════════════════════════════════
211
- // OneBot11 标准 API
212
- // ══════════════════════════════════════════════════════════════════
213
-
214
- async sendMsg(messageType: 'private' | 'group', id: number, message: MessageSegment[]) {
215
- return this.callApi<{ message_id: number }>('send_msg', { message_type: messageType, [messageType === 'group' ? 'group_id' : 'user_id']: id, message });
216
- }
217
- async deleteMsg(messageId: number) { return this.callApi('delete_msg', { message_id: messageId }); }
218
- async getMsg(messageId: number) { return this.callApi('get_msg', { message_id: messageId }); }
219
-
220
- async $getMsg(messageId: string): Promise<QuotedMessagePayload> {
221
- const idParam = /^\d+$/.test(messageId) ? Number(messageId) : messageId;
222
- const data = await this.callApi('get_msg', { message_id: idParam });
223
- return parseOneBotGetMsgResponse(messageId, data);
224
- }
225
- async getForwardMsg(id: string) { return this.callApi('get_forward_msg', { id }); }
226
- async sendLike(userId: number, times = 1) { return this.callApi('send_like', { user_id: userId, times }); }
227
-
228
- // 群管理
229
- async setGroupKick(groupId: number, userId: number, rejectAddRequest = false) { return this.callApi('set_group_kick', { group_id: groupId, user_id: userId, reject_add_request: rejectAddRequest }); }
230
- async setGroupBan(groupId: number, userId: number, duration = 600) { return this.callApi('set_group_ban', { group_id: groupId, user_id: userId, duration }); }
231
- async setGroupWholeBan(groupId: number, enable = true) { return this.callApi('set_group_whole_ban', { group_id: groupId, enable }); }
232
- async setGroupAdmin(groupId: number, userId: number, enable = true) { return this.callApi('set_group_admin', { group_id: groupId, user_id: userId, enable }); }
233
- async setGroupCard(groupId: number, userId: number, card: string) { return this.callApi('set_group_card', { group_id: groupId, user_id: userId, card }); }
234
- async setGroupName(groupId: number, groupName: string) { return this.callApi('set_group_name', { group_id: groupId, group_name: groupName }); }
235
- async setGroupLeave(groupId: number, isDismiss = false) { return this.callApi('set_group_leave', { group_id: groupId, is_dismiss: isDismiss }); }
236
- 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 }); }
237
-
238
- // 好友/群请求
239
- async setFriendAddRequest(flag: string, approve = true, remark?: string) { return this.callApi('set_friend_add_request', { flag, approve, remark }); }
240
- async setGroupAddRequest(flag: string, subType: string, approve = true, reason?: string) { return this.callApi('set_group_add_request', { flag, sub_type: subType, approve, reason }); }
241
-
242
- // 信息查询
243
- async getLoginInfo() { return this.callApi('get_login_info'); }
244
- async getStrangerInfo(userId: number, noCache = false) { return this.callApi('get_stranger_info', { user_id: userId, no_cache: noCache }); }
245
- async getFriendList() { return this.callApi('get_friend_list'); }
246
- async getGroupInfo(groupId: number, noCache = false) { return this.callApi('get_group_info', { group_id: groupId, no_cache: noCache }); }
247
- async getGroupList() { return this.callApi('get_group_list'); }
248
- async getGroupMemberInfo(groupId: number, userId: number, noCache = false) { return this.callApi('get_group_member_info', { group_id: groupId, user_id: userId, no_cache: noCache }); }
249
- async getGroupMemberList(groupId: number) { return this.callApi('get_group_member_list', { group_id: groupId }); }
250
- async getGroupHonorInfo(groupId: number, type: string) { return this.callApi('get_group_honor_info', { group_id: groupId, type }); }
251
-
252
- // 凭证
253
- async getCookies(domain?: string) { return this.callApi('get_cookies', { domain }); }
254
- async getCsrfToken() { return this.callApi('get_csrf_token'); }
255
- async getCredentials(domain?: string) { return this.callApi('get_credentials', { domain }); }
256
-
257
- // 媒体
258
- async getRecord(file: string, outFormat: string) { return this.callApi('get_record', { file, out_format: outFormat }); }
259
- async getImage(file: string) { return this.callApi('get_image', { file }); }
260
- async canSendImage() { return this.callApi('can_send_image'); }
261
- async canSendRecord() { return this.callApi('can_send_record'); }
262
-
263
- // 系统
264
- async getStatus() { return this.callApi('get_status'); }
265
- async getVersionInfo() { return this.callApi('get_version_info'); }
266
- async cleanCache() { return this.callApi('clean_cache'); }
267
-
268
- // ══════════════════════════════════════════════════════════════════
269
- // go-cqhttp 扩展 API
270
- // ══════════════════════════════════════════════════════════════════
271
-
272
- async setQQProfile(nickname: string, company?: string, email?: string, college?: string, personalNote?: string) {
273
- return this.callApi('set_qq_profile', { nickname, company, email, college, personal_note: personalNote });
274
- }
275
- async getOnlineClients(noCache = false) { return this.callApi('get_online_clients', { no_cache: noCache }); }
276
- async deleteFriend(userId: number) { return this.callApi('delete_friend', { user_id: userId }); }
277
- async markMsgAsRead(messageId: number) { return this.callApi('mark_msg_as_read', { message_id: messageId }); }
278
- async sendGroupForwardMsg(groupId: number, messages: any[]) { return this.callApi('send_group_forward_msg', { group_id: groupId, messages }); }
279
- async sendPrivateForwardMsg(userId: number, messages: any[]) { return this.callApi('send_private_forward_msg', { user_id: userId, messages }); }
280
- async getGroupMsgHistory(groupId: number, messageSeq?: number, count?: number) { return this.callApi('get_group_msg_history', { group_id: groupId, message_seq: messageSeq, count }); }
281
- async ocrImage(image: string) { return this.callApi('ocr_image', { image }); }
282
- async getGroupSystemMsg() { return this.callApi('get_group_system_msg'); }
283
- async getEssenceMsgList(groupId: number) { return this.callApi('get_essence_msg_list', { group_id: groupId }); }
284
- async getGroupAtAllRemain(groupId: number) { return this.callApi('get_group_at_all_remain', { group_id: groupId }); }
285
- async setGroupPortrait(groupId: number, file: string) { return this.callApi('set_group_portrait', { group_id: groupId, file }); }
286
- async setEssenceMsg(messageId: number) { return this.callApi('set_essence_msg', { message_id: messageId }); }
287
- async deleteEssenceMsg(messageId: number) { return this.callApi('delete_essence_msg', { message_id: messageId }); }
288
- async sendGroupSign(groupId: number) { return this.callApi('send_group_sign', { group_id: groupId }); }
289
- async sendGroupNotice(groupId: number, content: string, image?: string) { return this.callApi('_send_group_notice', { group_id: groupId, content, image }); }
290
- async getGroupNotice(groupId: number) { return this.callApi('_get_group_notice', { group_id: groupId }); }
291
- async deleteGroupNotice(groupId: number, noticeId: string) { return this.callApi('_del_group_notice', { group_id: groupId, notice_id: noticeId }); }
292
- async uploadGroupFile(groupId: number, file: string, name: string, folder?: string) { return this.callApi('upload_group_file', { group_id: groupId, file, name, folder }); }
293
- async deleteGroupFile(groupId: number, fileId: string, busid: number) { return this.callApi('delete_group_file', { group_id: groupId, file_id: fileId, busid }); }
294
- async createGroupFileFolder(groupId: number, name: string, parentId = '/') { return this.callApi('create_group_file_folder', { group_id: groupId, name, parent_id: parentId }); }
295
- async deleteGroupFolder(groupId: number, folderId: string) { return this.callApi('delete_group_folder', { group_id: groupId, folder_id: folderId }); }
296
- async getGroupFileSystemInfo(groupId: number) { return this.callApi('get_group_file_system_info', { group_id: groupId }); }
297
- async getGroupRootFiles(groupId: number) { return this.callApi('get_group_root_files', { group_id: groupId }); }
298
- async getGroupFilesByFolder(groupId: number, folderId: string) { return this.callApi('get_group_files_by_folder', { group_id: groupId, folder_id: folderId }); }
299
- async getGroupFileUrl(groupId: number, fileId: string, busid: number) { return this.callApi('get_group_file_url', { group_id: groupId, file_id: fileId, busid }); }
300
- async uploadPrivateFile(userId: number, file: string, name: string) { return this.callApi('upload_private_file', { user_id: userId, file, name }); }
301
- async downloadFile(url: string, threadCount = 1, headers?: string[]) { return this.callApi('download_file', { url, thread_count: threadCount, headers }); }
302
- async checkUrlSafely(url: string) { return this.callApi('check_url_safely', { url }); }
303
-
304
- // ══════════════════════════════════════════════════════════════════
305
- // NapCat 独有 API
306
- // ══════════════════════════════════════════════════════════════════
307
-
308
- async setGroupSign(groupId: number) { return this.callApi('set_group_sign', { group_id: groupId }); }
309
- async arkSharePeer(userId: number) { return this.callApi('ArkSharePeer', { user_id: userId }); }
310
- async arkShareGroup(groupId: number) { return this.callApi('ArkShareGroup', { group_id: groupId }); }
311
- async getRobotUinRange() { return this.callApi('get_robot_uin_range'); }
312
- async setOnlineStatus(status: number, extStatus: number) { return this.callApi('set_online_status', { status, ext_status: extStatus }); }
313
- async getFriendsWithCategory() { return this.callApi('get_friends_with_category'); }
314
- async setQQAvatar(file: string) { return this.callApi('set_qq_avatar', { file }); }
315
- async getFile(fileId: string) { return this.callApi('get_file', { file_id: fileId }); }
316
- async forwardFriendSingleMsg(userId: number, messageId: number) { return this.callApi('forward_friend_single_msg', { user_id: userId, message_id: messageId }); }
317
- async forwardGroupSingleMsg(groupId: number, messageId: number) { return this.callApi('forward_group_single_msg', { group_id: groupId, message_id: messageId }); }
318
- async translateEn2Zh(sourceText: string) { return this.callApi('translate_en2zh', { source_text: sourceText }); }
319
- async setMsgEmojiLike(messageId: number, emojiId: string) { return this.callApi('set_msg_emoji_like', { message_id: messageId, emoji_id: emojiId }); }
320
- async sendForwardMsg(messageType: 'private' | 'group', id: number, messages: any[]) {
321
- return this.callApi('send_forward_msg', { message_type: messageType, [messageType === 'group' ? 'group_id' : 'user_id']: id, messages });
322
- }
323
- async markPrivateMsgAsRead(userId: number) { return this.callApi('mark_private_msg_as_read', { user_id: userId }); }
324
- async markGroupMsgAsRead(groupId: number) { return this.callApi('mark_group_msg_as_read', { group_id: groupId }); }
325
- async getFriendMsgHistory(userId: number, messageSeq?: number, count?: number) { return this.callApi('get_friend_msg_history', { user_id: userId, message_seq: messageSeq, count }); }
326
- async createCollection(briefContent: string, rawData: string) { return this.callApi('create_collection', { brief: briefContent, rawData }); }
327
- async getCollectionList(page = 0, limit = 20) { return this.callApi('get_collection_list', { page, limit }); }
328
- async setSelfLongnick(longnick: string) { return this.callApi('set_self_longnick', { longNick: longnick }); }
329
- async getRecentContact(count = 10) { return this.callApi('get_recent_contact', { count }); }
330
- async markAllAsRead() { return this.callApi('_mark_all_as_read'); }
331
- async getProfileLike() { return this.callApi('get_profile_like'); }
332
- async fetchCustomFace() { return this.callApi('fetch_custom_face'); }
333
- async fetchEmojiLike(messageId: number, emojiId: string, emojiType: string) { return this.callApi('fetch_emoji_like', { message_id: messageId, emoji_id: emojiId, emoji_type: emojiType }); }
334
- async setInputStatus(userId: number, eventType: string) { return this.callApi('set_input_status', { user_id: userId, event_type: eventType }); }
335
- async getGroupInfoEx(groupId: number) { return this.callApi('get_group_info_ex', { group_id: groupId }); }
336
- async getGroupIgnoreAddRequest(groupId: number) { return this.callApi('get_group_ignore_add_request', { group_id: groupId }); }
337
- async friendPoke(userId: number) { return this.callApi('friend_poke', { user_id: userId }); }
338
- async groupPoke(groupId: number, userId: number) { return this.callApi('group_poke', { group_id: groupId, user_id: userId }); }
339
- async sendPoke(userId: number, groupId?: number) { return this.callApi('send_poke', { user_id: userId, group_id: groupId }); }
340
- async ncGetPacketStatus() { return this.callApi('nc_get_packet_status'); }
341
- async ncGetUserStatus(userId: number) { return this.callApi('nc_get_user_status', { user_id: userId }); }
342
- async ncGetRkey() { return this.callApi('nc_get_rkey'); }
343
- async getGroupShutList(groupId: number) { return this.callApi('get_group_shut_list', { group_id: groupId }); }
344
- async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string) {
345
- return this.callApi('get_mini_app_ark', { type, title, desc, picUrl, jumpUrl });
346
- }
347
- async getAiRecord(groupId: number, characterId: string, text: string) { return this.callApi('get_ai_record', { group_id: groupId, character: characterId, text }); }
348
- async getAiCharacters(groupId: number) { return this.callApi('get_ai_characters', { group_id: groupId }); }
349
- async sendGroupAiRecord(groupId: number, characterId: string, text: string) { return this.callApi('send_group_ai_record', { group_id: groupId, character: characterId, text }); }
350
-
351
- // ══════════════════════════════════════════════════════════════════
352
- // Adapter 群管理接口适配
353
- // ══════════════════════════════════════════════════════════════════
354
-
355
- async kickMember(groupId: number, userId: number, reject = false) { await this.setGroupKick(groupId, userId, reject); return true; }
356
- async muteMember(groupId: number, userId: number, duration = 600) { await this.setGroupBan(groupId, userId, duration); return true; }
357
- async muteAll(groupId: number, enable = true) { await this.setGroupWholeBan(groupId, enable); return true; }
358
- async setAdmin(groupId: number, userId: number, enable = true) { await this.setGroupAdmin(groupId, userId, enable); return true; }
359
- async setCard(groupId: number, userId: number, card: string) { await this.setGroupCard(groupId, userId, card); return true; }
360
- async setTitle(groupId: number, userId: number, title: string, duration = -1) { await this.setGroupSpecialTitle(groupId, userId, title, duration); return true; }
361
- async getMemberList(groupId: number) { return this.getGroupMemberList(groupId); }
362
- }