Welcome

Welcome to the discord.js v11.5 documentation. The v11.5 release contains bugfixes from v11.4 and backports features from the in-development v12.Version 12 is still very much a work-in-progress, as we're aiming to make it the best it can possibly be before releasing. If you are fond of living life on the bleeding-edge, check out the master branch.

About

discord.js is a powerful Node.js module that allows you to interact with the Discord API very easily.

  • Object-oriented
  • Predictable bstractions
  • Performant
  • 100% coverage of the discord API

Example code

const discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}!`);
});
  
client.on("message", msg => {
  if (msg.content === "ping") {
    msg.reply("Pong!");
  }
});

client.login("TOKEN");

Ping

This command returns the word 'pong' whenever it's called upon with 'ping'

Guide:

  • Import the discord.js module
  • Create an instance of a discord client
  • The ready event is vital, it means that only after this the bot will respond to information received from discord
  • Create an event listener for messages
  • Log the bot in with the special token

Example code

const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
  console.log("I am ready!");
});

client.on("message", message => {
  if (message.content === "ping") {
    message.channel.send("Pong!");
  }
});

client.login("TOKEN");

Avatars

This command returns a link to the user's avatar

Guide:

  • Import the discord.js module
  • Create an instance of a discord client
  • The ready event is vital, it means that only after this the bot will respond to information received from discord
  • Create an event listener for messages
  • Log the bot in with the special token

Example code

const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
  console.log("I am ready!");
});
               
client.on("message", message => {
  // If the message is "what is my avatar"
  if (message.content === "what is my avatar") {
    // Send the user's avatar URL
    message.reply(message.author.avatarURL);
  }
});

client.login('your token here');

Moderation

This command allows you to kick a member

const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
  console.log("I am ready!");
});

client.on("message", message => {
  if (!message.guild) return;
  if (message.content.startsWith("!kick")) {
    const user = message.mentions.users.first();
    if (user) {
      const member = message.guild.member(user);
        if (member) {
          member.kick("Optional reason that will display in the audit logs").then(() => {
            message.reply(`Successfully kicked ${user.tag}.`);
          }).catch(err => {
            message.reply("I was unable to kick the member");
            console.error(err);
          });
        } else {
          message.reply("That user isn't in this guild!");
        }
    } else {
      message.reply("You didn't mention the user to kick!");
    }
  }
});

client.login("TOKEN");

This command allows you to ban a member

const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
  console.log("I am ready!");
});

client.on("message", message => {
  if (!message.guild) return;
  if (message.content.startsWith("!ban")) {
    const user = message.mentions.users.first();
    if (user) {
      const member = message.guild.member(user);
        if (member) {
          member.ban({ reason: "Optional reason that will display in the audit logs" }).then(() => {
            message.reply(`Successfully banned ${user.tag}.`);
          }).catch(err => {
            message.reply("I was unable to ban the member");
            console.error(err);
          });
        } else {
          message.reply("That user isn't in this guild!");
        }
    } else {
      message.reply("You didn't mention the user to ban!");
    }
  }
});

client.login("TOKEN");

Webhooks

Send a message using a webhook.

const Discord = require("discord.js");
const hook = new Discord.WebhookClient("webhook id", "webhook token");
hook.send("I am now alive!");
                  

Emoji

Edit the emoji.

[Emoji].edit({ name: 'NewNameForEmoji' })
.then(e => console.log(`Edited emoji ${e}.`))
.catch(console.error);

Server Greeting

Allows the bot to welcome new guild members when they join

const Discord = require("discord.js");
const client = new Discord.Client();

client.on("ready", () => {
  console.log("I am ready!");
});

client.on("guildMemberAdd", member => {
  const channel = member.guild.channels.find(c => c.name === "arrivals");
  if (!channel) return;
  
  channel.send(`Welcome to the server, ${member}. :wave:`);
});

client.login("TOKEN");

Purge

This command can remove bulk messages from a channel, up to 100.

const deleteCount = parseInt(args[0], 10);
if (isNaN(deleteCount) || deleteCount < 2 || deleteCount > 100) return message.reply("Please provide a number between 2 and 100 for the number of messages to delete");
const fetched = await message.channel.fetchMessages({ limit: deleteCount });
message.channel.bulkDelete(fetched).catch(error => message.reply(`Couldn't delete messages because of: ${error}`));
message.reply(`Deleted **${deleteCount}** messages.`)

Guild

This piece of code creates a guild

async function createGuild(client, message) {
  try {
    const guild = await client.user.createGuild("Example Guild", "london");
    const defaultChannel = guild.channels.find(channel => channel.permissionsFor(guild.me).has("SEND_MESSAGES"));
    const invite = await defaultChannel.createInvite();
    await message.author.send(invite.url);
    const role = await guild.createRole({ name: "Owner", permissions: ["ADMINISTRATOR"] });
    await message.author.send(role.id);
    
    client.on("guildMemberAdd", async (member) => {
      if (member.guild.id === guild.id && member.id === message.author.id) {
        await member.addRole(role.id);
      }
    });
  } catch (e) {
    console.error(e);
  }
}

createGuild(client, message);

Rich Embed

This creates a rich embed.

const embed = new Discord.RichEmbed()
  .setTitle("This is your title, it can hold 256 characters")
  .setAuthor("Author Name", "https://i.imgur.com/lm8s41J.png")
  .setColor(0x00AE86)
  .setDescription("This is the main body of text, it can hold 2048 characters.")
  .setImage("http://i.imgur.com/yVpymuV.png")
   .setThumbnail("http://i.imgur.com/p2qNFag.png")
   .setTimestamp()
   .setURL("https://discord.js.org/#/docs/main/indev/class/RichEmbed")
   .addField("This is a field title, it can hold 256 characters","This is a field value, it can hold 1024 characters.")
   .addField("Inline Field", "They can also be inline.", true)
   .addBlankField(true)
   .addField("Inline Field 3", "You can have a maximum of 25 fields.", true);

message.channel.send(embed);

Swear Detector

This quick and dirty swear detector takes an array of swear words we don't want to see, and triggers on it.

const swearWords = ["darn", "shucks", "frak", "shite"];
if (swearWords.some(word => message.content.includes(word))) {
  message.reply("Oh no you said a bad word!!!");
  message.delete().catch(e => {});
}
Powered By ConvertKit