Skip to content

Commit f2a91e1

Browse files
committed
document sharding
1 parent fe64394 commit f2a91e1

File tree

1 file changed

+64
-1
lines changed

1 file changed

+64
-1
lines changed
Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,66 @@
11
---
2-
title: Sharding your bot
2+
title: Sharding Your Discord Bot
33
---
4+
5+
Sharding is a method of splitting your bot into multiple processes, or
6+
"shards". This is useful for large bots that have a lot of guilds, as
7+
it allows you to distribute the load across multiple processes.
8+
Discord actually requires sharding for bots in more than 2,500 guilds,
9+
so understanding how to implement it is crucial as your bot grows.
10+
11+
Sharding is a built-in feature of discord.js, and CommandKit does not
12+
alter the way sharding works. While this guide covers how to shard
13+
your bot using CommandKit, you can learn more about sharding in
14+
discord.js by checking out the
15+
[discord.js guide](https://discordjs.guide/sharding).
16+
17+
## When to use sharding
18+
19+
You should consider implementing sharding in the following scenarios:
20+
21+
- Your bot is in, or approaching, 2,500 guilds (required by Discord)
22+
- You're experiencing memory or performance issues with a single
23+
process
24+
- You want to distribute your bot's workload across multiple
25+
cores/machines
26+
- You're considering scaling your bot in the future
27+
28+
## Creating a sharding manager file
29+
30+
You can simply create a new file in your source directory named
31+
`sharding-manager.ts` (or `sharding-manager.js` if you're using
32+
JavaScript) and CommandKit will automatically detect it and use it as
33+
the sharding manager. This file will be responsible for creating the
34+
shards and managing them.
35+
36+
```ts title="src/sharding-manager.ts"
37+
import { ShardingManager } from 'discord.js';
38+
import { join } from 'node:path';
39+
40+
process.loadEnvFile('./.env');
41+
42+
const manager = new ShardingManager(
43+
join(import.meta.dirname, 'index.js'),
44+
{
45+
token: process.env.DISCORD_TOKEN,
46+
totalShards: 2,
47+
mode: 'worker',
48+
},
49+
);
50+
51+
manager.on('shardCreate', (shard) =>
52+
console.log(`Launched shard ${shard.id}`),
53+
);
54+
55+
await manager.spawn();
56+
```
57+
58+
:::info
59+
60+
If you're confused about `index.js` being used, this is an
61+
autogenerated entrypoint file that sets up the CommandKit environment.
62+
When running `commandkit start` or `commandkit dev`, CommandKit
63+
automatically detects the entrypoint file (either
64+
`sharding-manager.js` or `index.js`) and loads it.
65+
66+
:::

0 commit comments

Comments
 (0)