lolka.js 0.4.1 → 0.4.3

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/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.3",
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
  }
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
  /**
@@ -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 {
@@ -8160,6 +8162,17 @@ export function joinVoiceChannel(options: VoiceConnectionOptions): VoiceConnecti
8160
8162
 
8161
8163
  //#endregion
8162
8164
 
8165
+ // Lolka
8166
+ export class LolkaCDN extends CDN {
8167
+ public constructor(cdn?: string, mediaProxy?: string);
8168
+ }
8169
+ export const LolkaCDNBase: string;
8170
+ export const LolkaWebBase: string;
8171
+ export const LolkaInviteBase: string;
8172
+ export const LolkaApiBase: string;
8173
+ export function channelLink(channelId: Snowflake, guildId?: Snowflake | '@me'): string;
8174
+ export function messageLink(channelId: Snowflake, messageId: Snowflake, guildId?: Snowflake | '@me'): string;
8175
+
8163
8176
  // External
8164
8177
  export * from 'discord-api-types/v10';
8165
8178
  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 {
@@ -8160,6 +8162,17 @@ export function joinVoiceChannel(options: VoiceConnectionOptions): VoiceConnecti
8160
8162
 
8161
8163
  //#endregion
8162
8164
 
8165
+ // Lolka
8166
+ export class LolkaCDN extends CDN {
8167
+ public constructor(cdn?: string, mediaProxy?: string);
8168
+ }
8169
+ export const LolkaCDNBase: string;
8170
+ export const LolkaWebBase: string;
8171
+ export const LolkaInviteBase: string;
8172
+ export const LolkaApiBase: string;
8173
+ export function channelLink(channelId: Snowflake, guildId?: Snowflake | '@me'): string;
8174
+ export function messageLink(channelId: Snowflake, messageId: Snowflake, guildId?: Snowflake | '@me'): string;
8175
+
8163
8176
  // External
8164
8177
  export * from 'discord-api-types/v10';
8165
8178
  export * from '@discordjs/builders';