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 id = interaction.options.get('target')?.value;
guild.members.unban(id);
1
2

TIP

Because you cannot ping a user who isn't in the server, you have to pass in the user id. To do this, we use a CommandInteractionOptionopen in new window. See here for more information on this topic.

How do I kick a user?

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

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

client.user.setActivity('activity', { type: 'WATCHING' });
client.user.setActivity('activity', { type: 'LISTENING' });
client.user.setActivity('activity', { type: 'COMPETING' });
1
2
3

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?

client.user.setStatus('online');
client.user.setStatus('idle');
client.user.setStatus('dnd');
client.user.setStatus('invisible');
1
2
3
4

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

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

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 DM a specific user?

const user = client.users.cache.get('id');
user.send('content');
1
2

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 description 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 filter = m => interaction.user.id === m.author.id;

	interaction.channel.awaitMessages({ filter, time: 60000, 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('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('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().then(fetchedMembers => {
	const totalOnline = fetchedMembers.filter(member => member.presence.status === '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 GUILD_PRESENCES 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('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.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

How do I play music from YouTube?

For this to work, you need to have ytdl-core and @discordjs/voice installed.

npm install ytdl-core @discordjs/voice
yarn add ytdl-core @discordjs/voice
pnpm add ytdl-core @discordjs/voice

Additionally, you may need the following:

npm install --save @discordjs/opus # opus engine (if missing)
sudo apt-get install ffmpeg # ffmpeg debian/ubuntu
npm install ffmpeg-static # ffmpeg windows
yarn add --save @discordjs/opus # opus engine (if missing)
sudo apt-get install ffmpeg # ffmpeg debian/ubuntu
yarn add ffmpeg-static # ffmpeg windows
pnpm add --save @discordjs/opus # opus engine (if missing)
sudo apt-get install ffmpeg # ffmpeg debian/ubuntu
pnpm add ffmpeg-static # ffmpeg windows
const ytdl = require('ytdl-core');
const {
	AudioPlayerStatus,
	StreamType,
	createAudioPlayer,
	createAudioResource,
	joinVoiceChannel,
} = require('@discordjs/voice');

// ...

const connection = joinVoiceChannel({
	channelId: voiceChannel.id,
	guildId: guild.id,
	adapterCreator: guild.voiceAdapterCreator,
});

const stream = ytdl('youtube link', { filter: 'audioonly' });
const resource = createAudioResource(stream, { inputType: StreamType.Arbitrary });
const player = createAudioPlayer();

player.play(resource);
connection.subscribe(player);

player.on(AudioPlayerStatus.Idle, () => connection.destroy());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

TIP

You can learn more about these methods in the voice section of this guide!

WARNING

This only works correctly if you have the GUILD_VOICE_STATES intent enabled for your application and client. If you want to learn more about intents, check out this dedicated guide on intents!

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