A Guide to Discord Bots

Sharding

Definition

Sharding is basically a form of multi-threading: as your bot joins more and more servers, it can become quite slow, so we split it into multiple process (shards) to be faster.
This will increase memory usage, but also increase your bot's performances.

Each shard has a different set of guilds, and will only get events from guilds that are present in their set.
To calculate what events will be sent to what shard, the following formula can be used:
(guild_id >> 22) % num_shards == shard_id

Use Cases

For bots which are in more than 2.500 servers. If your bot is near this limit, you should add sharding to it.
Note: this is obligatory and Discord will shut down your bot if you don't add sharding when your bot is in more than 2.500 servers!
If it is in 100.000 servers or more, there are additional considerations you might need to take; Discord will contact you if it is needed.

Sharding Your Bot

You could theoretically have 2.500 guilds/shard.
However, you might want to put the count to 1.500 g/s or 1.000 g/s.

To know how many shards to use: guildCount / desiredGps = shardCount.
guildCount: number of guilds your bot is in desiredGps: your desired number of guilds/shard

If your bot is in 2500 guilds (servers), and you want 1.500 g/s: 2500 / 1000 = 2.5 You would use 3 shards (2 < 2.5).

Put the following code into its own file, and run this file instead of your original one (which is 'index.js' for me).

// sharding.js
const Discord = require('discord.js');
const Manager = new Discord.ShardingManager('./index.js');

Manager.spawn(3);
Manager.on('launch', shard => console.log(`- Spawned shard ${shard.id} -`)); // Optional
// index.js
const Discord = require('discord.js');
const moment = require('moment');

client.login('token');

client.on('ready', () => {
    if (client.shard.id == 0)
        console.log(`-- ${moment().utc().format('MMMM Do')}, ${moment().utc().format('hh:mm a')} --`);

    console.log(`Shard ${client.shard.id} ready!`);
});
// Output
-- April 25th, 02:06 pm --
Shard 0 ready!
- Spawned shard 1 -
Shard 1 ready!
- Spawned shard 2 -
Shard 2 ready!
  • The 'ready' event will be executed once per shard.
  • The first shard will not emit 'launch'

Sources

discordapp.com
docs.thesarks.xyz

results matching ""

    No results matching ""