discord.js/packages/ws
DD 093ac924ae
feat(WebSocketShard): explicit time out network error handling (#10375)
* feat(WebSocketShard): explicit time out network error handling

* refactor: use constant
2024-07-02 20:25:22 +00:00
..
__tests__ refactor: use interfaces for AsyncEventEmitter event maps (#10044) 2023-12-14 16:09:13 +00:00
docs chore: refactor workspace 2023-05-03 02:14:22 +02:00
src feat(WebSocketShard): explicit time out network error handling (#10375) 2024-07-02 20:25:22 +00:00
.cliff-jumperrc.json chore: No identifier base in development versions (#9848) 2023-10-03 19:24:13 +00:00
.gitignore chore: refactor workspace 2023-05-03 02:14:22 +02:00
.lintstagedrc.js build: multi-config build and dep update 2023-11-14 01:26:22 +01:00
.prettierignore build: ignores/swap/concurrency 2023-08-24 21:58:34 +02:00
.prettierrc.js build: multi-config build and dep update 2023-11-14 01:26:22 +01:00
api-extractor.json feat(website): add support for source file links (#9048) 2023-01-12 13:49:11 +01:00
CHANGELOG.md chore(release): @discordjs/builders 1.8.2, @discordjs/ws 1.1.1, and discord.js 14.15.3 (#10315) 2024-06-03 00:13:41 +03:00
cliff.toml build: git-cliff config 2023-04-02 01:55:39 +02:00
LICENSE chore: update license files (#9862) 2023-09-30 00:42:43 +00:00
package.json build: Bump discord-api-types to 0.37.90 (#10354) 2024-06-18 18:37:16 +00:00
README.md refactor: native zlib support (#10316) 2024-06-02 22:51:26 +00:00
tsconfig.docs.json build: fix the messy dependency graph 2023-11-09 00:13:01 +01:00
tsconfig.eslint.json build: fix the messy dependency graph 2023-11-09 00:13:01 +01:00
tsconfig.json build: fix the messy dependency graph 2023-11-09 00:13:01 +01:00
tsup.config.ts build: multi-config build and dep update 2023-11-14 01:26:22 +01:00


discord.js


Discord server npm version npm downloads Build status Code coverage

Vercel Cloudflare Workers

About

@discordjs/ws is a powerful wrapper around Discord's gateway.

Installation

Node.js 16.11.0 or newer is required.

npm install @discordjs/ws
yarn add @discordjs/ws
pnpm add @discordjs/ws
bun add @discordjs/ws

Optional packages

  • zlib-sync for WebSocket data compression and inflation (npm install zlib-sync)
  • bufferutil for a much faster WebSocket connection (npm install bufferutil)

Example usage

import { WebSocketManager, WebSocketShardEvents, CompressionMethod } from '@discordjs/ws';
import { REST } from '@discordjs/rest';

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
	rest,
	// 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();

Specify shards

// Spawn 4 shards
const manager = new WebSocketManager({
	token: process.env.DISCORD_TOKEN,
	intents: 0,
	rest,
	shardCount: 4,
});

// 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,
	rest,
	shardCount: 8,
	shardIds: [0, 2, 4, 6],
});

// Alternatively, if your shards are consecutive, you can pass in a range
const manager = new WebSocketManager({
	token: process.env.DISCORD_TOKEN,
	intents: 0,
	rest,
	shardCount: 8,
	shardIds: {
		start: 0,
		end: 4,
	},
});

Specify 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,
	rest,
	shardCount: 6,
	// 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,
	rest,
	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' });

Contributing

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.

Help

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.