lolka.js 0.2.0 → 0.3.1
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/README.md +53 -0
- package/package.json +6 -2
- package/src/client/voice/VoiceConnection.js +420 -0
- package/src/index.js +4 -0
- package/typings/index.d.mts +36 -0
- package/typings/index.d.ts +36 -0
package/README.md
CHANGED
|
@@ -34,3 +34,56 @@ client.on('messageCreate', (message) => {
|
|
|
34
34
|
|
|
35
35
|
client.login('token');
|
|
36
36
|
```
|
|
37
|
+
|
|
38
|
+
## Voice
|
|
39
|
+
|
|
40
|
+
Voice works over WebRTC (lolka's voice stack, not Discord's UDP transport) and ships with the base
|
|
41
|
+
install — there's nothing extra to add. The API is in the spirit of `@discordjs/voice`: get a
|
|
42
|
+
connection with `joinVoiceChannel`, play audio, and (optionally) receive other participants' audio.
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
const { Client, GatewayIntentBits, joinVoiceChannel } = require('lolka.js');
|
|
46
|
+
|
|
47
|
+
const client = new Client({
|
|
48
|
+
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.GuildMessages],
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
client.on('messageCreate', async (message) => {
|
|
52
|
+
if (message.content !== '!play') return;
|
|
53
|
+
|
|
54
|
+
const channel = message.member?.voice?.channel;
|
|
55
|
+
if (!channel) return message.reply('Join a voice channel first.');
|
|
56
|
+
|
|
57
|
+
const connection = joinVoiceChannel({
|
|
58
|
+
channelId: channel.id,
|
|
59
|
+
guildId: channel.guild.id,
|
|
60
|
+
adapterCreator: channel.guild.voiceAdapterCreator,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// receive other participants' audio (optional)
|
|
64
|
+
connection.on('track', (track, userId) => {
|
|
65
|
+
// `track` is a MediaStreamTrack from @roamhq/wrtc
|
|
66
|
+
console.log(`receiving audio from ${userId}`);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
await connection.awaitReady();
|
|
70
|
+
connection.play('song.mp3'); // a file path or any Readable stream (decoded via ffmpeg)
|
|
71
|
+
|
|
72
|
+
connection.on('idle', () => console.log('playback finished'));
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
client.login('token');
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Leave the channel with `connection.destroy()`, and stop playback (without leaving) with
|
|
79
|
+
`connection.stop()`. Playing files requires `ffmpeg` to be available in the bot's environment.
|
|
80
|
+
|
|
81
|
+
`joinVoiceChannel(options)` accepts:
|
|
82
|
+
|
|
83
|
+
| option | type | description |
|
|
84
|
+
| --- | --- | --- |
|
|
85
|
+
| `channelId` | `string` | Voice channel id |
|
|
86
|
+
| `guildId` | `string` | Guild id |
|
|
87
|
+
| `adapterCreator` | `Function` | `guild.voiceAdapterCreator` |
|
|
88
|
+
| `selfMute` | `boolean` | default `false` |
|
|
89
|
+
| `selfDeaf` | `boolean` | default `false` |
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "lolka.js",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.1",
|
|
5
5
|
"description": "A powerful library for interacting with the lolka bot API (discord.js-compatible fork)",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"build": "node ./scripts/esmDts.mjs",
|
|
@@ -52,12 +52,16 @@
|
|
|
52
52
|
"@discordjs/rest": "^2.6.1",
|
|
53
53
|
"@discordjs/util": "^1.2.0",
|
|
54
54
|
"@discordjs/ws": "^1.2.3",
|
|
55
|
+
"@roamhq/wrtc": "^0.10.0",
|
|
55
56
|
"discord-api-types": "^0.38.40",
|
|
56
57
|
"fast-deep-equal": "3.1.3",
|
|
57
58
|
"lodash.snakecase": "4.1.1",
|
|
58
59
|
"magic-bytes.js": "^1.13.0",
|
|
60
|
+
"mediasoup-client": "^3.21.0",
|
|
61
|
+
"prism-media": "^1.3.5",
|
|
59
62
|
"tslib": "^2.6.3",
|
|
60
|
-
"undici": "6.24.1"
|
|
63
|
+
"undici": "6.24.1",
|
|
64
|
+
"ws": "^8.18.0"
|
|
61
65
|
},
|
|
62
66
|
"devDependencies": {
|
|
63
67
|
"@types/node": "^20.0.0",
|
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// WebRTC-голос для lolka.js.
|
|
4
|
+
//
|
|
5
|
+
// lolka voice работает через WebRTC (как клиенты lolka), а не через Discord UDP.
|
|
6
|
+
// Использует официальный WebRTC-клиент поверх @roamhq/wrtc для Node
|
|
7
|
+
// и говорит с голосовым сервером по простому JSON-RPC поверх WebSocket.
|
|
8
|
+
//
|
|
9
|
+
// Публичный API в духе @discordjs/voice:
|
|
10
|
+
// const conn = joinVoiceChannel({ channelId, guildId, adapterCreator });
|
|
11
|
+
// await conn.awaitReady();
|
|
12
|
+
// conn.play('song.mp3'); // путь к файлу или Readable-поток
|
|
13
|
+
// conn.on('track', (track, userId) => {}); // приём чужого звука (wrtc MediaStreamTrack)
|
|
14
|
+
// conn.destroy();
|
|
15
|
+
|
|
16
|
+
const EventEmitter = require('node:events');
|
|
17
|
+
|
|
18
|
+
// Зависимости голоса подгружаются лениво: `require('lolka.js')` не тянет WebRTC,
|
|
19
|
+
// пока голос реально не используется.
|
|
20
|
+
let wrtc;
|
|
21
|
+
let rtcClient;
|
|
22
|
+
let WebSocketImpl;
|
|
23
|
+
let FFmpeg;
|
|
24
|
+
let depsReady = false;
|
|
25
|
+
|
|
26
|
+
function ensureVoiceDeps() {
|
|
27
|
+
if (depsReady) return;
|
|
28
|
+
wrtc = require('@roamhq/wrtc');
|
|
29
|
+
rtcClient = require('mediasoup-client');
|
|
30
|
+
WebSocketImpl = require('ws');
|
|
31
|
+
FFmpeg = require('prism-media').FFmpeg;
|
|
32
|
+
// WebRTC-клиент браузерный, ему нужны WebRTC-глобалы.
|
|
33
|
+
for (const key of [
|
|
34
|
+
'RTCPeerConnection', 'RTCSessionDescription', 'RTCIceCandidate', 'MediaStream',
|
|
35
|
+
'MediaStreamTrack', 'RTCRtpSender', 'RTCRtpReceiver', 'RTCRtpTransceiver',
|
|
36
|
+
'RTCDtlsTransport', 'RTCIceTransport', 'RTCDataChannel', 'RTCSctpTransport',
|
|
37
|
+
]) {
|
|
38
|
+
if (wrtc[key] && !global[key]) global[key] = wrtc[key];
|
|
39
|
+
}
|
|
40
|
+
depsReady = true;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const SAMPLE_RATE = 48000;
|
|
44
|
+
const CHANNELS = 2;
|
|
45
|
+
const FRAME_SAMPLES = 480; // 10 мс
|
|
46
|
+
const FRAME_BYTES = FRAME_SAMPLES * CHANNELS * 2;
|
|
47
|
+
|
|
48
|
+
// JSON-RPC поверх WebSocket к голосовому серверу.
|
|
49
|
+
// request: { id, method, data }
|
|
50
|
+
// response: { id, response: true, data } | { id, response: true, error }
|
|
51
|
+
// notification: { notification: true, method, data }
|
|
52
|
+
class VoiceSignaling {
|
|
53
|
+
constructor(url, onNotification) {
|
|
54
|
+
this.url = url;
|
|
55
|
+
this.onNotification = onNotification;
|
|
56
|
+
this.ws = null;
|
|
57
|
+
this.pending = new Map();
|
|
58
|
+
this.nextId = 1;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
connect() {
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
this.ws = new WebSocketImpl(this.url);
|
|
64
|
+
this.ws.on('open', resolve);
|
|
65
|
+
this.ws.on('error', reject);
|
|
66
|
+
this.ws.on('message', buffer => {
|
|
67
|
+
let obj;
|
|
68
|
+
try {
|
|
69
|
+
obj = JSON.parse(buffer.toString());
|
|
70
|
+
} catch {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (obj.response) {
|
|
74
|
+
const p = this.pending.get(obj.id);
|
|
75
|
+
if (p) {
|
|
76
|
+
this.pending.delete(obj.id);
|
|
77
|
+
if (obj.error) p.reject(new Error(String(obj.error)));
|
|
78
|
+
else p.resolve(obj.data ?? {});
|
|
79
|
+
}
|
|
80
|
+
} else if (obj.notification) {
|
|
81
|
+
Promise.resolve(this.onNotification(obj.method, obj.data ?? {})).catch(() => {});
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
request(method, data = {}, timeout = 15000) {
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
const id = this.nextId++;
|
|
90
|
+
this.pending.set(id, { resolve, reject });
|
|
91
|
+
this.ws.send(JSON.stringify({ id, method, data }));
|
|
92
|
+
setTimeout(() => {
|
|
93
|
+
if (this.pending.has(id)) {
|
|
94
|
+
this.pending.delete(id);
|
|
95
|
+
reject(new Error(`voice signaling timeout: ${method}`));
|
|
96
|
+
}
|
|
97
|
+
}, timeout);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
close() {
|
|
102
|
+
try {
|
|
103
|
+
this.ws?.close();
|
|
104
|
+
} catch {
|
|
105
|
+
// ignore
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Активное голосовое соединение в канале.
|
|
112
|
+
* @extends {EventEmitter}
|
|
113
|
+
*/
|
|
114
|
+
class VoiceConnection extends EventEmitter {
|
|
115
|
+
constructor({ channelId, guildId, adapterCreator, selfMute = false, selfDeaf = false }) {
|
|
116
|
+
super();
|
|
117
|
+
if (!channelId || !guildId || typeof adapterCreator !== 'function') {
|
|
118
|
+
throw new TypeError('joinVoiceChannel requires { channelId, guildId, adapterCreator }');
|
|
119
|
+
}
|
|
120
|
+
ensureVoiceDeps();
|
|
121
|
+
|
|
122
|
+
this.channelId = channelId;
|
|
123
|
+
this.guildId = guildId;
|
|
124
|
+
this.state = 'connecting';
|
|
125
|
+
|
|
126
|
+
this.sessionId = null;
|
|
127
|
+
this.token = null;
|
|
128
|
+
this.endpoint = null;
|
|
129
|
+
|
|
130
|
+
this._signaling = null;
|
|
131
|
+
this._device = null;
|
|
132
|
+
this._sendTransport = null;
|
|
133
|
+
this._recvTransport = null;
|
|
134
|
+
this._audioSource = null;
|
|
135
|
+
this._audioTrack = null;
|
|
136
|
+
this._producer = null;
|
|
137
|
+
this._consumers = new Map();
|
|
138
|
+
|
|
139
|
+
this._playToken = null;
|
|
140
|
+
this._playTimer = null;
|
|
141
|
+
this._playFF = null;
|
|
142
|
+
|
|
143
|
+
this._started = false;
|
|
144
|
+
this._destroyed = false;
|
|
145
|
+
|
|
146
|
+
let readyResolve;
|
|
147
|
+
let readyReject;
|
|
148
|
+
this._ready = new Promise((res, rej) => {
|
|
149
|
+
readyResolve = res;
|
|
150
|
+
readyReject = rej;
|
|
151
|
+
});
|
|
152
|
+
this._ready.catch(() => {}); // не роняем процесс, если никто не ждёт
|
|
153
|
+
this._readyResolve = readyResolve;
|
|
154
|
+
this._readyReject = readyReject;
|
|
155
|
+
|
|
156
|
+
this._adapter = adapterCreator({
|
|
157
|
+
onVoiceStateUpdate: data => {
|
|
158
|
+
this.sessionId = data.session_id;
|
|
159
|
+
if (data.channel_id === null || data.channel_id === undefined) {
|
|
160
|
+
this.destroy();
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
onVoiceServerUpdate: data => {
|
|
164
|
+
this.token = data.token;
|
|
165
|
+
this.endpoint = data.endpoint;
|
|
166
|
+
this._maybeStart();
|
|
167
|
+
},
|
|
168
|
+
destroy: () => this._cleanup(),
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// Op 4 — Voice State Update (просим сервер подключить нас к каналу).
|
|
172
|
+
this._adapter.sendPayload({
|
|
173
|
+
op: 4,
|
|
174
|
+
d: { guild_id: guildId, channel_id: channelId, self_mute: Boolean(selfMute), self_deaf: Boolean(selfDeaf) },
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Дождаться готовности соединения (WebRTC поднят). */
|
|
179
|
+
awaitReady(timeout = 30000) {
|
|
180
|
+
return Promise.race([
|
|
181
|
+
this._ready,
|
|
182
|
+
new Promise((_, rej) => setTimeout(() => rej(new Error('voice connection timeout')), timeout)),
|
|
183
|
+
]);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async _maybeStart() {
|
|
187
|
+
if (this._started || this._destroyed || !this.token || !this.endpoint) return;
|
|
188
|
+
this._started = true;
|
|
189
|
+
try {
|
|
190
|
+
await this._start();
|
|
191
|
+
this.state = 'ready';
|
|
192
|
+
this.emit('ready');
|
|
193
|
+
this._readyResolve();
|
|
194
|
+
} catch (error) {
|
|
195
|
+
this.state = 'error';
|
|
196
|
+
this.emit('error', error);
|
|
197
|
+
this._readyReject(error);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
_signalingUrl() {
|
|
202
|
+
let ep = this.endpoint || '';
|
|
203
|
+
if (!ep.includes('://')) ep = `ws://${ep}`;
|
|
204
|
+
return `${ep}${ep.includes('?') ? '&' : '?'}token=${this.token}`;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async _start() {
|
|
208
|
+
this._signaling = new VoiceSignaling(this._signalingUrl(), (method, data) => this._onNotification(method, data));
|
|
209
|
+
await this._signaling.connect();
|
|
210
|
+
|
|
211
|
+
const routerRtpCapabilities = await this._signaling.request('getRouterRtpCapabilities', {});
|
|
212
|
+
this._device = new rtcClient.Device({ handlerName: 'Chrome111' });
|
|
213
|
+
await this._device.load({ routerRtpCapabilities });
|
|
214
|
+
|
|
215
|
+
await this._createSendTransport();
|
|
216
|
+
await this._createRecvTransport();
|
|
217
|
+
|
|
218
|
+
// Постоянный исходящий трек; play() подаёт в него PCM.
|
|
219
|
+
this._audioSource = new wrtc.nonstandard.RTCAudioSource();
|
|
220
|
+
this._audioTrack = this._audioSource.createTrack();
|
|
221
|
+
this._producer = await this._sendTransport.produce({ track: this._audioTrack });
|
|
222
|
+
|
|
223
|
+
const { producers } = await this._signaling.request('getProducers', {});
|
|
224
|
+
for (const p of producers) await this._consume(p.producerId, p.userId, p.kind);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async _createSendTransport() {
|
|
228
|
+
const params = await this._signaling.request('createWebRtcTransport', { direction: 'send' });
|
|
229
|
+
this._sendTransport = this._device.createSendTransport(params);
|
|
230
|
+
this._sendTransport.on('connect', ({ dtlsParameters }, callback, errback) =>
|
|
231
|
+
this._signaling
|
|
232
|
+
.request('connectTransport', { transportId: this._sendTransport.id, dtlsParameters })
|
|
233
|
+
.then(() => callback())
|
|
234
|
+
.catch(errback),
|
|
235
|
+
);
|
|
236
|
+
this._sendTransport.on('produce', ({ kind, rtpParameters, appData }, callback, errback) =>
|
|
237
|
+
this._signaling
|
|
238
|
+
.request('produce', { transportId: this._sendTransport.id, kind, rtpParameters, appData })
|
|
239
|
+
.then(({ id }) => callback({ id }))
|
|
240
|
+
.catch(errback),
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async _createRecvTransport() {
|
|
245
|
+
const params = await this._signaling.request('createWebRtcTransport', { direction: 'recv' });
|
|
246
|
+
this._recvTransport = this._device.createRecvTransport(params);
|
|
247
|
+
this._recvTransport.on('connect', ({ dtlsParameters }, callback, errback) =>
|
|
248
|
+
this._signaling
|
|
249
|
+
.request('connectTransport', { transportId: this._recvTransport.id, dtlsParameters })
|
|
250
|
+
.then(() => callback())
|
|
251
|
+
.catch(errback),
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async _consume(producerId, userId, kind) {
|
|
256
|
+
if (this._consumers.has(producerId) || !this._recvTransport) return;
|
|
257
|
+
try {
|
|
258
|
+
const params = await this._signaling.request('consume', {
|
|
259
|
+
transportId: this._recvTransport.id,
|
|
260
|
+
producerId,
|
|
261
|
+
rtpCapabilities: this._device.rtpCapabilities,
|
|
262
|
+
});
|
|
263
|
+
const consumer = await this._recvTransport.consume(params);
|
|
264
|
+
await this._signaling.request('resumeConsumer', { consumerId: consumer.id });
|
|
265
|
+
this._consumers.set(producerId, consumer);
|
|
266
|
+
this.emit('track', consumer.track, userId, producerId);
|
|
267
|
+
} catch (error) {
|
|
268
|
+
this.emit('error', error);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async _onNotification(method, data) {
|
|
273
|
+
if (method === 'newProducer') {
|
|
274
|
+
await this._consume(data.producerId, data.userId, data.kind);
|
|
275
|
+
} else if (method === 'consumerClosed' || method === 'producerClosed') {
|
|
276
|
+
if (data.producerId) this._consumers.delete(data.producerId);
|
|
277
|
+
} else if (method === 'kicked') {
|
|
278
|
+
this.destroy();
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Проиграть аудио в канал.
|
|
284
|
+
* @param {string|import('node:stream').Readable} input Путь к файлу или Readable-поток (любой формат — через ffmpeg).
|
|
285
|
+
*/
|
|
286
|
+
play(input) {
|
|
287
|
+
if (!this._audioSource) throw new Error('voice connection is not ready');
|
|
288
|
+
this.stop();
|
|
289
|
+
|
|
290
|
+
const args =
|
|
291
|
+
typeof input === 'string'
|
|
292
|
+
? ['-i', input]
|
|
293
|
+
: ['-i', 'pipe:0'];
|
|
294
|
+
const ff = new FFmpeg({
|
|
295
|
+
args: [...args, '-analyzeduration', '0', '-loglevel', '0', '-f', 's16le', '-ar', String(SAMPLE_RATE), '-ac', String(CHANNELS)],
|
|
296
|
+
});
|
|
297
|
+
if (typeof input !== 'string' && input && typeof input.pipe === 'function') input.pipe(ff);
|
|
298
|
+
|
|
299
|
+
let ended = false;
|
|
300
|
+
ff.on('end', () => {
|
|
301
|
+
ended = true;
|
|
302
|
+
});
|
|
303
|
+
ff.on('error', error => {
|
|
304
|
+
ended = true;
|
|
305
|
+
this.emit('error', error);
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
const token = {};
|
|
309
|
+
this._playToken = token;
|
|
310
|
+
this._playFF = ff;
|
|
311
|
+
const start = performance.now();
|
|
312
|
+
let frame = 0;
|
|
313
|
+
this.emit('playing');
|
|
314
|
+
|
|
315
|
+
const tick = () => {
|
|
316
|
+
if (this._playToken !== token) return;
|
|
317
|
+
let chunk = ff.read(FRAME_BYTES);
|
|
318
|
+
if (ended && !chunk) {
|
|
319
|
+
this._playToken = null;
|
|
320
|
+
this.emit('idle');
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
// wrtc требует Int16Array в отдельном ArrayBuffer ровно нужного размера.
|
|
324
|
+
const ab = new ArrayBuffer(FRAME_BYTES);
|
|
325
|
+
if (chunk) {
|
|
326
|
+
if (chunk.length < FRAME_BYTES) {
|
|
327
|
+
const padded = Buffer.alloc(FRAME_BYTES);
|
|
328
|
+
chunk.copy(padded);
|
|
329
|
+
chunk = padded;
|
|
330
|
+
}
|
|
331
|
+
new Uint8Array(ab).set(chunk.subarray(0, FRAME_BYTES));
|
|
332
|
+
}
|
|
333
|
+
// Если данных нет (джиттер) — кадр остаётся тишиной, расписание не сбиваем.
|
|
334
|
+
this._audioSource.onData({
|
|
335
|
+
samples: new Int16Array(ab),
|
|
336
|
+
sampleRate: SAMPLE_RATE,
|
|
337
|
+
bitsPerSample: 16,
|
|
338
|
+
channelCount: CHANNELS,
|
|
339
|
+
numberOfFrames: FRAME_SAMPLES,
|
|
340
|
+
});
|
|
341
|
+
frame += 1;
|
|
342
|
+
const target = start + frame * 10;
|
|
343
|
+
this._playTimer = setTimeout(tick, Math.max(0, target - performance.now()));
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
// preroll ~400 мс: даём ffmpeg наполнить буфер, чтобы не было стартовых пропусков.
|
|
347
|
+
this._playTimer = setTimeout(tick, 400);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Остановить текущее воспроизведение. */
|
|
351
|
+
stop() {
|
|
352
|
+
this._playToken = null;
|
|
353
|
+
if (this._playTimer) {
|
|
354
|
+
clearTimeout(this._playTimer);
|
|
355
|
+
this._playTimer = null;
|
|
356
|
+
}
|
|
357
|
+
if (this._playFF) {
|
|
358
|
+
try {
|
|
359
|
+
this._playFF.destroy();
|
|
360
|
+
} catch {
|
|
361
|
+
// ignore
|
|
362
|
+
}
|
|
363
|
+
this._playFF = null;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Выйти из канала и освободить ресурсы. */
|
|
368
|
+
destroy() {
|
|
369
|
+
if (this._destroyed) return;
|
|
370
|
+
this._destroyed = true;
|
|
371
|
+
this.state = 'destroyed';
|
|
372
|
+
this.stop();
|
|
373
|
+
try {
|
|
374
|
+
this._adapter?.sendPayload({
|
|
375
|
+
op: 4,
|
|
376
|
+
d: { guild_id: this.guildId, channel_id: null, self_mute: false, self_deaf: false },
|
|
377
|
+
});
|
|
378
|
+
} catch {
|
|
379
|
+
// ignore
|
|
380
|
+
}
|
|
381
|
+
this._cleanup();
|
|
382
|
+
try {
|
|
383
|
+
this._adapter?.destroy();
|
|
384
|
+
} catch {
|
|
385
|
+
// ignore
|
|
386
|
+
}
|
|
387
|
+
this.emit('destroyed');
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
_cleanup() {
|
|
391
|
+
this._consumers.clear();
|
|
392
|
+
for (const transport of [this._sendTransport, this._recvTransport]) {
|
|
393
|
+
try {
|
|
394
|
+
transport?.close();
|
|
395
|
+
} catch {
|
|
396
|
+
// ignore
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
this._sendTransport = null;
|
|
400
|
+
this._recvTransport = null;
|
|
401
|
+
this._signaling?.close();
|
|
402
|
+
this._signaling = null;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Подключиться к голосовому каналу.
|
|
408
|
+
* @param {Object} options
|
|
409
|
+
* @param {string} options.channelId ID голосового канала
|
|
410
|
+
* @param {string} options.guildId ID сервера
|
|
411
|
+
* @param {Function} options.adapterCreator `guild.voiceAdapterCreator`
|
|
412
|
+
* @param {boolean} [options.selfMute=false]
|
|
413
|
+
* @param {boolean} [options.selfDeaf=false]
|
|
414
|
+
* @returns {VoiceConnection}
|
|
415
|
+
*/
|
|
416
|
+
function joinVoiceChannel(options) {
|
|
417
|
+
return new VoiceConnection(options);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
module.exports = { VoiceConnection, joinVoiceChannel };
|
package/src/index.js
CHANGED
|
@@ -13,6 +13,10 @@ exports.ShardClientUtil = require('./sharding/ShardClientUtil');
|
|
|
13
13
|
exports.ShardingManager = require('./sharding/ShardingManager');
|
|
14
14
|
exports.WebhookClient = require('./client/WebhookClient');
|
|
15
15
|
|
|
16
|
+
// Voice (WebRTC)
|
|
17
|
+
exports.joinVoiceChannel = require('./client/voice/VoiceConnection').joinVoiceChannel;
|
|
18
|
+
exports.VoiceConnection = require('./client/voice/VoiceConnection').VoiceConnection;
|
|
19
|
+
|
|
16
20
|
// Errors
|
|
17
21
|
exports.DiscordjsError = require('./errors/DJSError').DiscordjsError;
|
|
18
22
|
exports.DiscordjsTypeError = require('./errors/DJSError').DiscordjsTypeError;
|
package/typings/index.d.mts
CHANGED
|
@@ -8124,6 +8124,42 @@ export type InternalDiscordGatewayAdapterCreator = (
|
|
|
8124
8124
|
|
|
8125
8125
|
//#endregion
|
|
8126
8126
|
|
|
8127
|
+
//#region Voice (WebRTC)
|
|
8128
|
+
|
|
8129
|
+
export interface VoiceConnectionOptions {
|
|
8130
|
+
channelId: string;
|
|
8131
|
+
guildId: string;
|
|
8132
|
+
adapterCreator: InternalDiscordGatewayAdapterCreator;
|
|
8133
|
+
selfMute?: boolean;
|
|
8134
|
+
selfDeaf?: boolean;
|
|
8135
|
+
}
|
|
8136
|
+
|
|
8137
|
+
export type VoiceConnectionState = 'connecting' | 'ready' | 'error' | 'destroyed';
|
|
8138
|
+
|
|
8139
|
+
export class VoiceConnection extends EventEmitter {
|
|
8140
|
+
private constructor(options: VoiceConnectionOptions);
|
|
8141
|
+
public channelId: string;
|
|
8142
|
+
public guildId: string;
|
|
8143
|
+
public state: VoiceConnectionState;
|
|
8144
|
+
public sessionId: string | null;
|
|
8145
|
+
public token: string | null;
|
|
8146
|
+
public endpoint: string | null;
|
|
8147
|
+
public awaitReady(timeout?: number): Promise<void>;
|
|
8148
|
+
public play(input: string | NodeJS.ReadableStream): void;
|
|
8149
|
+
public stop(): void;
|
|
8150
|
+
public destroy(): void;
|
|
8151
|
+
public on(event: 'ready' | 'playing' | 'idle' | 'destroyed', listener: () => void): this;
|
|
8152
|
+
public on(event: 'error', listener: (error: Error) => void): this;
|
|
8153
|
+
public on(event: 'track', listener: (track: unknown, userId: string, producerId: string) => void): this;
|
|
8154
|
+
public once(event: 'ready' | 'playing' | 'idle' | 'destroyed', listener: () => void): this;
|
|
8155
|
+
public once(event: 'error', listener: (error: Error) => void): this;
|
|
8156
|
+
public once(event: 'track', listener: (track: unknown, userId: string, producerId: string) => void): this;
|
|
8157
|
+
}
|
|
8158
|
+
|
|
8159
|
+
export function joinVoiceChannel(options: VoiceConnectionOptions): VoiceConnection;
|
|
8160
|
+
|
|
8161
|
+
//#endregion
|
|
8162
|
+
|
|
8127
8163
|
// External
|
|
8128
8164
|
export * from 'discord-api-types/v10';
|
|
8129
8165
|
export * from '@discordjs/builders';
|
package/typings/index.d.ts
CHANGED
|
@@ -8124,6 +8124,42 @@ export type InternalDiscordGatewayAdapterCreator = (
|
|
|
8124
8124
|
|
|
8125
8125
|
//#endregion
|
|
8126
8126
|
|
|
8127
|
+
//#region Voice (WebRTC)
|
|
8128
|
+
|
|
8129
|
+
export interface VoiceConnectionOptions {
|
|
8130
|
+
channelId: string;
|
|
8131
|
+
guildId: string;
|
|
8132
|
+
adapterCreator: InternalDiscordGatewayAdapterCreator;
|
|
8133
|
+
selfMute?: boolean;
|
|
8134
|
+
selfDeaf?: boolean;
|
|
8135
|
+
}
|
|
8136
|
+
|
|
8137
|
+
export type VoiceConnectionState = 'connecting' | 'ready' | 'error' | 'destroyed';
|
|
8138
|
+
|
|
8139
|
+
export class VoiceConnection extends EventEmitter {
|
|
8140
|
+
private constructor(options: VoiceConnectionOptions);
|
|
8141
|
+
public channelId: string;
|
|
8142
|
+
public guildId: string;
|
|
8143
|
+
public state: VoiceConnectionState;
|
|
8144
|
+
public sessionId: string | null;
|
|
8145
|
+
public token: string | null;
|
|
8146
|
+
public endpoint: string | null;
|
|
8147
|
+
public awaitReady(timeout?: number): Promise<void>;
|
|
8148
|
+
public play(input: string | NodeJS.ReadableStream): void;
|
|
8149
|
+
public stop(): void;
|
|
8150
|
+
public destroy(): void;
|
|
8151
|
+
public on(event: 'ready' | 'playing' | 'idle' | 'destroyed', listener: () => void): this;
|
|
8152
|
+
public on(event: 'error', listener: (error: Error) => void): this;
|
|
8153
|
+
public on(event: 'track', listener: (track: unknown, userId: string, producerId: string) => void): this;
|
|
8154
|
+
public once(event: 'ready' | 'playing' | 'idle' | 'destroyed', listener: () => void): this;
|
|
8155
|
+
public once(event: 'error', listener: (error: Error) => void): this;
|
|
8156
|
+
public once(event: 'track', listener: (track: unknown, userId: string, producerId: string) => void): this;
|
|
8157
|
+
}
|
|
8158
|
+
|
|
8159
|
+
export function joinVoiceChannel(options: VoiceConnectionOptions): VoiceConnection;
|
|
8160
|
+
|
|
8161
|
+
//#endregion
|
|
8162
|
+
|
|
8127
8163
|
// External
|
|
8128
8164
|
export * from 'discord-api-types/v10';
|
|
8129
8165
|
export * from '@discordjs/builders';
|