Skip to content

Commit

Permalink
feat(FetchRecommendedShardsOptions): account for large bot sharding (#…
Browse files Browse the repository at this point in the history
…6184)

Co-authored-by: Justin <justinleeong@gmail.com>
  • Loading branch information
scottbucher and J-Human committed Jul 29, 2021
1 parent 4f1f32f commit 19b242a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
12 changes: 9 additions & 3 deletions src/util/Util.js
Expand Up @@ -254,13 +254,19 @@ class Util extends null {
return text.replace(/\|\|/g, '\\|\\|');
}

/**
* @typedef {Object} FetchRecommendedShardsOptions
* @property {number} [guildsPerShard=1000] Number of guilds assigned per shard
* @property {number} [multipleOf=1] The multiple the shard count should round up to. (16 for large bot sharding)
*/

/**
* Gets the recommended shard count from Discord.
* @param {string} token Discord auth token
* @param {number} [guildsPerShard=1000] Number of guilds per shard
* @param {FetchRecommendedShardsOptions} [options] Options for fetching the recommended shard count
* @returns {Promise<number>} The recommended number of shards
*/
static fetchRecommendedShards(token, guildsPerShard = 1000) {
static fetchRecommendedShards(token, { guildsPerShard = 1000, multipleOf = 1 } = {}) {
if (!token) throw new DiscordError('TOKEN_MISSING');
const defaults = Options.createDefault();
return fetch(`${defaults.http.api}/v${defaults.http.version}${Endpoints.botGateway}`, {
Expand All @@ -272,7 +278,7 @@ class Util extends null {
if (res.status === 401) throw new DiscordError('TOKEN_INVALID');
throw res;
})
.then(data => data.shards * (1000 / guildsPerShard));
.then(data => Math.ceil((data.shards * (1000 / guildsPerShard)) / multipleOf) * multipleOf);
}

/**
Expand Down
7 changes: 6 additions & 1 deletion typings/index.d.ts
Expand Up @@ -1535,6 +1535,11 @@ export class ShardingManager extends EventEmitter {
public once(event: 'shardCreate', listener: (shard: Shard) => Awaited<void>): this;
}

export interface FetchRecommendedShardsOptions {
guildsPerShard?: number;
multipleOf?: number;
}

export class SnowflakeUtil extends null {
private constructor();
public static deconstruct(snowflake: Snowflake): DeconstructedSnowflake;
Expand Down Expand Up @@ -1795,7 +1800,7 @@ export class Util extends null {
public static escapeStrikethrough(text: string): string;
public static escapeSpoiler(text: string): string;
public static cleanCodeBlockContent(text: string): string;
public static fetchRecommendedShards(token: string, guildsPerShard?: number): Promise<number>;
public static fetchRecommendedShards(token: string, options?: FetchRecommendedShardsOptions): Promise<number>;
public static flatten(obj: unknown, ...props: Record<string, boolean | string>[]): unknown;
public static idToBinary(num: Snowflake): string;
public static makeError(obj: MakeErrorOptions): Error;
Expand Down

0 comments on commit 19b242a

Please sign in to comment.