Frequently asked questions
Legend
-
client
is a placeholder for the Client object:
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
. -
interaction
is a placeholder for the BaseInteraction:
client.on(Events.InteractionCreate, interaction => { ... });
. -
guild
is a placeholder for the Guild object:
interaction.guild
orclient.guilds.cache.get('id')
-
voiceChannel
is a placeholder for the VoiceChannel:
interaction.member.voice.channel
.
For a more detailed explanation of the notations commonly used in this guide, the docs, and the support server, see here.
Administrative
How do I ban a user?
_10const user = interaction.options.getUser('target');_10await guild.members.ban(user);
How do I unban a user?
_10const user = interaction.options.getUser('target');_10await guild.members.unban(user);
Discord validates and resolves user ids for users not on the server in user slash command options. To retrieve and use the full structure from the resulting interaction, you can use the CommandInteractionOptionResolver#getUser() method.
How do I kick a guild member?
_10const member = interaction.options.getMember('target');_10await member.kick();
How do I timeout a guild member?
_10const member = interaction.options.getMember('target');_10await member.timeout(60_000); // Timeout for one minute
Timeout durations are measured by the millisecond. The maximum timeout duration you can set is 28 days. To remove a
timeout set on a member, pass null
instead of a timeout duration.
How do I add a role to a guild member?
_10const role = interaction.options.getRole('role');_10const member = interaction.options.getMember('target');_10await member.roles.add(role);
How do I check if a guild member has a specific role?
_10const role = interaction.options.getRole('role');_10const member = interaction.options.getMember('target');_10_10if (member.roles.cache.has(role.id) {_10 // ..._10}
How do I limit a command to a single user?
_10if (interaction.user.id === 'id') {_10 // ..._10}
Bot Configuration and Utility
How do I set my bot's username?
_10await client.user.setUsername('username');
How do I set my bot's avatar?
_10await client.user.setAvatar('URL or path');
How do I set my playing status?
_10client.user.setActivity('activity');
How do I set my status to "Watching/Listening to/Competing in ..."?
_10import { ActivityType } from 'discord.js';_10_10client.user.setActivity('activity', { type: ActivityType.Watching });_10client.user.setActivity('activity', { type: ActivityType.Listening });_10client.user.setActivity('activity', { type: ActivityType.Competing });
If you would like to set your activity upon startup, you can use the ClientOptions object to set the appropriate PresenceData.
How do I make my bot display online/idle/dnd/invisible?
_10client.user.setStatus('online');_10client.user.setStatus('idle');_10client.user.setStatus('dnd');_10client.user.setStatus('invisible');
How do I set both status and activity in one go?
_10client.user.setPresence({ activities: [{ name: 'activity' }], status: 'idle' });
Miscellaneous
How do I send a message to a specific channel?
_10const channel = client.channels.cache.get('id');_10await channel.send('content');
How do I create a post in a forum channel?
Currently, the only way to get tag ids is programmatically through ForumChannel#availableTags.
_10const channel = client.channels.cache.get('id');_10_10await channel.threads.create({_10 name: 'Post name',_10 message: { content: 'Message content' },_10 appliedTags: ['tagId', 'anotherTagId'],_10});
How do I DM a specific user?
_10await client.users.send('id', 'content');
If you want to send a direct message to the user who sent the interaction, you can use interaction.user.send()
.
How do I mention a specific user in a message?
_10const user = interaction.options.getUser('target');_10await interaction.reply(`Hi, ${user}.`);_10await interaction.followUp(`Hi, <@${user.id}>.`);
Mentions in embeds may resolve correctly in embed titles, descriptions and field values but will never notify the user. Other areas do not support mentions at all.
How do I control which users and/or roles are mentioned in a message?
Controlling which mentions will send a ping is done via the allowedMentions
option, which replaces disableMentions
.
This can be set as a default in ClientOptions, and controlled per-message sent by your bot.
_10new Client({ allowedMentions: { parse: ['users', 'roles'] } });
Even more control can be achieved by listing specific users
or roles
to be mentioned by id, e.g.:
_10await channel.send({_10 content: '<@123456789012345678> <@987654321098765432> <@&102938475665748392>',_10 allowedMentions: { users: ['123456789012345678'], roles: ['102938475665748392'] },_10});
How do I prompt the user for additional input?
_10await interaction.reply('Please enter more input.');_10const filter = (m) => interaction.user.id === m.author.id;_10_10try {_10 const messages = await interaction.channel.awaitMessages({ filter, time: 60000, max: 1, errors: ['time'] });_10 await interaction.followUp(`You've entered: ${messages.first().content}`);_10} catch {_10 await interaction.followUp('You did not enter any input!');_10}
If you want to learn more about this syntax or other types of collectors, check out this dedicated guide page for collectors!
How do I block a user from using my bot?
_10const blockedUsers = ['id1', 'id2'];_10_10client.on(Events.InteractionCreate, (interaction) => {_10 if (blockedUsers.includes(interaction.user.id)) return;_10});
You do not need to have a constant local variable like blockedUsers
above. If you have a database system that you
use to store ids of blocked users, you can query the database instead.
_10client.on(Events.InteractionCreate, async (interaction) => {_10 const blockedUsers = await database.query('SELECT user_id FROM blocked_users;');_10 if (blockedUsers.includes(interaction.user.id)) return;_10});
Note that this is just a showcase of how you could do such a check.
How do I react to the message my bot sent?
_10const sentMessage = await interaction.channel.send('My message to react to.');_10// Unicode emoji_10await sentMessage.react('👍');_10_10// Custom emoji_10await sentMessage.react('123456789012345678');_10await sentMessage.react('<emoji:123456789012345678>');_10await sentMessage.react('<a:emoji:123456789012345678>');_10await sentMessage.react('emoji:123456789012345678');_10await sentMessage.react('a:emoji:123456789012345678');
If you want to learn more about reactions, check out this dedicated guide on reactions!
How do I restart my bot with a command?
_10process.exit();
What is the difference between a User and a GuildMember?
A User represents a global Discord user, and a GuildMember represents a Discord user on a specific server. That means only GuildMembers can have permissions, roles, and nicknames, for example, because all of these things are server-bound information that could be different on each server that the user is in.
How do I find all online members of a guild?
_10// First use guild.members.fetch to make sure all members are cached_10const fetchedMembers = await guild.members.fetch({ withPresences: true });_10const totalOnline = fetchedMembers.filter((member) => member.presence?.status === 'online');_10// Now you have a collection with all online member objects in the totalOnline variable_10console.log(`There are currently ${totalOnline.size} members online in this guild!`);
This only works correctly if you have the GuildPresences
intent enabled for your application and client. If you
want to learn more about intents, check out this dedicated guide on intents!
How do I check which role was added/removed and for which member?
_17// Start by declaring a guildMemberUpdate listener_17// This code should be placed outside of any other listener callbacks to prevent listener nesting_17client.on(Events.GuildMemberUpdate, (oldMember, newMember) => {_17 // If the role(s) are present on the old member object but no longer on the new one (i.e role(s) were removed)_17 const removedRoles = oldMember.roles.cache.filter((role) => !newMember.roles.cache.has(role.id));_17_17 if (removedRoles.size > 0) {_17 console.log(`The roles ${removedRoles.map((r) => r.name)} were removed from ${oldMember.displayName}.`);_17 }_17_17 // If the role(s) are present on the new member object but are not on the old one (i.e role(s) were added)_17 const addedRoles = newMember.roles.cache.filter((role) => !oldMember.roles.cache.has(role.id));_17_17 if (addedRoles.size > 0) {_17 console.log(`The roles ${addedRoles.map((r) => r.name)} were added to ${oldMember.displayName}.`);_17 }_17});
How do I check the bot's ping?
There are two common measurements for bot pings. The first, websocket heartbeat, is the average interval of a regularly sent signal indicating the healthy operation of the websocket connection the library receives events over:
_10await interaction.reply(`Websocket heartbeat: ${client.ws.ping}ms.`);
If you're using sharding, a specific shard's heartbeat can be found on the WebSocketShard instance,
accessible at client.ws.shards.get(id).ping
.
The second, Roundtrip Latency, describes the amount of time a full API roundtrip (from the creation of the command message to the creation of the response message) takes. You then edit the response to the respective value to avoid needing to send yet another message:
_10const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true });_10await interaction.editReply(`Roundtrip latency: ${sent.createdTimestamp - interaction.createdTimestamp}ms`);
Why do some emojis behave weirdly?
If you've tried using the usual method of retrieving unicode emojis, you may have noticed that some characters don't provide the expected results. Here's a short snippet that'll help with that issue. You can toss this into a file of its own and use it anywhere you need! Alternatively feel free to simply copy-paste the characters from below:
You can use the ⌃ Control ⌘ Command Space keyboard shortcut to open up an emoji picker that can be used for quick, easy access to all the Unicode emojis available to you.
On Windows, the shortcut is ⊞ ..