Core client functionality for connecting to Discord, managing WebSocket connections, handling sharding for large bots, and managing the overall bot lifecycle.
The main hub for interacting with the Discord API and the starting point for any Discord bot.
/**
* The main Discord client that connects to the Discord API
* @extends BaseClient
*/
class Client extends BaseClient {
constructor(options: ClientOptions);
// Authentication and connection
login(token?: string): Promise<string>;
destroy(): Promise<void>;
// Core properties
readonly user: ClientUser | null;
readonly application: ClientApplication | null;
readonly readyAt: Date | null;
readonly uptime: number | null;
// Managers
readonly guilds: GuildManager;
readonly channels: ChannelManager;
readonly users: UserManager;
// Events (inherited from EventEmitter)
on<K extends keyof ClientEvents>(event: K, listener: (...args: ClientEvents[K]) => Awaitable<void>): this;
emit<K extends keyof ClientEvents>(event: K, ...args: ClientEvents[K]): boolean;
// Utility methods
generateInvite(options?: InviteGenerationOptions): string;
fetchInvite(invite: InviteResolvable, options?: ClientFetchInviteOptions): Promise<Invite>;
fetchWebhook(id: Snowflake, token?: string): Promise<Webhook>;
fetchGuildTemplate(template: GuildTemplateResolvable): Promise<GuildTemplate>;
}
interface ClientOptions {
/** Gateway intents to subscribe to */
intents: BitFieldResolvable<GatewayIntentsString, number>;
/** Number of shards to spawn (defaults to recommended count) */
shardCount?: number | 'auto';
/** Specific shards for this client to handle */
shards?: number | number[] | 'auto';
/** Time in milliseconds before connections are forced closed */
closeTimeout?: number;
/** REST API options */
restOptions?: Partial<RESTOptions>;
/** Initial presence data */
presence?: PresenceData;
/** Array of partials to enable */
partials?: Partials[];
/** Cache sweep options */
sweepers?: SweeperOptions;
}Usage Examples:
import { Client, GatewayIntentBits, Events } from 'discord.js';
// Basic client setup
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
// Login and handle ready event
client.on(Events.Ready, () => {
console.log(`Logged in as ${client.user?.tag}!`);
});
await client.login(process.env.DISCORD_TOKEN);
// Generate OAuth2 invite URL
const inviteUrl = client.generateInvite({
scopes: [OAuth2Scopes.Bot, OAuth2Scopes.ApplicationsCommands],
permissions: [PermissionFlagsBits.SendMessages, PermissionFlagsBits.ViewChannel]
});Application-level managers for handling emojis and monetization features.
/**
* Manages API methods for application emojis and stores their cache
* @extends CachedManager
*/
class ApplicationEmojiManager extends CachedManager<Snowflake, ApplicationEmoji, ApplicationEmojiResolvable> {
constructor(application: ClientApplication);
readonly application: ClientApplication;
// Create application emoji
create(options: ApplicationEmojiCreateOptions): Promise<ApplicationEmoji>;
// Edit application emoji
edit(emoji: ApplicationEmojiResolvable, options: ApplicationEmojiEditOptions): Promise<ApplicationEmoji>;
// Delete application emoji
delete(emoji: ApplicationEmojiResolvable, reason?: string): Promise<void>;
// Resolve emoji from various inputs
resolve(emoji: ApplicationEmojiResolvable): ApplicationEmoji | null;
resolveId(emoji: ApplicationEmojiResolvable): Snowflake | null;
}
/**
* Manages API methods for entitlements (monetization)
* @extends CachedManager
*/
class EntitlementManager extends CachedManager<Snowflake, Entitlement, EntitlementResolvable> {
constructor(client: Client);
// Fetch entitlements for the application
fetch(options?: EntitlementFetchOptions): Promise<Collection<Snowflake, Entitlement>>;
// Create test entitlement for testing monetization
createTest(options: TestEntitlementCreateOptions): Promise<Entitlement>;
// Delete test entitlement
deleteTest(entitlement: EntitlementResolvable): Promise<void>;
// Consume one-time purchase entitlement
consume(entitlement: EntitlementResolvable): Promise<void>;
}
interface ApplicationEmojiCreateOptions {
name: string;
image: BufferResolvable | Base64Resolvable;
}
interface ApplicationEmojiEditOptions {
name?: string;
}
interface EntitlementFetchOptions {
user?: UserResolvable;
skus?: SKUResolvable[];
before?: Snowflake;
after?: Snowflake;
limit?: number;
guildId?: Snowflake;
excludeEnded?: boolean;
}
interface TestEntitlementCreateOptions {
sku: SKUResolvable;
owner: UserResolvable | GuildResolvable;
ownerType: EntitlementOwnerType;
}Base client providing core functionality shared by Client and WebhookClient.
/**
* Base class for Discord clients
* @extends EventEmitter
*/
class BaseClient extends EventEmitter {
constructor(options: BaseClientOptions);
readonly options: BaseClientOptions;
readonly rest: REST;
// Destroy the client and close connections
destroy(): Promise<void>;
// Set timeout for operations
setTimeout(fn: (...args: any[]) => void, delay: number, ...args: any[]): NodeJS.Timeout;
clearTimeout(timeout: NodeJS.Timeout): void;
setInterval(fn: (...args: any[]) => void, delay: number, ...args: any[]): NodeJS.Timeout;
clearInterval(interval: NodeJS.Timeout): void;
}
interface BaseClientOptions {
/** REST API options */
rest?: Partial<RESTOptions>;
}Webhook-only client for sending messages through Discord webhooks without requiring a bot token.
/**
* Client for interacting with Discord webhooks
* @extends BaseClient
*/
class WebhookClient extends BaseClient {
constructor(data: WebhookClientData, options?: WebhookClientOptions);
readonly id: Snowflake;
readonly token: string | null;
readonly url: string;
// Send messages via webhook
send(options: string | MessagePayload | WebhookMessageCreateOptions): Promise<Message>;
// Edit webhook messages
editMessage(
message: MessageResolvable,
options: string | MessagePayload | WebhookMessageEditOptions
): Promise<Message>;
// Delete webhook messages
deleteMessage(message: MessageResolvable, threadId?: Snowflake): Promise<void>;
// Fetch webhook information
fetch(options?: WebhookFetchOptions): Promise<Webhook>;
// Edit webhook settings
edit(options: WebhookEditOptions): Promise<Webhook>;
// Delete the webhook
delete(reason?: string): Promise<void>;
}
type WebhookClientData =
| { id: Snowflake; token: string }
| { url: string };
interface WebhookClientOptions extends BaseClientOptions {
allowedMentions?: MessageMentionOptions;
}For large bots that need to be distributed across multiple processes or servers.
/**
* Manages multiple shards across processes
*/
class ShardingManager extends EventEmitter {
constructor(file: string, options?: ShardingManagerOptions);
readonly file: string;
readonly shards: Collection<number, Shard>;
readonly totalShards: number | 'auto';
readonly shardArgs: string[];
readonly execArgv: string[];
// Create and spawn shards
createShard(id: number): Shard;
spawn(options?: MultipleShardSpawnOptions): Promise<Collection<number, Shard>>;
// Shard communication
broadcast(message: any): Promise<Shard[]>;
broadcastEval<T>(fn: (client: Client) => Awaitable<T>): Promise<T[]>;
// Fetch recommended shard count
fetchClientValues(prop: string): Promise<any[]>;
respawn(options?: MultipleShardRespawnOptions): Promise<Collection<number, Shard>>;
}
/**
* Individual shard instance
*/
class Shard extends EventEmitter {
constructor(manager: ShardingManager, id: number);
readonly manager: ShardingManager;
readonly id: number;
readonly args: string[];
readonly execArgv: string[];
readonly env: Record<string, any>;
readonly ready: boolean;
readonly worker: Worker | ChildProcess | null;
// Shard lifecycle
spawn(options?: ShardSpawnOptions): Promise<ChildProcess | Worker>;
respawn(options?: ShardRespawnOptions): Promise<ChildProcess | Worker>;
kill(): Promise<void>;
// Communication
send(message: any): Promise<Shard>;
eval<T>(script: string): Promise<T>;
fetchClientValue(prop: string): Promise<any>;
}
/**
* Utilities for sharded clients
*/
class ShardClientUtil {
constructor(client: Client, mode?: ShardingManagerMode);
readonly client: Client;
readonly mode: ShardingManagerMode;
readonly parentPort: MessagePort | null;
// Get shard information
readonly count: number | null;
readonly ids: number[] | null;
// Send data to shard manager
send(message: any): Promise<void>;
fetchClientValues(prop: string): Promise<any[]>;
broadcastEval<T>(fn: (client: Client) => Awaitable<T>): Promise<T[]>;
respawnAll(options?: MultipleShardRespawnOptions): Promise<void>;
}
/**
* Manages WebSocket connections for the Discord gateway
*/
class WebSocketManager extends EventEmitter {
constructor(options: WebSocketManagerOptions);
readonly options: WebSocketManagerOptions;
readonly shards: Collection<number, WebSocketShard>;
// Connection management
connect(): Promise<void>;
destroy(options?: WebSocketDestroyOptions): Promise<void>;
// Send data to specific shard
send(shardId: number, payload: GatewayPayload): void;
// Status information
readonly status: Status;
readonly ping: number;
}
/**
* Individual WebSocket shard connection
*/
class WebSocketShard extends EventEmitter {
constructor(manager: WebSocketManager, id: number);
readonly manager: WebSocketManager;
readonly id: number;
readonly status: Status;
readonly ping: number;
// Connection management
connect(): Promise<void>;
destroy(options?: WebSocketShardDestroyOptions): Promise<void>;
// Send data through this shard
send(data: GatewayPayload): void;
// Status checking
readonly connectedAt: Date | null;
readonly readyAt: Date | null;
}
interface WebSocketManagerOptions {
token: string;
intents: number;
shardCount?: number;
shardIds?: number[];
rest?: REST;
}
interface WebSocketDestroyOptions {
code?: number;
reason?: string;
recover?: boolean;
}
interface WebSocketShardDestroyOptions extends WebSocketDestroyOptions {
code?: number;
reason?: string;
}
/**
* Shard event constants for shard lifecycle management
*/
const ShardEvents: {
/** Emitted when a shard process dies */
Death: 'death';
/** Emitted when a shard disconnects */
Disconnect: 'disconnect';
/** Emitted when a shard encounters an error */
Error: 'error';
/** Emitted when a shard receives a message */
Message: 'message';
/** Emitted when a shard becomes ready */
Ready: 'ready';
/** Emitted when a shard is reconnecting */
Reconnecting: 'reconnecting';
/** Emitted when a shard resumes connection */
Resume: 'resume';
/** Emitted when a shard spawns */
Spawn: 'spawn';
};Core events emitted by the Discord client during its lifecycle.
interface ClientEvents {
/** Emitted when the client becomes ready */
ready: [client: Client<true>];
/** Emitted when a shard becomes ready */
shardReady: [id: number, unavailableGuilds: Set<Snowflake> | undefined];
/** Emitted when a shard encounters an error */
shardError: [error: Error, shardId: number];
/** Emitted when a shard disconnects */
shardDisconnect: [closeEvent: CloseEvent, shardId: number];
/** Emitted when a shard reconnects */
shardReconnecting: [shardId: number];
/** Emitted when a shard resumes */
shardResume: [shardId: number, replayedEvents: number];
/** Emitted when all shards have disconnected */
disconnect: [closeEvent: CloseEvent];
/** Emitted when attempting to reconnect */
reconnecting: [];
/** Emitted on various warnings */
warn: [message: string];
/** Emitted on debug information */
debug: [message: string];
/** Emitted when encountering errors */
error: [error: Error];
}Control which events your bot receives from Discord to optimize performance and comply with privileged intent requirements.
/**
* BitField for managing Discord Gateway intents
*/
class IntentsBitField extends BitField<GatewayIntentsString> {
static Flags: typeof GatewayIntentBits;
static resolve(bit?: BitFieldResolvable<GatewayIntentsString, number>): number;
}
const GatewayIntentBits: {
/** Guilds intent - guild create/update/delete, guild role/emoji/sticker updates */
Guilds: 1 << 0;
/** Guild members intent - guild member add/update/remove */
GuildMembers: 1 << 1;
/** Guild moderation intent - guild ban add/remove */
GuildModeration: 1 << 2;
/** Guild emojis and stickers intent */
GuildEmojisAndStickers: 1 << 3;
/** Guild integrations intent */
GuildIntegrations: 1 << 4;
/** Guild webhooks intent */
GuildWebhooks: 1 << 5;
/** Guild invites intent */
GuildInvites: 1 << 6;
/** Guild voice states intent */
GuildVoiceStates: 1 << 7;
/** Guild presences intent - member presence updates (privileged) */
GuildPresences: 1 << 8;
/** Guild messages intent */
GuildMessages: 1 << 9;
/** Guild message reactions intent */
GuildMessageReactions: 1 << 10;
/** Guild message typing intent */
GuildMessageTyping: 1 << 11;
/** Direct messages intent */
DirectMessages: 1 << 12;
/** Direct message reactions intent */
DirectMessageReactions: 1 << 13;
/** Direct message typing intent */
DirectMessageTyping: 1 << 14;
/** Message content intent - access to message content (privileged) */
MessageContent: 1 << 15;
/** Guild scheduled events intent */
GuildScheduledEvents: 1 << 16;
/** Auto moderation configuration intent */
AutoModerationConfiguration: 1 << 20;
/** Auto moderation execution intent */
AutoModerationExecution: 1 << 21;
/** Guild message polls intent */
GuildMessagePolls: 1 << 24;
/** Direct message polls intent */
DirectMessagePolls: 1 << 25;
};
type GatewayIntentsString = keyof typeof GatewayIntentBits;Usage Examples:
// Basic intents for most bots
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages
]
});
// All non-privileged intents
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.GuildScheduledEvents
]
});
// Privileged intents (require approval for verified bots)
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers, // Privileged
GatewayIntentBits.GuildPresences, // Privileged
GatewayIntentBits.MessageContent // Privileged
]
});/**
* Client presence status
*/
class ClientPresence extends Presence {
constructor(client: Client, data?: RawPresenceData);
set(presence: PresenceData): ClientPresence;
}
interface PresenceData {
status?: PresenceStatusData;
afk?: boolean;
activities?: ActivitiesOptions[];
shardId?: number | number[];
}
type PresenceStatusData = 'online' | 'idle' | 'invisible' | 'dnd';
interface ActivitiesOptions {
name: string;
type: ActivityType;
url?: string;
}
const Status: {
Ready: 0;
Connecting: 1;
Reconnecting: 2;
Idle: 3;
Nearly: 4;
Disconnected: 5;
WaitingForGuilds: 6;
Identifying: 7;
Resuming: 8;
};