Welcome to discord.js’s documentation!¶
discord.js is an easy-to-use and intuitive JavaScript API for Discord. It’s fairly high level, so if you’re looking for something low level, check out discord.io.
if you’re having problems, check out the troubleshooting guide.
Feel free to make any contributions you want, whether it be through creating an issue, giving a suggestion or making a pull request!
Note
This documentation is still a work-in-progress, apologies if something isn’t yet documented!
Installing discord.js¶
To install discord.js, you need a few dependencies.
Warning
When installing with any of these methods, you’ll encounter some errors. This is because an optional dependency isn’t working properly, but discord.js should still work fine.
Windows¶
- You need Visual Studio and Python 2.7.
Your Visual Studio installation ideally has to be recent, but you can try installing without it first. You can use Express, Community, Enteprise or any others apart from VS Code
.
- You (obviously) need NodeJS. Node 4 or higher is recommended.
After you have installed these things, to install just run: npm install --save --msvs_version=2015 discord.js
to install the latest version of discord.js for your project.
Linux (Debian-based)¶
- You (obviously) need NodeJS Linux. Node 4 or higher is recommended.
$ sudo apt-get install build-essential
$ npm install --save discord.js
Additional Audio Support¶
$ sudo apt-get install ffmpeg
Note: Ubuntu 14.04 needs to do:
$ sudo add-apt-repository ppa:mc3man/trusty-media && sudo apt-get update && sudo apt-get install ffmpeg
Updating to v5.0.0¶
If you’re coming from versions below v5, you might find some changes. Here are the major changes:
Change 1¶
// OLD:
client.getUser();
client.getServer();
server.getMember(); // etc etc
// NEW:
client.users.get();
client.servers.get();
client.members.get();
Change 2¶
// OLD:
client.on("serverNewMember", (member, server) => {
});
// NEW:
client.on("serverNewMember", (server, user) => {
});
Change 3¶
The Member Class has been removed, meaning you can’t use member.permissionsIn(channel)
. To get permissions, use channel.permissionsOf(user)
.
Troubleshooting¶
General¶
Occasionally, the API can stop working for whatever reason. If it was working previously and it stopped working on the same version, it means that either we screwed code up or there’s been a change to the Discord API. You can try asking around in the discord.js channel in the API server. You could also make an issue if one relating to a similar issue doesn’t exist. Please post a stacktrace if there is one, and be as detailed as possible - “the API isn’t working” doesn’t help at all.
If there is already an issue, feel free to comment that you’re also experiencing the same thing. This helps to see how widespread the bug is.
You can try reconnecting before submitting an issue, as sometimes some of the servers may be slightly different.
If you’re your bot or client is exiting unexpectedly with no error, this is likely caused by websocket disconnects. Make sure you have autoReconnect
enabled. See Client.
Voice¶
Often, especially if you’re on Windows, voice will not work out of the box. Follow the steps below, one by one.
- Is your system supported? The following are:
- Linux x64 & ia32
- Linux ARM (Raspberry Pi 1 & 2)
- Mac OS X x64
- Windows x64
- Did you install Python 2.7.x correctly? Is it in your PATH?
python -V
. If not, install it correctly or try reinstalling. - Windows - See https://python.org/downloads/
- Linux / Mac OS - Unix systems should already have it installed, but if not, use the OS’s package manager
- Did you install Python 2.7.x correctly? Is it in your PATH?
- Did you install FFMPEG correctly? Is it in your PATH?
ffmpeg -version
. If not, install it correctly or try reinstalling. - Windows - Follow this guide
- Linux / Mac OS - Use your OS’s package manager
- Did you install FFMPEG correctly? Is it in your PATH?
- Did you install the required C++ compiler tool for your OS? If not, install the corresponding program, then try reinstalling discord.js
npm i -S discord.js
- Windows - Visual Studio 2015 with C++ Support enabled
- Linux - build-essential
- Mac OS - Xcode CLI tools
- Did you install the required C++ compiler tool for your OS? If not, install the corresponding program, then try reinstalling discord.js
- If you’re still having problems try
npm cache clean
npm config set msvs_version 2015
npm i -S discord.js
If nothing of the above helped, feel free to jump on the discord.js channel in the API server
Client¶
extends EventEmitter
This page contains documentation on the Discord.Client class. This should be used when you want to start creating things with the API.
Parameters¶
Client takes an options object, and supports the following options:.
autoReconnect¶
Have discord.js autoreconnect when connection is lost.
compress¶
Have Discord send a compressed READY packet.
forceFetchUsers¶
Make the library get all the users in all guilds, and delay the ready event until all users are received. This will slow down ready times and increase initial network traffic.
guildCreateTimeout¶
How long in milliseconds to wait for more guilds during the initial ready stream. Default is 1000ms. Increase this number if you are getting some serverCreated events right after ready.
largeThreshold¶
Set a custom large_threshold (the max number of offline members Discord sends in the initial GUILD_CREATE). The maximum is 250.
maxCachedMessages¶
The maximum number of messages to cache per channel. Decreasing this leads to more missing messageUpdated/messageDeleted events, increasing this leads to more RAM usage, especially over time.
rateLimitAsError¶
Have the lib throw a rejection Promise/callback when being ratelimited, instead of auto-retrying.
disableEveryone¶
Have the lib insert a zero width space between here and everyone mentions disabling them.
shardCount¶
The total number of shards.
shardId¶
A zero-based integer representing the value of the current shard.
Attributes¶
channels¶
A Cache of ServerChannel objects that the client has cached.
privateChannels¶
A Cache of PMChannel objects that the client has cached. These are all the Private/Direct Chats the client is in.
voiceConnections¶
A Cache of VoiceConnection objects that the client is in.
voiceConnection¶
Returns a VoiceConnection object, is an alias to voiceConnections[0].
readyTime¶
A Number unix timestamp dating to when the Client emitted ready.
uptime¶
A Number in milliseconds representing how long the Client has been ready for.
userAgent¶
An object containing url, version and full. Setting this property allows the discord developers to keep track of active bots, it defaults to the discord.js git repo and the current version of the package. url should be the repository/homepage of the creator. version should be the version of your bot. full is read only and will be automatically generated upon setting.
Functions¶
Note
Any functions used here that take callbacks as an optional parameter can also be used as Promises. Promises take the exact same parameters for each use case, except errors are moved to catch statements instead of then. For example, you can do:
bot.login(email, password).then(success).catch(err);
function success(token){
// handle success
}
function err(error){
// handle error
}
or use callbacks:
bot.login(email, password, function(error, token){
// handle error and success
});
login(email, password, callback)¶
Logs the client in so it can begin initialising. Use this after registering your events to ensure they are called!
email - The e-mail used to sign in, String.
password - The password used to sign in, String.
- callback - function that takes the following parameters:
- error - An error if any occurred
- token - The token received after logging in, String.
loginWithToken(token, email, password, callback)¶
Logs the client in, using just a token. The specified email and password are optional - they’re only needed when using updateDetails which requires them for authentication.
token - A valid Discord authentication token used to log in, String
email - (Optional) The e-mail used for later authentication, String.
password - (Optional) The password used for later authentication, String.
- callback - function that takes the following parameters:
- error - An error if any occurred
- token - A String containing the specified token. This is only used for compatibility with login, this token will always be identical to the specified one.
logout(callback)¶
Logs the client out and closes the WebSocket connections.
- callback - function that takes the following parameter:
- error - An error if any occurred
destroy(callback)¶
Similar to logout but should be used if you’re not going to create the Client again later in your program.
- callback - function that takes the following parameter:
- error - An error if any occurred
sendMessage(channel, content, options, callback)¶
Sends a message to the specified channel.
channel - a Channel Resolvable or User Resolvable
content - (Optional if file is passed in options) a String Resolvable - the message you want to send
- options - (Optional) object containing:
tts - (Optional) Boolean, should message be text-to-speech
disableEveryone - (Optional) Boolean, disable here and everyone mentions
- file - (Optional) object, containing:
- file - a File Resolvable
- name - (Optional) String, filename to upload file as
- callback - function that takes the following parameters:
- error - error object if any occurred
- message - the sent Message
sendTTSMessage(channel, content, callback)¶
An alias for sendMessage(channel, content, {tts: true}, callback)
sendFile(channel, attachment, name, content, callback)¶
Sends a file to the specified channel.
channel - a Channel Resolvable or User Resolvable
attachment - A File Resolvable
name - (Optional) String, filename to upload file as
content - (Optional) String, text message to send with the attachment
- callback - function taking the following:
- error - error if any occurred
- message - the sent Message
reply(message, content, options, callback)¶
Shortcut to sendMessage but prepends a mention to the sender of the original message to the start of your message.
message - The Message to reply to
content - a String Resolvable - the message you want to send
- options - object containing:
- tts - Boolean, should message be text-to-speech
- callback - function that takes the following parameters:
- error - error object if any occurred
- message - the sent Message
replyTTS(message, content, callback)¶
An alias for reply(message, content, {tts: true}, callback)
awaitResponse(message, prompt, options, callback)¶
Wait for a response from the same user in the same channel as an existing message.
message - The original Message
prompt - a String Resolvable - a message you want to send to prompt the user
- options - object containing:
- tts - Boolean, should message be text-to-speech
- callback - function that takes the following parameters:
- error - error object if any occurred
- message - the sent Message
updateMessage(message, content, options, callback)¶
Updates the content of a previously sent message
message - The Message to update
content - a String Resolvable - the content you want to update the message with
- options - object containing:
- tts - Boolean, should message be text-to-speech
- callback - function that takes the following parameters:
- error - error object if any occurred
- message - the sent Message
deleteMessage(message, options, callback)¶
Attempts to delete a message
message - The Message Resolvable to delete
- options - object containing the following:
- wait - Milliseconds as a number to wait before deleting the message
- callback - function that takes the following parameters:
- error - error object if any occurred
deleteMessages(messages, callback)¶
Attempts to bulk delete messages from the same channel
message - Array of Message Resolvable to delete
- callback - function that takes the following parameters:
- error - error object if any occurred
getChannelLogs(channel, limit, options, callback)¶
Gets a list of previously sent messages in a channel.
channel - A Channel Resolvable to get messages from
limit - The maximum amount of messages to retrieve - defaults to 50. A Number
- options - An object containing either of the following:
- before - A Message Resolvable - gets messages before this message.
- after - A Message Resolvable - gets messages after this message.
- around - A Message Resolvable - gets the messages around this message.
- callback - function taking the following:
- error - error if any occurred
- messages - array of Message objects sent in channel
getMessage(channel, messageID, callback)¶
Gets a message. This also works for messages that aren’t cached but will only work for OAuth bot accounts.
pinMessage(message, callback)¶
Pins a message to a channel.
message - The Message to pin.
- callback - function taking the following:
- error - error if any occurred
unpinMessage(message, callback)¶
Unpins a message from a channel.
message - The Message to unpin.
- callback - function taking the following:
- error - error if any occurred
getPinnedMessages(channel, callback)¶
Gets a list of all pinned messages in a channel.
getBans(server, callback)¶
Gets a list of banned users in a server.
server - Server Resolvable - The server to get banned users of
- callback - function taking the following:
- error - error if any occurred
- users - array of banned users in the server
joinServer(invite, callback)¶
Joins a server from the given invite. This will not work for OAuth bot accounts, you must use OAuth invite URLs instead.
invite - an Invite Resolvable
- callback - function taking the following:
- error - error if any occurred
- server - the joined Server
createServer(name, region, callback)¶
Creates a server
name - String, name of the server
region - String, region of the server, currently us-west, us-east, us-south, us-central, singapore, london, sydney, frankfurt or amsterdam
- callback - function taking the following:
- error - error if any occurred
- server - the created Server
updateServer(server, options, callback)¶
Updates the information, such as name or region, of a server the client is in
server - a Server Resolvable
- options - object containing (all optional):
- name - String, name of the server
- region - String, region of the server, currently us-west, us-east, us-south, us-central, singapore, london, sydney, frankfurt or amsterdam
- ownerID - a User Resolvable, user to transfer the server to (must be owner)
- icon - a Base64 Resolvable
- splash - a Base64 Resolvable (VIP only)
- verificationLevel - Number, a verification level (0, 1, 2, 3)
- afkChannelID - a Channel Resolvable, the AFK voice channel
- afkTimeout - Number, AFK timeout in seconds
- callback - function taking the following:
- error - error if any occurred
deleteServer(server, callback)¶
Deletes a server that the client is in
server - a Server Resolvable
- callback - function taking the following:
- error - error if any occurred
leaveServer(server, callback)¶
Leaves a server that the client is in
server - a Server Resolvable
- callback - function taking the following:
- error - error if any occurred
createChannel(server, name, type, callback)¶
Creates a channel in a server
server - a Server Resolvable
name - String, name of the channel. Spaces not allowed.
type - defaults to text, but can also be voice
- callback - function taking the following:
- error - error if any occurred
- channel - the created ServerChannel
deleteChannel(channel, callback)¶
Deletes a channel in a server.
channel - a Channel Resolvable to delete
- callback - function taking the following:
- error - error if any occurred.
banMember(user, server, length, callback)¶
Bans a user from a server.
user - A User Resolvable to ban
server - A Server Resolvable to ban the user from
length - Number, how many days to go back and delete messages from that user
- callback - function taking the following:
- error - error if any occurred.
unbanMember(user, server, callback)¶
Unbans a user from a server.
user - A User Resolvable to unban
server - A Server Resolvable to unban the user from
- callback - function taking the following:
- error - error if any occurred.
kickMember(user, server, callback)¶
Removes a user from a server
user - A User Resolvable to kick
server - A Server Resolvable to kick the user from
- callback - function taking the following:
- error - error if any occurred.
moveMember(user, channel, callback)¶
Moves a user from one voice channel into another.
user - A User Resolvable that should be moved
channel - The Channel Resolvable to move the user to
- callback - function taking the following:
- error - error if any occurred.
createInvite(channel, options, callback)¶
Creates an invite for the specified channel (or server)
channel - A Channel Resolvable
- options - object containing:
- maxAge - Number for maximum time in seconds for invite’s validity
- maxUses - Number, maximum uses of invite
- temporary - Boolean, whether the invite should be temporary
- xkcd - Boolean, whether the invite should be human-readable-friendly.
- callback - function taking the following:
- error - error if any occurred
- invite - the created Invite
getInvite(invite, callback)¶
Gets more info on a specific invite
invite - An Invite Resolvable
- callback - function taking the following:
- error - error if any occurred
- invite - an Invite object
getInvites(source, callback)¶
Gets all the invites in a channel/server
source - A Channel Resolvable or Server Resolvable
- callback - function taking the following:
- error - error if any occurred
- invite - Array of Invite objects
deleteInvite(invite, callback)¶
Deletes an invite
invite - An Invite Resolvable
- callback - a function taking the following:
- error - error if any occurred
setStatus(status, game, callback)¶
Sets the Discord Status of the Client
status - String, either
online, here, active, available
oridle, away
game - String, Name of game being played, or Object with the properties name url type, or null to clear
- callback - function taking the following:
- error - error if any occurred
setStatusOnline()¶
Aliases: setStatusHere, setStatusActive, setStatusAvailable
Sets the status of the Client to Online
setPlayingGame(game, callback)¶
Sets the Discord Status of the Client
game - String, Name of game being played, or null to clear
- callback - function taking the following:
- error - error if any occurred
setStreaming(name, url, type, callback)¶
Sets the Discord Status of the Client
name - String, Name of game being played
url - String, URL that it will link to, only supports twitch.tv urls at this time.
type - Number, 1 indicates streaming
- callback - function taking the following:
- error - error if any occurred
setChannelTopic(channel, topic, callback)¶
Sets the topic of a channel
channel - A Channel Resolvable
topic - A String
- callback - function taking the following:
- error - error if any occurred
setChannelName(channel, name, callback)¶
Sets the name of a channel
channel - A Channel Resolvable
name - A String
- callback - function taking the following:
- error - error if any occurred
setChannelNameAndTopic(channel, name, topic, callback)¶
Sets the name and topic of a channel
channel - A Channel Resolvable
name - A String
topic - A String
- callback - function taking the following:
- error - error if any occurred
setChannelUserLimit(channel, limit, callback)¶
Sets the user limit of a voice channel
channel - A Channel Resolvable
limit - A Number, user limit (0 - 99)
- callback - function taking the following:
- error - error if any occurred
setChannelBitrate(channel, bitrate, callback)¶
Sets the bitrate of a voice channel
channel - A Channel Resolvable
bitrate - A Number, bitrate (in kb/s) (8 - 96)
- callback - function taking the following:
- error - error if any occurred
updateChannel(channel, data, callback)¶
Updates the settings of a channel
channel - A Channel Resolvable
- details - object containing any of the following:
- name - String, the new name of channel
- topic - String, the new topic of the channel (TextChannel only)
- position - Number, the new position of the channel
- userLimit - Number, the new user limit of the channel (VoiceChannel only)
- bitrate - Number, the new bitrate (in kb/s) of the channel (VoiceChannel only)
- callback - function taking the following:
- error - error if any occurred
startTyping(channel, callback)¶
Marks the client as typing in a channel.
channel - A Channel Resolvable
- callback - function taking the following:
- error - error if any occurred
stopTyping(channel, callback)¶
Marks the client as not typing in a channel (takes a few seconds to go active).
channel - A Channel Resolvable
- callback - function taking the following:
- error - error if any occurred
updateDetails(details, callback)¶
Updates the details of the client
- details - object containing any of the following:
- avatar - Base64 Resolvable, new avatar of the client
- email - String, new email of the client
- newPassword - String, new password of the client
- username - String, new username of the client
- callback - function taking the following:
- error - error if any occurred
setAvatar(avatar, callback)¶
Sets the avatar of the client
avatar - Base64 Resolvable, new avatar of the client
- callback - function taking the following:
- error - error if any occurred
setUsername(name, callback)¶
Sets the username of the client
username - String, new username of the Client
- callback - function taking the following:
- error - error if any occurred
joinVoiceChannel(channel, callback)¶
Joins a Voice Channel to begin transmitting audio. If you have an OAuth bot account, you can connect to multiple voice channels at once, but only one per guild.
channel - A VoiceChannel Resolvable
- callback - function that takes the following:
- error - error if any occurred
- connection - VoiceConnection, the created Voice Connection.
leaveVoiceChannel(channel, callback)¶
Leaves the specified Voice Channel if connected
channel - A VoiceChannel Resolvable
- callback - function that takes the following:
- error - error if any occurred
createRole(server, data, callback)¶
Creates a new role in a server.
server - a Server Resolvable
data - object containing the structure below
- callback - function that takes the following:
- error - error if any occurred
- role - the created Role
// structure of data parameter (all attrs optional):
{
color : 0xFF0000,
hoist : false,
name : "A New Role!",
permissions : [
// see the constants documentation for full permissions
"attachFiles", "sendMessages"
],
mentionable: false
}
updateRole(role, data, callback)¶
Updates a role in a server.
role - a Role
data - an object taking the structure shown below
- callback - a function taking the following:
- error - error if any occurred
- role - the updated Role
// structure of data parameter (all attrs optional):
{
color : 0xFF0000,
hoist : false,
name : "A New Role!",
permissions : [
// see the constants documentation for full permissions
"attachFiles", "sendMessages"
],
mentionable: false
}
deleteRole(role, callback)¶
Deletes a role from a server
role - The Role to delete
- callback - function that takes the following:
- error - error if any occurred
addMemberToRole(member, role, callback)¶
Aliases : addUserToRole
Adds a member of a server to a role in the server
member - A User Resolvable
role - A Role Resolvable or an array of Role Resolvable
- callback - function that takes the following:
- error - error if any occurred
memberHasRole(member, role)¶
Aliases : userHasRole
Returns if a user has a role
- member - A User Resolvable
- role - A Role Resolvable or an array of Role Resolvable
removeMemberFromRole(member, role, callback)¶
Aliases : removeUserFromRole
Removes a member of a server from a role in the server
member - A User Resolvable
role - A Role Resolvable or an array of Role Resolvable
- callback - function that takes the following:
- error - error if any occurred
overwritePermissions(channel, roleOrUser, options, callback)¶
Overwrites the permissions of a role or a user in a channel
channel - a Channel Resolvable
options - an object containing a structure as shown below
- callback - function that takes the following:
- error - error if any occurred
{
"sendMessages" : false,
"attachFiles" : true
}
muteMember(user, server, callback)¶
Server-mutes a member.
user - A User Resolvable to mute
server - A Server Resolvable to mute the user in
- callback - function taking the following:
- error - error if any occurred.
unmuteMember(user, server, callback)¶
Server-unmutes a member.
user - A User Resolvable to unmute
server - A Server Resolvable to unmute the user in
- callback - function taking the following:
- error - error if any occurred.
deafenMember(user, server, callback)¶
Server-deafens a member.
user - A User Resolvable to deafen
server - A Server Resolvable to deafen the user in
- callback - function taking the following:
- error - error if any occurred.
undeafenMember(user, server, callback)¶
Server-undeafens a member.
user - A User Resolvable to undeafen
server - A Server Resolvable to undeafen the user in
- callback - function taking the following:
- error - error if any occurred.
setNickname(server, nickname, user, callback)¶
Set the nickname of a user on a server.
server - A Server Resolvable to set the nickname of the user in
nickname - string of the nickname
user - The User Resolvable to perform the nickname change on. If no user is specified, this will change the bot user’s nickname
- callback - function taking the following:
- error - error if any occurred.
setNote(user, note, callback)¶
Set the note of a user. This will only work for user accounts.
user - A User Resolvable to which the note is applied.
note - String, content of the note, or null to clear.
- callback - function taking the following:
- error - error if any occurred.
Events¶
Discord.Client is an EventEmitter, so you can use .on() and .off() to add and remove events.
ready¶
Emitted when the client is ready to use
debug¶
Emitted when the client debugs or wants to log something internally
warn¶
Emitted when the client has encountered a small error that can be avoided.
messageDeleted¶
Emitted when a message has been deleted and the Client finds out, supplies a Message object IF available, and a Channel object.
messageUpdated¶
Emitted when a message has been updated and the client finds out. Supplies two Message objects, the first being the message before the update, the second being the new, updated message.
disconnected¶
Emitted when the client is disconnected from the Discord server.
error¶
Emitted when the client runs into a big problem, supplies an error object.
raw¶
Emitted when a message over WebSocket is received, it supplies one object containing the raw data from the WebSocket.
serverUpdated¶
Emitted when a server is updated (e.g. name change). Supplies two Server objects, the first being the server before the update, the second being the new, updated server.
channelCreated¶
Emitted when a channel is created, supplies a Channel object (includes PM chats as well as server channels).
channelUpdated¶
Emitted when a channel is updated (e.g. name/topic change). Supplies two Channel objects, the first being the channel before the update, the second being the new, updated channel.
serverRoleUpdated¶
Emitted when a role is updated in a server, supplies two Role objects. The first is the old role, the second is the updated role.
serverMemberRemoved¶
Emitted when a member is removed from a server. Supplies a Server object and a User object.
serverMemberUpdated¶
Emitted when a member in a server is updated. Supplies a Server object and 2 User objects, the first being the new, updated user, the second being the old one. The old user object could be null if the bot didn’t previously have the member cached.
presence¶
Emitted when a user goes online/offline/idle, starts/stops playing a game, or changes their username/avatar/similar. Supplies 2 User objects, the first being the old user, the second being the new, updated user.
userTypingStarted¶
Emitted when a user starts typing in a channel. Supplies two parameters, a User object and a Channel object.
userTypingStopped¶
Emitted when a user stop typing in a channel. Supplies two parameters, a User object and a Channel object.
userBanned¶
Emitted when a user is banned from a server. Supplies two parameters, a User object and a Server object.
userUnbanned¶
Emitted when a user is unbanned from a server. Supplies two parameters, a User object and a Server object.
noteUpdated¶
Emitted when a note is updated. Supplies a User object (containing the updated note) and the old note.
voiceJoin¶
Emitted when a user joins a voice channel, supplies a VoiceChannel and a User.
voiceSwitch¶
Emitted when a user switches voice channels, supplies the old VoiceChannel, the new VoiceChannel, and a User.
voiceLeave¶
Emitted when a user leaves a voice channel, supplies a VoiceChannel and a User.
voiceStateUpdate¶
Emitted when a user mutes/deafens, supplies a VoiceChannel, User, an object containing the old mute/selfMute/deaf/selfDeaf properties, and an object containing the new mute/selfMute/deaf/selfDeaf properties.
voiceSpeaking¶
Emitted when a user starts or stops speaking, supplies a VoiceChannel, and User. The speaking property under the supplied User object can be used to determine whether the user started or stopped speaking.
Server¶
extends Equality
Stores information about a Discord Server.
Attributes¶
region¶
String, region of the server.
name¶
String, name of the server.
id¶
String, ID of the server - never changes.
channels¶
Channels in the server, a Cache of ServerChannel objects.
icon¶
ID/Hash of server icon, use server.iconURL
for an URL to the icon.
afkTimeout¶
Number, the AFK timeout in seconds before a user is classed as AFK. If there isn’t an AFK timeout, this will be null.
afkChannel¶
The channel where AFK users are moved to, ServerChannel object. If one isn’t set, this will be null.
iconURL¶
The URL of the Server’s icon. If the server doesn’t have an icon, this will be null.
createdAt¶
A Date referring to when the server was created.
Functions¶
rolesOfUser(user)¶
Aliases: rolesOf, rolesOfMember
Returns an array of the roles affecting a user server-wide.
usersWithRole(role)¶
Aliases: membersWithRole
Returns an array of users that have the specified role.
detailsOfUser(user)¶
Aliases detailsOf, detailsOfMember
Returns an object containing metadata of a user within the server, containing a structure similar to the following:
{
joinedAt: 1449339323747,
roles: [],
mute: false,
selfMute: false,
deaf: false,
selfDeaf: false,
nick: 'Nickname'
}
leave()¶
createInvite(options, callback)¶
client.createInvite(server, options, callback)
createRole(data, callback)¶
client.createRole(server, data, callback)
createChannel(name, type, callback)¶
client.createChannel(server, name, type, callback)
getBans(callback)¶
client.getBans(server, callback)
banMember(user, length, callback)¶
client.banMember(member, server, length, callback)
unbanMember(user, callback)¶
client.unbanMember(member, server, callback)
kickMember(user, callback)¶
client.kickMember(member, server, callback)
setNickname(nickname, user, callback)¶
client.setNickname(server, nickname, user, callback)
User¶
extends Equality
Stores information about users.
Attributes¶
discriminator¶
Integer from 0-9999, don’t use this to identify users. Used to separate the user from the 9998 others that may have the same username. Made redundant by user.id
.
id¶
String (do not parse to an Integer, will become inaccurate). The ID of a user, never changes.
avatar¶
String, the ID/hash of a user’s avatar. To get a path to their avatar, see user.avatarURL
.
status¶
The status of a user, String. Either online
, offline
or idle
.
game¶
The game object of a user. null if not playing a game, otherwise Object containing the following values:
{
name : 'Game Name' //Name of game user is playing
}
typing¶
Object containing the following values:
{
since : 1448038288519, //timestamp of when
channel : <Channel Object> // channel they are typing in.
}
avatarURL¶
A valid URL to the user’s avatar if they have one, otherwise null.
bot¶
A boolean that represents if the user is an official OAuth bot account or not.
voiceChannel¶
The VoiceChannel the user is connected to. If they aren’t in any voice channels, this will be null
.
createdAt¶
A Date referring to when the user was created.
note¶
The note of the user, String.
speaking¶
A boolean that represents whether or not the user is speaking in a voice channel, default is false.
Functions¶
mention()¶
Returns a valid string that can be sent in a message to mention the user. By default, user.toString()
does this so by adding a user object to a string, e.g. user + ""
, their mention code will be retrieved.
sendMessage(content, options, callback)¶
client.sendMessage(channel, content, options, callback)
sendTTSMessage(content, callback)¶
client.sendTTSMessage(channel, content, callback)
sendFile(attachment, name, content, callback)¶
client.sendFile(channel, attachment, name, content, callbasck)
startTyping(callback)¶
client.startTyping(channel, callback)
stopTyping(callback)¶
client.stopTyping(channel, callback)
addTo(role, callback)¶
client.addMemberToRole(member, role, callback)
removeFrom(role, callback)¶
client.removeMemberFromRole(member, role, callback)
getLogs(limit, options, callback)¶
client.getChannelLogs(channel, limit, options, callback)
getMessage(messageID, callback)¶
client.getMessage(channel, messageID, callback)
hasRole(role)¶
client.memberHasRole(member, role)
Message¶
extends Equality
A Message object is used to represent the data of a message.
Attributes¶
channel¶
The channel the message was sent in, either a TextChannel or PMChannel.
server¶
The Server the message was sent in. Will be undefined if the message was sent in a PMChannel.
attachments¶
A raw array of attachment objects.
tts¶
Boolean, true if the message was text-to-speech.
embeds¶
A raw array of embed objects.
timestamp¶
Number, timestamp of when the message was sent.
everyoneMentioned¶
Boolean, true if @everyone
was mentioned.
id¶
String, ID of the message.
editedTimestamp¶
Timestamp on when the message was last edited, Number. Potentially null.
content¶
String, content of the message.
cleanContent¶
String, content of the message with valid user mentions (<@123>) replaced with “@username”.
pinned¶
Boolean, true if the message is pinned to its channel.
Functions¶
isMentioned(user)¶
Returns true if the given user was mentioned in the message.
- user - A User Resolvable
toString()¶
Returns the content of the Message.
delete(options, callback)¶
client.deleteMessage(message, options, callback
update(content, options, callback)¶
client.updateMessage(message, content, options, callback)
reply(content, options, callback)¶
client.reply(message, content, options, callback)
replyTTS(content, callback)¶
client.replyTTS(message, content, callback)
pin(callback)¶
client.pinMessage(message, callback)
unpin(callback)¶
client.unpinMessage(message, callback)
Invite¶
Used to represent data of an invite.
Attributes¶
maxAge¶
Number, how long (in seconds) the invite has since creation before expiring.
code¶
String, the invite code.
channel¶
The ServerChannel the invite is for.
revoked¶
Boolean, whether the invite has been revoked or not.
createdAt¶
Number, timestamp of when the invite was created.
temporary¶
Boolean, whether the invite is temporary or not.
uses¶
Number, uses of the invite remaining.
maxUses¶
Number, maximum uses of the invite.
xkcd¶
Boolean, whether the invite is intended to be easy to read and remember by a human.
VoiceConnection¶
discord.js currently supports sending audio data over Discord voice chat. A voice connection can be initiated using client.joinVoiceChannel and then later accessed again using the client.voiceConnection property. You can play something using the playXYZ methods and then later stop the playback and listen for events that tell you about the playback status.
Note that discord.js does not support receiving data from voice yet, only sending.
Attributes¶
voiceChannel¶
VoiceChannel that the connection is for
token¶
The token used to authenticate with Discord
encoder¶
The AudioEncoder_ used to encode data in this particular session
playingIntent¶
A stream intent used to bind events to the voice connection
playing¶
Whether or not the bot is currently playing something
paused¶
Whether or not the playback is currently paused
streamTime¶
The amount of time the current track has been playing for, in milliseconds
Functions¶
playFile(path, options, callback)¶
Plays a file to the voice channel. The file can be in practically any format; if you’re looking for a list, look here: Format list. In addition to a file path local to your computer, it can also accept a URL, however this is not recommended as the entire content of the URL will be read before any playback starts. This can cause delays from seconds to minutes - you can use playRawStream with a Stream obtained from the URL instead.
The options object can be used to control playback properties, currently, it allows setting the seek (in seconds) using the seek property, and the volume using the volume property, which can be in any of the following formats:
- A number representing the linear change in volume; 1 is equal to no change, 0 is completely silent, 0.5 is half the regular volume and 2 is double the regular volume.
- A string representing the linear change in volume, if this is more convenient for you.
- A string representing decibel gain, where “0dB” is no change, “-3dB” is half the volume (in linear units), “+6dB” is four times the volume (in linear units) and so on.
It is recommended to change the volume, because the default of 1 is usually too loud. (A reasonable setting is 0.25 or “-6dB”).
The callback will be called immediately after playback has started, it will have an error object and the stream intent as its parameters. The callback will only receive an error if the encoding fails, for playback errors, you can bind a function to the error event of the intent. The intent supports the following events:
- The time event is emitted every packet (20 milliseconds) and has the current playback time in milliseconds as its only parameter. The playback time can also be checked at any time using the streamTime attribute.
- The end event is emitted once playback ends. Depending on various factors, it may be emitted a couple seconds earlier than the actual stream ending, you may have to add an offset if necessary.
- The error event is emitted if an error happens during playback, such as failing to send a packet.
The intent can later be accessed again using the playingIntent property. If you prefer _Promises over callbacks, this method will return a promise you can use in the same way as the callback.
playRawStream(stream, options, callback)¶
This method is used in much the same way as playFile, except it plays data back from a stream containing audio data instead of a file or URL.
playArbitraryFFmpeg(ffmpegOptions, volume, callback)¶
This method can be used to play data obtained from an arbitrary call to ffmpeg. Note that the array of options given as the parameter will still be concatenated with the following options so it can be used with Discord:
-loglevel 0
-f s16le
-ar 48000
-ac 2
pipe:1
setSpeaking(value)¶
Sets whether or not the user is speaking (green circle around user on the official client). discord.js does this automatically when playing something, but you may want to spoof it or manually disable it.
- value - true or false: whether or not you want the bot to show as speaking
setVolume(volume)¶
Sets the current volume of the connecion. 1.0 is normal, 0.5 is half as loud, 2.0 is twice as loud.
getVolume()¶
Returns the current volume. 1.0 is normal, 0.5 is half as loud, 2.0 is twice as loud.
pause()¶
Pauses the current connection’s audio.
resume()¶
Resumes the current connection’s audio.
stopPlaying()¶
Stops the current playback immediately. After this method has finished, it is safe to play something else.
destroy()¶
Disconnects from the voice server and destroys all network connection. It’s impossible to play anything on this connection afterwards, you will have to re-initiate a connection using client.joinVoiceChannel. This method also calls stopPlaying internally, you don’t have to do that yourself.
Channel¶
extends Equality
The Channel class is the base class for all types of channel.
Attributes¶
id¶
The ID of the channel, a String.
isPrivate¶
Indicates whether the channel is PM channel, is Boolean.
createdAt¶
A Date referring to when the channel was created.
PMChannel¶
extends Channel
A PMChannel is a Private/Direct channel between the Client and another user.
Attributes¶
Functions¶
toString()¶
Returns a mention of the recipient.
sendMessage(content, options, callback)¶
client.sendMessage(channel, content, options, callback)
sendTTSMessage(content, callback)¶
client.sendTTSMessage(channel, content, callback)
sendFile(attachment, name, content, callback)¶
client.sendFile(channel, attachment, name, content, callbasck)
startTyping(callback)¶
client.startTyping(channel, callback)
stopTyping(callback)¶
client.stopTyping(channel, callback)
getLogs(limit, options, callback)¶
client.getChannelLogs(channel, limit, options, callback)
getMessage(messageID, callback)¶
client.getMessage(channel, messageID, callback)
ServerChannel¶
extends Channel
A ServerChannel is a Channel that belongs to a Server.
Attributes¶
name¶
String, name of the channel.
type¶
String, either voice
or text
.
position¶
Number, position in the channel list.
permissionOverwrites¶
Cache of all the PermissionOverwrite objects affecting the channel.
Functions¶
permissionsOf(userOrRole)¶
Aliases: permsOf
Returns a ChannelPermissions object of a user or role’s permissions in that channel.
mention()¶
Returns a string that can be used in discord messages to mention a channel. serverChannel.toString() defaults to this.
update(data, callback)¶
client.updateChannel(channel, data, callback)
TextChannel¶
extends ServerChannel
A text channel of a server.
Attributes¶
topic¶
The topic of the channel, a String.
Functions¶
setTopic(topic, callback)¶
client.setChannelTopic(channel, topic, callback)
setNameAndTopic(name, topic, callback)¶
client.setChannelNameAndTopic(channel, name, topic, callback)
sendMessage(content, options, callback)¶
client.sendMessage(channel, content, options, callback)
sendTTSMessage(content, callback)¶
client.sendTTSMessage(channel, content, callback)
sendFile(attachment, name, content, callback)¶
client.sendFile(channel, attachment, name, content, callbasck)
startTyping(callback)¶
client.startTyping(channel, callback)
stopTyping(callback)¶
client.stopTyping(channel, callback)
getLogs(limit, options, callback)¶
getMessage(messageID, callback)¶
client.getMessage(channel, messageID, callback)
VoiceChannel¶
extends ServerChannel
A voice channel of a server. Currently, the voice channel class has no differences to the ServerChannel class.
Attributes¶
userLimit¶
The maximum amount of users that can connect to the voice channel. If it’s 0, there is no limit
bitrate¶
The bitrate of the voice channel (in kb/s).
Permission Constants¶
In discord.js, you can handle permissions in two ways. The preferred way is to just use the string name of the permission, alternatively you can use Discord.Constants.Permissions["permission name"]
.
Valid Permission Names¶
{
// general
administrator,
createInstantInvite,
kickMembers,
banMembers,
manageRoles,
managePermissions,
manageChannels,
manageChannel,
manageServer,
changeNickname,
manageNicknames,
// text
readMessages,
sendMessages,
sendTTSMessages,
manageMessages,
embedLinks,
attachFiles,
readMessageHistory,
mentionEveryone,
// voice
voiceConnect,
voiceSpeak,
voiceMuteMembers,
voiceDeafenMembers,
voiceMoveMembers,
voiceUseVAD
};
Preferred Way¶
The preferred way of using permissions in discord.js is to just use the name. E.g:
role.hasPermission("voiceUseVAD")
Alternative¶
You can also go the long way round and use the numerical permission like so:
role.hasPermission( Discord.Constants.Permissions.voiceUseVAD )
Role¶
Represents data for a Server Role.
Attributes¶
position¶
Number, position of the role when viewing the roles of a server.
name¶
String, name of the role.
managed¶
Boolean, whether Discord has created the role itself. Currently only used for Twitch integration.
id¶
String, ID of the role.
hoist¶
Boolean, whether the role should be displayed as a separate category in the users section.
color¶
Number, a base 10 colour. Use role.colorAsHex()
to get a hex colour instead.
createdAt¶
A Date referring to when the role was created.
Functions¶
serialise()¶
Aliases: serialize
Makes an object with the permission names found in Permission Constants and a boolean value for them.
hasPermission(permission)¶
Sees whether the role has the permission given.
- permission - See Permission Constants for valid permission names.
colorAsHex()¶
Returns the role’s colour as hex, e.g. #FF0000
.
mention()¶
Returns a valid string that can be sent in a message to mention the role. By default, role.toString()
does this so by adding a role object to a string, e.g. role + ""
, their mention code will be retrieved. If the role isn’t mentionable, its name gets returned.
delete()¶
client.deleteRole(role)
update(data)¶
addMember(member, callback)¶
client.addMemberToRole(member, roles, callback)
removeMember(member, callback)¶
client.removeMemberFromRole(member, roles, callback)
PermissionOverwrite¶
PermissionOverwrite is used to represent data about permission overwrites for roles or users in channels.
Attributes¶
id¶
String, the ID of the PermissionOverwrite. If overwrite.type
is role
, this is the role’s ID. Otherwise, it is a User overwrite.
type¶
String, type of the overwrite. Either member
or role
.
allowed¶
Returns the permissions explicitly allowed by the overwrite. An Array of Strings, which are names of permissions. More can be found at Permission Constants
denied¶
Returns the permissions explicitly denied by the overwrite. An Array of Strings, which are names of permissions. More can be found at Permission Constants
ChannelPermissions¶
ChannelPermissions is used to represent the final permissions of a user in a channel, to see exactly what they are and aren’t allowed to do.
Examples:
var user_permissions = channel.permissionsOf(user);
var can_mention_everyone = user_permissions.hasPermission("mentionEveryone");
Functions¶
serialize()¶
Aliases: serialise
Returns an object containing permission names and values. E.g:
{
createInstantInvite : true,
kickMembers : false
}
For more on valid permission names, see Permission Constants.
hasPermission(permission)¶
Sees whether the user has the permission given.
- permission - See Permission Constants for valid permission names.
Cache¶
extends Array
A Cache object extends an Array (so it can be used like a regular array) but introduces helper functions to make it more useful when developing with discord.js. Unlike a regular array, it doesn’t care about the instance or prototype of an object, it works purely on properties.
Examples:
client.users.get("id", 11238414);
client.channels.getAll("name", "general");
Functions¶
get(key, value)¶
Returns a contained object where object[key] == value
. Also works if value is a regex or a function. Returns the first object found that matches the criteria.
get(value)¶
Returns a contained object where object["id"] == value
. Shorthand for get("id", value)
. Returns null
if ID is not found.
getAll(key, value)¶
Similar to cache.get(key, value)
, but returns a Cache of any objects that meet the criteria.
has(key, value)¶
Returns true if there is an object that meets the condition object[key] == value
in the cache
add(data)¶
Adds an object to the Cache as long as all the other objects in the cache don’t have the same ID as it.
update(old, data)¶
Updates an old object in the Cache (if it exists) with the new one.
remove(data)¶
Removes an object from the cache if it exists.
random()¶
Get a random object from the cache.
Equality¶
The Equality class is used to see if two objects are equal, based on object_1.id === object_2.id
.
If any class in Discord extends equality, it means you should never the default equality operands (==
& ===
) as they could potentially be different instances and therefore appear not to be equal. Instead, use equalityObject.equals()
as shown below.
object1.equals(object2); // GOOD ✓
object1 == object2; // BAD ✖
Resolvables¶
In discord.js, the aim is to allow the end developer to have freedom in what sort of data types they supply. References to any sort of resolvable basically mean what types of data you can provide. The different resolvables are shown before:
Channel Resolvable¶
A Channel Resolvable allows:
User Resolvable¶
A User Resolvable allows:
- User
- Message
- TextChannel
- PMChannel
- Server
- String of User ID
Server Resolvable¶
A Server Resolvable allows:
- Server
- ServerChannel
- Message (only for messages from server channels)
- String of Server ID