Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
@discordjs/ws
Advanced tools
@discordjs/ws
is a powerful wrapper around Discord's gateway.
Node.js 22.12.0 or newer is required.
npm install @discordjs/ws
yarn add @discordjs/ws
pnpm add @discordjs/ws
bun add @discordjs/ws
npm install zlib-sync
)npm install bufferutil
)import { WebSocketManager, WebSocketShardEvents, CompressionMethod } from '@discordjs/ws';
import { REST } from '@discordjs/rest';
import type { RESTGetAPIGatewayBotResult } from 'discord-api-types/v10';
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
// This example will spawn Discord's recommended shard count, all under the current process.
const manager = new WebSocketManager({
token: process.env.DISCORD_TOKEN,
intents: 0, // for no intents
fetchGatewayInformation() {
return rest.get(Routes.gatewayBot()) as Promise<RESTGetAPIGatewayBotResult>;
},
// uncomment if you have zlib-sync installed and want to use compression
// compression: CompressionMethod.ZlibSync,
// alternatively, we support compression using node's native `node:zlib` module:
// compression: CompressionMethod.ZlibNative,
});
manager.on(WebSocketShardEvents.Dispatch, (event) => {
// Process gateway events here.
});
await manager.connect();
// Spawn 4 shards
const manager = new WebSocketManager({
token: process.env.DISCORD_TOKEN,
intents: 0,
shardCount: 4,
fetchGatewayInformation() {
return rest.get(Routes.gatewayBot()) as Promise<RESTGetAPIGatewayBotResult>;
},
});
// The manager also supports being responsible for only a subset of your shards:
// Your bot will run 8 shards overall
// This manager will only take care of 0, 2, 4, and 6
const manager = new WebSocketManager({
token: process.env.DISCORD_TOKEN,
intents: 0,
shardCount: 8,
shardIds: [0, 2, 4, 6],
fetchGatewayInformation() {
return rest.get(Routes.gatewayBot()) as Promise<RESTGetAPIGatewayBotResult>;
},
});
// Alternatively, if your shards are consecutive, you can pass in a range
const manager = new WebSocketManager({
token: process.env.DISCORD_TOKEN,
intents: 0,
shardCount: 8,
shardIds: {
start: 0,
end: 4,
},
fetchGatewayInformation() {
return rest.get(Routes.gatewayBot()) as Promise<RESTGetAPIGatewayBotResult>;
},
});
worker_threads
You can also have the shards spawn in worker threads:
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,
shardCount: 6,
fetchGatewayInformation() {
return rest.get(Routes.gatewayBot()) as Promise<RESTGetAPIGatewayBotResult>;
},
// This will cause 3 workers to spawn, 2 shards per each
buildStrategy: (manager) => new WorkerShardingStrategy(manager, { shardsPerWorker: 2 }),
// Or maybe you want all your shards under a single worker
buildStrategy: (manager) => 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:
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,
fetchGatewayInformation() {
return rest.get(Routes.gatewayBot()) as Promise<RESTGetAPIGatewayBotResult>;
},
buildStrategy: (manager) =>
new WorkerShardingStrategy(manager, {
shardsPerWorker: 2,
workerPath: './worker.js',
// Optionally, if you have custom messaging, like for analytic collection, you can use this:
async unknownPayloadHandler(data: any) {
// handle data here :3
},
}),
});
And your worker.ts
file:
import { WorkerBootstrapper, WebSocketShardEvents } from '@discordjs/ws';
import { parentPort } from 'node:worker_threads';
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
});
},
});
// This will go to `unknownPayloadHandler` in the main thread, or be ignored if not provided
parentPort!.postMessage({ custom: 'data' });
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the
documentation.
See the contribution guide if you'd like to submit a PR.
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official discord.js Server.
FAQs
Wrapper around Discord's gateway
The npm package @discordjs/ws receives a total of 54,740 weekly downloads. As such, @discordjs/ws popularity was classified as popular.
We found that @discordjs/ws demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.