Build a Discord Bot in 6 Minutes With Node.js and Autocode
Tags: discord, node, api, tutorial
Published: 2021-04-22 06:58:29

---
title: Build a Discord Bot in 6 Minutes With Node.js and Autocode
published: true
description: Set up a fully-customizable Discord bot that responds when mentioned in just minutes
tags: Discord, node, api, tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e01thcrdrfqf6h7qfxsa.png
---

In this article, I'll show you how to set up a fully customizable [Discord](https://discord.com) bot that you can have running in your guild in 6 minutes (or less!). I'll also give you some helpful tips you can use to further customize your bot after getting the basic example working.

![Your bot responding with a message when it is mentioned](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/591tnsqh3a2dqf7t958j.png)

We'll be using [Autocode](https://autocode.com) to do the heavy lifting around authenticating to the Discord API, handling incoming events, and hosting our bot's Node.js code &mdash; all for free. We've got an online editor as well, so the only other thing you'll need to get started is a Discord account!

Let's dive in!

# Quickstart

Start by going to to the [Discord starter app page](https://autocode.com/app/discord/basic-discord-example/) on Autocode. The bot's source code is completely open, so if you're curious, feel free to take a look!

When you're ready, press the green **Install Free** button. If you haven't already, create an Autocode account, then select a name for your project.

![Name your Discord project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kimi2z4ph1nozvci4xcd.png)

On the next screen, you'll be prompted to link a Discord account:

![Link a Discord account](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7gfdhujv57zyrlp337nz.png)

Press **Link**, then **Link New Resource** in the modal that appears and follow the instructions to link a Discord app. This involves creating an app from [Discord's developer portal](https://discord.com/developers/applications) and installing it into your guild, then pasting the app's authentication credentials into Autocode when prompted. 

Finally, press **Install App**. And that's it! If your guild has a `#general` channel, you'll see a welcome message confirming installation. Mention your bot in a message by typing `@BotName` and your bot will respond!

# How Does It Work?

Autocode listens for events from Discord using the bot credentials you supplied earlier. When it receives an event, Autocode triggers the appropriate endpoints in projects with the same bot linked.

In this specific case, Autocode triggers the `functions/events/discord/bot_mention.js` endpoint of the app you just installed. This endpoint contains a call to the messages.create method of the [discord.channels API](https://autocode.com/lib/discord/channels/#messages-create) from Autocode's standard library, which sends the message. Here's what that code looks like:

```javascript
// authenticates you with the API standard library
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});

let messageResponse = await lib.discord.channels['@0.0.6'].messages.create({
  channel_id: `${context.params.event.channel_id}`,
  content: [
    `Hey <@!${context.params.event.author.id}>! I'm a bot powered by Autocode.`,
    `You mentioned me in a message, so here I am!`
  ].join('\n'),
  embed: {
    title: 'Guild Information',
    type: 'rich',
    color: 0x00AA00, // Green color
    description: 'You could add some information here for guild members to view!',
    fields: [{
      name: 'Message Formatting',
      value: [
        'Check out this link for more details on formatting message embeds:',
        'https://discord.com/developers/docs/resources/channel#embed-object-embed-structure'
      ].join('\n')
    }, {
      name: 'Setting up Slash Commands',
      value: [
        'Check out the README for this bot on Autocode for help setting up slash commands:',
        'https://autocode.com/app/discord/basic-discord-example/'
      ].join('\n')
    }]
  },
  tts: false
});

return messageResponse;
```

Pretty straightforward! Autocode automatically populates and defines a `context` parameter containing details about the incoming event from Discord. We can access this data under `context.params.event` as shown above.

# Slash Commands

The other endpoint in the app, `functions/events/discord/command.js`, sends a message containing the number of users and bots currently in the guild when slash command called `/member-count` is triggered:

![Successful member count message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gkgjbijecdj062kdk9d3.png)

However, before this will work, we need to register the slash command with Discord. Fortunately, this is easy with Autocode's built in Discord Slash Command Builder! 

Navigate to the [Discord Slash Command Builder](https://autocode.com/discord-command-builder/), and link the same bot you created during the installation flow. Select the guild you installed your bot into, and then name the command `member-count`. Give it a description as well:

![Creating a Discord slash command via the Discord Slash Command Builder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8s7cfw4ab5yhlj9gr73.png)

When you're ready, press **Save All**. Congratulations! You've created a slash command in your guild. Try it out in your guild by typing `/member-count`. If you've done everything correctly, you should see...

![Privileged intents required](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/om6eohz56ayg19gskmjn.png)

Whoops. There's one more thing we need to do!

## Setting Up Privileged Intents

If you look at the code for the `functions/events/discord/command.js` endpoint, you'll notice that it calls the members.list method of the [discord.guilds API](https://autocode.com/lib/discord/guilds/#members-list). Discord treats this API as privileged, so to use it, you must manually grant access to your bot.

Go back to the [Discord developer portal](https://discord.com/developers/applications) and open your bot settings. Open the **Bot** pane, and scroll down until you see the **Privileged Gateway Intent** settings:

![Privileged intent settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vtzy5smvp86kczlb8pum.png)

Enable the toggle labeled **Server Members Intent**, then go back to your Discord server and run the command again. You should then see a proper message:

![Successful member count message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gkgjbijecdj062kdk9d3.png)

You've now fully set up the starter app! You can modify it's code to your heart's content, as well as add new endpoints for other Discord events, by reopening your project in Autocode.

# Additional Tips

As you continue to build, here are some additional tips you might find useful:

## Finding Your Guild Id

One way you can find your guild id (as well as ids for channels, users, and roles) is to enable **Developer Mode**. Open your **User Settings** by clicking the gear in the bottom left corner of your client, then click the **Advanced** menu item in the left sidebar and turn on the **Developer Mode** toggle:

![Enabling developer mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rfukisooj42jrbjgvij4.png)

Once enabled, exit your settings and right click the icon of the guild containing your bot in the left sidebar. The menu that appears will contain a new `Copy ID` item:

![The copy id item](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9hn18d4prvswekq0w30.png)

Select it, and the guild id will be copied to your clipboard. Right clicking users, channels, and roles will have a similar `Copy ID` option.

## Formatting Messages

Posting simple messages to Discord is easy with the [discord.channels API](https://autocode.com/lib/discord/channels/#messages-create), and Discord even supports markdown for easy formatting. However, as messages get more complex, here are a few tips to keep in mind:

- Mentioning a user or a bot in your message requires you to surround their id with brackets in a specific way. Here's an example: `This message is tagging a user: <@!000000000000>`.
- Discord will automatically unfurl links in your messages, which you can use to your advantage to easily create useful notifications.
- Adding rich embeds to your message can really help it stand out in your channel. You can use the messages in the sample app endpoints as a starting point for what's possible, and check out the full list of embed object fields in [Discord's docs](https://discord.com/developers/docs/resources/channel#embed-object).
- One gotcha with embeds is the `color` parameter &mdash; it takes a number, not a string. A convenient way to represent RGB colors as a number for this parameter is to use hexadecimal (`0x00AA00` with no quotes for green instead of `'#00AA00'`.
- `tts` stands for "text to speech" &mdash; setting it to true will make Discord read your message aloud to anyone with the right settings, so be careful when testing it in a guild with others!

## Useful Links

- [Official Guide to Building Discord Bots on Autocode](https://autocode.com/guides/how-to-build-a-discord-bot/)
- [The Discord Slash Command Builder](https://autocode.com/discord-command-builder/)
- [Formatting Discord messages](https://discord.com/developers/docs/reference#message-formatting)
- [Discord message embed structure](https://discord.com/developers/docs/resources/channel#embed-object)
- [Discord slash commands](https://discord.com/developers/docs/interactions/slash-commands)
- [Discord developer portal](https://discord.com/developers/applications)
- [Autocode discord/commands API page for creating slash commands](https://autocode.com/lib/discord/commands/)
- [How to find your Discord guild id](https://support.discord.com/hc/en-us/articles/206346498-Where-can-I-find-my-User-Server-Message-ID-)

# Thank You!

If you have any questions, feedback, or if you just want to chat, join Autocode Discord! We've got a growing community who would be happy to help. You can get an invite under **Docs > Join Discord** in the topbar on autocode.com. 

You can also reach out to me directly on Twitter [@Hacubu](https://twitter.com/hacubu). And for more Autocode updates, follow us on Twitter [@AutocodeHQ](https://twitter.com/AutocodeHQ). Until next time!