mirror of
https://github.com/discordjs/discord.js.git
synced 2026-03-17 03:53:29 +01:00
feat(ws): custom workers (#9004)
* feat(ws): custom workers * chore: typo * refactor(WebSocketShard): expose shard id * chore: remove outdated readme comment * chore: nits * chore: remove unnecessary mutation * feat: fancier resolution * chore: remove unnecessary exports * chore: apply suggestions * refactor: use range errors Co-authored-by: Aura Román <kyradiscord@gmail.com>
This commit is contained in:
@@ -99,7 +99,9 @@ You can also have the shards spawn in worker threads:
|
||||
|
||||
```ts
|
||||
import { WebSocketManager, WorkerShardingStrategy } from '@discordjs/ws';
|
||||
import { REST } from '@discordjs/rest';
|
||||
|
||||
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
|
||||
const manager = new WebSocketManager({
|
||||
token: process.env.DISCORD_TOKEN,
|
||||
intents: 0,
|
||||
@@ -113,6 +115,51 @@ manager.setStrategy(new WorkerShardingStrategy(manager, { shardsPerWorker: 2 }))
|
||||
manager.setStrategy(new WorkerShardingStrategy(manager, { shardsPerWorker: 'all' }));
|
||||
```
|
||||
|
||||
**Note**: By default, this will cause the workers to effectively only be responsible for the WebSocket connection, they simply pass up all the events back to the main process for the manager to emit. If you want to have the workers handle events as well, you can pass in a `workerPath` option to the `WorkerShardingStrategy` constructor:
|
||||
|
||||
```ts
|
||||
import { WebSocketManager, WorkerShardingStrategy } from '@discordjs/ws';
|
||||
import { REST } from '@discordjs/rest';
|
||||
|
||||
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
|
||||
const manager = new WebSocketManager({
|
||||
token: process.env.DISCORD_TOKEN,
|
||||
intents: 0,
|
||||
rest,
|
||||
});
|
||||
|
||||
manager.setStrategy(
|
||||
new WorkerShardingStrategy(manager, {
|
||||
shardsPerWorker: 2,
|
||||
workerPath: './worker.js',
|
||||
}),
|
||||
);
|
||||
```
|
||||
|
||||
And your `worker.ts` file:
|
||||
|
||||
```ts
|
||||
import { WorkerBootstrapper, WebSocketShardEvents } from '@discordjs/ws';
|
||||
|
||||
const bootstrapper = new WorkerBootstrapper();
|
||||
void bootstrapper.bootstrap({
|
||||
// Those will be sent to the main thread for the manager to emit
|
||||
forwardEvents: [
|
||||
WebSocketShardEvents.Closed,
|
||||
WebSocketShardEvents.Debug,
|
||||
WebSocketShardEvents.Hello,
|
||||
WebSocketShardEvents.Ready,
|
||||
WebSocketShardEvents.Resumed,
|
||||
],
|
||||
shardCallback: (shard) => {
|
||||
shard.on(WebSocketShardEvents.Dispatch, (event) => {
|
||||
// Process gateway events here however you want (e.g. send them through a message broker)
|
||||
// You also have access to shard.id if you need it
|
||||
});
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
- [Website][website] ([source][website-source])
|
||||
|
||||
Reference in New Issue
Block a user