Preview environment

class Client

extends

BaseClient
export class Client<Ready extends boolean = boolean> extends BaseClient

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

Constructors

constructor(
options: ClientOptions
)

Type Parameters

optional
Ready? extends boolean = boolean

application : If<Ready, ClientApplication>

The application of this bot

channels : ChannelManager

All of the BaseChannels 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.

readonly
emojis : BaseGuildEmojiManager

All custom emojis that the client has access to, mapped by their ids

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

options : Omit<ClientOptions, 'intents'> & { intents: IntentsBitField }

The options the client was instantiated with

readonly
readyAt : If<Ready, 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)

readyTimestamp : If<Ready, number>

Timestamp of the time the client was last Ready at

rest : REST

The REST manager of the client

Inherited from: BaseClient

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

sweepers : Sweepers

The sweeping functions and their intervals used to periodically sweep caches

token : If<Ready, string, string | null>

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.

readonly
uptime : If<Ready, number>

How long it has been since the client last entered the Ready state in milliseconds

user : If<Ready, ClientUser>

User that the client is logged in as

users : UserManager

All of the User objects that have been cached at any point, mapped by their ids

The voice manager of the client

The WebSocket manager of the client

[Symbol.asyncDispose]() : Promise<void>

Inherited from: BaseClient

deleteWebhook() : Promise<void>

Deletes a webhook.

destroy() : Promise<void>

Logs out, terminates the connection to Discord, and destroys the client.

emit<

Event extends keyof ClientEvents

>(
event: Event
...args: ClientEvents[Event]
) : boolean

fetchGuildPreview() : Promise<GuildPreview>

Obtains a guild preview from Discord, available for all guilds the bot is in and all Discoverable guilds.

fetchGuildTemplate() : Promise<GuildTemplate>

Obtains a template from Discord.

Examples:
client.fetchGuildTemplate('https://discord.new/FKvmczH2HyUf')
  .then(template => console.log(`Obtained template with code: ${template.code}`))
  .catch(console.error);

fetchGuildWidget() : Promise<Widget>

Obtains the widget data of a guild from Discord, available for guilds with the widget enabled.

fetchInvite() : Promise<Invite>

Obtains an invite from Discord.

Examples:
client.fetchInvite('https://discord.gg/djs')
  .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
  .catch(console.error);

deprecated
fetchPremiumStickerPacks() : ReturnType<Client['fetchStickerPacks']>

Obtains the list of available sticker packs.

fetchSticker() : Promise<Sticker>

Obtains a sticker from Discord.

Examples:
client.fetchSticker('id')
  .then(sticker => console.log(`Obtained sticker with name: ${sticker.name}`))
  .catch(console.error);

fetchStickerPacks(
options: { packId: Snowflake }
) : Promise<StickerPack>

Obtains the list of available sticker packs.

Examples:
client.fetchStickerPacks()
  .then(packs => console.log(`Available sticker packs are: ${packs.map(pack => pack.name).join(', ')}`))
  .catch(console.error);
client.fetchStickerPacks({ packId: '751604115435421716' })
  .then(pack => console.log(`Sticker pack name: ${pack.name}`))
  .catch(console.error);

Returns: A collection of sticker packs, or a single sticker pack if a packId was provided

fetchVoiceRegions() : Promise<Collection<string, VoiceRegion>>

Obtains the available voice regions from Discord.

Examples:
client.fetchVoiceRegions()
  .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`))
  .catch(console.error);

fetchWebhook(
token?: string
) : Promise<Webhook>

Obtains a webhook from Discord.

Examples:
client.fetchWebhook('id', 'token')
  .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`))
  .catch(console.error);

generateInvite() : string

Generates a link that can be used to invite the bot to a guild.

Examples:
const link = client.generateInvite({
  scopes: [OAuth2Scopes.ApplicationsCommands],
});
console.log(`Generated application invite link: ${link}`);
const link = client.generateInvite({
  permissions: [
    PermissionFlagsBits.SendMessages,
    PermissionFlagsBits.ManageGuild,
    PermissionFlagsBits.MentionEveryone,
  ],
  scopes: [OAuth2Scopes.Bot],
});
console.log(`Generated bot invite link: ${link}`);

isReady() : this is Client<true>

Returns whether the client has logged in, indicative of being able to access properties such as user and application.

login(
token?: string
) : Promise<string>

Logs the client in, establishing a WebSocket connection to Discord.

Examples:
client.login('my token');

Returns: Token of the account used

off<

Event extends keyof ClientEvents

>(
event: Event
listener: (...args: ClientEvents[Event]) => void
) : this

on<

Event extends keyof ClientEvents

>(
event: Event
listener: (...args: ClientEvents[Event]) => void
) : this

static
on<

Emitter extends EventEmitter

Event extends keyof ClientEvents

>(
eventEmitter: Emitter
eventName: Emitter extends Client ? Event : string | symbol
options?: { signal?: AbortSignal | undefined }
) : AsyncIterableIterator<Emitter extends Client ? ClientEvents[Event] : any[]>

once<

Event extends keyof ClientEvents

>(
event: Event
listener: (...args: ClientEvents[Event]) => void
) : this

static
once<

Emitter extends EventEmitter

Event extends keyof ClientEvents

>(
eventEmitter: Emitter
eventName: Emitter extends Client ? Event : string | symbol
options?: { signal?: AbortSignal | undefined }
) : Promise<Emitter extends Client ? ClientEvents[Event] : any[]>

removeAllListeners<

Event extends keyof ClientEvents

>(
event?: Event
) : this

toJSON() : unknown

applicationCommandPermissionsUpdate()

Emitted whenever permissions for an application command in a guild were updated. This includes permission updates for other applications in addition to the logged in client, check data.applicationId to verify which application the update is for

autoModerationActionExecution(
autoModerationActionExecution: AutoModerationActionExecution
)

Emitted whenever an auto moderation rule is triggered. This event requires the PermissionFlagsBits.ManageGuild permission.

autoModerationRuleCreate(
autoModerationRule: AutoModerationRule
)

Emitted whenever an auto moderation rule is created. This event requires the PermissionFlagsBits.ManageGuild permission.

autoModerationRuleDelete(
autoModerationRule: AutoModerationRule
)

Emitted whenever an auto moderation rule is deleted. This event requires the PermissionFlagsBits.ManageGuild permission.

autoModerationRuleUpdate(
oldAutoModerationRule: AutoModerationRule | null
newAutoModerationRule: AutoModerationRule
)

Emitted whenever an auto moderation rule gets updated. This event requires the PermissionFlagsBits.ManageGuild permission.

channelCreate(
channel: GuildChannel
)

Emitted whenever a guild channel is created.

channelDelete()

Emitted whenever a channel is deleted.

channelPinsUpdate(
time: Date
)

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.

channelUpdate(
oldChannel: DMChannel | GuildChannel
newChannel: DMChannel | GuildChannel
)

Emitted whenever a channel is updated - e.g. name change, topic change, channel type change.

debug(
info: string
)

Emitted for general debugging information.

emojiCreate(
emoji: GuildEmoji
)

Emitted whenever a custom emoji is created in a guild.

emojiDelete(
emoji: GuildEmoji
)

Emitted whenever a custom emoji is deleted in a guild.

emojiUpdate(
oldEmoji: GuildEmoji
newEmoji: GuildEmoji
)

Emitted whenever a custom emoji is updated in a guild.

entitlementCreate(
entitlement: Entitlement
)

Emitted whenever an entitlement is created.

entitlementDelete(
entitlement: Entitlement
)

Emitted whenever an entitlement is deleted. Entitlements are not deleted when they expire. This is only triggered when Discord issues a refund or deletes the entitlement manually.

entitlementUpdate(
oldEntitlement: Entitlement | null
newEntitlement: Entitlement
)

Emitted whenever an entitlement is updated - i.e. when a user's subscription renews.

error(
error: Error
)

Emitted when the client encounters an error. Errors thrown within this event do not have a catch handler, it is recommended to not use async functions as error event handlers. See the [Node.js docs](https://nodejs.org/api/events.html#capture-rejections-of-promises) for details.

guildAuditLogEntryCreate(
auditLogEntry: GuildAuditLogsEntry
guild: Guild
)

Emitted whenever a guild audit log entry is created.

guildAvailable(
guild: Guild
)

Emitted whenever a guild becomes available.

guildBanAdd()

Emitted whenever a member is banned from a guild.

guildBanRemove()

Emitted whenever a member is unbanned from a guild.

guildCreate(
guild: Guild
)

Emitted whenever the client joins a guild.

guildDelete(
guild: Guild
)

Emitted whenever a guild kicks the client or the guild is deleted/left.

guildIntegrationsUpdate(
guild: Guild
)

Emitted whenever a guild integration is updated

guildMemberAdd(
member: GuildMember
)

Emitted whenever a user joins a guild.

guildMemberAvailable(
member: GuildMember
)

Emitted whenever a member becomes available.

guildMemberRemove(
member: GuildMember
)

Emitted whenever a member leaves a guild, or is kicked.

guildMembersChunk()

Emitted whenever a chunk of guild members is received (all members come from the same guild).

guildMemberUpdate(
oldMember: GuildMember
newMember: GuildMember
)

Emitted whenever a guild member changes - i.e. new role, removed role, nickname.

guildScheduledEventCreate(
guildScheduledEvent: GuildScheduledEvent
)

Emitted whenever a guild scheduled event is created.

guildScheduledEventDelete(
guildScheduledEvent: GuildScheduledEvent
)

Emitted whenever a guild scheduled event is deleted.

guildScheduledEventUpdate(
oldGuildScheduledEvent: GuildScheduledEvent | null
newGuildScheduledEvent: GuildScheduledEvent
)

Emitted whenever a guild scheduled event gets updated.

guildScheduledEventUserAdd(
guildScheduledEvent: GuildScheduledEvent
user: User
)

Emitted whenever a user subscribes to a guild scheduled event

guildScheduledEventUserRemove(
guildScheduledEvent: GuildScheduledEvent
user: User
)

Emitted whenever a user unsubscribes from a guild scheduled event

guildUnavailable(
guild: Guild
)

Emitted whenever a guild becomes unavailable, likely due to a server outage.

guildUpdate(
oldGuild: Guild
newGuild: Guild
)

Emitted whenever a guild is updated - e.g. name change.

interactionCreate(
interaction: BaseInteraction
)

Emitted when an interaction is created.

inviteCreate(
invite: Invite
)

Emitted when an invite is created. This event requires the PermissionFlagsBits.ManageChannels permission for the channel.

inviteDelete(
invite: Invite
)

Emitted when an invite is deleted. This event requires the PermissionFlagsBits.ManageChannels permission for the channel.

messageCreate(
message: Message
)

Emitted whenever a message is created.

messageDelete(
message: Message
)

Emitted whenever a message is deleted.

messageDeleteBulk()

Emitted whenever messages are deleted in bulk.

messagePollVoteAdd(
pollAnswer: PollAnswer
userId: Snowflake
)

Emitted whenever a user votes in a poll.

messagePollVoteRemove(
pollAnswer: PollAnswer
userId: Snowflake
)

Emitted whenever a user removes their vote in a poll.

messageReactionAdd(
messageReaction: MessageReaction
user: User
)

Emitted whenever a reaction is added to a cached message.

messageReactionRemove(
messageReaction: MessageReaction
user: User
)

Emitted whenever a reaction is removed from a cached message.

messageReactionRemoveAll()

Emitted whenever all reactions are removed from a cached message.

messageReactionRemoveEmoji(
reaction: MessageReaction
)

Emitted when a bot removes an emoji reaction from a cached message.

messageUpdate(
oldMessage: Message
newMessage: Message
)

Emitted whenever a message is updated - e.g. embed or content change.

presenceUpdate(
oldPresence: Presence | null
newPresence: Presence
)

Emitted whenever a guild member's presence (e.g. status, activity) is changed.

ready(
client: Client
)

Emitted when the client becomes ready to start working.

roleCreate(
role: Role
)

Emitted whenever a role is created.

roleDelete(
role: Role
)

Emitted whenever a guild role is deleted.

roleUpdate(
oldRole: Role
newRole: Role
)

Emitted whenever a guild role is updated.

shardDisconnect(
event: CloseEvent
id: number
)

Emitted when a shard's WebSocket disconnects and will no longer reconnect.

shardError(
error: Error
shardId: number
)

Emitted whenever a shard's WebSocket encounters a connection error.

shardReady(
id: number
unavailableGuilds: Set<Snowflake> | null
)

Emitted when a shard turns ready.

shardReconnecting(
id: number
)

Emitted when a shard is attempting to reconnect or re-identify.

shardResume(
id: number
replayedEvents: number
)

Emitted when a shard resumes successfully.

stageInstanceCreate(
stageInstance: StageInstance
)

Emitted whenever a stage instance is created.

stageInstanceDelete(
stageInstance: StageInstance
)

Emitted whenever a stage instance is deleted.

stageInstanceUpdate(
oldStageInstance: StageInstance | null
newStageInstance: StageInstance
)

Emitted whenever a stage instance gets updated - e.g. change in topic or privacy level

stickerCreate(
sticker: Sticker
)

Emitted whenever a custom sticker is created in a guild.

stickerDelete(
sticker: Sticker
)

Emitted whenever a custom sticker is deleted in a guild.

stickerUpdate(
oldSticker: Sticker
newSticker: Sticker
)

Emitted whenever a custom sticker is updated in a guild.

threadCreate(
newlyCreated: boolean
)

Emitted whenever a thread is created or when the client user is added to a thread.

threadDelete()

Emitted whenever a thread is deleted.

threadListSync()

Emitted whenever the client user gains access to a text or news channel that contains threads

threadMembersUpdate()

Emitted whenever members are added or removed from a thread. This event requires the GatewayIntentBits.GuildMembers privileged gateway intent.

threadMemberUpdate(
oldMember: ThreadMember
newMember: ThreadMember
)

Emitted whenever the client user's thread member is updated.

threadUpdate(
oldThread: ThreadChannel
newThread: ThreadChannel
)

Emitted whenever a thread is updated - e.g. name change, archive state change, locked state change.

typingStart(
typing: Typing
)

Emitted whenever a user starts typing in a channel.

userUpdate(
oldUser: User
newUser: User
)

Emitted whenever a user's details (e.g. username) are changed. Triggered by the Discord gateway events UserUpdate, GuildMemberUpdate, and PresenceUpdate.

voiceStateUpdate(
oldState: VoiceState
newState: VoiceState
)

Emitted whenever a member changes voice state - e.g. joins/leaves a channel, mutes/unmutes.

warn(
info: string
)

Emitted for general warnings.

Emitted whenever a channel has its webhooks changed.

deprecated
webhookUpdate()

Emitted whenever a channel has its webhooks changed.