Class: Client

Client

The main hub for interacting with the Discord API, and the starting point for any bot.

Constructor

new Client(optionsopt)

Parameters:
Name Type Attributes Description
options ClientOptions <optional>
Options for the client
Source:

Extends

Members

(private) _immediates :Set.<Immediate>

Intervals set by BaseClient#setImmediate that are still active
Type:
  • Set.<Immediate>
Overrides:
Source:

(private) _intervals :Set.<Timeout>

Intervals set by BaseClient#setInterval that are still active
Type:
  • Set.<Timeout>
Overrides:
Source:

(private) _timeouts :Set.<Timeout>

Timeouts set by BaseClient#setTimeout that are still active
Type:
  • Set.<Timeout>
Overrides:
Source:

(private) actions :ActionsManager

The action manager of the client
Type:
  • ActionsManager
Source:

(private, readonly) api :Object

API shortcut
Type:
  • Object
Overrides:
Source:

channels :ChannelManager

All of the Channels that the client is currently handling, mapped by their IDs - as long as sharding isn't being used, this will be *every* channel in *every* guild the bot is a member of. Note that DM channels will not be initially cached, and thus not be present in the Manager without their explicit fetching or use.
Type:
Source:

(readonly) emojis :GuildEmojiManager

All custom emojis that the client has access to, mapped by their IDs
Type:
Source:

guilds :GuildManager

All of the guilds the client is currently handling, mapped by their IDs - as long as sharding isn't being used, this will be *every* guild the bot is a member of
Type:
Source:

options :ClientOptions

The options the client was instantiated with
Type:
Overrides:
Source:

(private) presence :ClientPresence

The presence of the Client
Type:
Source:

(nullable) readyAt :Date

Time at which the client was last regarded as being in the `READY` state (each time the client disconnects and successfully reconnects, this will be overwritten)
Type:
  • Date
Source:

(readonly, nullable) readyTimestamp :number

Timestamp of the time the client was last `READY` at
Type:
  • number
Source:

(private) rest :RESTManager

The REST manager of the client
Type:
  • RESTManager
Overrides:
Source:

(nullable) shard :ShardClientUtil

Shard helpers for the client (only if the process was spawned from a ShardingManager)
Type:
Source:

(nullable) token :string

Authorization token for the logged in bot. If present, this defaults to `process.env.DISCORD_TOKEN` when instantiating the client This should be kept private at all times.
Type:
  • string
Source:

(readonly, nullable) uptime :number

How long it has been since the client last entered the `READY` state in milliseconds
Type:
  • number
Source:

(nullable) user :ClientUser

User that the client is logged in as
Type:
Source:

users :UserManager

All of the User objects that have been cached at any point, mapped by their IDs
Type:
Source:

(nullable) voice :ClientVoiceManager

The voice manager of the client (`null` in browsers)
Type:
Source:

ws :WebSocketManager

The WebSocket manager of the client
Type:
Source:

Methods

(private) _eval(script) → {*}

Parameters:
Name Type Description
script string Script to eval
Source:
Returns:
Type
*

(private) _validateOptions(optionsopt)

Validates the client options.
Parameters:
Name Type Attributes Default Description
options ClientOptions <optional>
this.options Options to validate
Source:

clearImmediate(immediate)

Clears an immediate.
Parameters:
Name Type Description
immediate Immediate Immediate to cancel
Overrides:
Source:

clearInterval(interval)

Clears an interval.
Parameters:
Name Type Description
interval Timeout Interval to cancel
Overrides:
Source:

clearTimeout(timeout)

Clears a timeout.
Parameters:
Name Type Description
timeout Timeout Timeout to cancel
Overrides:
Source:

(private) decrementMaxListeners()

Decrements max listeners by one, if they are not zero.
Overrides:
Source:

destroy() → {void}

Logs out, terminates the connection to Discord, and destroys the client.
Overrides:
Source:
Returns:
Type
void

fetchApplication() → {Promise.<ClientApplication>}

Obtains the OAuth Application of this bot from Discord.
Source:
Returns:
Type
Promise.<ClientApplication>

fetchGuildPreview(guild) → {Promise.<GuildPreview>}

Obtains a guild preview from Discord, available for all guilds the bot is in and all Discoverable guilds.
Parameters:
Name Type Description
guild GuildResolvable The guild to fetch the preview for
Source:
Returns:
Type
Promise.<GuildPreview>

fetchInvite(invite) → {Promise.<Invite>}

Obtains an invite from Discord.
Parameters:
Name Type Description
invite InviteResolvable Invite code or URL
Source:
Returns:
Type
Promise.<Invite>
Example
client.fetchInvite('https://discord.gg/bRCvFy9')
  .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
  .catch(console.error);

fetchVoiceRegions() → {Promise.<Collection.<string, VoiceRegion>>}

Obtains the available voice regions from Discord.
Source:
Returns:
Type
Promise.<Collection.<string, VoiceRegion>>
Example
client.fetchVoiceRegions()
  .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`))
  .catch(console.error);

fetchWebhook(id, tokenopt) → {Promise.<Webhook>}

Obtains a webhook from Discord.
Parameters:
Name Type Attributes Description
id Snowflake ID of the webhook
token string <optional>
Token for the webhook
Source:
Returns:
Type
Promise.<Webhook>
Example
client.fetchWebhook('id', 'token')
  .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`))
  .catch(console.error);

(async) generateInvite(optionsopt) → {Promise.<string>}

Generates a link that can be used to invite the bot to a guild.
Parameters:
Name Type Attributes Description
options InviteGenerationOptions | PermissionResolvable <optional>
Permissions to request
Source:
Returns:
Type
Promise.<string>
Example
client.generateInvite({
  permissions: ['SEND_MESSAGES', 'MANAGE_GUILD', 'MENTION_EVERYONE'],
})
  .then(link => console.log(`Generated bot invite link: ${link}`))
  .catch(console.error);

(private) incrementMaxListeners()

Increments max listeners by one, if they are not zero.
Overrides:
Source:

(async) login(tokenopt) → {Promise.<string>}

Logs the client in, establishing a websocket connection to Discord.
Parameters:
Name Type Attributes Default Description
token string <optional>
this.token Token of the account to log in with
Source:
Returns:
Token of the account used
Type
Promise.<string>
Example
client.login('my token');

setImmediate(fn, …args) → {Immediate}

Sets an immediate that will be automatically cancelled if the client is destroyed.
Parameters:
Name Type Attributes Description
fn function Function to execute
args * <repeatable>
Arguments for the function
Overrides:
Source:
Returns:
Type
Immediate

setInterval(fn, delay, …args) → {Timeout}

Sets an interval that will be automatically cancelled if the client is destroyed.
Parameters:
Name Type Attributes Description
fn function Function to execute
delay number Time to wait between executions (in milliseconds)
args * <repeatable>
Arguments for the function
Overrides:
Source:
Returns:
Type
Timeout

setTimeout(fn, delay, …args) → {Timeout}

Sets a timeout that will be automatically cancelled if the client is destroyed.
Parameters:
Name Type Attributes Description
fn function Function to execute
delay number Time to wait before executing (in milliseconds)
args * <repeatable>
Arguments for the function
Overrides:
Source:
Returns:
Type
Timeout

sweepMessages(lifetimeopt) → {number}

Sweeps all text-based channels' messages and removes the ones older than the max message lifetime. If the message has been edited, the time of the edit is used rather than the time of the original message.
Parameters:
Name Type Attributes Default Description
lifetime number <optional>
this.options.messageCacheLifetime Messages that are older than this (in seconds) will be removed from the caches. The default is based on ClientOptions#messageCacheLifetime
Source:
Returns:
Amount of messages that were removed from the caches, or -1 if the message cache lifetime is unlimited
Type
number
Example
// Remove all messages older than 1800 seconds from the messages cache
const amount = client.sweepMessages(1800);
console.log(`Successfully removed ${amount} messages from the cache.`);

Events

channelCreate

Emitted whenever a channel is created.
Parameters:
Name Type Description
channel DMChannel | GuildChannel The channel that was created
Source:

channelDelete

Emitted whenever a channel is deleted.
Parameters:
Name Type Description
channel DMChannel | GuildChannel The channel that was deleted
Source:

channelPinsUpdate

Emitted whenever the pins of a channel are updated. Due to the nature of the WebSocket event, not much information can be provided easily here - you need to manually check the pins yourself.
Parameters:
Name Type Description
channel DMChannel | TextChannel The channel that the pins update occurred in
time Date The time of the pins update
Source:

channelUpdate

Emitted whenever a channel is updated - e.g. name change, topic change, channel type change.
Parameters:
Name Type Description
oldChannel DMChannel | GuildChannel The channel before the update
newChannel DMChannel | GuildChannel The channel after the update
Source:

debug

Emitted for general debugging information.
Parameters:
Name Type Description
info string The debug information
Source:

emojiCreate

Emitted whenever a custom emoji is created in a guild.
Parameters:
Name Type Description
emoji GuildEmoji The emoji that was created
Source:

emojiDelete

Emitted whenever a custom emoji is deleted in a guild.
Parameters:
Name Type Description
emoji GuildEmoji The emoji that was deleted
Source:

emojiUpdate

Emitted whenever a custom emoji is updated in a guild.
Parameters:
Name Type Description
oldEmoji GuildEmoji The old emoji
newEmoji GuildEmoji The new emoji
Source:

error

Emitted when the client encounters an error.
Parameters:
Name Type Description
error Error The error encountered
Source:

guildBanAdd

Emitted whenever a member is banned from a guild.
Parameters:
Name Type Description
guild Guild The guild that the ban occurred in
user User The user that was banned
Source:

guildBanRemove

Emitted whenever a member is unbanned from a guild.
Parameters:
Name Type Description
guild Guild The guild that the unban occurred in
user User The user that was unbanned
Source:

guildCreate

Emitted whenever the client joins a guild.
Parameters:
Name Type Description
guild Guild The created guild
Source:

guildDelete

Emitted whenever a guild kicks the client or the guild is deleted/left.
Parameters:
Name Type Description
guild Guild The guild that was deleted
Source:

guildIntegrationsUpdate

Emitted whenever a guild integration is updated
Parameters:
Name Type Description
guild Guild The guild whose integrations were updated
Source:

guildMemberAdd

Emitted whenever a user joins a guild.
Parameters:
Name Type Description
member GuildMember The member that has joined a guild
Source:

guildMemberRemove

Emitted whenever a member leaves a guild, or is kicked.
Parameters:
Name Type Description
member GuildMember The member that has left/been kicked from the guild
Source:

guildMembersChunk

Emitted whenever a chunk of guild members is received (all members come from the same guild).
Parameters:
Name Type Description
members Collection.<Snowflake, GuildMember> The members in the chunk
guild Guild The guild related to the member chunk
chunk Object Properties of the received chunk
Properties
Name Type Attributes Description
index number Index of the received chunk
count number Number of chunks the client should receive
nonce string <nullable>
Nonce for this chunk
Source:

guildMemberSpeaking

Emitted once a guild member changes speaking state.
Parameters:
Name Type Description
member GuildMember The member that started/stopped speaking
speaking Readonly.<Speaking> The speaking state of the member
Source:

guildMemberUpdate

Emitted whenever a guild member changes - i.e. new role, removed role, nickname. Also emitted when the user's details (e.g. username) change.
Parameters:
Name Type Description
oldMember GuildMember The member before the update
newMember GuildMember The member after the update
Source:

guildUnavailable

Emitted whenever a guild becomes unavailable, likely due to a server outage.
Parameters:
Name Type Description
guild Guild The guild that has become unavailable
Source:

guildUpdate

Emitted whenever a guild is updated - e.g. name change.
Parameters:
Name Type Description
oldGuild Guild The guild before the update
newGuild Guild The guild after the update
Source:

invalidated

Emitted when the client's session becomes invalidated. You are expected to handle closing the process gracefully and preventing a boot loop if you are listening to this event.
Source:

inviteCreate

Emitted when an invite is created. This event only triggers if the client has `MANAGE_GUILD` permissions for the guild, or `MANAGE_CHANNEL` permissions for the channel.
Parameters:
Name Type Description
invite Invite The invite that was created
Source:

inviteDelete

Emitted when an invite is deleted. This event only triggers if the client has `MANAGE_GUILD` permissions for the guild, or `MANAGE_CHANNEL` permissions for the channel.
Parameters:
Name Type Description
invite Invite The invite that was deleted
Source:

message

Emitted whenever a message is created.
Parameters:
Name Type Description
message Message The created message
Source:

messageDelete

Emitted whenever a message is deleted.
Parameters:
Name Type Description
message Message The deleted message
Source:

messageDeleteBulk

Emitted whenever messages are deleted in bulk.
Parameters:
Name Type Description
messages Collection.<Snowflake, Message> The deleted messages, mapped by their ID
Source:

messageReactionAdd

Emitted whenever a reaction is added to a cached message.
Parameters:
Name Type Description
messageReaction MessageReaction The reaction object
user User The user that applied the guild or reaction emoji
Source:

messageReactionRemove

Emitted whenever a reaction is removed from a cached message.
Parameters:
Name Type Description
messageReaction MessageReaction The reaction object
user User The user whose emoji or reaction emoji was removed
Source:

messageReactionRemoveAll

Emitted whenever all reactions are removed from a cached message.
Parameters:
Name Type Description
message Message The message the reactions were removed from
Source:

messageReactionRemoveEmoji

Emitted when a bot removes an emoji reaction from a cached message.
Parameters:
Name Type Description
reaction MessageReaction The reaction that was removed
Source:

messageUpdate

Emitted whenever a message is updated - e.g. embed or content change.
Parameters:
Name Type Description
oldMessage Message The message before the update
newMessage Message The message after the update
Source:

presenceUpdate

Emitted whenever a guild member's presence (e.g. status, activity) is changed.
Parameters:
Name Type Attributes Description
oldPresence Presence <nullable>
The presence before the update, if one at all
newPresence Presence The presence after the update
Source:

rateLimit

Emitted when the client hits a rate limit while making a request
Parameters:
Name Type Description
rateLimitInfo Object Object containing the rate limit info
Properties
Name Type Description
timeout number Timeout in ms
limit number Number of requests that can be made to this endpoint
method string HTTP method used for request that triggered this event
path string Path used for request that triggered this event
route string Route used for request that triggered this event
Source:

ready

Emitted when the client becomes ready to start working.
Source:

roleCreate

Emitted whenever a role is created.
Parameters:
Name Type Description
role Role The role that was created
Source:

roleDelete

Emitted whenever a guild role is deleted.
Parameters:
Name Type Description
role Role The role that was deleted
Source:

roleUpdate

Emitted whenever a guild role is updated.
Parameters:
Name Type Description
oldRole Role The role before the update
newRole Role The role after the update
Source:

shardDisconnect

Emitted when a shard's WebSocket disconnects and will no longer reconnect.
Parameters:
Name Type Description
event CloseEvent The WebSocket close event
id number The shard ID that disconnected
Source:

shardError

Emitted whenever a shard's WebSocket encounters a connection error.
Parameters:
Name Type Description
error Error The encountered error
shardID number The shard that encountered this error
Source:

shardReady

Emitted when a shard turns ready.
Parameters:
Name Type Attributes Description
id number The shard ID that turned ready
unavailableGuilds Set.<string> <nullable>
Set of unavailable guild IDs, if any
Source:

shardReconnecting

Emitted when a shard is attempting to reconnect or re-identify.
Parameters:
Name Type Description
id number The shard ID that is attempting to reconnect
Source:

shardResume

Emitted when a shard resumes successfully.
Parameters:
Name Type Description
id number The shard ID that resumed
replayedEvents number The amount of replayed events
Source:

typingStart

Emitted whenever a user starts typing in a channel.
Parameters:
Name Type Description
channel Channel The channel the user started typing in
user User The user that started typing
Source:

userUpdate

Emitted whenever a user's details (e.g. username) are changed. Triggered by the Discord gateway events USER_UPDATE, GUILD_MEMBER_UPDATE, and PRESENCE_UPDATE.
Parameters:
Name Type Description
oldUser User The user before the update
newUser User The user after the update
Source:

voiceStateUpdate

Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.
Parameters:
Name Type Description
oldState VoiceState The voice state before the update
newState VoiceState The voice state after the update
Source:

warn

Emitted for general warnings.
Parameters:
Name Type Description
info string The warning
Source:

webhookUpdate

Emitted whenever a guild text channel has its webhooks changed.
Parameters:
Name Type Description
channel TextChannel The channel that had a webhook update
Source: