Want to make your Discord server stand out? Are you trying to figure out how to add custom features, moderation, or just some fun commands? Maybe you have an idea for a bot but don’t know where to start.

This guide shows you exactly how to create your own Discord bot from scratch using JavaScript (Node.js). You will learn everything, step by step, from setting up your application to writing your first lines of code and getting it online.

Prerequisites: What You Need Before You Start

Before you get into the code, you need a few tools. Make sure you have all of these ready. This will make the process much smoother.

  • A Discord account and a server where you have admin rights to add and test your bot.
  • Node.js installed on your computer. If you don’t have it, you can install NodeJS from the official website. This lets you run JavaScript code outside of your browser.
  • A code editor. Visual Studio Code (VS Code) is a popular free option, but any text editor works.
  • A basic understanding of JavaScript. You don’t need to be an expert, but you should know what variables and functions are.

Step 1: Create Your Application on the Discord Developer Portal

Your bot isn’t just code; it’s also an « application » inside Discord’s system. The first step is to register it. This is where you get all the keys and IDs needed for your code to communicate with the Discord API.

Access the Portal and Create a New Application

First, you need to head over to the main hub for all Discord developers. This is where every bot begins its life.

  1. Go to the Discord Developer Portal and log in with your Discord account.
  2. Click the « New Application » button in the top-right corner.
  3. Give your application a name. This name will be visible to users, so pick something that fits your bot’s purpose. Agree to the terms and click « Create ».

That’s it. You now have an application shell inside Discord. Next, we need to turn this application into a bot.

Configure Your Bot and Get the Token

Now you need to add a « Bot » user to your application. This is the user that will appear in your server and respond to commands.

Inside your application page, click on the « Bot » tab in the left-hand menu. Then, click the « Add Bot » button and confirm. You now have a bot account linked to your application.

On this page, you will see an option to « Reset Token » or « View Token ». Click it and copy the string of characters it gives you. This is your Bot Token.

⚠️ Important: Keep Your Token Secret Your bot token is a password. Never share it with anyone or post it publicly (like on GitHub). Anyone with your token can take full control of your bot. Treat it like a password for all your servers.

Get Your Public Key and Application ID

You’ll need two more pieces of information for your code to work correctly. These are not as secret as the token but are just as important.

Go back to the « General Information » tab for your application. Here you will find:

  • Application ID: A long number that is the unique ID for your application.
  • Public Key: A string of characters used to verify that interactions are coming from Discord.

Copy both of these and save them somewhere safe, along with your token. You will need them soon.

Configure Permissions and Privileged Intents

Intents tell Discord what types of events your bot wants to receive information about. For example, if your bot needs to know when new members join, you need to enable the right intent.

On the « Bot » page, scroll down to the « Privileged Gateway Intents » section. For a simple bot that just responds to commands, you don’t need these yet. But for more advanced features, you might need to enable them. For now, you can leave them off.

Step 2: Set Up Your Local Development Environment

Now that the Discord side is set up, it’s time to create a space on your computer for the bot’s code. This involves creating a folder and installing the necessary tools to help you talk to the Discord API.

Create Your Project Folder

This is simple. Create a new folder anywhere on your computer. Name it something clear, like `my-discord-bot`. Open this folder in your code editor, like VS Code. All your bot’s files will live inside this folder.

Initialize Your Project with npm

Next, you need to turn this folder into a Node.js project. Open a terminal or command prompt directly inside your project folder. Most code editors have a built-in terminal you can use.

Run the following command. The `-y` flag just accepts all the default prompts.

npm init -y

This command creates a file named `package.json`. This file keeps track of your project’s details and all the code libraries (dependencies) it needs to run.

Install the discord.js Library

You don’t want to build all the code to talk to the Discord API from scratch. A library called `discord.js` makes this much easier. It provides pre-built functions for nearly everything you want to do.

In your terminal, run this command to install it:

npm install discord.js

This will download `discord.js` and add it as a dependency in your `package.json` file. Now you are ready to write the actual code for your bot.

Step 3: Write the Code for Your First Bot

This is the main part. You’ll create a file, add the JavaScript code to connect to Discord, and program the bot to respond to a simple command. For this guide, we’ll create a basic `/ping` command that makes the bot reply with « Pong! ».

Basic Structure of the Main File (`index.js`)

Inside your project folder, create a new file and name it `index.js`. This will be the main entry point for your bot. All the code for this step will go into this file. First, you need to import the necessary parts from the `discord.js` library.

// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits } = require('discord.js');

// Get your token from a config file or environment variable
// For this example, we'll hardcode it, but this is NOT recommended for production
const token = 'YOUR_BOT_TOKEN_HERE';

Initialize the Client and Connect to Discord

The `Client` object is your bot’s connection to Discord. You need to create a new instance of it and tell it which « intents » you need. For a basic bot, `GatewayIntentBits.Guilds` is enough.

// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

// Log in to Discord with your client's token
client.login(token);

Make sure to replace `’YOUR_BOT_TOKEN_HERE’` with the actual token you copied from the Developer Portal. This code prepares your bot and logs it into Discord’s service.

Handle the « ready » Event: Check That the Bot is Online

How do you know if your bot connected successfully? You can listen for the `ClientReady` event. This event fires once after the bot logs in and is ready to start working. It’s a good practice to log a message to your console to confirm everything is working.

// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
	console.log(`Ready! Logged in as ${c.user.tag}`);
});

When you run your bot, this code will print a message like « Ready! Logged in as YourBotName#1234 » in your terminal. This is your first sign of success.

Create and Register a First Slash Command (e.g., `/ping`)

Modern Discord bots use slash commands (commands that start with `/`). You need to define your commands in your code and then register them with Discord’s API. This is more complex than old prefix commands, but it provides a better user experience.

You need a separate script to register the commands. Create a new file called `deploy-commands.js`.

const { REST, Routes } = require('discord.js');

// Get your Application ID and Guild (Server) ID
const clientId = 'YOUR_APPLICATION_ID';
const guildId = 'YOUR_SERVER_ID';
const token = 'YOUR_BOT_TOKEN_HERE';

const commands = [
	{
		name: 'ping',
		description: 'Replies with Pong!',
	},
];

// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(token);

// and deploy your commands!
(async () => {
	try {
		console.log(`Started refreshing ${commands.length} application (/) commands.`);

		// The put method is used to fully refresh all commands in the guild with the current set
		const data = await rest.put(
			Routes.applicationGuildCommands(clientId, guildId),
			{ body: commands },
		);

		console.log(`Successfully reloaded ${data.length} application (/) commands.`);
	} catch (error) {
		console.error(error);
	}
})();
How to Get Your Server ID To get the `guildId`, you need to enable Developer Mode in Discord. Go to User Settings > Advanced > turn on Developer Mode. Then, right-click on your server’s icon and choose « Copy Server ID ».

Replace the placeholders with your real IDs and token. Then, run this script once from your terminal with `node deploy-commands.js`. This tells Discord about your new `/ping` command.

Listen and Respond to Interactions (The Bot Replies « Pong! »)

Now, go back to your `index.js` file. You need to add code that listens for when a user actually runs your command. This is done by listening for the `InteractionCreate` event.

client.on(Events.InteractionCreate, async interaction => {
	// Check if the interaction is a slash command
	if (!interaction.isChatInputCommand()) return;

	const { commandName } = interaction;

	if (commandName === 'ping') {
		// If the command is 'ping', reply with 'Pong!'
		await interaction.reply('Pong!');
	}
});

This code checks every interaction on the server. If it’s a chat input command and its name is `ping`, the bot will execute the code inside the `if` block. Here, it simply uses the `interaction.reply()` method to send a message back.

Step 4: Launch Your Bot and Test It

All the code is written. Now it’s time to bring your bot to life and see if it works as expected. This involves running your main script from the terminal and checking its status on your Discord server.

Launch the Bot via the Terminal

Make sure you have saved all your changes in `index.js`. Go to your terminal, which should still be open in your project folder. To run the bot, use the `node` command followed by your main file’s name.

node index.js

Or, if your `package.json` has ` »main »: « index.js »`, you can just type `node .`.

Check the Console and the Bot’s Status on Discord

If everything is correct, you should see the message « Ready! Logged in as YourBotName#1234 » appear in your console. This confirms the bot has successfully connected to Discord.

Now, look at your Discord server. If you invited the bot correctly (we’ll cover that next), you should see its name in the member list on the right, and it should have a green circle indicating it is online. You can now go to any text channel and type `/ping`. Your bot should instantly reply with « Pong! ».

Step 5: Invite Your Bot to a Server

Your bot is running, but it can’t do anything until it’s actually in a server. You need to generate a special invitation link that grants it the correct permissions to join and function.

Use the « OAuth2 URL Generator »

Go back to the Discord Developer Portal and select your application. In the left menu, click on « OAuth2 » and then « URL Generator ». This tool creates the invitation link for you.

Select the Scopes (`bot` and `applications.commands`)

In the « Scopes » section, you need to check two boxes:

  • `bot`: This identifies the URL as an invitation for a bot user.
  • `applications.commands`: This allows your bot to create slash commands in the server.

Once you select these, a new panel for « Bot Permissions » will appear at the bottom.

Define the Bot’s Permissions

Here, you select what your bot is allowed to do on the server. For our simple bot, it only needs to send messages. So, you can check « Send Messages ».

Principle of Least Privilege Only give your bot the permissions it absolutely needs to function. Don’t just check « Administrator » because it’s easy. This is a key security practice to protect your server in case your bot’s token is ever compromised.

Use the Generated Link to Add the Bot

After selecting the scopes and permissions, a URL will be generated at the bottom of the page. Copy this invitation link. Paste it into your browser, select the server you want to add it to from the dropdown menu, and click « Authorize ».

Your bot should now appear in your server’s member list. If it’s already running, it will be online and ready for your commands.

Frequently Asked Questions (FAQ) on Creating Discord Bots

Creating a bot can bring up a lot of questions. Here are answers to some of the most common ones.

What is a Token and why must it remain secret?

A bot token is a unique key that authenticates your code with the Discord API. It’s effectively the password for your bot account. If someone else gets your token, they can log in as your bot, control its actions, and potentially cause damage to any server it’s in. You should never share it or upload it to public websites like GitHub.

What are « Privileged Intents » and when should I activate them?

Privileged Intents are special permissions you must enable to get access to sensitive data. They are required for bots that need to track things like member presence (online status) or read message content in channels. Discord requires you to request and justify their use for bots in over 100 servers. For a simple command bot, you don’t need them.

My bot goes offline when I close my computer. How do I keep it online 24/7?

Your bot is just a script running on your machine. When you shut down your computer, the script stops. To keep it running 24/7, you need to host it on a server that is always on. Options include:

  • Cloud Hosting Platforms: Services like Heroku, Replit, or a small VPS (Virtual Private Server) from providers like DigitalOcean or AWS.
  • Dedicated Hosting: For very large bots, you might rent a dedicated machine.

These services run your `node index.js` command continuously, so your bot is always available.

Can I create a bot with a language other than JavaScript?

Yes, absolutely. While `discord.js` is very popular, there are powerful libraries for many other languages. The most well-known is an alternative populaire en Python, discord.py. There are also libraries for Java, C#, Go, and more. The process of creating the application in the Developer Portal is the same for all languages; only the code itself changes.

Congratulations! You have successfully built and launched your very first Discord bot. You’ve learned how to set up an application, write the code for a basic command, and get it running on your server.

This is just the beginning. From here, the possibilities are huge. You can explore creating more complex commands, managing server roles, playing music, or integrating with other APIs. Bravo for building votre premier bot, and have fun exploring what you can create next for all your servers.

Articles similaires