Last updated: July 23, 2026
This step-by-step guide shows you how to create a JavaScript Discord bot using Discord.js and Node.js — from registering your bot with Discord to writing its code and running it.
.env file — In your project folder, create a file named .env with:
TOKEN=your-bot-token-here
This file safely stores your token so it stays out of your main code.bot and applications.commands, then set the required permissions. Use the generated URL to invite the bot to your server.Discord.js is a library (a set of pre-written code) that makes it easy to build Discord bots with JavaScript.
Run these commands in your project folder to install the libraries your bot needs:
npm install discord.js
npm install dotenv
Create index.js (your bot's main file):
const { Client, Events, GatewayIntentBits } = require('discord.js');
require('dotenv').config();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
]
});
client.once(Events.ClientReady, (c) => {
console.log(`Logged in as ${c.user.tag}`);
});
client.login(process.env.TOKEN);
This code makes the bot reply "Pong!" whenever someone sends ?ping in a channel it can see:
client.on(Events.MessageCreate, (message) => {
if (message.content === '?ping') {
message.reply('Pong!');
}
});
Slash commands are commands players run by typing a / command in Discord (like /ping). Create a commands folder with a command file. Example commands/ping.js:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply('Pong!');
}
};
Then load commands using fs and a Collection, and handle InteractionCreate to execute them.
Deploying sends your slash command definitions to Discord so they appear in the chat box. Create a deploy-commands.js file:
const { REST, Routes } = require('discord.js');
require('dotenv').config();
const commands = [
new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!')
].map(cmd => cmd.toJSON());
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
// Guild commands (instant, for testing)
rest.put(
Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
{ body: commands }
);
// OR Global commands (takes 1-2 hours to propagate)
rest.put(
Routes.applicationCommands(CLIENT_ID),
{ body: commands }
);
Replace CLIENT_ID and GUILD_ID in the code with your bot's client ID and your server's ID. Then run node deploy-commands.js once. After that, start your bot.
Once your bot is ready, follow the How to Host a Javascript Discord Bot guide to upload and run it in the NolimitHost panel.