Frequently asked Questions

Legend

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?

const user = interaction.options.getUser('target');
guild.members.ban(user);
1
2

How do I unban a user?

const user = interaction.options.getUser('target');
guild.members.unban(user);
1
2

TIP

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()open in new window method.

How do I kick a guild member?

const member = interaction.options.getMember('target');
member.kick();
1
2

How do I timeout a guild member?

const member = interaction.options.getMember('target');
member.timeout(60_000); // Timeout for one minute
1
2

TIP

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?

const role = interaction.options.getRole('role');
const member = interaction.options.getMember('target');
member.roles.add(role);
1
2
3

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

const member = interaction.options.getMember('target');
if (member.roles.cache.some(role => role.name === 'role name')) {
	// ...
}
1
2
3
4

How do I limit a command to a single user?

if (interaction.user.id === 'id') {
	// ...
}
1
2
3

Bot Configuration and Utility

How do I set my bot's username?

client.user.setUsername('username');
1

How do I set my bot's avatar?

client.user.setAvatar('URL or path');
1

How do I set my playing status?

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

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

const { ActivityType } = require('discord.js');

client.user.setActivity('activity', { type: ActivityType.Watching });
client.user.setActivity('activity', { type: ActivityType.Listening });
client.user.setActivity('activity', { type: ActivityType.Competing });
1
2
3
4
5

TIP

If you would like to set your activity upon startup, you can use the ClientOptions object to set the appropriate Presence data.

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

const { PresenceUpdateStatus } = require('discord.js');

client.user.setStatus(PresenceUpdateStatus.Online);
client.user.setStatus(PresenceUpdateStatus.Idle);
client.user.setStatus(PresenceUpdateStatus.DoNotDisturb);
client.user.setStatus(PresenceUpdateStatus.Invisible);
1
2
3
4
5
6

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

const { PresenceUpdateStatus } = require('discord.js');

client.user.setPresence({ activities: [{ name: 'activity' }], status: PresenceUpdateStatus.Idle });
1
2
3

Miscellaneous

How do I send a message to a specific channel?

const channel = client.channels.cache.get('id');
channel.send('content');
1
2

How do I create a post in a forum channel?

TIP

Currently, the only way to get tag ids is programmatically through ForumChannel#availableTagsopen in new window.

const channel = client.channels.cache.get('id');
channel.threads.create({ name: 'Post name', message: { content: 'Message content' }, appliedTags: ['tagID', 'anotherTagID'] });
1
2

How do I DM a specific user?

client.users.send('id', 'content');
1

TIP

If you want to DM the user who sent the interaction, you can use interaction.user.send().

How do I mention a specific user in a message?

const user = interaction.options.getUser('target');
await interaction.reply(`Hi, ${user}.`);
await interaction.followUp(`Hi, <@${user.id}>.`);
1
2
3

TIP

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.

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

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

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

How do I prompt the user for additional input?

interaction.reply('Please enter more input.').then(() => {
	const collectorFilter = m => interaction.user.id === m.author.id;

	interaction.channel.awaitMessages({ filter: collectorFilter, time: 60_000, max: 1, errors: ['time'] })
		.then(messages => {
			interaction.followUp(`You've entered: ${messages.first().content}`);
		})
		.catch(() => {
			interaction.followUp('You did not enter any input!');
		});
});
1
2
3
4
5
6
7
8
9
10
11

TIP

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?

const blockedUsers = ['id1', 'id2'];
client.on(Events.InteractionCreate, interaction => {
	if (blockedUsers.includes(interaction.user.id)) return;
});
1
2
3
4

TIP

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:

client.on(Events.InteractionCreate, async interaction => {
	const blockedUsers = await database.query('SELECT user_id FROM blocked_users;');
	if (blockedUsers.includes(interaction.user.id)) return;
});
1
2
3
4

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?

interaction.channel.send('My message to react to.').then(sentMessage => {
	// Unicode emoji
	sentMessage.react('👍');

	// Custom emoji
	sentMessage.react('123456789012345678');
	sentMessage.react('<emoji:123456789012345678>');
	sentMessage.react('<a:emoji:123456789012345678>');
	sentMessage.react('emoji:123456789012345678');
	sentMessage.react('a:emoji:123456789012345678');
});
1
2
3
4
5
6
7
8
9
10
11

TIP

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

How do I restart my bot with a command?

process.exit();
1

DANGER

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

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?

// First use guild.members.fetch to make sure all members are cached
guild.members.fetch({ withPresences: true }).then(fetchedMembers => {
	const totalOnline = fetchedMembers.filter(member => member.presence?.status === PresenceUpdateStatus.Online);
	// Now you have a collection with all online member objects in the totalOnline variable
	console.log(`There are currently ${totalOnline.size} members online in this guild!`);
});
1
2
3
4
5
6

WARNING

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?

// Start by declaring a guildMemberUpdate listener
// This code should be placed outside of any other listener callbacks to prevent listener nesting
client.on(Events.GuildMemberUpdate, (oldMember, newMember) => {
	// If the role(s) are present on the old member object but no longer on the new one (i.e role(s) were removed)
	const removedRoles = oldMember.roles.cache.filter(role => !newMember.roles.cache.has(role.id));
	if (removedRoles.size > 0) {
		console.log(`The roles ${removedRoles.map(r => r.name)} were removed from ${oldMember.displayName}.`);
	}

	// If the role(s) are present on the new member object but are not on the old one (i.e role(s) were added)
	const addedRoles = newMember.roles.cache.filter(role => !oldMember.roles.cache.has(role.id));
	if (addedRoles.size > 0) {
		console.log(`The roles ${addedRoles.map(r => r.name)} were added to ${oldMember.displayName}.`);
	}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

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:

interaction.reply(`Websocket heartbeat: ${client.ws.ping}ms.`);
1

TIP

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:

const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true });
interaction.editReply(`Roundtrip latency: ${sent.createdTimestamp - interaction.createdTimestamp}ms`);
1
2

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:

// emojiCharacters.js
module.exports = {
	a: '🇦', b: '🇧', c: '🇨', d: '🇩',
	e: '🇪', f: '🇫', g: '🇬', h: '🇭',
	i: '🇮', j: '🇯', k: '🇰', l: '🇱',
	m: '🇲', n: '🇳', o: '🇴', p: '🇵',
	q: '🇶', r: '🇷', s: '🇸', t: '🇹',
	u: '🇺', v: '🇻', w: '🇼', x: '🇽',
	y: '🇾', z: '🇿', 0: '0️⃣', 1: '1️⃣',
	2: '2️⃣', 3: '3️⃣', 4: '4️⃣', 5: '5️⃣',
	6: '6️⃣', 7: '7️⃣', 8: '8️⃣', 9: '9️⃣',
	10: '🔟', '#': '#️⃣', '*': '*️⃣',
	'!': '❗', '?': '❓',
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// index.js
const emojiCharacters = require('./emojiCharacters.js');

console.log(emojiCharacters.a); // 🇦
console.log(emojiCharacters[10]); // 🔟
console.log(emojiCharacters['!']); // ❗
1
2
3
4
5
6

TIP

On Windows, you may be able to use the Win + . keyboard shortcut to open up an emoji picker that can be used for quick, easy access to all the Unicode emojis available to you. Some of the emojis listed above may not be represented there, though (e.g., the 0-9 emojis).

You can also use the Control + Command + Space keyboard shortcut to perform the same behavior on macOS.