diff --git a/lib/Client.js b/lib/Client.js index 496d81cb9..09279da3d 100644 --- a/lib/Client.js +++ b/lib/Client.js @@ -73,7 +73,7 @@ class Client extends EventEmitter { * @arg {Number} [options.guildCreateTimeout=2000] How long in milliseconds to wait for a GUILD_CREATE before "ready" is fired. Increase this value if you notice missing guilds * @arg {Number} [options.largeThreshold=250] The maximum number of offline users per guild during initial guild data transmission * @arg {Number} [options.lastShardID=options.maxShards - 1] The ID of the last shard to run for this client - * @arg {Number} [options.maxShards=1] The total number of shards you want to run + * @arg {Number|String} [options.maxShards=1] The total number of shards you want to run. If "auto" Eris will use Discord's recommended shard count. * @arg {Number} [options.messageLimit=100] The maximum size of a channel message cache * @arg {Boolean} [options.opusOnly=false] Whether to suppress the node-opus not found error or not * @arg {Boolean} [options.restMode=false] Whether to enable getting objects over REST. This should only be enabled if you are not connecting to the gateway. Bot tokens must be prefixed manually in REST mode @@ -110,7 +110,7 @@ class Client extends EventEmitter { this.options[property] = options[property]; } } - if(this.options.lastShardID === undefined) { + if(this.options.lastShardID === undefined && this.options.maxShards !== "auto") { this.options.lastShardID = this.options.maxShards - 1; } if(typeof window !== "undefined") { @@ -166,8 +166,10 @@ class Client extends EventEmitter { * @returns {Promise} Resolves when all shards are initialized */ connect() { - return this.getGateway().then((data) => { - if(!data.url) { + const gatewayPromise = this.options.maxShards === "auto" ? this.getBotGateway() : this.getGateway(); + + return gatewayPromise.then((data) => { + if(!data.url || (this.options.maxShards === "auto" && !data.shards)) { return Promise.reject(new Error("Invalid response from gateway REST call")); } if(data.url.includes("?")) { @@ -177,6 +179,17 @@ class Client extends EventEmitter { data.url += "/"; } this.gatewayURL = data.url + "?v=" + Constants.GATEWAY_VERSION + "&encoding=" + (Erlpack ? "etf" : "json"); + + if (this.options.maxShards === "auto") { + if (!data.shards) { + return Promise.reject(new Error("Failed to autoshard due to lack of data from Discord.")); + } + this.options.maxShards = data.shards; + if(this.options.lastShardID === undefined) { + this.options.lastShardID = data.shards - 1; + } + } + for(var i = this.options.firstShardID; i <= this.options.lastShardID; ++i) { this.shards.spawn(i); }