How To Bulid A Free Discord With Node.js(Autocode.com)
How to build a free Discord bot with Node.js
This guide will teach you everything you need to know about building a Discord bot with Node.js. We'll be using Autocode to host your code for free, handle auth to Discord and automatically set up webhook handlers to make it easy.

Introduction
If you haven't used Discord yet, chances are this is your first time using the internet. Welcome, friend! It is a magical place. All joking aside, Discord is a messaging platform with fantastic voice and video streaming capabilities originally built to service gaming communities. It offers a lot of extensibility via bots, custom moderation tools and more which we'll show you how to work with here.
In this tutorial we'll cover how to set up a fully customizable Discord bot that you can have running in your server in around 10 minutes. We'll be using Autocode, which will provide you with free hosting, automatically handle authentication to Discord and set up webhooks for you. This will allow you to focus on the fun part: building an awesome bot for your server!
What you'll get
By completing this tutorial you'll get a Discord bot installed on your server that can be customized any way you want. To start, it will:
Respond to a basic
/pingslash command.Send a message when you say hey, hi, hello, or sup.
An embed message to welcome new members to your guild.
Prerequisites
The only three things that you will need to complete this tutorial are:
-
A free Discord account. We'll walk through the bot generation later.
-
A free Autocode account. Our basic app example will also cover this.
-
A relentless curiosity. If you like building, hacking and learning new things — this one's for you!
Quickstart
If you just want to quickly get your bot up and running, we have a pre-built basic Discord example app for you to get started with. This app will set up a barebones bot project with handlers for bot_mention and message.create events, as well as a handler for a slash command called member-count. The rest of this tutorial will walk through building a similar bot from scratch.
Watch the video tutorial
Prefer videos? Check out our handy YouTube tutorial instead!
Step 1: Create your Discord bot
Before we start building, we need to create a bot account and application.
1. First, go to the Discord developer portal. Click on the New Application button to create your application.

2. Give your application a name and click Create. This will create the app and take you to a new app management screen.

3. Click the Bots tab on the left sidebar. On this screen, click Add Bot. Confirm the message popup and voila! Your bot is alive!

4. Since some of the functionality we'll be building deals with member information, turn on server member intents in the bot section of your app on the Discord developer portal.

Congrats, you've got a bot to work with. Now, we can start creating functionality for it with Autocode!
Step 2: Create your Autocode project
To understand the basics of how Autocode works with Discord, we'll create a simple slash command. Slash commands are how you tell your bot what to do. To start we'll make a simple /ping command that will respond with Pong!. If you haven't already signed up for Autocode, you can do that now by clicking here.
This is the code that will power our simple command. We’ll show you how to get it set up and hosted for free on Autocode:
1. From your dashboard, click the New Project button.

2. Since we want this to respond to a command, click the endpoint trigger button (pictured below):

3. Set your trigger as Discord and your event as command. A command input will now appear, which we'll set as ping. Hit the blue Okay to finish setting the trigger.

4. Replace the existing code in your command file with the following:
Let's break down what's happening here! On line 3, we're including our lib node package. This is what allows you to connect to any of our integrated APIs with one line of code. All endpoints on Autocode have a context.params property that will contain all the data for the event. Specifically, the Discord event data is stored in context.params.event, which Autocode and Discord work together to populate for you. Finally, we're sending "Pong!" back to the channel that sent the command with the await lib.discord.channels['@0.1.0'].messages.create call. You can view this API reference here: discord/channels API reference.
5. Click the orange Save button. If you haven't saved the project, you'll be prompted to give it a name first.

Awesome, you now have an Autocode project with an echo command ready and deployed live! 👏
Step 3: Link your Discord account to Autocode
Before we can start playing ping pong with our bot, we need to connect our Discord account with our Autocode account.
1. Click the red Required button in the left sidebar. This will bring up our linked resources manager.

2. Click the blue Link button where you see the Discord row. This will start the linking flow.

3. If you already connected a Discord account you can simply click the green Choose button next to your bot of choice. Otherwise, click the blue Link new resource button.

4. The first screen will prompt you to create a bot, but since we've already done that, we can go right to providing our authentication credentials. Press next, then on the second screen input your Client ID and Client secret.

5. On the next screen, copy the Redirect URL and paste it and add it on your Discord auth page as seen in the modal.

6. Input your bot token on the next screen and click the blue Finish button.

7. Follow Discord's authentication instructions. You'll be asked to choose a server to add your bot to.

Once you've completed authentication, Autocode will link your accounts. With this step complete, your Discord bot will now be widely available to this project and any future projects you build!
Step 4: Create your slash command
You've got your bot installed, you have your response code written, now you need to let Discord know you want to control it with a /ping slash command. This requires you to register the command, either globally or for a specific server, with Discord via an API call. Thankfully, this is really easy with our Discord Slash Command Builder!
1. Link your Discord bot account to the command builder. If you've previously linked one, you can click the green choose button, or link a new resource. Follow the prompts in the linking modal as seen in step 3.

2. In a new command block, enter ping as the name and Responds with "Pong!" in the description.

3. Click the orange Save All button. This will also update any commands you've change as well. That's it, your /ping command is now registered and ready to go in your server!

Step 5: Customize your Bot
Awesome, we now have a working bot and slash command! But what if we want to make changes or add functionality?
Because of the way Autocode automatically sets up Discord webhooks for you, each event our bot responds to will have a corresponding JavaScript file in your Autocode project: just like functions/events/discord/command.js. All you need to do is edit your file in the Autocode editor and press Save to see your changes immediately reflected! Let's go over an example.
1. Open your project in the Autocode editor. You can find this on your Autocode dashboard. If you just installed the app example, it will likely already be open in your browser.
2. Create a new endpoint like you did for the /ping command. This time however, set your event trigger to message.create.
3. Let's add some code that will make your bot check whether a message includes the word "hello". We can do this fairly simply by checking any message string with the .includes() function:
Also note that we used the .toLowerCase() function first, so that we can match both "Hello" and "hello", or any other combination of uppercase and lowercase letters.
4. What if we wanted it to respond to more than just "hello"? We can change our previous example to use something called a regular expression. Let's write a regular regular expression to make our bot respond any time you say "hi", "hey", "sup", or "hello":
This time we don't need toLowerCase() because we have an i flag that makes the regular expression case insensitive.
5. Let's say you want to change this to run when someone sends a message containing "goodbye" or "bye". You could change the if statement to:
The event.content.match(/cya|gtg|bye/i) line above is using what's called a regular expression (specifically, the /cya|gtg|bye/i). It's a way to match strings of text against a given pattern. The first / starts the pattern. cya|gtg|bye means match "cya" OR "gtg" OR "bye". The final / ends the pattern, and i is what's called a flag and it means case insensitive; the characters can be uppercase or lowercase, e.g. this would also match "BYE".
5. Now, press the orange save button in the bottom right corner of your editor:

Once that finishes, that's it! Your updated project is live. Try typing goodbye in your guild, and you'll see the same response as before.
Step 6: Format your bot messages and embeds
Building messages for your bot can take many shapes, from very simple to very complex. For a full breakdown on formatting messages, check out Discord's docs. To make things a little easier, we created the Discord Embed Builder! Let's use it to make a new, fancy welcome message to send people when they join our guild:

1. Make sure Server Members Intent is turned on for your bot, under the Privileged Gateway Intents section.

2. Create a new endpoint file and set the event trigger to Discord and guild.member.add.

3. Go to the embed builder and start creating your message. For this example we'll set a simple welcome message and add some rules and an image to an embed.

4. Once you're happy with how your embed is looking, hit the Copy Code button at the very bottom of the embed form.

5. Back in your project, select all of the boilerplate code in your new endpoint file and replace it with the code you just copied from the embed builder.

6. Change line 4 to use a real channel ID. Since this is a guild.member.add event, we don't get that in our payload. The line should read something like this: 'channel_id': '12345789123456789'. You can get your desired channel ID by right clicking any channel in your guild and choosing Copy ID in the dropdown. You'll need to enable developer mode first to see this option.

7. For a little added personalization, we'll change our message content on line 5 to include a mention to the new user. This can be done using this structure <@!00000000000000>. Since we have the user id in our payload, we can use <@!${context.params.event.user.id}>. We'll need to also set it up as a template string, so the line should look like this:
Step 7: Test your commands
As you're building your commands and interactions, you can test quickly and easily with our built in sample payloads. For example, in our command.js file, the one handling the /ping command, Autocode will automatically populate a sample payload for you with sample data so that you can run the code directly from our editor.
This data will include some placeholder values that you can change to real values in order to test. Every value in the test payload is editable, so you can use it to simulate real responses. Let's walk through how you can change this information to make testing easier:
1. Click the Edit test payload button on the top bar of your editor.

2. In the test payload modal, locate the channel_id and guild_id property. Replace the placeholder strings with the channel and guild you want to send your test commands to. You can find this by right clicking any channel and choosing Copy ID from the dropdown that appears.

3. Once you're done adjusting the payload, click the blue Save Payload button. Once your project is done saving this new payload you can hit Run to test it.

Step 8: Code examples for bot actions
Here are just a few examples of common things people do with Discord bots.
Send a direct message
Let's say you want a slash command for sending helpful info to your members. You want to send that helpful message to someone without spamming your channel. This might be a job for DMs!
First, you could register a /help command and create the corresponding endpoint. The code you would use to start building the DM might look like this:
Responding to a message
Replying to a message can be done a couple ways, the most common ones being when a message is created, and when a bot is mentioned.
Before slash commands were added, responding to specific messages was how members typically interacted with bots. For this setup you would want an endpoint with Discord as the event source and message.create as the trigger. From there you will need to check those messages for your specific command. Here's a simple example for responding when a member types !ping in the channel:
The other time that you might want to respond to a message is when your bot is mentioned. For this setup, you can create an endpoint with Discord as the event source and bot_mention as the trigger. From there, responding is easy! Here's our example of a helpful message on formatting embed objects:
Formatting embeds
There are a lot of options for creating embeds, which you can check out in Discord's embed object documation. Here's a basic example of an embed explaining guild rules for a /rules slash command:
React to a message with an emoji
Using the same message.create event trigger as the previous example, we can also programmatically respond to messages with an emoji.
There are two ways to react with emojis depending on whether or not it's one you've added to your guild. If it's a standard emoji, you can react with this code:
Custom emojis require a little extra code as the :emoji-name: syntax won't work. For custom emojis you'll need structure your emoji field as <:emoji_name:emoji_id>.
You can get your emoji's ID by typing \:emoji_name: anywhere in your Discord server.
Set a role for a user
To add a role to a user, use the members.roles.update() method from the discord/guilds API.
Combine this with a slash command to make a quick role assignment tool:

Set a role based on emoji reactions
A common use case in Discord is to assign a role based on reactions. This is helpful for things like verifying users, setting a language role, etc. In Autocode, you can do this by creating an endpoint for the Discord message.reaction.add event trigger.
Now let's say you have a specific welcome message with 3 possible roles to assign via reaction. The basic setup might look something like this:
Ban / kick a user
Ban and kick are some of the most common commands you will need for your bot when moderating a server. Thankfully this can be achieved relatively easily! Let's imagine you have 3 slash commands set up: one for /ban and one for /kick. They all have a required user option and a reason option for /ban as well.

For bans, the code might look like this:
Kicks might look like this:
Restrict commands by role
If you're creating commands for your bot (like a ban or kick command for example), you can take advantage of roles to restrict who can use the command. Here's an example of a /ban command that's restricted by Role ID:
Restrict commands by permissions
If we want to use actual permission flags instead, you can do so by converting permission strings based on the values in this permissions table. Here's an example for administrator permissions:
Update your bot's status
You can update your bot's status with a custom message and change its state using the me.status.update() method from the discord/users API.
Discord currently limits status messages for bots to various activities ("Playing", "Watching", "Streaming", etc.). Discord also only allows the url parameter for statuses with activity_type set to STREAMING.
For a full list of options, check out the API documentation page.
Attaching images
There's actually 3 ways that you can attach an image to your message, depending on what images you're working with.
The first and easiest way to attach an image is to simply set the content of your message as an image URL:
If you want to attach an image within an embed, you can do it like this:
Working with image files outside of an embed is pretty similar:
Step 9: Advanced slash command builder tips
Building slash commands can get pretty complex, so we've added a lot of functionality to make it as streamlined as possible. Here are some additional tips for working with our command builder.
Generating handlers for commands
To generate a new handler for your command, you can click the Create Handler. This will send you to the Autocode editor pre-filled with an autogenerated code template.

Toggling code view
To view the code being used to generate the slash command you can toggle the View Code switch. This can be easily copied into any existing Autocode project you may have and run to continue updating the command.

Creating global slash commands
To create a global commmand, you can choose Global Command from the dropdown pictured below:

Removing a slash command
To remove a command, click the grey x at the top right of the command box. Please note: This is not reversible! If you delete a command from your bot it will be gone for good and you'll have to rebuild it, so watch out for that.

Using Options, Subcommands, Subcommand Groups
Options allow you to specify the data you want to send along with your slash command. There a finite set of options you can configure: String, Integer, Boolean, User, Channel, Role, Subcommand Group and Subcommand.
Here's how configuring the basic /blep command would work in our command builder:

In this example we've configured animal to be a string from a set of choices. By setting choices we are restricting what strings are allowed on our animal option to a specific list. Choices can only be set for Strings and Integer options. We've also set an optional only_smol boolean option.
Subcommands and subcommand groups are a special kind of option that allow you to set multiple commands under a single base command. If you set subcommands or subcommand groups on your command, the base command will not be accessible. Subcommand groups can only contain subcommands and can only be one level deep. You cannot mix subcommands and non-subcommands on the base command, as it will throw an error. You can read more about subcommands and subcommand groups in Discord's docs.
Here is an example of an info command with user and role subcommands:

Because the subcommands are on the info command, they will both show up in Discord's slash command UI when you search for them.
You can create pretty advanced options for your command with this tool, and we do our best to make that process smooth. For more in depth information about how options are configured, you can read about it in Discord's developer docs.
Frequently asked questions
Q: How do I enable developer mode in Discord?
Developer mode can be enabled from your user settings page. Click on the cog icon next to your profile near the bottom left of the Discord app, then find the Advanced tab on the left sidebar. Toggle the Developer Mode option on.
Q: How do I find my Guild ID?
Follow the directions above to enable developer mode, then right click on the guild thumbnail on the left hand side of your Discord application. In the dropdown, click the very last option which will be Copy ID.
Q: Why isn't the color parameter working in my bot's message response?
The color parameter is a little different in that it uses a hexadecimal number instead of a string. Thankfully the translation from hex is pretty simple. For example, the hex string for red (
'#FF0000') would instead be passed as0xFF0000.Q: Why should I use slash commands instead of prefixed messages?
Slash commands are Discord's new way to interact with your bots! They provide some much needed structure to interacting with bots as well as some really powerful tools to build great commands. For more specifics on what you can create with slash commands, check out Discord's commands documentation.
Q: How do I use discord.js with Autocode?
Discord.js and Autocode use a fundamentally different structure for interacting with the Discord API. Autocode leverages serverless hosting, async functions and event based triggers to run code, whereas most discord.js examples expect a callback structure.
For this reason, most examples need to be converted to use our events gateway and async (e.gawait client.setStatus('idle');) in place of the usualclient.on('ready', () => { ... })callback structure you might be used to.Q: How can I get back to my project if I closed the Autocode editor?
You can find your recent projects on your Autocode dashboard.
Q: I'm getting permission errors from Discord. How can I reset my authentication?
Try re-authing with this link (replacing
YOUR_BOT_IDwith your actual bot ID): https://discord.com/oauth2/authorize?client_id=YOUR_BOT_ID&scope=identify%20bot%20applications.commands&permissions=2146958591Q: How do I invite my bot to other servers?
You can use give the same OAuth2 URL used to invite the bot to your own server to any other server owner. Be sure to replace
YOUR_BOT_IDwith your actual bot ID first: https://discord.com/oauth2/authorize?client_id=YOUR_BOT_ID&scope=identify%20bot%20applications.commands&permissions=2146958591Q: Where can I get help with my Discord bot project?
Come and join us in our Discord Developers Community Server. We can help answer your questions and get you started.
Conclusion
Building Discord bots can be a lot of fun! By following the instructions in this tutorial, we've linked our Discord account to Autocode, taking care of our hosting and authentication with Discord. We've also built our first basic slash command, jazzed it up with message formatting and worked through a few code examples.
If you have any questions or feedback, please let us know in our Discord server. We're always happy to help. Happy hacking!
More Discord Resources
There's a lot involved when building your bots, so we've created a few additional tools and resources to make things go a little smoother.
- 👾 Guide: How to build a Discord music bot
Learn how you can create your own custom music bot for your server from scratch!
- 🧱 Discord Slash Command Builder
Create Discord Slash commands with ease! Add subcommands and options, see command previews, and autogenerate new endpoints and code to easily handle incoming events.
- 🏗 Discord Embed Builder
Build embed messages for your Discord bot! Auto-generates a message preview and all the code needed to send it.
Get started quickly with Discord apps
Looking for inspiration? We have a great selection of beginner apps built by the community to get you started.



Comments
Post a Comment