DEV Community

Cover image for Build a Discord Bot in 6 Minutes With Node.js and Autocode
Jacob Lee
Jacob Lee

Posted on • Updated on

Build a Discord Bot in 6 Minutes With Node.js and Autocode

In this article, I'll show you how to set up a fully customizable Discord 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

We'll be using Autocode to do the heavy lifting around authenticating to the Discord API, handling incoming events, and hosting our bot's Node.js code — 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 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

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

Link a Discord account

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 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 from Autocode's standard library, which sends the message. Here's what that code looks like:

// 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;
Enter fullscreen mode Exit fullscreen mode

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

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, 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

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

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. 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 and open your bot settings. Open the Bot pane, and scroll down until you see the Privileged Gateway Intent settings:

Privileged intent settings

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

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

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

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, 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.
  • One gotcha with embeds is the color parameter — 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" — 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

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. And for more Autocode updates, follow us on Twitter @AutocodeHQ. Until next time!

Top comments (2)

Collapse
 
king11 profile image
Lakshya Singh

Wow this seems like an alternative to discord slash commands but more powerful

Collapse
 
hacubu profile image
Jacob Lee

It actually uses Discord slash commands!