Skip to content

Instantly share code, notes, and snippets.

@aziznatour
Created January 22, 2018 22:55
Show Gist options
  • Save aziznatour/9a4f7beddb1f5ad71bf6a3ed72a8eab2 to your computer and use it in GitHub Desktop.
Save aziznatour/9a4f7beddb1f5ad71bf6a3ed72a8eab2 to your computer and use it in GitHub Desktop.
Getting started with discord.js

This short tutorial will help you get started with discord.js - the node-based javascript library for building Discord bots.

It is expected that you have a basic understanding of programming, JavaScript, nodejs, npm and working with CLI. Otherwise, check these wonderful resoruces and then come back to this tutorial:

Getting Started - Installing Discord.js

Make sure you have npm installed as it will be used to install and manage node packages/libraries including discord.js.

  1. Start by making a new folder, let's call it my-discordjs-bot and then enter it

  2. Open a console/terminal window in your folder and run the npm init command. The console will start asking you questions, you can simply skip all by clicking enter. Final result should look similar to this: npm init gif

    You will notice that npm init created a file in your folder called package.json, this file holds info about your project and used packages.

  3. Now run npm install discord.js --save in your console to install the latest stable version of discord.js, demo: npm install discord.js

Initializing Bot Client

  1. Create a new file in root folder, called bot.js
  2. Add the following code
    /**
     * use the Discord.js library which we installed with npm
     */
    const Discord = require('discord.js');
    
    /**
     * initialize client
     */
    const client = new Discord.Client();

Now we have access to the client object which we can use to listen to events and run commands.

Getting a bot token

All bots on Discord have a unique token for authentication, to get a token you need to register a new bot on the official Discord Developers website.

  1. Head over to https://discordapp.com/developers/applications/me and login with your Discord account.
  2. Click on New App
  3. Enter a name and avatar (optional) for your bot then click on Create App
  4. On the bot page, scroll down to the Bot section and click on Create a Bot user
  5. Your token should be available in the Bot section

Connect client with token

Return to your bot.js file and add the following code:

/**
 * Use `client.on` to handle discord events
 */
client.on('ready', () => {
  console.log('I am ready!');
});

/**
 * add your token here to connect bot
 * keep this line at end of file to make sure your bot has read
 * the entire script before going online
 */
client.login('your token');

Watch your bot online on Discord

You can now run the bot to see it online. All you have to do is invite your bot to a discord server. It is recommended that you make a new Discord server to test your creations.

  1. To general an invitation link, go to your Bot App page on Discord Developers site
  2. Scroll down and click on the Generate OAuth2 URL
  3. Make sure the scope is bot
  4. Select all the neccessary permissions that you think your bot will require - you can leave it blank for now
  5. Click on copy and open the URL in your browser.
  6. Select your server from the drop menu then hit Authorize

At this point your will see your bot on your server, but it will be offline. To log it in, go back to your console and run:

node bot.js

If everything went as expected, you should see a message in your console I'm ready and your bot will be online. Congratulations!

Writing your first command

Commands are essentially messages, that means we can listen to them through the message event listener that is available in our client object:

/**
 * listen for new messages
 */
client.on('message', message => {
  /**
   * basic command condition
   */
  if (message.content === 'say hi') {
    message.reply('hello to you!');
  }
});

The above code instructs bot client to listen for all new messages, and then check if the message content is say hi (the condition) and then replies with hello to you if the condition was met. This is the basis for creating various commands.

A note about command prefixes

It is recommended that your commands start with a unique prefix so that your bot does not process something it shouldn't have.

A basic prefix implementation would look something like this:

const myPrefix = '!mybot';

client.on('message', message => {
  // message: !mybot ping
  if (message.content.startsWith(myPrefix + ' ping')) {
    return message.reply('pong');
  }
  // message: !mybot
  if (message.content.startsWith(myPrefix)) {
    return message.reply('I have your attention');
  }
});

Ignoring other bots

You almost never need to process message by other bots, so it is a good practice to ignore messages by bots to prevent any potential chaos and infinite loops..

  if (message.author.bot) {
    return;
  }

Deployment

After you're done, save the bot.js then run it again in the terminal with node bot.js (if your bot was already running, use ctrl+c to stop the process or simply close terminal window)

The final bot.js code should be similar to the following:

/**
 * use the Discord.js library which we installed with npm
 */
const Discord = require('discord.js');

/**
 * initialize client
 */
const client = new Discord.Client();

/**
 * Use `client.on` to handle discord events
 */
client.on('ready', () => {
  console.log('I am ready!');
});

/**
 * listen for new messages
 */
const myPrefix = '!mybot';

client.on('message', message => {
  // ignore other bots
  if (message.author.bot) {
    return;
  }
  // message: !mybot ping
  if (message.content.startsWith(myPrefix + ' ping')) {
    return message.reply('pong');
  }
  // message: !mybot
  if (message.content.startsWith(myPrefix)) {
    return message.reply('I have your attention');
  }
});

/**
 * add your token here to connect bot
 * keep this line at end of file to make sure your bot has read
 * the entire script before going online
 */
client.login('your token');

This has been a basic tutorial on starting your own Discord bot with discord.js Contact me for feedback or additional help

@LopesKatsui
Copy link

Thanks Bro! helped me a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment