How to Build a Discord Bot: A Complete 2026 Tutorial for Beginners
How to Build a Discord Bot: A Complete 2026 Tutorial for Beginners
Think you need to be a coding wizard to build a Discord bot? Think again. In 2026, the tools and libraries are more accessible than ever. You can go from zero to a live, functional bot in under an hour. This isn't about theory—it's a hands-on, step-by-step walkthrough. We'll set up your bot's identity, write its first commands, and get it running online 24/7. By the end, you'll have a real bot responding to commands in your server. Let's get started.
Prerequisites: What You Need Before You Start Coding
Before we write a single line of code, we need to gather our tools. You don't need much, but these three things are non-negotiable. Get them ready now.
Essential Accounts and Tools
First, you need a Discord account. Not just any account—you need access to the Discord Developer Portal. This is where you'll register your bot and get its unique "password." You'll also need a Discord server where you have "Manage Server" permissions. This is your private testing ground.
Second, install Node.js. This is the runtime environment that will execute your bot's code. Head to the official Node.js website and download the LTS (Long Term Support) version. The installation includes npm (Node Package Manager), which we'll use to install libraries. To check it worked, open a terminal and type node --version. You should see a number like 18.x or higher.
Finally, grab a code editor. Visual Studio Code is the popular, free choice with great extensions for JavaScript. But any editor you're comfortable with will work. Honestly, Notepad would do in a pinch, but you'll have a much better time with proper syntax highlighting and an integrated terminal.
- A Discord Developer Account and a server to test your bot
- Node.js and npm installed on your computer
- A code editor like Visual Studio Code
Step 1: Setting Up Your Bot in the Discord Developer Portal
This step creates your bot's digital identity on Discord's servers. It's all done through a web portal—no code yet.
Creating the Application and Generating Your Token
Go to the Discord Developer Portal and log in. Click the bright "New Application" button. Give it a name—this is your bot's application name, which you can change later. Click "Create."
Now, navigate to the "Bot" section in the left sidebar. Click "Add Bot." A confirmation window will pop up; click "Yes, do it!" Congratulations, you've just created a bot user.
Here's the most critical part: Your bot token. Under the bot's username, click "Reset Token" and then "Copy." This token is your bot's password. Anyone with it can control your bot. Never share it, commit it to public GitHub repositories, or paste it into random websites. We'll handle it securely in the next step. For now, paste it into a temporary text file.
While you're here, scroll down to the "Privileged Gateway Intents" section. For a basic bot, you can leave these disabled. If you plan to make a moderation bot that needs to see message content (which is most bots), you must enable the "Message Content Intent". Toggle it on.
Finally, we need to invite the bot to your server. Go to the "OAuth2" > "URL Generator" section. Under "Scopes," check bot. Then, in the "Bot Permissions" box that appears, select "Administrator" for now to keep things simple for testing. A generated URL will appear at the bottom. Copy and paste it into your browser, choose your test server, and authorize the bot. You should see it appear offline in your server's member list.
Step 2: Building Your Project and Writing the Core Code
Time to leave the browser and open your code editor. This is where we build the project structure and write the script that brings your bot to life.
Initializing Your Project and Installing discord.js
Create a new folder on your computer for your bot project. Open your terminal, navigate into that folder, and run:
npm init -y
This creates a package.json file, which tracks your project's dependencies. Now, install the essential library: discord.js. It's the powerhouse that handles all communication with the Discord API documentation. Run:
npm install discord.js
You'll also want to install dotenv. This lets us securely load that bot token from a file instead of hardcoding it. Run:
npm install dotenv
In your project folder, create two files: .env and index.js. The .env file is where your secret token lives. Open it and add this line:
DISCORD_TOKEN=your_token_goes_here
Replace your_token_goes_here with the token you copied earlier. Now, open index.js. This is your main bot file. Let's write the core connection code.
// Load environment variables and the Discord.js library
require('dotenv').config();
const { Client, GatewayIntentBits } = require('discord.js');
// Create a new client instance
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent, // Required for reading message content
]
});
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
// Log in to Discord with your client's token
client.login(process.env.DISCORD_TOKEN);
Save the file. In your terminal, run node index.js. If everything is set up correctly, you'll see "Logged in as [YourBotName]!" in the console, and your bot will show as online in your Discord server. That's a huge milestone. Press Ctrl+C in the terminal to stop it for now.
Step 3: Implementing Your Bot's First Commands
Your bot is online, but it's just a spectator. Let's teach it to listen and reply. We'll start with a classic: the ping command.
Handling Events and Creating a Ping Command
Discord.js works on an event-driven model. The bot listens for events (like a new message) and executes code in response. We already used the ready event. Now, let's listen for messages.
Add this code to your index.js file, before the client.login() line:
// Listen for messages
client.on('messageCreate', message => {
// Ignore messages from bots to prevent loops
if (message.author.bot) return;
// Check if the message starts with your chosen prefix
const prefix = '!';
if (!message.content.startsWith(prefix)) return;
// Remove the prefix and split the command into arguments
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase(); // The first word is the command
// Simple ping-pong command
if (command === 'ping') {
message.reply('Pong!');
}
// Add a simple help command
if (command === 'help') {
message.channel.send('I am a test bot! Commands: !ping');
}
});
Let's break this down. The bot now listens to every message. If the message author is another bot, it stops. If the message doesn't start with our prefix (we're using !), it stops. Then, it slices off the !, takes the first word as the command, and any following words as arguments.
If the command is ping, it replies to the user with "Pong!" Save the file, run node index.js again, and go to your Discord server. Type !ping. Your bot should reply directly to you. You've just built your first feature.
This basic handler works, but it gets messy fast with more commands. For your next step, consider structuring commands into separate files. This is a key topic covered in our guide on advanced Discord bot development.
Step 4: Deploying Your Bot and Keeping It Online
Running your bot from your laptop is fine for testing, but close your laptop and the bot goes offline. To have a 24/7 bot, you need to host it on a server.
Choosing a Hosting Platform and Launching
You have several options for the best Discord bot hosting, ranging from free to paid. For a beginner, free tiers are a great starting point.
- Free Tier (Heroku Alternatives, Replit, Railway): Services like Railway or Replit offer generous free plans that can keep a simple bot online. They're perfect for learning and small communities. The catch? Resources are limited, and some may sleep after inactivity.
- Paid VPS (DigitalOcean, Linode, AWS): For about $5-7 a month, you get a virtual private server (VPS). You have full control and reliable uptime. This is the professional standard for larger bots.
- Specialized Bot Hosting: Some services are built specifically for Discord bots, offering easy dashboards and built-in features. They can simplify management but often at a higher cost per resource.
Let's assume you choose a VPS or a platform like Railway. You'll need to get your code there. The simplest way is to use Git. Initialize a Git repo in your project folder (git init), create a .gitignore file to exclude your node_modules folder and .env file, and push your code to GitHub. Then, you can connect your hosting service to that GitHub repository.
On the hosting side, you'll set your DISCORD_TOKEN as an environment variable (often called a "Config Var" or "Secret"). This keeps it safe. The platform will then run npm install and start your bot with node index.js.
But what if your bot crashes? You need a process manager. On a VPS, you'd use PM2. After connecting via SSH, you'd install it globally (npm install -g pm2) and start your bot with pm2 start index.js --name my-bot. PM2 keeps it running, restarts it on failure, and logs output. To make it start on server reboot, run pm2 startup and follow the instructions.
Finally, add some basic logging to your index.js file to monitor health. A simple console.log for errors can save you hours of debugging.
client.on('error', console.error);
Next Steps and Where to Go From Here
You've built, coded, and deployed a bot. That's the foundation. Where you go next depends on what you want your bot to do.
Expanding Your Bot's Capabilities
First, move beyond prefix commands. Discord now heavily favors Slash Commands (/). They're cleaner, have built-in argument validation, and can be integrated into the UI. The discord.js guide has excellent documentation on implementing them.
Second, add a database. If you want your bot to remember data—like user preferences, server settings, or a custom economy—you need persistent storage. For beginners, a simple JSON file works for tiny projects, but it breaks quickly. Look into SQLite (easy file-based SQL) or a cloud database like Supabase (free tier available).
Third, dive into specific functionalities. Want to build a Discord moderation bot setup? You'll need to learn about banning, kicking, message filtering, and setting up role-based permissions. The concepts you've learned here—event listening, command handling, deployment—are the exact same. You're just applying them to new Discord API features.
Always handle errors gracefully. Wrap risky code in try/catch blocks. Never let an unhandled error crash your bot without logging why. And revisit security: ensure any user input is sanitized, especially if you ever interact with a database or the file system.
The journey from a simple ping bot to a complex, multi-featured application is a series of small, manageable steps. You've already taken the hardest one: getting started.
Najczesciej zadawane pytania
What is the first step to building a Discord bot?
The first step is to set up a developer account and create a new application on the Discord Developer Portal. This is where you'll get your bot token, which is essential for your code to connect to and control the bot.
What programming language is most commonly used for Discord bot development?
JavaScript (using the Node.js runtime) with the discord.js library is the most common and beginner-friendly language for Discord bot development. Python with the discord.py library is also a very popular alternative.
Do I need to know how to code to create a Discord bot?
Yes, creating a custom Discord bot requires basic programming knowledge. Tutorials are designed for beginners and will guide you through the code, but familiarity with concepts like variables, functions, and installing software is necessary.
What is a 'bot token' and why is it important?
A bot token is a secret password that uniquely identifies and authorizes your bot. It's crucial for your code to log the bot into Discord. You must keep your token private and never share it or commit it to public code repositories, as it would allow anyone to control your bot.
How do I add my bot to a Discord server?
You add a bot to a server by generating an invite URL in the Discord Developer Portal. This URL includes specific permissions your bot needs. You, as a server administrator, then use this URL to authorize and invite the bot to your chosen server.