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 or client.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?


_10
const user = interaction.options.getUser('target');
_10
await guild.members.ban(user);

How do I unban a user?


_10
const user = interaction.options.getUser('target');
_10
await 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.

Tip

How do I kick a guild member?


_10
const member = interaction.options.getMember('target');
_10
await member.kick();

How do I timeout a guild member?


_10
const member = interaction.options.getMember('target');
_10
await 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.

Tip

How do I add a role to a guild member?


_10
const role = interaction.options.getRole('role');
_10
const member = interaction.options.getMember('target');
_10
await member.roles.add(role);

How do I check if a guild member has a specific role?


_10
const role = interaction.options.getRole('role');
_10
const member = interaction.options.getMember('target');
_10
_10
if (member.roles.cache.has(role.id) {
_10
// ...
_10
}

How do I limit a command to a single user?


_10
if (interaction.user.id === 'id') {
_10
// ...
_10
}

Bot Configuration and Utility

How do I set my bot's username?


_10
await client.user.setUsername('username');

How do I set my bot's avatar?


_10
await client.user.setAvatar('URL or path');

How do I set my playing status?


_10
client.user.setActivity('activity');

How do I set my status to "Watching/Listening to/Competing in ..."?


_10
import { ActivityType } from 'discord.js';
_10
_10
client.user.setActivity('activity', { type: ActivityType.Watching });
_10
client.user.setActivity('activity', { type: ActivityType.Listening });
_10
client.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.

Tip

How do I make my bot display online/idle/dnd/invisible?


_10
client.user.setStatus('online');
_10
client.user.setStatus('idle');
_10
client.user.setStatus('dnd');
_10
client.user.setStatus('invisible');

How do I set both status and activity in one go?


_10
client.user.setPresence({ activities: [{ name: 'activity' }], status: 'idle' });

Miscellaneous

How do I send a message to a specific channel?


_10
const channel = client.channels.cache.get('id');
_10
await 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.

Tip

_10
const channel = client.channels.cache.get('id');
_10
_10
await channel.threads.create({
_10
name: 'Post name',
_10
message: { content: 'Message content' },
_10
appliedTags: ['tagId', 'anotherTagId'],
_10
});

How do I DM a specific user?


_10
await 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().

Tip

How do I mention a specific user in a message?


_10
const user = interaction.options.getUser('target');
_10
await interaction.reply(`Hi, ${user}.`);
_10
await 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.

Tip

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.


_10
new Client({ allowedMentions: { parse: ['users', 'roles'] } });

Even more control can be achieved by listing specific users or roles to be mentioned by id, e.g.:


_10
await channel.send({
_10
content: '<@123456789012345678> <@987654321098765432> <@&102938475665748392>',
_10
allowedMentions: { users: ['123456789012345678'], roles: ['102938475665748392'] },
_10
});

How do I prompt the user for additional input?


_10
await interaction.reply('Please enter more input.');
_10
const filter = (m) => interaction.user.id === m.author.id;
_10
_10
try {
_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!

Tip

How do I block a user from using my bot?


_10
const blockedUsers = ['id1', 'id2'];
_10
_10
client.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.

Tip

_10
client.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?


_10
const sentMessage = await interaction.channel.send('My message to react to.');
_10
// Unicode emoji
_10
await sentMessage.react('👍');
_10
_10
// Custom emoji
_10
await sentMessage.react('123456789012345678');
_10
await sentMessage.react('<emoji:123456789012345678>');
_10
await sentMessage.react('<a:emoji:123456789012345678>');
_10
await sentMessage.react('emoji:123456789012345678');
_10
await sentMessage.react('a:emoji:123456789012345678');

If you want to learn more about reactions, check out this dedicated guide on reactions!

Tip

How do I restart my bot with a command?


_10
process.exit();

process.exit() will only kill your Node process, but when using PM2, it will restart the process whenever it gets killed. You can read our guide on PM2 here.

Warning

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
_10
const fetchedMembers = await guild.members.fetch({ withPresences: true });
_10
const totalOnline = fetchedMembers.filter((member) => member.presence?.status === 'online');
_10
// Now you have a collection with all online member objects in the totalOnline variable
_10
console.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!

Warning

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
_17
client.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:


_10
await 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.

Tip

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:


_10
const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true });
_10
await 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:

index.js
emojiCharacters.js

_10
import { emojiCharacters } from './emojiCharacters.js';
_10
_10
console.log(emojiCharacters.a); // 🇦
_10
console.log(emojiCharacters[10]); // 🔟
_10
console.log(emojiCharacters['!']); // ❗

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 ..

Tip