@zhin.js/adapter-onebot12 3.0.2 → 4.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.
- package/CHANGELOG.md +460 -0
- package/README.md +40 -74
- package/adapters/onebot12.ts +50 -0
- package/lib/index.d.ts +6 -19
- package/lib/index.js +5 -27
- package/lib/protocol.d.ts +151 -0
- package/lib/protocol.js +242 -0
- package/lib/webhook.d.ts +25 -0
- package/lib/webhook.js +140 -0
- package/lib/ws-endpoint.d.ts +25 -0
- package/lib/ws-endpoint.js +240 -0
- package/lib/ws-types.d.ts +16 -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 +24 -0
- package/lib/wss-endpoint.js +193 -0
- package/package.json +41 -15
- package/plugin.ts +8 -0
- package/schema.json +66 -0
- package/src/index.ts +46 -37
- package/src/protocol.ts +387 -0
- package/src/webhook.ts +180 -0
- package/src/ws-endpoint.ts +287 -0
- package/src/ws-types.ts +19 -0
- package/src/wss-auth.ts +17 -0
- package/src/wss-endpoint.ts +226 -0
- package/lib/adapter.d.ts +0 -20
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -43
- package/lib/adapter.js.map +0 -1
- package/lib/api.d.ts +0 -14
- package/lib/api.d.ts.map +0 -1
- package/lib/api.js +0 -34
- package/lib/api.js.map +0 -1
- package/lib/endpoint-webhook.d.ts +0 -25
- package/lib/endpoint-webhook.d.ts.map +0 -1
- package/lib/endpoint-webhook.js +0 -122
- package/lib/endpoint-webhook.js.map +0 -1
- package/lib/endpoint-ws.d.ts +0 -26
- package/lib/endpoint-ws.d.ts.map +0 -1
- package/lib/endpoint-ws.js +0 -214
- package/lib/endpoint-ws.js.map +0 -1
- package/lib/endpoint-wss.d.ts +0 -26
- package/lib/endpoint-wss.d.ts.map +0 -1
- package/lib/endpoint-wss.js +0 -191
- package/lib/endpoint-wss.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/segment-mapper.d.ts +0 -2
- package/lib/segment-mapper.d.ts.map +0 -1
- package/lib/segment-mapper.js +0 -2
- package/lib/segment-mapper.js.map +0 -1
- package/lib/types.d.ts +0 -77
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js +0 -5
- package/lib/types.js.map +0 -1
- package/lib/utils.d.ts +0 -45
- package/lib/utils.d.ts.map +0 -1
- package/lib/utils.js +0 -62
- package/lib/utils.js.map +0 -1
- package/src/adapter.ts +0 -56
- package/src/api.ts +0 -48
- package/src/endpoint-webhook.ts +0 -136
- package/src/endpoint-ws.ts +0 -228
- package/src/endpoint-wss.ts +0 -208
- package/src/segment-mapper.ts +0 -1
- package/src/types.ts +0 -86
- package/src/utils.ts +0 -89
package/src/endpoint-ws.ts
DELETED
|
@@ -1,228 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OneBot 12 正向 WebSocket Bot:应用连 OneBot 实现的 WS,收事件、发动作
|
|
3
|
-
*/
|
|
4
|
-
import WebSocket from 'ws';
|
|
5
|
-
import { EventEmitter } from 'events';
|
|
6
|
-
import { clearInterval, clearTimeout } from 'node:timers';
|
|
7
|
-
import { formatCompact, Endpoint, Message, segment, SendOptions, expandInteractiveSegmentsInContent,} from 'zhin.js';
|
|
8
|
-
import type { OneBot12WsConfig, OneBot12Event, OneBot12ActionRequest, OneBot12ActionResponse } from './types.js';
|
|
9
|
-
import type { OneBot12Adapter } from './adapter.js';
|
|
10
|
-
import { formatOneBot12MessagePayload, isMessageEvent, contentToOb12Segments } from './utils.js';
|
|
11
|
-
import { fromCanonicalSegments } from './segment-mapper.js';
|
|
12
|
-
|
|
13
|
-
export class OneBot12WsClient extends EventEmitter implements Endpoint<OneBot12WsConfig, OneBot12Event> {
|
|
14
|
-
$connected: boolean;
|
|
15
|
-
private ws?: WebSocket;
|
|
16
|
-
private reconnectTimer?: NodeJS.Timeout;
|
|
17
|
-
private heartbeatTimer?: NodeJS.Timeout;
|
|
18
|
-
private requestId = 0;
|
|
19
|
-
private pendingRequests = new Map<string, { resolve: (value: unknown) => void; reject: (err: Error) => void; timeout: NodeJS.Timeout }>();
|
|
20
|
-
|
|
21
|
-
get logger() {
|
|
22
|
-
return this.adapter.plugin.logger;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
constructor(public adapter: OneBot12Adapter, public $config: OneBot12WsConfig) {
|
|
26
|
-
super();
|
|
27
|
-
this.$connected = false;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
get $id() {
|
|
31
|
-
return this.$config.name;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
private startHeartbeat(): void {
|
|
35
|
-
const interval = this.$config.heartbeat_interval ?? 30000;
|
|
36
|
-
this.heartbeatTimer = setInterval(() => {
|
|
37
|
-
this.callAction('get_status', {}).catch(() => {});
|
|
38
|
-
}, interval);
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
private scheduleReconnect(): void {
|
|
42
|
-
if (this.reconnectTimer) return;
|
|
43
|
-
const delay = this.$config.reconnect_interval ?? 5000;
|
|
44
|
-
this.reconnectTimer = setTimeout(() => {
|
|
45
|
-
this.reconnectTimer = undefined;
|
|
46
|
-
this.$connect().catch((err) => this.logger.warn(formatCompact( {
|
|
47
|
-
op: 'reconnect',
|
|
48
|
-
endpoint: this.$id,
|
|
49
|
-
ok: false,
|
|
50
|
-
error: err instanceof Error ? err.message : String(err),
|
|
51
|
-
})));
|
|
52
|
-
}, delay);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
private callAction(action: string, params: Record<string, unknown>): Promise<OneBot12ActionResponse['data']> {
|
|
56
|
-
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
57
|
-
return Promise.reject(new Error('WebSocket 未连接'));
|
|
58
|
-
}
|
|
59
|
-
const echo = `ob12_${++this.requestId}`;
|
|
60
|
-
const req: OneBot12ActionRequest = { action, params, echo };
|
|
61
|
-
return new Promise((resolve, reject) => {
|
|
62
|
-
const timeout = setTimeout(() => {
|
|
63
|
-
this.pendingRequests.delete(echo);
|
|
64
|
-
reject(new Error(`OneBot12 动作超时: ${action}`));
|
|
65
|
-
}, 30000);
|
|
66
|
-
this.pendingRequests.set(echo, {
|
|
67
|
-
resolve: (data: unknown) => resolve(data as OneBot12ActionResponse['data']),
|
|
68
|
-
reject,
|
|
69
|
-
timeout,
|
|
70
|
-
});
|
|
71
|
-
this.ws!.send(JSON.stringify(req));
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
async $connect(): Promise<void> {
|
|
76
|
-
return new Promise((resolve, reject) => {
|
|
77
|
-
const headers: Record<string, string> = {};
|
|
78
|
-
let connectUrl = this.$config.url;
|
|
79
|
-
if (this.$config.access_token) {
|
|
80
|
-
headers['Authorization'] = `Bearer ${this.$config.access_token}`;
|
|
81
|
-
const url = new URL(this.$config.url);
|
|
82
|
-
url.searchParams.set('access_token', this.$config.access_token);
|
|
83
|
-
connectUrl = url.toString();
|
|
84
|
-
}
|
|
85
|
-
this.ws = new WebSocket(connectUrl, { headers });
|
|
86
|
-
|
|
87
|
-
this.ws.on('open', () => {
|
|
88
|
-
this.$connected = true;
|
|
89
|
-
const safeUrl = new URL(connectUrl);
|
|
90
|
-
safeUrl.searchParams.delete('access_token');
|
|
91
|
-
this.logger.debug(formatCompact({ endpoint: this.$id, mode: 'ws' }));
|
|
92
|
-
this.startHeartbeat();
|
|
93
|
-
resolve();
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
this.ws.on('message', (data) => {
|
|
97
|
-
try {
|
|
98
|
-
const msg = JSON.parse(data.toString()) as OneBot12Event | OneBot12ActionResponse;
|
|
99
|
-
if ('echo' in msg && typeof (msg as OneBot12ActionResponse).echo === 'string') {
|
|
100
|
-
const resp = msg as OneBot12ActionResponse;
|
|
101
|
-
const pending = this.pendingRequests.get(resp.echo!);
|
|
102
|
-
if (pending) {
|
|
103
|
-
this.pendingRequests.delete(resp.echo!);
|
|
104
|
-
clearTimeout(pending.timeout);
|
|
105
|
-
if (resp.status === 'ok') pending.resolve(resp.data);
|
|
106
|
-
else pending.reject(new Error(`OneBot12 retcode=${resp.retcode}: ${resp.message}`));
|
|
107
|
-
}
|
|
108
|
-
return;
|
|
109
|
-
}
|
|
110
|
-
const ev = msg as OneBot12Event;
|
|
111
|
-
if (ev.type === 'message' && isMessageEvent(ev)) {
|
|
112
|
-
const message = this.$formatMessage(ev);
|
|
113
|
-
this.adapter.emit('message.receive', message);
|
|
114
|
-
this.logger.debug(`${this.$config.name} recv ${message.$channel.type}(${message.$channel.id}):${segment.raw(message.$content)}`);
|
|
115
|
-
}
|
|
116
|
-
} catch (error) {
|
|
117
|
-
this.emit('error', error);
|
|
118
|
-
}
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
this.ws.on('close', (code, reason) => {
|
|
122
|
-
this.$connected = false;
|
|
123
|
-
const reasonStr = reason?.toString?.() || String(reason);
|
|
124
|
-
const codeHint = code === 1005 ? ' [无状态,多为服务端/代理未发 close 帧即断开]' : code === 1006 ? ' [异常关闭]' : '';
|
|
125
|
-
this.logger.warn(formatCompact( {
|
|
126
|
-
op: 'disconnect',
|
|
127
|
-
endpoint: this.$config.name,
|
|
128
|
-
code,
|
|
129
|
-
error: `${reasonStr || 'closed'}${codeHint}`,
|
|
130
|
-
reconnect_ms: this.$config.reconnect_interval ?? 5000,
|
|
131
|
-
}));
|
|
132
|
-
reject(new Error(`OneBot12 WS 关闭: ${code} ${reasonStr}`));
|
|
133
|
-
this.scheduleReconnect();
|
|
134
|
-
});
|
|
135
|
-
|
|
136
|
-
this.ws.on('error', (err) => {
|
|
137
|
-
this.logger.warn(formatCompact( {
|
|
138
|
-
op: 'ws_error',
|
|
139
|
-
endpoint: this.$config.name,
|
|
140
|
-
ok: false,
|
|
141
|
-
error: err instanceof Error ? err.message : String(err),
|
|
142
|
-
}));
|
|
143
|
-
reject(err);
|
|
144
|
-
});
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
async $disconnect(): Promise<void> {
|
|
149
|
-
if (this.reconnectTimer) {
|
|
150
|
-
clearTimeout(this.reconnectTimer);
|
|
151
|
-
this.reconnectTimer = undefined;
|
|
152
|
-
}
|
|
153
|
-
if (this.heartbeatTimer) {
|
|
154
|
-
clearInterval(this.heartbeatTimer);
|
|
155
|
-
this.heartbeatTimer = undefined;
|
|
156
|
-
}
|
|
157
|
-
for (const [, p] of this.pendingRequests) {
|
|
158
|
-
clearTimeout(p.timeout);
|
|
159
|
-
p.reject(new Error('连接已关闭'));
|
|
160
|
-
}
|
|
161
|
-
this.pendingRequests.clear();
|
|
162
|
-
if (this.ws) {
|
|
163
|
-
this.ws.close();
|
|
164
|
-
this.ws = undefined;
|
|
165
|
-
}
|
|
166
|
-
this.$connected = false;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
$formatMessage(ev: OneBot12Event): Message<OneBot12Event> {
|
|
170
|
-
if (!isMessageEvent(ev)) {
|
|
171
|
-
return Message.from(ev, {
|
|
172
|
-
$id: '',
|
|
173
|
-
$adapter: 'onebot12',
|
|
174
|
-
$endpoint: this.$config.name,
|
|
175
|
-
$channel: { id: '', type: 'private' },
|
|
176
|
-
$sender: { id: '', name: '' },
|
|
177
|
-
$content: [],
|
|
178
|
-
$raw: '',
|
|
179
|
-
$timestamp: ev.time ?? 0,
|
|
180
|
-
$recall: async () => {},
|
|
181
|
-
$reply: async () => '',
|
|
182
|
-
});
|
|
183
|
-
}
|
|
184
|
-
const payload = formatOneBot12MessagePayload(
|
|
185
|
-
ev,
|
|
186
|
-
this.$config.name,
|
|
187
|
-
(id) => this.$recallMessage(id),
|
|
188
|
-
(channel, content, _quote) =>
|
|
189
|
-
this.adapter.sendMessage({
|
|
190
|
-
...channel,
|
|
191
|
-
context: 'onebot12',
|
|
192
|
-
endpoint: this.$config.name,
|
|
193
|
-
content: content as import('zhin.js').SendContent,
|
|
194
|
-
}),
|
|
195
|
-
);
|
|
196
|
-
return Message.from(ev, payload);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
async $sendMessage(options: SendOptions): Promise<string> {
|
|
200
|
-
const expanded = expandInteractiveSegmentsInContent(options.content);
|
|
201
|
-
const arr = Array.isArray(expanded) ? expanded : [expanded];
|
|
202
|
-
const wire = fromCanonicalSegments(
|
|
203
|
-
arr.map((c) => (typeof c === 'string' ? { type: 'text' as const, data: { text: c } } : c)),
|
|
204
|
-
);
|
|
205
|
-
const message = contentToOb12Segments(wire);
|
|
206
|
-
const params: Record<string, unknown> = { message };
|
|
207
|
-
if (options.type === 'private') {
|
|
208
|
-
params.detail_type = 'private';
|
|
209
|
-
params.user_id = options.id;
|
|
210
|
-
} else if (options.type === 'group') {
|
|
211
|
-
params.detail_type = 'group';
|
|
212
|
-
params.group_id = options.id;
|
|
213
|
-
} else {
|
|
214
|
-
const [guildId, channelId] = options.id.includes(':') ? options.id.split(':') : [undefined, options.id];
|
|
215
|
-
params.detail_type = 'channel';
|
|
216
|
-
params.channel_id = channelId ?? options.id;
|
|
217
|
-
if (guildId) params.guild_id = guildId;
|
|
218
|
-
}
|
|
219
|
-
const data = await this.callAction('send_message', params) as { message_id?: string } | undefined;
|
|
220
|
-
const msgId = data?.message_id ?? '';
|
|
221
|
-
this.logger.debug(`${this.$config.name} send ${options.type}(${options.id}):${segment.raw(options.content)}`);
|
|
222
|
-
return msgId;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
async $recallMessage(id: string): Promise<void> {
|
|
226
|
-
await this.callAction('delete_message', { message_id: id });
|
|
227
|
-
}
|
|
228
|
-
}
|
package/src/endpoint-wss.ts
DELETED
|
@@ -1,208 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OneBot 12 反向 WebSocket Bot:应用开 WS 服务端,OneBot 实现连上来
|
|
3
|
-
*/
|
|
4
|
-
import WebSocket, { WebSocketServer } from 'ws';
|
|
5
|
-
import { EventEmitter } from 'events';
|
|
6
|
-
import { clearInterval, clearTimeout } from 'node:timers';
|
|
7
|
-
import { IncomingMessage } from 'http';
|
|
8
|
-
import { formatCompact, Endpoint, Message, segment, SendOptions, expandInteractiveSegmentsInContent,} from 'zhin.js';
|
|
9
|
-
import type { Router } from '@zhin.js/host-router';
|
|
10
|
-
import type { OneBot12WssConfig, OneBot12Event, OneBot12ActionRequest, OneBot12ActionResponse } from './types.js';
|
|
11
|
-
import type { OneBot12Adapter } from './adapter.js';
|
|
12
|
-
import { formatOneBot12MessagePayload, isMessageEvent, contentToOb12Segments } from './utils.js';
|
|
13
|
-
import { fromCanonicalSegments } from './segment-mapper.js';
|
|
14
|
-
|
|
15
|
-
export class OneBot12WssServer extends EventEmitter implements Endpoint<OneBot12WssConfig, OneBot12Event> {
|
|
16
|
-
$connected: boolean = false;
|
|
17
|
-
#wss?: WebSocketServer;
|
|
18
|
-
#client?: WebSocket;
|
|
19
|
-
private heartbeatTimer?: NodeJS.Timeout;
|
|
20
|
-
private requestId = 0;
|
|
21
|
-
private pendingRequests = new Map<string, { resolve: (value: unknown) => void; reject: (err: Error) => void; timeout: NodeJS.Timeout }>();
|
|
22
|
-
|
|
23
|
-
get logger() {
|
|
24
|
-
return this.adapter.plugin.logger;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
constructor(
|
|
28
|
-
public adapter: OneBot12Adapter,
|
|
29
|
-
public router: Router,
|
|
30
|
-
public $config: OneBot12WssConfig,
|
|
31
|
-
) {
|
|
32
|
-
super();
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
get $id() {
|
|
36
|
-
return this.$config.name;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
private getClient(): WebSocket | undefined {
|
|
40
|
-
return this.#client && this.#client.readyState === WebSocket.OPEN ? this.#client : undefined;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
private callAction(action: string, params: Record<string, unknown>): Promise<OneBot12ActionResponse['data']> {
|
|
44
|
-
const client = this.getClient();
|
|
45
|
-
if (!client) return Promise.reject(new Error('反向 WebSocket 未连接'));
|
|
46
|
-
const echo = `ob12wss_${++this.requestId}`;
|
|
47
|
-
const req: OneBot12ActionRequest = { action, params, echo };
|
|
48
|
-
return new Promise((resolve, reject) => {
|
|
49
|
-
const timeout = setTimeout(() => {
|
|
50
|
-
this.pendingRequests.delete(echo);
|
|
51
|
-
reject(new Error(`OneBot12 动作超时: ${action}`));
|
|
52
|
-
}, 30000);
|
|
53
|
-
this.pendingRequests.set(echo, {
|
|
54
|
-
resolve: (data: unknown) => resolve(data as OneBot12ActionResponse['data']),
|
|
55
|
-
reject,
|
|
56
|
-
timeout,
|
|
57
|
-
});
|
|
58
|
-
client.send(JSON.stringify(req));
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
async $connect(): Promise<void> {
|
|
63
|
-
const path = this.$config.path.startsWith('/') ? this.$config.path : `/${this.$config.path}`;
|
|
64
|
-
this.#wss = this.router.ws(path, {
|
|
65
|
-
verifyClient: (info: { req: IncomingMessage }) => {
|
|
66
|
-
const auth = info.req.headers['authorization'];
|
|
67
|
-
if (this.$config.access_token && auth !== `Bearer ${this.$config.access_token}`) {
|
|
68
|
-
this.logger.error('OneBot12 反向 WS 鉴权失败');
|
|
69
|
-
return false;
|
|
70
|
-
}
|
|
71
|
-
return true;
|
|
72
|
-
},
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
this.#wss.on('connection', (ws: WebSocket) => {
|
|
76
|
-
if (this.#client && this.#client.readyState === WebSocket.OPEN) {
|
|
77
|
-
this.#client.close();
|
|
78
|
-
}
|
|
79
|
-
this.#client = ws;
|
|
80
|
-
this.$connected = true;
|
|
81
|
-
this.logger.debug(formatCompact({ endpoint: this.$config.name, mode: 'wss' }));
|
|
82
|
-
|
|
83
|
-
ws.on('message', (data) => {
|
|
84
|
-
try {
|
|
85
|
-
const msg = JSON.parse(data.toString()) as OneBot12Event | OneBot12ActionResponse;
|
|
86
|
-
if ('echo' in msg && typeof (msg as OneBot12ActionResponse).echo === 'string') {
|
|
87
|
-
const resp = msg as OneBot12ActionResponse;
|
|
88
|
-
const pending = this.pendingRequests.get(resp.echo!);
|
|
89
|
-
if (pending) {
|
|
90
|
-
this.pendingRequests.delete(resp.echo!);
|
|
91
|
-
clearTimeout(pending.timeout);
|
|
92
|
-
if (resp.status === 'ok') pending.resolve(resp.data);
|
|
93
|
-
else pending.reject(new Error(`OneBot12 retcode=${resp.retcode}: ${resp.message}`));
|
|
94
|
-
}
|
|
95
|
-
return;
|
|
96
|
-
}
|
|
97
|
-
const ev = msg as OneBot12Event;
|
|
98
|
-
if (ev.type === 'message' && isMessageEvent(ev)) {
|
|
99
|
-
const message = this.$formatMessage(ev);
|
|
100
|
-
this.adapter.emit('message.receive', message);
|
|
101
|
-
this.logger.debug(`${this.$config.name} recv ${message.$channel.type}(${message.$channel.id}):${segment.raw(message.$content)}`);
|
|
102
|
-
}
|
|
103
|
-
} catch (error) {
|
|
104
|
-
this.emit('error', error);
|
|
105
|
-
}
|
|
106
|
-
});
|
|
107
|
-
|
|
108
|
-
ws.on('close', (code, reason) => {
|
|
109
|
-
this.$connected = false;
|
|
110
|
-
this.#client = undefined;
|
|
111
|
-
const reasonStr = reason?.toString?.() || String(reason ?? '');
|
|
112
|
-
const codeHint = code === 1005 ? ' [无状态]' : code === 1006 ? ' [异常关闭]' : '';
|
|
113
|
-
this.logger.warn(formatCompact( {
|
|
114
|
-
op: 'disconnect',
|
|
115
|
-
endpoint: this.$config.name,
|
|
116
|
-
code: code ?? '?',
|
|
117
|
-
error: `${reasonStr || 'closed'}${codeHint}`,
|
|
118
|
-
}));
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
ws.on('error', (err) => {
|
|
122
|
-
this.logger.warn(formatCompact( {
|
|
123
|
-
op: 'ws_error',
|
|
124
|
-
endpoint: this.$config.name,
|
|
125
|
-
ok: false,
|
|
126
|
-
error: err instanceof Error ? err.message : String(err),
|
|
127
|
-
}));
|
|
128
|
-
});
|
|
129
|
-
});
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
async $disconnect(): Promise<void> {
|
|
133
|
-
if (this.heartbeatTimer) {
|
|
134
|
-
clearInterval(this.heartbeatTimer);
|
|
135
|
-
this.heartbeatTimer = undefined;
|
|
136
|
-
}
|
|
137
|
-
for (const [, p] of this.pendingRequests) {
|
|
138
|
-
clearTimeout(p.timeout);
|
|
139
|
-
p.reject(new Error('连接已关闭'));
|
|
140
|
-
}
|
|
141
|
-
this.pendingRequests.clear();
|
|
142
|
-
if (this.#client) {
|
|
143
|
-
this.#client.close();
|
|
144
|
-
this.#client = undefined;
|
|
145
|
-
}
|
|
146
|
-
this.#wss?.close();
|
|
147
|
-
this.#wss = undefined;
|
|
148
|
-
this.$connected = false;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
$formatMessage(ev: OneBot12Event): Message<OneBot12Event> {
|
|
152
|
-
if (!isMessageEvent(ev)) {
|
|
153
|
-
return Message.from(ev, {
|
|
154
|
-
$id: '',
|
|
155
|
-
$adapter: 'onebot12',
|
|
156
|
-
$endpoint: this.$config.name,
|
|
157
|
-
$channel: { id: '', type: 'private' },
|
|
158
|
-
$sender: { id: '', name: '' },
|
|
159
|
-
$content: [],
|
|
160
|
-
$raw: '',
|
|
161
|
-
$timestamp: ev.time ?? 0,
|
|
162
|
-
$recall: async () => {},
|
|
163
|
-
$reply: async () => '',
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
const payload = formatOneBot12MessagePayload(
|
|
167
|
-
ev,
|
|
168
|
-
this.$config.name,
|
|
169
|
-
(id) => this.$recallMessage(id),
|
|
170
|
-
(channel, content, _quote) =>
|
|
171
|
-
this.adapter.sendMessage({
|
|
172
|
-
...channel,
|
|
173
|
-
context: 'onebot12',
|
|
174
|
-
endpoint: this.$config.name,
|
|
175
|
-
content: content as import('zhin.js').SendContent,
|
|
176
|
-
}),
|
|
177
|
-
);
|
|
178
|
-
return Message.from(ev, payload);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
async $sendMessage(options: SendOptions): Promise<string> {
|
|
182
|
-
const expanded = expandInteractiveSegmentsInContent(options.content);
|
|
183
|
-
const arr = Array.isArray(expanded) ? expanded : [expanded];
|
|
184
|
-
const wire = fromCanonicalSegments(
|
|
185
|
-
arr.map((c) => (typeof c === 'string' ? { type: 'text' as const, data: { text: c } } : c)),
|
|
186
|
-
);
|
|
187
|
-
const message = contentToOb12Segments(wire);
|
|
188
|
-
const params: Record<string, unknown> = { message };
|
|
189
|
-
if (options.type === 'private') {
|
|
190
|
-
params.detail_type = 'private';
|
|
191
|
-
params.user_id = options.id;
|
|
192
|
-
} else if (options.type === 'group') {
|
|
193
|
-
params.detail_type = 'group';
|
|
194
|
-
params.group_id = options.id;
|
|
195
|
-
} else {
|
|
196
|
-
const [guildId, channelId] = options.id.includes(':') ? options.id.split(':') : [undefined, options.id];
|
|
197
|
-
params.detail_type = 'channel';
|
|
198
|
-
params.channel_id = channelId ?? options.id;
|
|
199
|
-
if (guildId) params.guild_id = guildId;
|
|
200
|
-
}
|
|
201
|
-
const data = await this.callAction('send_message', params) as { message_id?: string } | undefined;
|
|
202
|
-
return data?.message_id ?? '';
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
async $recallMessage(id: string): Promise<void> {
|
|
206
|
-
await this.callAction('delete_message', { message_id: id });
|
|
207
|
-
}
|
|
208
|
-
}
|
package/src/segment-mapper.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { toCanonicalSegments, fromCanonicalSegments } from 'zhin.js';
|
package/src/types.ts
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OneBot 12 适配器类型(参考 https://12.onebot.dev/ )
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
/** 配置公共字段;单一适配器 context 均为 'onebot12',连接方式由 connection 区分 */
|
|
6
|
-
export interface OneBot12ConfigBase {
|
|
7
|
-
context: 'onebot12';
|
|
8
|
-
name: string;
|
|
9
|
-
/** 访问令牌,鉴权用 */
|
|
10
|
-
access_token?: string;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/** 正向 WebSocket:应用连 OneBot 实现的 WS 服务器 */
|
|
14
|
-
export interface OneBot12WsConfig extends OneBot12ConfigBase {
|
|
15
|
-
connection: 'ws';
|
|
16
|
-
/** OneBot 实现提供的 WebSocket 地址,如 ws://127.0.0.1:6700 */
|
|
17
|
-
url: string;
|
|
18
|
-
reconnect_interval?: number;
|
|
19
|
-
heartbeat_interval?: number;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** HTTP Webhook:OneBot 实现 POST 事件到应用提供的 path */
|
|
23
|
-
export interface OneBot12WebhookConfig extends OneBot12ConfigBase {
|
|
24
|
-
connection: 'webhook';
|
|
25
|
-
/** 应用接收事件的 POST 路径 */
|
|
26
|
-
path: string;
|
|
27
|
-
/** 可选:OneBot 实现的 HTTP 端点,用于发消息等动作(实现 POST 事件到我们,我们 POST 动作到该 url) */
|
|
28
|
-
api_url?: string;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/** 反向 WebSocket:应用开 WS 服务端,OneBot 实现连上来 */
|
|
32
|
-
export interface OneBot12WssConfig extends OneBot12ConfigBase {
|
|
33
|
-
connection: 'wss';
|
|
34
|
-
/** 应用侧 WS 路径 */
|
|
35
|
-
path: string;
|
|
36
|
-
heartbeat_interval?: number;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export type OneBot12EndpointConfig = OneBot12WsConfig | OneBot12WebhookConfig | OneBot12WssConfig;
|
|
40
|
-
|
|
41
|
-
/** 机器人自身标识(事件与动作中的 self) */
|
|
42
|
-
export interface OneBot12Self {
|
|
43
|
-
platform: string;
|
|
44
|
-
user_id: string;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** 事件(实现推送给应用) */
|
|
48
|
-
export interface OneBot12Event {
|
|
49
|
-
id: string;
|
|
50
|
-
time: number;
|
|
51
|
-
type: 'meta' | 'message' | 'notice' | 'request';
|
|
52
|
-
detail_type: string;
|
|
53
|
-
sub_type: string;
|
|
54
|
-
self?: OneBot12Self;
|
|
55
|
-
message_id?: string;
|
|
56
|
-
message?: OneBot12Segment[];
|
|
57
|
-
alt_message?: string;
|
|
58
|
-
user_id?: string;
|
|
59
|
-
group_id?: string;
|
|
60
|
-
channel_id?: string;
|
|
61
|
-
guild_id?: string;
|
|
62
|
-
[key: string]: unknown;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/** 消息段 */
|
|
66
|
-
export interface OneBot12Segment {
|
|
67
|
-
type: string;
|
|
68
|
-
data?: Record<string, unknown>;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/** 动作请求(应用发给实现) */
|
|
72
|
-
export interface OneBot12ActionRequest {
|
|
73
|
-
action: string;
|
|
74
|
-
params: Record<string, unknown>;
|
|
75
|
-
echo?: string;
|
|
76
|
-
self?: OneBot12Self;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** 动作响应(实现返回给应用) */
|
|
80
|
-
export interface OneBot12ActionResponse {
|
|
81
|
-
status: 'ok' | 'failed';
|
|
82
|
-
retcode: number;
|
|
83
|
-
data?: unknown;
|
|
84
|
-
message: string;
|
|
85
|
-
echo?: string;
|
|
86
|
-
}
|
package/src/utils.ts
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OneBot 12 事件与 zhin Message 的转换、消息段转换
|
|
3
|
-
*/
|
|
4
|
-
import type { SendContent } from 'zhin.js';
|
|
5
|
-
import type { OneBot12Event, OneBot12Segment } from './types.js';
|
|
6
|
-
import { toCanonicalSegments } from './segment-mapper.js';
|
|
7
|
-
|
|
8
|
-
/** 判断是否为消息事件(type=message) */
|
|
9
|
-
export function isMessageEvent(ev: OneBot12Event): ev is OneBot12Event & { message_id: string; message?: OneBot12Segment[] } {
|
|
10
|
-
return ev.type === 'message' && !!ev.message_id;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/** 从事件得到 zhin 场景 id:私聊 user_id,群 group_id,频道 channel_id 或 guild_id:channel_id */
|
|
14
|
-
export function getChannelId(ev: OneBot12Event): string {
|
|
15
|
-
if (ev.detail_type === 'private' && ev.user_id) return ev.user_id;
|
|
16
|
-
if (ev.detail_type === 'group' && ev.group_id) return ev.group_id;
|
|
17
|
-
if (ev.detail_type === 'channel' && ev.channel_id) {
|
|
18
|
-
return ev.guild_id ? `${ev.guild_id}:${ev.channel_id}` : ev.channel_id;
|
|
19
|
-
}
|
|
20
|
-
return '';
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** 从事件得到 channel 类型 */
|
|
24
|
-
export function getChannelType(ev: OneBot12Event): 'private' | 'group' {
|
|
25
|
-
if (ev.detail_type === 'private') return 'private';
|
|
26
|
-
return 'group';
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/** 将 OneBot 12 消息事件转为 zhin Message 的 MessageBase 所需字段 */
|
|
30
|
-
export function formatOneBot12MessagePayload(
|
|
31
|
-
ev: OneBot12Event,
|
|
32
|
-
endpointName: string,
|
|
33
|
-
recallFn: (msgId: string) => Promise<void>,
|
|
34
|
-
replyFn: (channel: { id: string; type: 'group' | 'private' }, content: (string | { type: string; data?: Record<string, unknown> })[], quote?: boolean | string) => Promise<string>,
|
|
35
|
-
): {
|
|
36
|
-
$id: string;
|
|
37
|
-
$adapter: 'onebot12';
|
|
38
|
-
$endpoint: string;
|
|
39
|
-
$channel: { id: string; type: 'group' | 'private' };
|
|
40
|
-
$sender: { id: string; name: string };
|
|
41
|
-
$content: Array<{ type: string; data: Record<string, unknown> }>;
|
|
42
|
-
$raw: string;
|
|
43
|
-
$timestamp: number;
|
|
44
|
-
$recall: () => Promise<void>;
|
|
45
|
-
$reply: (content: SendContent, quote?: boolean | string) => Promise<string>;
|
|
46
|
-
} {
|
|
47
|
-
const channelId = getChannelId(ev);
|
|
48
|
-
const channelType = getChannelType(ev);
|
|
49
|
-
const raw = ev.alt_message ?? (Array.isArray(ev.message) ? ev.message.map((s) => (s.type === 'text' ? (s.data?.text as string) ?? '' : '')).join('') : '');
|
|
50
|
-
const wire = Array.isArray(ev.message)
|
|
51
|
-
? ev.message.map((s) => ({ type: s.type, data: (s.data ?? {}) as Record<string, unknown> }))
|
|
52
|
-
: [{ type: 'text', data: { text: raw } }];
|
|
53
|
-
const content = toCanonicalSegments(wire);
|
|
54
|
-
const senderId = ev.user_id ?? '';
|
|
55
|
-
const senderName = (ev as Record<string, unknown>)['user.name'] as string | undefined ?? (ev as Record<string, unknown>)['qq.nickname'] as string | undefined ?? senderId;
|
|
56
|
-
|
|
57
|
-
return {
|
|
58
|
-
$id: ev.message_id!,
|
|
59
|
-
$adapter: 'onebot12',
|
|
60
|
-
$endpoint: endpointName,
|
|
61
|
-
$channel: { id: channelId, type: channelType },
|
|
62
|
-
$sender: { id: senderId, name: senderName },
|
|
63
|
-
$content: content,
|
|
64
|
-
$raw: raw,
|
|
65
|
-
$timestamp: ev.time ?? 0,
|
|
66
|
-
$recall: () => recallFn(ev.message_id!),
|
|
67
|
-
$reply: (cnt: SendContent, quote?: boolean | string) =>
|
|
68
|
-
replyFn(
|
|
69
|
-
{ id: channelId, type: channelType },
|
|
70
|
-
(Array.isArray(cnt) ? cnt : [cnt]) as (string | { type: string; data?: Record<string, unknown> })[],
|
|
71
|
-
quote,
|
|
72
|
-
),
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/** 将 zhin 的 content(segment 数组或字符串)转为 OneBot 12 message 段数组;简单实现仅 text */
|
|
77
|
-
export function contentToOb12Segments(content: SendContent): OneBot12Segment[] {
|
|
78
|
-
const arr = Array.isArray(content) ? content : [content];
|
|
79
|
-
const segs: OneBot12Segment[] = [];
|
|
80
|
-
for (const c of arr) {
|
|
81
|
-
if (typeof c === 'string') {
|
|
82
|
-
segs.push({ type: 'text', data: { text: c } });
|
|
83
|
-
} else if (c && typeof c === 'object' && 'type' in c) {
|
|
84
|
-
const el = c as { type: string; data?: Record<string, unknown> };
|
|
85
|
-
segs.push({ type: el.type, data: el.data ?? {} });
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
return segs.length ? segs : [{ type: 'text', data: { text: '' } }];
|
|
89
|
-
}
|