Discordjs Cheatsheet


HelloWorld discordjs bot

The very basic hello world bot can be coded by copying this:

const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}!`)
})

client.on("messageCreate", msg => {
  if (msg.content === "ping") {
    msg.reply("pong");
  }
})

client.login('Token-from-discord-here')

This bot will respond with pong when the user messages ping in the channel.

Make sure that you add the token from discord developers section for this bot.

Check if bot can assign a role to users

This needs 2 parts:

  • To see if bot can alter or manage the user
  • To see if bot can use the role assignment for specified role

Both of them can be done by using this piece of code:

if(!requiredMember.manageable){
    console.log("can not manage this member")
}

if(!requiredRole.editable) {
    console.log("can not handle this role")
}

Passing member to bot in message

We can pass a member to bot in message by typing @ and then selecting the user from the list that appears (or keep typing the name to filter the list).

The bot can then use the name from the message by using: (this is work if there is only one member mentioned, or if we want to work with first mentioned member only)

  let member = msg.mentions.members.first()

Passing role to bot in message

We can pass the role to the bot in message in the same way as we do with members.

Just type @ and then start typing the role name to filter it form the list and then select it.

Now the bot can capture this role by using the code:

  let role = msg.mentions.roles.first()

Add role to a user

Note that when we’re adding the role to a user, we need member as complete object while role as id only.

So the code will look like this:

  member.roles.add(role.id);

We can acquire the member and role from the code examples above, or combine both of them too in same message.

Discordjs get channel by id

You can get channel by passing in the id by using the following command (note that I have shared both .then Promise way and async await way. It need to be awaited as it’s an async request.

// change client to your bot variable, e.g. this.client, bot, etc.

let channel = await client.channels.fetch('channel-id-here')

// or you can use:

client.channels.fetch('channel-id-here').then( () => {
  // do something here
})

Get channel messages by id

If you don’t have the channel variable itself, then use the block above to get channel by id. Once you have it, use it to fetch the messages like this:

let messages = await channel.messages.fetch({ limit: 100 })

Get user Avatar URL

You can get the user avatar URL to use anywhere (including inside the discordjs embed) by using this (note that we need to use second method if member / user is acquired through code from message mentions etc.):

// get avatar url of the message author
let url = message.author.displayAvatarURL

// if member is acquired through code like mentions in messages:
// especially when directly getting displayAvatarURL returns undefined
let url = member.user.displayAvatarURL

Mention a user by userid

We can mention the user using their user id by using the code (note that it will not work in pre as no mentions work in that.:

// note the @ and &
'<@&' + userid + '>'

Discordjs blank field to show empty value for embed

Discordjs doesn’t allow us to have an empty value for embed fields. So we can add invisible space character in there. This is helpful when we need to set an initial variable that might or might not get a value in our function before getting displayed in embed.

\u200B is called zero width space.

// code is: \u200b

let a = '\u200b'

if(some_logic) { a = 'new value' }

const embed = new Discord.MessageEmbed()
    .addFields(
        { name: 'some name (can use \u200b here too)', value: a}
    )
// now we will not get error if some_logic was false

How to add custom emoji to discord via Bot using discordjs

Make sure that the bot has permission to handle emojis.

Make sure that the channel allows using external emojis, turn it on by going to: channel settings > permissions > <user role> (or everyone) > Use External Emoji and clicking the tick mark to make it green.

You can now add emojis to the server manually or via bot.

For manual addition, you can goto server setting > Emoji and then add your images (in png format for example). Then you can change the alias next to the uploaded image on same page.

To add emoji to the server using the bot use this code and to also use this emoji too:

// make sure that you change rip to a unique long name if needed

let emoji_id = ''
// check if emoji with same name exists already
let emoji_exists = await client.emojis.cache.find(em => em.name === "rip")
if(!emoji_exists){
    emoji_id = emoji_exists.id
    console.log("emoji: :rip: already exists")
}else{
    // if not, then add:
    emoji_id = await msg.guild.emojis.create('https://i.imgur.com/w3duR07.png', 'rip')
}

// now use it via:
message.reply(`${emoji_id}`)

Difference between client.emojis.cache & message.guild.emojis.cache

client.emojis.cache refers to the list of emojis that the current bot client has access to.

message.guild.emojis.cache refers to list of available emojis in the current guild.

Discord.js check if emoji exists with name

let emoji_exists = await client.emojis.cache.find(em => em.name === "rip")
// or
let emoji_exists = await message.guild.emojis.cache.find(em => em.name === "rip")

Please let me know if you need help with discordjs, bot or javascript.


Leave a Reply

Your email address will not be published.