lolka.js 0.4.1 → 0.4.4

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 CHANGED
@@ -78,6 +78,16 @@ client.login('token');
78
78
  Leave the channel with `connection.destroy()`, and stop playback (without leaving) with
79
79
  `connection.stop()`. Playing files requires `ffmpeg` to be available in the bot's environment.
80
80
 
81
+ Calling `joinVoiceChannel` again for a guild that already has a live connection reuses it and moves the
82
+ bot via `connection.rejoin({ channelId, selfMute, selfDeaf })` (all fields optional), like `@discordjs/voice`.
83
+ Moving the bot between channels, or the channel being moved to another voice server, is transparent to
84
+ `play()`: the outgoing track is kept and playback continues. After such a move the `track` event fires
85
+ again for every participant (the old tracks end), and `ready` is still emitted only once. If the voice
86
+ server kicks the bot, or the connection to the voice server is lost, and no move follows within a few
87
+ seconds, the connection is destroyed (`state` stays `'ready'` during that grace period). A failed initial
88
+ start also destroys the connection, so the next `joinVoiceChannel` creates a fresh one. Connections are
89
+ reused per client and guild, so several clients in one process do not interfere.
90
+
81
91
  `joinVoiceChannel(options)` accepts:
82
92
 
83
93
  | option | type | description |
@@ -87,3 +97,31 @@ Leave the channel with `connection.destroy()`, and stop playback (without leavin
87
97
  | `adapterCreator` | `Function` | `guild.voiceAdapterCreator` |
88
98
  | `selfMute` | `boolean` | default `false` |
89
99
  | `selfDeaf` | `boolean` | default `false` |
100
+
101
+ ## Configuration
102
+
103
+ `lolka.js` talks to the public lolka by default. These environment variables override the endpoints
104
+ (read when a client is created, no trailing slash needed):
105
+
106
+ | variable | default | description |
107
+ | --- | --- | --- |
108
+ | `LOLKA_API_BASE` | `https://lolka.app/api/bot` | Bot API base (the library appends `/v10`). The gateway URL is taken from `GET /gateway/bot` |
109
+ | `LOLKA_CDN` | `https://cdn.lolka.app` | CDN for avatars, banners, icons, emojis, soundboard |
110
+ | `LOLKA_WEB` | `https://lolka.app` | Web client, used for channel/message links and bot authorization |
111
+ | `LOLKA_INVITE` | `https://lolka.gg` | Base of invite links |
112
+
113
+ ### CDN
114
+
115
+ The lolka CDN does no resizing and serves only webp, so the `size`, `extension` and `forceStatic`
116
+ options of `avatarURL()`, `iconURL()`, `bannerURL()` and friends are ignored. `client.rest.cdn` is a
117
+ `LolkaCDN` (exported, together with the `LolkaCDNBase`, `LolkaWebBase`, `LolkaInviteBase` and
118
+ `LolkaApiBase` constants, which are snapshots of the values at load time).
119
+
120
+ ### Links
121
+
122
+ - `invite.url` is `https://lolka.gg/{code}`; invites are also recognised as `https://lolka.app/i/{code}`
123
+ - `client.generateInvite()` returns `https://lolka.app/bot-authorize?client_id=...`
124
+ - `webhook.url` is `https://lolka.app/api/webhooks/{id}/{token}`; `WebhookClient` accepts such URLs
125
+ - `channel.url` is `https://lolka.app/servers/{guild}/channels/{channel}` (DMs: `/me/channels/{channel}`),
126
+ `message.url` appends `/{message}`
127
+ - the exported `channelLink()` and `messageLink()` build the same URLs
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "lolka.js",
4
- "version": "0.4.1",
4
+ "version": "0.4.4",
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",
8
- "prepack": "npm run build"
8
+ "prepack": "npm run build",
9
+ "test": "node --test test/*.test.js test/*.test.mjs"
9
10
  },
10
11
  "main": "./src/index.js",
11
12
  "types": "./typings/index.d.ts",
@@ -4,6 +4,7 @@ const EventEmitter = require('node:events');
4
4
  const { REST } = require('@discordjs/rest');
5
5
  const { Routes } = require('discord-api-types/v10');
6
6
  const { DiscordjsTypeError, ErrorCodes } = require('../errors');
7
+ const LolkaCDN = require('../util/LolkaCDN');
7
8
  const Options = require('../util/Options');
8
9
  const { flatten } = require('../util/Util');
9
10
 
@@ -53,6 +54,7 @@ class BaseClient extends EventEmitter {
53
54
  * @type {REST}
54
55
  */
55
56
  this.rest = new REST(this.options.rest);
57
+ this.rest.cdn = new LolkaCDN(this.options.rest.cdn, this.options.rest.mediaProxy);
56
58
  }
57
59
 
58
60
  /**
@@ -27,6 +27,7 @@ const Widget = require('../structures/Widget');
27
27
  const { resolveInviteCode, resolveGuildTemplateCode } = require('../util/DataResolver');
28
28
  const Events = require('../util/Events');
29
29
  const IntentsBitField = require('../util/IntentsBitField');
30
+ const { resolveWebBase } = require('../util/LolkaConstants');
30
31
  const Options = require('../util/Options');
31
32
  const PermissionsBitField = require('../util/PermissionsBitField');
32
33
  const Status = require('../util/Status');
@@ -269,7 +270,7 @@ class Client extends BaseClient {
269
270
  * @param {ClientFetchInviteOptions} [options] Options for fetching the invite
270
271
  * @returns {Promise<Invite>}
271
272
  * @example
272
- * client.fetchInvite('https://discord.gg/djs')
273
+ * client.fetchInvite('https://lolka.gg/djs')
273
274
  * .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
274
275
  * .catch(console.error);
275
276
  */
@@ -496,7 +497,7 @@ class Client extends BaseClient {
496
497
  query.set('guild_id', guildId);
497
498
  }
498
499
 
499
- return `${this.options.rest.api}${Routes.oauth2Authorization()}?${query}`;
500
+ return `${resolveWebBase()}/bot-authorize?${query}`;
500
501
  }
501
502
 
502
503
  toJSON() {
@@ -3,7 +3,7 @@
3
3
  const BaseClient = require('./BaseClient');
4
4
  const { DiscordjsError, ErrorCodes } = require('../errors');
5
5
  const Webhook = require('../structures/Webhook');
6
- const { parseWebhookURL } = require('../util/Util');
6
+ const { parseWebhookURLWithOrigin } = require('../util/Util');
7
7
 
8
8
  /**
9
9
  * The webhook client.
@@ -41,19 +41,23 @@ class WebhookClient extends BaseClient {
41
41
  * @param {WebhookClientOptions} [options] Options for the webhook client
42
42
  */
43
43
  constructor(data, options) {
44
- super(options);
45
- Object.defineProperty(this, 'client', { value: this });
46
44
  let { id, token } = data;
47
45
 
48
46
  if ('url' in data) {
49
- const parsed = parseWebhookURL(data.url);
47
+ const parsed = parseWebhookURLWithOrigin(data.url);
50
48
  if (!parsed) {
51
49
  throw new DiscordjsError(ErrorCodes.WebhookURLInvalid);
52
50
  }
53
51
 
54
52
  ({ id, token } = parsed);
53
+ if ((options === undefined || (typeof options === 'object' && options !== null)) && !options?.rest?.api) {
54
+ options = { ...options, rest: { ...options?.rest, api: `${parsed.origin}/api/bot` } };
55
+ }
55
56
  }
56
57
 
58
+ super(options);
59
+ Object.defineProperty(this, 'client', { value: this });
60
+
57
61
  this.id = id;
58
62
  Object.defineProperty(this, 'token', { value: token, writable: true, configurable: true });
59
63
  }
@@ -44,15 +44,27 @@ const SAMPLE_RATE = 48000;
44
44
  const CHANNELS = 2;
45
45
  const FRAME_SAMPLES = 480; // 10 мс
46
46
  const FRAME_BYTES = FRAME_SAMPLES * CHANNELS * 2;
47
+ const DEFAULT_KICK_GRACE_MS = 5000;
48
+
49
+ // Живые соединения: owner (голосовой менеджер клиента) -> guildId -> соединение. Повторный
50
+ // joinVoiceChannel переиспользует соединение через rejoin(); разные клиенты не пересекаются.
51
+ const defaultOwner = {};
52
+ const connections = new WeakMap();
53
+
54
+ function ownerOf(adapterCreator) {
55
+ return adapterCreator?.voiceManager ?? defaultOwner;
56
+ }
47
57
 
48
58
  // JSON-RPC поверх WebSocket к голосовому серверу.
49
59
  // request: { id, method, data }
50
60
  // response: { id, response: true, data } | { id, response: true, error }
51
61
  // notification: { notification: true, method, data }
52
62
  class VoiceSignaling {
53
- constructor(url, onNotification) {
63
+ constructor(url, onNotification, onClose) {
54
64
  this.url = url;
55
65
  this.onNotification = onNotification;
66
+ this.onClose = onClose;
67
+ this.closing = false;
56
68
  this.ws = null;
57
69
  this.pending = new Map();
58
70
  this.nextId = 1;
@@ -63,6 +75,13 @@ class VoiceSignaling {
63
75
  this.ws = new WebSocketImpl(this.url);
64
76
  this.ws.on('open', resolve);
65
77
  this.ws.on('error', reject);
78
+ this.ws.on('close', () => {
79
+ for (const [id, p] of this.pending) {
80
+ this.pending.delete(id);
81
+ p.reject(new Error('voice signaling closed'));
82
+ }
83
+ if (!this.closing) this.onClose?.();
84
+ });
66
85
  this.ws.on('message', buffer => {
67
86
  let obj;
68
87
  try {
@@ -87,18 +106,34 @@ class VoiceSignaling {
87
106
  request(method, data = {}, timeout = 15000) {
88
107
  return new Promise((resolve, reject) => {
89
108
  const id = this.nextId++;
90
- this.pending.set(id, { resolve, reject });
91
- this.ws.send(JSON.stringify({ id, method, data }));
92
- setTimeout(() => {
109
+ const timer = setTimeout(() => {
93
110
  if (this.pending.has(id)) {
94
111
  this.pending.delete(id);
95
112
  reject(new Error(`voice signaling timeout: ${method}`));
96
113
  }
97
114
  }, timeout);
115
+ this.pending.set(id, {
116
+ resolve: value => {
117
+ clearTimeout(timer);
118
+ resolve(value);
119
+ },
120
+ reject: error => {
121
+ clearTimeout(timer);
122
+ reject(error);
123
+ },
124
+ });
125
+ try {
126
+ this.ws.send(JSON.stringify({ id, method, data }));
127
+ } catch (error) {
128
+ this.pending.delete(id);
129
+ clearTimeout(timer);
130
+ reject(error);
131
+ }
98
132
  });
99
133
  }
100
134
 
101
135
  close() {
136
+ this.closing = true;
102
137
  try {
103
138
  this.ws?.close();
104
139
  } catch {
@@ -119,6 +154,7 @@ class VoiceConnection extends EventEmitter {
119
154
  }
120
155
  ensureVoiceDeps();
121
156
 
157
+ this._owner = ownerOf(adapterCreator);
122
158
  this.channelId = channelId;
123
159
  this.guildId = guildId;
124
160
  this.state = 'connecting';
@@ -140,8 +176,13 @@ class VoiceConnection extends EventEmitter {
140
176
  this._playTimer = null;
141
177
  this._playFF = null;
142
178
 
179
+ this._kickTimer = null;
143
180
  this._started = false;
144
181
  this._destroyed = false;
182
+ this._migration = 0; // счётчик переездов: результат устаревшего старта/переезда игнорируется
183
+ this._readyAnnounced = false;
184
+ this._roomChanged = false;
185
+ this._stateReceived = false;
145
186
 
146
187
  let readyResolve;
147
188
  let readyReject;
@@ -153,132 +194,270 @@ class VoiceConnection extends EventEmitter {
153
194
  this._readyResolve = readyResolve;
154
195
  this._readyReject = readyReject;
155
196
 
197
+ this._selfMute = Boolean(selfMute);
198
+ this._selfDeaf = Boolean(selfDeaf);
199
+
156
200
  this._adapter = adapterCreator({
157
201
  onVoiceStateUpdate: data => {
158
202
  this.sessionId = data.session_id;
159
203
  if (data.channel_id === null || data.channel_id === undefined) {
160
- this.destroy();
204
+ if (this._stateReceived) this.destroy();
205
+ return;
206
+ }
207
+ this._stateReceived = true;
208
+ const channelId = String(data.channel_id);
209
+ if (channelId !== String(this.channelId)) {
210
+ this.channelId = channelId;
211
+ if (this._started) this._roomChanged = true;
161
212
  }
162
213
  },
163
214
  onVoiceServerUpdate: data => {
215
+ // Повторный Voice Server Update у уже поднятого соединения приходит, когда голосовой сервер
216
+ // канала сменили вручную (SetChannelVoiceServer -> migrateBotParticipant) или назначенный
217
+ // сервер нездоров и бот повторил op 4; также после перемещения бота в другой канал (тот же
218
+ // endpoint, но новая комната). Failover мёртвого сервера сюда не приходит — он только кикает.
219
+ // Смена одного лишь токена сессию не трогает: бэкенд перевыпускает его на каждый
220
+ // Voice State Update (например, при self_mute).
221
+ const serverChanged =
222
+ this._started && Boolean(data.endpoint) && (data.endpoint !== this.endpoint || this._roomChanged);
164
223
  this.token = data.token;
165
- this.endpoint = data.endpoint;
166
- this._maybeStart();
224
+ if (data.endpoint || !this._started) this.endpoint = data.endpoint;
225
+ if (serverChanged) {
226
+ this._roomChanged = false;
227
+ this._migrate();
228
+ } else {
229
+ this._maybeStart();
230
+ }
231
+ },
232
+ // Шард отключился безвозвратно: полный локальный teardown без op 4 и без adapter.destroy().
233
+ destroy: () => {
234
+ if (this._destroyed) return;
235
+ this._destroyed = true;
236
+ this.state = 'destroyed';
237
+ this._finalize();
238
+ this.emit('destroyed');
167
239
  },
168
- destroy: () => this._cleanup(),
169
240
  });
170
241
 
242
+ this._sendState(channelId);
243
+ }
244
+
245
+ _sendState(channelId) {
171
246
  // Op 4 — Voice State Update (просим сервер подключить нас к каналу).
172
- this._adapter.sendPayload({
247
+ return this._adapter.sendPayload({
173
248
  op: 4,
174
- d: { guild_id: guildId, channel_id: channelId, self_mute: Boolean(selfMute), self_deaf: Boolean(selfDeaf) },
249
+ d: { guild_id: this.guildId, channel_id: channelId, self_mute: this._selfMute, self_deaf: this._selfDeaf },
175
250
  });
176
251
  }
177
252
 
253
+ /**
254
+ * Переместить соединение в другой канал (или обновить mute/deaf) без пересоздания.
255
+ * @param {Object} options
256
+ * @param {string} [options.channelId] ID нового голосового канала
257
+ * @param {boolean} [options.selfMute]
258
+ * @param {boolean} [options.selfDeaf]
259
+ * @returns {boolean} Удалось ли отправить op 4
260
+ */
261
+ rejoin({ channelId = this.channelId, selfMute = this._selfMute, selfDeaf = this._selfDeaf } = {}) {
262
+ if (this._destroyed) throw new Error('voice connection is destroyed');
263
+ this._selfMute = Boolean(selfMute);
264
+ this._selfDeaf = Boolean(selfDeaf);
265
+ return this._sendState(channelId);
266
+ }
267
+
178
268
  /** Дождаться готовности соединения (WebRTC поднят). */
179
269
  awaitReady(timeout = 30000) {
180
- return Promise.race([
181
- this._ready,
182
- new Promise((_, rej) => setTimeout(() => rej(new Error('voice connection timeout')), timeout)),
183
- ]);
270
+ let timer;
271
+ const timeoutPromise = new Promise((_, rej) => {
272
+ timer = setTimeout(() => rej(new Error('voice connection timeout')), timeout);
273
+ });
274
+ return Promise.race([this._ready, timeoutPromise]).finally(() => clearTimeout(timer));
184
275
  }
185
276
 
186
277
  async _maybeStart() {
187
278
  if (this._started || this._destroyed || !this.token || !this.endpoint) return;
188
279
  this._started = true;
280
+ const migration = this._migration;
189
281
  try {
190
- await this._start();
191
- this.state = 'ready';
192
- this.emit('ready');
193
- this._readyResolve();
282
+ await this._start(migration);
283
+ // Пока поднимались, голосовой сервер сменился — исход этого старта уже не важен,
284
+ // готовность объявит _migrate.
285
+ if (migration !== this._migration) return;
286
+ this._markReady();
194
287
  } catch (error) {
195
- this.state = 'error';
196
- this.emit('error', error);
288
+ if (migration !== this._migration || this._destroyed) return;
197
289
  this._readyReject(error);
290
+ if (this.listenerCount('error') > 0) this.emit('error', error);
291
+ this.destroy();
198
292
  }
199
293
  }
200
294
 
295
+ /** Соединение поднято: `ready` и awaitReady() срабатывают один раз, даже после переездов. */
296
+ _markReady() {
297
+ this.state = 'ready';
298
+ if (this._readyAnnounced) return;
299
+ this._readyAnnounced = true;
300
+ this.emit('ready');
301
+ this._readyResolve();
302
+ }
303
+
201
304
  _signalingUrl() {
202
305
  let ep = this.endpoint || '';
203
306
  if (!ep.includes('://')) ep = `ws://${ep}`;
204
307
  return `${ep}${ep.includes('?') ? '&' : '?'}token=${this.token}`;
205
308
  }
206
309
 
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();
310
+ /**
311
+ * Голосовой сервер сменился — пересобираем сессию на новом endpoint. Исходящий трек
312
+ * сохраняется, поэтому текущее воспроизведение не прерывается.
313
+ */
314
+ async _migrate() {
315
+ if (this._destroyed) return;
316
+ const migration = ++this._migration;
317
+ this.state = 'connecting';
318
+ this._closeSession();
319
+ try {
320
+ await this._start(migration);
321
+ if (migration !== this._migration || this._destroyed) return;
322
+ this._markReady();
323
+ } catch (error) {
324
+ if (migration !== this._migration || this._destroyed) return;
325
+ this._readyReject(error);
326
+ if (this.listenerCount('error') > 0) this.emit('error', error);
327
+ this.destroy();
328
+ }
329
+ }
217
330
 
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 });
331
+ async _start(migration) {
332
+ const check = () => {
333
+ if (migration !== this._migration || this._destroyed) throw new Error('voice session superseded');
334
+ };
335
+ const signaling = new VoiceSignaling(
336
+ this._signalingUrl(),
337
+ (method, data) => {
338
+ // Уведомления от уже заменённого сигналинга (прежний голосовой сервер) игнорируем —
339
+ // иначе его запоздалый `kicked` уничтожил бы переехавшее соединение.
340
+ if (this._signaling !== signaling) return undefined;
341
+ return this._onNotification(method, data);
342
+ },
343
+ () => {
344
+ if (this._signaling === signaling) this._scheduleKickDestroy();
345
+ },
346
+ );
347
+ this._signaling = signaling;
348
+ await signaling.connect();
349
+ check();
350
+
351
+ const routerRtpCapabilities = await signaling.request('getRouterRtpCapabilities', {});
352
+ check();
353
+ const device = new rtcClient.Device({ handlerName: 'Chrome111' });
354
+ await device.load({ routerRtpCapabilities });
355
+ check();
356
+ this._device = device;
357
+
358
+ await this._createSendTransport(check);
359
+ await this._createRecvTransport(check);
360
+ check();
361
+
362
+ // Постоянный исходящий трек; play() подаёт в него PCM. Создаётся один раз и переживает
363
+ // смену голосового сервера (stopTracks: false — закрытие продюсера трек не останавливает).
364
+ if (!this._audioSource) {
365
+ this._audioSource = new wrtc.nonstandard.RTCAudioSource();
366
+ this._audioTrack = this._audioSource.createTrack();
367
+ }
368
+ this._producer = await this._sendTransport.produce({ track: this._audioTrack, stopTracks: false });
222
369
 
223
- const { producers } = await this._signaling.request('getProducers', {});
370
+ check();
371
+ const { producers } = await signaling.request('getProducers', {});
372
+ check();
224
373
  for (const p of producers) await this._consume(p.producerId, p.userId, p.kind);
225
374
  }
226
375
 
227
- async _createSendTransport() {
376
+ async _createSendTransport(check) {
228
377
  const params = await this._signaling.request('createWebRtcTransport', { direction: 'send' });
378
+ check();
229
379
  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 })
380
+ const signaling = this._signaling;
381
+ const transport = this._sendTransport;
382
+ transport.on('connect', ({ dtlsParameters }, callback, errback) =>
383
+ signaling
384
+ .request('connectTransport', { transportId: transport.id, dtlsParameters })
233
385
  .then(() => callback())
234
386
  .catch(errback),
235
387
  );
236
- this._sendTransport.on('produce', ({ kind, rtpParameters, appData }, callback, errback) =>
237
- this._signaling
238
- .request('produce', { transportId: this._sendTransport.id, kind, rtpParameters, appData })
388
+ transport.on('produce', ({ kind, rtpParameters, appData }, callback, errback) =>
389
+ signaling
390
+ .request('produce', { transportId: transport.id, kind, rtpParameters, appData })
239
391
  .then(({ id }) => callback({ id }))
240
392
  .catch(errback),
241
393
  );
242
394
  }
243
395
 
244
- async _createRecvTransport() {
396
+ async _createRecvTransport(check) {
245
397
  const params = await this._signaling.request('createWebRtcTransport', { direction: 'recv' });
398
+ check();
246
399
  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 })
400
+ const signaling = this._signaling;
401
+ const transport = this._recvTransport;
402
+ transport.on('connect', ({ dtlsParameters }, callback, errback) =>
403
+ signaling
404
+ .request('connectTransport', { transportId: transport.id, dtlsParameters })
250
405
  .then(() => callback())
251
406
  .catch(errback),
252
407
  );
253
408
  }
254
409
 
255
410
  async _consume(producerId, userId, kind) {
256
- if (this._consumers.has(producerId) || !this._recvTransport) return;
411
+ const recv = this._recvTransport;
412
+ const signaling = this._signaling;
413
+ if (kind !== 'audio' || !recv || !signaling || this._consumers.has(producerId)) return;
257
414
  try {
258
- const params = await this._signaling.request('consume', {
259
- transportId: this._recvTransport.id,
415
+ const params = await signaling.request('consume', {
416
+ transportId: recv.id,
260
417
  producerId,
261
418
  rtpCapabilities: this._device.rtpCapabilities,
262
419
  });
263
- const consumer = await this._recvTransport.consume(params);
264
- await this._signaling.request('resumeConsumer', { consumerId: consumer.id });
420
+ if (this._recvTransport !== recv) return;
421
+ const consumer = await recv.consume(params);
422
+ if (this._recvTransport !== recv) return;
423
+ await signaling.request('resumeConsumer', { consumerId: consumer.id });
424
+ if (this._recvTransport !== recv) return;
265
425
  this._consumers.set(producerId, consumer);
266
426
  this.emit('track', consumer.track, userId, producerId);
267
427
  } catch (error) {
268
- this.emit('error', error);
428
+ if (this._recvTransport === recv && this.listenerCount('error') > 0) this.emit('error', error);
269
429
  }
270
430
  }
271
431
 
272
432
  async _onNotification(method, data) {
273
433
  if (method === 'newProducer') {
274
434
  await this._consume(data.producerId, data.userId, data.kind);
275
- } else if (method === 'consumerClosed' || method === 'producerClosed') {
435
+ } else if (method === 'producerClosed') {
276
436
  if (data.producerId) this._consumers.delete(data.producerId);
437
+ } else if (method === 'consumerClosed') {
438
+ for (const [producerId, consumer] of this._consumers) {
439
+ if (consumer.id === data.consumerId) this._consumers.delete(producerId);
440
+ }
277
441
  } else if (method === 'kicked') {
278
- this.destroy();
442
+ this._scheduleKickDestroy();
279
443
  }
280
444
  }
281
445
 
446
+ /**
447
+ * Сервер кикнул нас (или сигналинг оборвался). При перемещении бота в другой канал за киком сразу
448
+ * следует переезд, поэтому уничтожаем соединение только если за grace-период переезда не было.
449
+ */
450
+ _scheduleKickDestroy() {
451
+ if (this._destroyed) return;
452
+ const migration = this._migration;
453
+ clearTimeout(this._kickTimer);
454
+ this._kickTimer = setTimeout(() => {
455
+ this._kickTimer = null;
456
+ if (!this._destroyed && migration === this._migration) this.destroy();
457
+ }, VoiceConnection.kickGraceMs);
458
+ this._kickTimer.unref?.();
459
+ }
460
+
282
461
  /**
283
462
  * Проиграть аудио в канал.
284
463
  * @param {string|import('node:stream').Readable} input Путь к файлу или Readable-поток (любой формат — через ffmpeg).
@@ -369,7 +548,6 @@ class VoiceConnection extends EventEmitter {
369
548
  if (this._destroyed) return;
370
549
  this._destroyed = true;
371
550
  this.state = 'destroyed';
372
- this.stop();
373
551
  try {
374
552
  this._adapter?.sendPayload({
375
553
  op: 4,
@@ -378,7 +556,7 @@ class VoiceConnection extends EventEmitter {
378
556
  } catch {
379
557
  // ignore
380
558
  }
381
- this._cleanup();
559
+ this._finalize();
382
560
  try {
383
561
  this._adapter?.destroy();
384
562
  } catch {
@@ -387,7 +565,25 @@ class VoiceConnection extends EventEmitter {
387
565
  this.emit('destroyed');
388
566
  }
389
567
 
390
- _cleanup() {
568
+ _finalize() {
569
+ clearTimeout(this._kickTimer);
570
+ this._kickTimer = null;
571
+ this.stop();
572
+ this._closeSession();
573
+ try {
574
+ this._audioTrack?.stop();
575
+ } catch {
576
+ // ignore
577
+ }
578
+ this._audioTrack = null;
579
+ this._audioSource = null;
580
+ if (!this._readyAnnounced) this._readyReject(new Error('voice connection destroyed'));
581
+ const byGuild = connections.get(this._owner);
582
+ if (byGuild?.get(this.guildId) === this) byGuild.delete(this.guildId);
583
+ }
584
+
585
+ /** Закрыть сессию с текущим голосовым сервером, не трогая исходящий трек. */
586
+ _closeSession() {
391
587
  this._consumers.clear();
392
588
  for (const transport of [this._sendTransport, this._recvTransport]) {
393
589
  try {
@@ -398,6 +594,7 @@ class VoiceConnection extends EventEmitter {
398
594
  }
399
595
  this._sendTransport = null;
400
596
  this._recvTransport = null;
597
+ this._producer = null;
401
598
  this._signaling?.close();
402
599
  this._signaling = null;
403
600
  }
@@ -414,7 +611,26 @@ class VoiceConnection extends EventEmitter {
414
611
  * @returns {VoiceConnection}
415
612
  */
416
613
  function joinVoiceChannel(options) {
417
- return new VoiceConnection(options);
614
+ const owner = ownerOf(options.adapterCreator);
615
+ let byGuild = connections.get(owner);
616
+ const existing = byGuild?.get(options.guildId);
617
+ if (existing && !existing._destroyed) {
618
+ existing.rejoin({ channelId: options.channelId, selfMute: options.selfMute, selfDeaf: options.selfDeaf });
619
+ return existing;
620
+ }
621
+ const connection = new VoiceConnection(options);
622
+ if (!byGuild) {
623
+ byGuild = new Map();
624
+ connections.set(owner, byGuild);
625
+ }
626
+ byGuild.set(options.guildId, connection);
627
+ return connection;
418
628
  }
419
629
 
630
+ /**
631
+ * How long (ms) the connection survives a kick or a lost signaling socket waiting for a move.
632
+ * @type {number}
633
+ */
634
+ VoiceConnection.kickGraceMs = DEFAULT_KICK_GRACE_MS;
635
+
420
636
  module.exports = { VoiceConnection, joinVoiceChannel };
package/src/index.js CHANGED
@@ -250,6 +250,17 @@ exports.WelcomeChannel = require('./structures/WelcomeChannel');
250
250
  exports.WelcomeScreen = require('./structures/WelcomeScreen');
251
251
 
252
252
  // External
253
+ // Lolka overrides: defined before the star-exports below, which never replace an existing export.
254
+ exports.LolkaCDN = require('./util/LolkaCDN');
255
+ const LolkaConstants = require('./util/LolkaConstants');
256
+ const LolkaLinks = require('./util/LolkaLinks');
257
+
258
+ exports.LolkaCDNBase = LolkaConstants.LolkaCDNBase;
259
+ exports.LolkaWebBase = LolkaConstants.LolkaWebBase;
260
+ exports.LolkaInviteBase = LolkaConstants.LolkaInviteBase;
261
+ exports.LolkaApiBase = LolkaConstants.LolkaApiBase;
262
+ exports.channelLink = LolkaLinks.channelLink;
263
+ exports.messageLink = LolkaLinks.messageLink;
253
264
  __exportStar(require('discord-api-types/v10'), exports);
254
265
  __exportStar(require('@discordjs/builders'), exports);
255
266
  __exportStar(require('@discordjs/formatters'), exports);
@@ -1,11 +1,12 @@
1
1
  'use strict';
2
2
 
3
- const { channelLink, channelMention } = require('@discordjs/formatters');
3
+ const { channelMention } = require('@discordjs/formatters');
4
4
  const { DiscordSnowflake } = require('../util/LolkaSnowflake');
5
5
  const { ChannelType, Routes } = require('discord-api-types/v10');
6
6
  const Base = require('./Base');
7
7
  const ChannelFlagsBitField = require('../util/ChannelFlagsBitField');
8
8
  const { ThreadChannelTypes } = require('../util/Constants');
9
+ const { channelLink } = require('../util/LolkaLinks');
9
10
 
10
11
  /**
11
12
  * Represents any channel on Discord.
@@ -64,7 +64,7 @@ class Emoji extends Base {
64
64
  deprecationEmittedForURL = true;
65
65
  }
66
66
 
67
- return this.imageURL({ extension: this.animated ? 'gif' : 'png' });
67
+ return this.imageURL();
68
68
  }
69
69
 
70
70
  /**
@@ -1457,7 +1457,7 @@ class Guild extends AnonymousGuild {
1457
1457
  * @readonly
1458
1458
  */
1459
1459
  get voiceAdapterCreator() {
1460
- return methods => {
1460
+ const creator = methods => {
1461
1461
  this.client.voice.adapters.set(this.id, methods);
1462
1462
  return {
1463
1463
  sendPayload: data => {
@@ -1466,10 +1466,13 @@ class Guild extends AnonymousGuild {
1466
1466
  return true;
1467
1467
  },
1468
1468
  destroy: () => {
1469
- this.client.voice.adapters.delete(this.id);
1469
+ if (this.client.voice.adapters.get(this.id) === methods) this.client.voice.adapters.delete(this.id);
1470
1470
  },
1471
1471
  };
1472
1472
  };
1473
+ // Метка владельца: voice-соединения разных клиентов в одной гильдии не пересекаются.
1474
+ creator.voiceManager = this.client.voice;
1475
+ return creator;
1473
1476
  }
1474
1477
 
1475
1478
  /**
@@ -137,8 +137,10 @@ class GuildMember extends Base {
137
137
  asset: data.avatar_decoration_data.asset,
138
138
  skuId: data.avatar_decoration_data.sku_id,
139
139
  };
140
- } else {
140
+ } else if ('avatar_decoration_data' in data) {
141
141
  this.avatarDecorationData = null;
142
+ } else {
143
+ this.avatarDecorationData ??= null;
142
144
  }
143
145
  }
144
146
 
@@ -1,9 +1,10 @@
1
1
  'use strict';
2
2
 
3
3
  const { DiscordSnowflake } = require('../util/LolkaSnowflake');
4
- const { GuildScheduledEventStatus, GuildScheduledEventEntityType, RouteBases } = require('discord-api-types/v10');
4
+ const { GuildScheduledEventStatus, GuildScheduledEventEntityType } = require('discord-api-types/v10');
5
5
  const Base = require('./Base');
6
6
  const { DiscordjsError, ErrorCodes } = require('../errors');
7
+ const { resolveInviteBase, resolveWebBase } = require('../util/LolkaConstants');
7
8
 
8
9
  /**
9
10
  * Represents a scheduled event in a {@link Guild}.
@@ -321,12 +322,12 @@ class GuildScheduledEvent extends Base {
321
322
  }
322
323
 
323
324
  /**
324
- * The URL to the guild scheduled event
325
+ * The URL to the guild scheduled event. Lolka has no page for events, so this is the URL of the guild
325
326
  * @type {string}
326
327
  * @readonly
327
328
  */
328
329
  get url() {
329
- return `${RouteBases.scheduledEvent}/${this.guildId}/${this.id}`;
330
+ return `${resolveWebBase()}/servers/${this.guildId}`;
330
331
  }
331
332
 
332
333
  /**
@@ -350,7 +351,7 @@ class GuildScheduledEvent extends Base {
350
351
  if (!channelId) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
351
352
  }
352
353
  const invite = await this.guild.invites.create(channelId, options);
353
- return `${RouteBases.invite}/${invite.code}?event=${this.id}`;
354
+ return `${resolveInviteBase()}/${invite.code}?event=${this.id}`;
354
355
  }
355
356
 
356
357
  /**
@@ -1,12 +1,22 @@
1
1
  'use strict';
2
2
 
3
- const { RouteBases, Routes, PermissionFlagsBits } = require('discord-api-types/v10');
3
+ const { Routes, PermissionFlagsBits } = require('discord-api-types/v10');
4
4
  const Base = require('./Base');
5
5
  const { GuildScheduledEvent } = require('./GuildScheduledEvent');
6
6
  const IntegrationApplication = require('./IntegrationApplication');
7
7
  const InviteStageInstance = require('./InviteStageInstance');
8
8
  const { DiscordjsError, ErrorCodes } = require('../errors');
9
9
  const { InviteFlagsBitField } = require('../util/InviteFlagsBitField.js');
10
+ const { resolveInviteBase } = require('../util/LolkaConstants');
11
+
12
+ const escapeRegExp = text => text.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');
13
+
14
+ function buildInvitesPattern() {
15
+ const hosts = ['lolka.gg', 'lolka.app/i'];
16
+ const custom = resolveInviteBase().replace(/^https?:\/\//i, '');
17
+ if (custom && !hosts.includes(custom.toLowerCase())) hosts.push(custom);
18
+ return new RegExp(`(?<![\\w.-])(?:www\\.)?(?:${hosts.map(escapeRegExp).join('|')})\\/(?<code>[\\w-]{2,255})`, 'i');
19
+ }
10
20
 
11
21
  /**
12
22
  * Represents an invitation to a guild channel.
@@ -14,12 +24,12 @@ const { InviteFlagsBitField } = require('../util/InviteFlagsBitField.js');
14
24
  */
15
25
  class Invite extends Base {
16
26
  /**
17
- * A regular expression that matches Discord invite links.
27
+ * A regular expression that matches Lolka invite links (`lolka.gg/{code}`, `lolka.app/i/{code}` and the host from `LOLKA_INVITE`).
18
28
  * The `code` group property is present on the `exec()` result of this expression.
19
29
  * @type {RegExp}
20
30
  * @memberof Invite
21
31
  */
22
- static InvitesPattern = /discord(?:(?:app)?\.com\/invite|\.gg(?:\/invite)?)\/(?<code>[\w-]{2,255})/i;
32
+ static InvitesPattern = buildInvitesPattern();
23
33
 
24
34
  constructor(client, data) {
25
35
  super(client);
@@ -296,7 +306,7 @@ class Invite extends Base {
296
306
  * @readonly
297
307
  */
298
308
  get url() {
299
- return `${RouteBases.invite}/${this.code}`;
309
+ return `${resolveInviteBase()}/${this.code}`;
300
310
  }
301
311
 
302
312
  /**
@@ -313,7 +323,7 @@ class Invite extends Base {
313
323
  * When concatenated with a string, this automatically concatenates the invite's URL instead of the object.
314
324
  * @returns {string}
315
325
  * @example
316
- * // Logs: Invite: https://discord.gg/A1b2C3
326
+ * // Logs: Invite: https://lolka.gg/A1b2C3
317
327
  * console.log(`Invite: ${invite}`);
318
328
  */
319
329
  toString() {
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { Collection } = require('@discordjs/collection');
4
- const { messageLink } = require('@discordjs/formatters');
4
+ const { messageLink } = require('../util/LolkaLinks');
5
5
  const { DiscordSnowflake } = require('../util/LolkaSnowflake');
6
6
  const {
7
7
  InteractionType,
@@ -340,11 +340,12 @@ class RichPresenceAssets {
340
340
  */
341
341
  smallImageURL(options = {}) {
342
342
  if (!this.smallImage) return null;
343
+ if (/^https?:\/\//.test(this.smallImage)) return this.smallImage;
343
344
  if (this.smallImage.includes(':')) {
344
345
  const [platform, id] = this.smallImage.split(':');
345
346
  switch (platform) {
346
347
  case 'mp':
347
- return `https://media.discordapp.net/${id}`;
348
+ return `${this.activity.presence.client.rest.cdn.mediaProxy}/${id}`;
348
349
  default:
349
350
  return null;
350
351
  }
@@ -360,11 +361,12 @@ class RichPresenceAssets {
360
361
  */
361
362
  largeImageURL(options = {}) {
362
363
  if (!this.largeImage) return null;
364
+ if (/^https?:\/\//.test(this.largeImage)) return this.largeImage;
363
365
  if (this.largeImage.includes(':')) {
364
366
  const [platform, id] = this.largeImage.split(':');
365
367
  switch (platform) {
366
368
  case 'mp':
367
- return `https://media.discordapp.net/${id}`;
369
+ return `${this.activity.presence.client.rest.cdn.mediaProxy}/${id}`;
368
370
  case 'spotify':
369
371
  return `https://i.scdn.co/image/${id}`;
370
372
  case 'youtube':
@@ -72,7 +72,7 @@ class Role extends Base {
72
72
  * These values are available as a constant: `Constants.HolographicStyle`
73
73
  */
74
74
 
75
- if ('colors' in data) {
75
+ if (data.colors) {
76
76
  /**
77
77
  * The colors of the role
78
78
  *
@@ -83,6 +83,12 @@ class Role extends Base {
83
83
  secondaryColor: data.colors.secondary_color,
84
84
  tertiaryColor: data.colors.tertiary_color,
85
85
  };
86
+ } else if ('color' in data || !this.colors) {
87
+ this.colors = {
88
+ primaryColor: data.color ?? this.color ?? 0,
89
+ secondaryColor: null,
90
+ tertiaryColor: null,
91
+ };
86
92
  }
87
93
 
88
94
  if ('hoist' in data) {
@@ -272,8 +272,7 @@ class User extends Base {
272
272
  get defaultAvatarURL() {
273
273
  // Lolka: свои дефолтные аватарки system/avatars/{0..5}.jpg вместо Discord embed/avatars.
274
274
  // Индекс по FNV-1a от id (как в веб/мобильном клиенте), чтобы дефолт совпадал во всех клиентах.
275
- const base = process.env.LOLKA_CDN ?? 'https://cdn.lolka.app';
276
- return `${base}/system/avatars/${lolkaDefaultAvatarIndex(this.id)}.jpg`;
275
+ return this.client.rest.cdn.defaultAvatar(lolkaDefaultAvatarIndex(this.id));
277
276
  }
278
277
 
279
278
  /**
@@ -423,7 +423,7 @@ class Webhook {
423
423
  * @readonly
424
424
  */
425
425
  get url() {
426
- return this.client.options.rest.api + Routes.webhook(this.id, this.token);
426
+ return `${new URL(this.client.options.rest.api).origin}/api${Routes.webhook(this.id, this.token)}`;
427
427
  }
428
428
 
429
429
  /**
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+
3
+ const { CDN } = require('@discordjs/rest');
4
+ const { resolveCdnBase } = require('./LolkaConstants');
5
+
6
+ const URL_PATTERN = /^https?:\/\//;
7
+
8
+ /**
9
+ * CDN URL builder for Lolka. Lolka returns full URLs or storage keys (`avatars/{uid}/{uuid}.webp`) for assets,
10
+ * the CDN does no resizing and serves only webp, so `size`, `extension` and `forceStatic` options are ignored
11
+ * for such values.
12
+ * @extends {CDN}
13
+ */
14
+ class LolkaCDN extends CDN {
15
+ constructor(cdn, mediaProxy) {
16
+ const base = String(cdn ?? resolveCdnBase()).replace(/\/+$/, '');
17
+ super(base, String(mediaProxy ?? base).replace(/\/+$/, ''));
18
+ }
19
+
20
+ /**
21
+ * Resolves a Lolka asset value (full URL, storage key) into a URL.
22
+ * @param {*} value The asset value
23
+ * @returns {?string} The URL, or null if the value is a legacy hash that needs a route
24
+ * @private
25
+ */
26
+ resolveAsset(value) {
27
+ if (typeof value !== 'string') return null;
28
+ if (URL_PATTERN.test(value)) return value;
29
+ if (value.includes('/')) return `${this.cdn}/${value.replace(/^\/+/, '')}`;
30
+ return null;
31
+ }
32
+
33
+ appAsset(clientId, assetHash, options) {
34
+ return this.resolveAsset(assetHash) ?? super.appAsset(clientId, assetHash, options);
35
+ }
36
+
37
+ appIcon(clientId, iconHash, options) {
38
+ return this.resolveAsset(iconHash) ?? super.appIcon(clientId, iconHash, options);
39
+ }
40
+
41
+ avatar(id, avatarHash, options) {
42
+ return this.resolveAsset(avatarHash) ?? super.avatar(id, avatarHash, options);
43
+ }
44
+
45
+ avatarDecoration(userIdOrAsset, userAvatarDecoration, options) {
46
+ if (userAvatarDecoration) {
47
+ return this.resolveAsset(userAvatarDecoration) ?? super.avatarDecoration(userIdOrAsset, userAvatarDecoration, options);
48
+ }
49
+ return this.resolveAsset(userIdOrAsset) ?? super.avatarDecoration(userIdOrAsset);
50
+ }
51
+
52
+ banner(id, bannerHash, options) {
53
+ return this.resolveAsset(bannerHash) ?? super.banner(id, bannerHash, options);
54
+ }
55
+
56
+ channelIcon(channelId, iconHash, options) {
57
+ return this.resolveAsset(iconHash) ?? super.channelIcon(channelId, iconHash, options);
58
+ }
59
+
60
+ defaultAvatar(index) {
61
+ return `${this.cdn}/system/avatars/${index}.jpg`;
62
+ }
63
+
64
+ discoverySplash(guildId, splashHash, options) {
65
+ return this.resolveAsset(splashHash) ?? super.discoverySplash(guildId, splashHash, options);
66
+ }
67
+
68
+ emoji(emojiId) {
69
+ return `${this.cdn}/emojis/${emojiId}.webp`;
70
+ }
71
+
72
+ guildMemberAvatar(guildId, userId, avatarHash, options) {
73
+ return this.resolveAsset(avatarHash) ?? super.guildMemberAvatar(guildId, userId, avatarHash, options);
74
+ }
75
+
76
+ guildMemberBanner(guildId, userId, bannerHash, options) {
77
+ return this.resolveAsset(bannerHash) ?? super.guildMemberBanner(guildId, userId, bannerHash, options);
78
+ }
79
+
80
+ icon(id, iconHash, options) {
81
+ return this.resolveAsset(iconHash) ?? super.icon(id, iconHash, options);
82
+ }
83
+
84
+ roleIcon(roleId, roleIconHash, options) {
85
+ return this.resolveAsset(roleIconHash) ?? super.roleIcon(roleId, roleIconHash, options);
86
+ }
87
+
88
+ splash(guildId, splashHash, options) {
89
+ return this.resolveAsset(splashHash) ?? super.splash(guildId, splashHash, options);
90
+ }
91
+
92
+ stickerPackBanner(bannerId, options) {
93
+ return this.resolveAsset(bannerId) ?? super.stickerPackBanner(bannerId, options);
94
+ }
95
+
96
+ teamIcon(teamId, iconHash, options) {
97
+ return this.resolveAsset(iconHash) ?? super.teamIcon(teamId, iconHash, options);
98
+ }
99
+
100
+ guildScheduledEventCover(scheduledEventId, coverHash, options) {
101
+ return this.resolveAsset(coverHash) ?? super.guildScheduledEventCover(scheduledEventId, coverHash, options);
102
+ }
103
+
104
+ soundboardSound(soundId) {
105
+ return `${this.cdn}/soundboard/${soundId}.ogg`;
106
+ }
107
+
108
+ guildTagBadge(guildId, badgeHash, options) {
109
+ return this.resolveAsset(badgeHash) ?? super.guildTagBadge(guildId, badgeHash, options);
110
+ }
111
+ }
112
+
113
+ module.exports = LolkaCDN;
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+
3
+ const resolveBase = (name, fallback) => {
4
+ const value = process.env[name]?.trim();
5
+ return (value || fallback).replace(/\/+$/, '');
6
+ };
7
+
8
+ /**
9
+ * Resolves the Lolka CDN base URL (no trailing slash) from `LOLKA_CDN` at call time.
10
+ * @returns {string}
11
+ */
12
+ const resolveCdnBase = () => resolveBase('LOLKA_CDN', 'https://cdn.lolka.app');
13
+
14
+ /**
15
+ * Resolves the Lolka web client base URL (no trailing slash) from `LOLKA_WEB` at call time.
16
+ * @returns {string}
17
+ */
18
+ const resolveWebBase = () => resolveBase('LOLKA_WEB', 'https://lolka.app');
19
+
20
+ /**
21
+ * Resolves the Lolka invite links base URL (no trailing slash) from `LOLKA_INVITE` at call time.
22
+ * @returns {string}
23
+ */
24
+ const resolveInviteBase = () => resolveBase('LOLKA_INVITE', 'https://lolka.gg');
25
+
26
+ /**
27
+ * Resolves the Lolka bot API base URL (no trailing slash) from `LOLKA_API_BASE` at call time.
28
+ * @returns {string}
29
+ */
30
+ const resolveApiBase = () => resolveBase('LOLKA_API_BASE', 'https://lolka.app/api/bot');
31
+
32
+ module.exports = {
33
+ resolveCdnBase,
34
+ resolveWebBase,
35
+ resolveInviteBase,
36
+ resolveApiBase,
37
+ // Snapshots taken when the module is first loaded, kept for the public exports.
38
+ LolkaCDNBase: resolveCdnBase(),
39
+ LolkaWebBase: resolveWebBase(),
40
+ LolkaInviteBase: resolveInviteBase(),
41
+ LolkaApiBase: resolveApiBase(),
42
+ };
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ const { resolveWebBase } = require('./LolkaConstants');
4
+
5
+ /**
6
+ * Formats a channel link for a channel.
7
+ * @param {string} channelId The id of the channel
8
+ * @param {string} [guildId] The id of the guild; DM-like channels (no guild or `@me`) use `/me/channels`
9
+ * @returns {string}
10
+ */
11
+ function channelLink(channelId, guildId) {
12
+ const base = resolveWebBase();
13
+ return !guildId || guildId === '@me'
14
+ ? `${base}/me/channels/${channelId}`
15
+ : `${base}/servers/${guildId}/channels/${channelId}`;
16
+ }
17
+
18
+ /**
19
+ * Formats a message link for a channel.
20
+ * @param {string} channelId The id of the channel
21
+ * @param {string} messageId The id of the message
22
+ * @param {string} [guildId] The id of the guild; DM-like channels (no guild or `@me`) use `/me/channels`
23
+ * @returns {string}
24
+ */
25
+ function messageLink(channelId, messageId, guildId) {
26
+ return `${channelLink(channelId, guildId)}/${messageId}`;
27
+ }
28
+
29
+ module.exports = { channelLink, messageLink };
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { DefaultRestOptions, DefaultUserAgentAppendix } = require('@discordjs/rest');
4
+ const { resolveApiBase, resolveCdnBase } = require('./LolkaConstants');
4
5
  const { toSnakeCase } = require('./Transformers');
5
6
  const { version } = require('../../package.json');
6
7
 
@@ -130,7 +131,9 @@ class Options extends null {
130
131
  // lolka: по умолчанию ходим в lolka bot API (база без версии; либа добавит /v{N}).
131
132
  // Переопределяется переменной окружения LOLKA_API_BASE. Gateway-URL бот узнаёт
132
133
  // автоматически через GET /gateway/bot, поэтому отдельный оверрайд не нужен.
133
- api: process.env.LOLKA_API_BASE ?? 'https://lolka.app/api/bot',
134
+ api: resolveApiBase(),
135
+ cdn: resolveCdnBase(),
136
+ mediaProxy: resolveCdnBase(),
134
137
  userAgentAppendix: this.userAgentAppendix,
135
138
  },
136
139
  jsonTransformer: toSnakeCase,
package/src/util/Util.js CHANGED
@@ -3,9 +3,10 @@
3
3
  const { parse } = require('node:path');
4
4
  const process = require('node:process');
5
5
  const { Collection } = require('@discordjs/collection');
6
- const { ChannelType, RouteBases, Routes } = require('discord-api-types/v10');
6
+ const { ChannelType, Routes } = require('discord-api-types/v10');
7
7
  const { fetch } = require('undici');
8
8
  const Colors = require('./Colors');
9
+ const { resolveApiBase } = require('./LolkaConstants');
9
10
  const { DiscordjsError, DiscordjsRangeError, DiscordjsTypeError, ErrorCodes } = require('../errors');
10
11
  const isObject = d => typeof d === 'object' && d !== null;
11
12
 
@@ -61,17 +62,18 @@ function flatten(obj, ...props) {
61
62
  * @typedef {Object} FetchRecommendedShardCountOptions
62
63
  * @property {number} [guildsPerShard=1000] Number of guilds assigned per shard
63
64
  * @property {number} [multipleOf=1] The multiple the shard count should round up to. (16 for large bot sharding)
65
+ * @property {string} [api] Base URL of the Lolka bot API (defaults to `LOLKA_API_BASE` or the public bot API)
64
66
  */
65
67
 
66
68
  /**
67
- * Gets the recommended shard count from Discord.
69
+ * Gets the recommended shard count from Lolka.
68
70
  * @param {string} token Discord auth token
69
71
  * @param {FetchRecommendedShardCountOptions} [options] Options for fetching the recommended shard count
70
72
  * @returns {Promise<number>} The recommended number of shards
71
73
  */
72
- async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multipleOf = 1 } = {}) {
74
+ async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multipleOf = 1, api = resolveApiBase() } = {}) {
73
75
  if (!token) throw new DiscordjsError(ErrorCodes.TokenMissing);
74
- const response = await fetch(RouteBases.api + Routes.gatewayBot(), {
76
+ const response = await fetch(`${api.replace(/\/+$/, '')}/v10${Routes.gatewayBot()}`, {
75
77
  method: 'GET',
76
78
  headers: { Authorization: `Bot ${token.replace(/^Bot\s*/i, '')}` },
77
79
  });
@@ -410,14 +412,26 @@ function cleanCodeBlockContent(text) {
410
412
  * @returns {?WebhookClientDataIdWithToken} `null` if the URL is invalid, otherwise the id and the token
411
413
  */
412
414
  function parseWebhookURL(url) {
415
+ const parsed = parseWebhookURLWithOrigin(url);
416
+ return parsed && { id: parsed.id, token: parsed.token };
417
+ }
418
+
419
+ /**
420
+ * Parses a webhook URL for the id, token and origin.
421
+ * @param {string} url The URL to parse
422
+ * @returns {?{id: string, token: string, origin: string}} `null` if the URL is invalid
423
+ * @private
424
+ */
425
+ function parseWebhookURLWithOrigin(url) {
413
426
  const matches = url.match(
414
- /https?:\/\/(?:ptb\.|canary\.)?discord\.com\/api(?:\/v\d{1,2})?\/webhooks\/(\d{17,19})\/([\w-]{68})/i,
427
+ /(https?:\/\/[^/\s]+)\/api(?:\/bot)?(?:\/v\d{1,2})?\/webhooks\/(\d+)\/([\w.-]+)/i,
415
428
  );
416
429
 
417
- if (!matches || matches.length <= 2) return null;
430
+ if (!matches) return null;
418
431
 
419
- const [, id, token] = matches;
432
+ const [, origin, id, token] = matches;
420
433
  return {
434
+ origin,
421
435
  id,
422
436
  token,
423
437
  };
@@ -546,6 +560,7 @@ module.exports = {
546
560
  cleanContent,
547
561
  cleanCodeBlockContent,
548
562
  parseWebhookURL,
563
+ parseWebhookURLWithOrigin,
549
564
  transformResolved,
550
565
  resolveSKUId,
551
566
  emitDeprecationWarningForUserFetchFlags,
@@ -45,6 +45,7 @@ import {
45
45
  REST,
46
46
  RESTOptions,
47
47
  ImageSize,
48
+ CDN,
48
49
  } from '@discordjs/rest';
49
50
  import {
50
51
  WebSocketManager as WSWebSocketManager,
@@ -3606,6 +3607,7 @@ export class ShardingManager extends EventEmitter {
3606
3607
  export interface FetchRecommendedShardCountOptions {
3607
3608
  guildsPerShard?: number;
3608
3609
  multipleOf?: number;
3610
+ api?: string;
3609
3611
  }
3610
3612
 
3611
3613
  export interface SnowflakeGenerateOptions {
@@ -8134,9 +8136,16 @@ export interface VoiceConnectionOptions {
8134
8136
  selfDeaf?: boolean;
8135
8137
  }
8136
8138
 
8139
+ export interface VoiceConnectionRejoinOptions {
8140
+ channelId?: string;
8141
+ selfMute?: boolean;
8142
+ selfDeaf?: boolean;
8143
+ }
8144
+
8137
8145
  export type VoiceConnectionState = 'connecting' | 'ready' | 'error' | 'destroyed';
8138
8146
 
8139
8147
  export class VoiceConnection extends EventEmitter {
8148
+ public static kickGraceMs: number;
8140
8149
  private constructor(options: VoiceConnectionOptions);
8141
8150
  public channelId: string;
8142
8151
  public guildId: string;
@@ -8145,6 +8154,7 @@ export class VoiceConnection extends EventEmitter {
8145
8154
  public token: string | null;
8146
8155
  public endpoint: string | null;
8147
8156
  public awaitReady(timeout?: number): Promise<void>;
8157
+ public rejoin(options?: VoiceConnectionRejoinOptions): boolean;
8148
8158
  public play(input: string | NodeJS.ReadableStream): void;
8149
8159
  public stop(): void;
8150
8160
  public destroy(): void;
@@ -8160,6 +8170,17 @@ export function joinVoiceChannel(options: VoiceConnectionOptions): VoiceConnecti
8160
8170
 
8161
8171
  //#endregion
8162
8172
 
8173
+ // Lolka
8174
+ export class LolkaCDN extends CDN {
8175
+ public constructor(cdn?: string, mediaProxy?: string);
8176
+ }
8177
+ export const LolkaCDNBase: string;
8178
+ export const LolkaWebBase: string;
8179
+ export const LolkaInviteBase: string;
8180
+ export const LolkaApiBase: string;
8181
+ export function channelLink(channelId: Snowflake, guildId?: Snowflake | '@me'): string;
8182
+ export function messageLink(channelId: Snowflake, messageId: Snowflake, guildId?: Snowflake | '@me'): string;
8183
+
8163
8184
  // External
8164
8185
  export * from 'discord-api-types/v10';
8165
8186
  export * from '@discordjs/builders';
@@ -45,6 +45,7 @@ import {
45
45
  REST,
46
46
  RESTOptions,
47
47
  ImageSize,
48
+ CDN,
48
49
  } from '@discordjs/rest';
49
50
  import {
50
51
  WebSocketManager as WSWebSocketManager,
@@ -3606,6 +3607,7 @@ export class ShardingManager extends EventEmitter {
3606
3607
  export interface FetchRecommendedShardCountOptions {
3607
3608
  guildsPerShard?: number;
3608
3609
  multipleOf?: number;
3610
+ api?: string;
3609
3611
  }
3610
3612
 
3611
3613
  export interface SnowflakeGenerateOptions {
@@ -8134,9 +8136,16 @@ export interface VoiceConnectionOptions {
8134
8136
  selfDeaf?: boolean;
8135
8137
  }
8136
8138
 
8139
+ export interface VoiceConnectionRejoinOptions {
8140
+ channelId?: string;
8141
+ selfMute?: boolean;
8142
+ selfDeaf?: boolean;
8143
+ }
8144
+
8137
8145
  export type VoiceConnectionState = 'connecting' | 'ready' | 'error' | 'destroyed';
8138
8146
 
8139
8147
  export class VoiceConnection extends EventEmitter {
8148
+ public static kickGraceMs: number;
8140
8149
  private constructor(options: VoiceConnectionOptions);
8141
8150
  public channelId: string;
8142
8151
  public guildId: string;
@@ -8145,6 +8154,7 @@ export class VoiceConnection extends EventEmitter {
8145
8154
  public token: string | null;
8146
8155
  public endpoint: string | null;
8147
8156
  public awaitReady(timeout?: number): Promise<void>;
8157
+ public rejoin(options?: VoiceConnectionRejoinOptions): boolean;
8148
8158
  public play(input: string | NodeJS.ReadableStream): void;
8149
8159
  public stop(): void;
8150
8160
  public destroy(): void;
@@ -8160,6 +8170,17 @@ export function joinVoiceChannel(options: VoiceConnectionOptions): VoiceConnecti
8160
8170
 
8161
8171
  //#endregion
8162
8172
 
8173
+ // Lolka
8174
+ export class LolkaCDN extends CDN {
8175
+ public constructor(cdn?: string, mediaProxy?: string);
8176
+ }
8177
+ export const LolkaCDNBase: string;
8178
+ export const LolkaWebBase: string;
8179
+ export const LolkaInviteBase: string;
8180
+ export const LolkaApiBase: string;
8181
+ export function channelLink(channelId: Snowflake, guildId?: Snowflake | '@me'): string;
8182
+ export function messageLink(channelId: Snowflake, messageId: Snowflake, guildId?: Snowflake | '@me'): string;
8183
+
8163
8184
  // External
8164
8185
  export * from 'discord-api-types/v10';
8165
8186
  export * from '@discordjs/builders';