3v-Hosting Blog

How to Create a Discord Bot

COMMON

7 min read


Discord has become the go-to hub for online communities, ranging from gaming clans and programming groups to study collectives and businesses. The platform's support for bots is a standout feature. Bots are automated scripts that can moderate servers, play music, post memes, and perform custom tasks. This technical article will teach you how to create a Discord bot from scratch, including the coding process, hosting, permissions, and deployment strategies.

This article is for technically inclined readers who want a step-by-step understanding of the subject. If you're a backend developer, DevOps engineer, or hobbyist coder, this Discord bot tutorial will walk you through every major component required to build a bot tailored to your needs.

 

 

 

Understanding the Discord Bot Architecture

 

Before writing any code, it's essential to understand what a Discord bot is. A bot is a special type of user account controlled via Discord's API rather than by a human. The bot connects to Discord servers through a WebSocket gateway, listens for specific events (e.g., new messages, user joins), and responds accordingly using programmed logic.

Discord bots are built using developer APIs provided by Discord. They require a valid token to authenticate and interact with servers. You can write a bot in various programming languages like JavaScript, Python, or TypeScript. Node.js and Discord.js are among the most popular choices.

 

 

 

 

Creating a Bot on the Discord Developer Portal

 

To begin, you must first create a bot application through Discord’s official Developer Portal:

    1. Navigate to https://discord.com/developers/applications.
    2. Click on "New Application" and give your bot a name.
    3. Inside the application, go to the "Bot" section and click "Add Bot".
    4. A bot token will be generated. This token is crucial—never share it. It’s the key to controlling your bot.

Once the bot is created, it exists as an entity, but it does nothing until you add it to a server and provide logic for its behavior.

 

 

 

 

How to Add a Bot to Discord Server

 

To integrate the bot into a server, you must generate an OAuth2 invite URL with proper scopes and permissions:

    1. Go to the OAuth2 → URL Generator section.
    2. Under Scopes, select bot.
    3. Under Bot Permissions, choose permissions like:
        - Read Messages
        - Send Messages
        - Manage Messages
        - Embed Links
        - Others depending on your use case.
    4. Copy the generated URL and open it in your browser.
    5. Choose the server where you want the bot to join (you must have "Manage Server" permissions).

 

This is how to add Discord bots to a server. Once added, the bot can start performing actions depending on the logic you define in your codebase.

 

 

 

 

Setting Up the Development Environment

 

Let’s proceed with how to code a Discord bot using Node.js and the Discord.js library:
Requirements:

    - Node.js installed (LTS version recommended)
    - A code editor like Visual Studio Code
    - Basic command-line skills

 

Steps:

    mkdir my-discord-bot
    cd my-discord-bot
    npm init -y
    npm install discord.js dotenv

 

Create a .env file for your bot token:

    DISCORD_BOT_TOKEN=your_bot_token_here

 

Create an index.js file with the following content:

    require('dotenv').config();
    const { Client, GatewayIntentBits } = require('discord.js');

    const client = new Client({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent
      ]
    });

    client.once('ready', () => {
      console.log(`Logged in as ${client.user.tag}`);
    });

    client.on('messageCreate', message => {
      if (message.content === '!ping') {
        message.channel.send('Pong!');
      }
    });

    client.login(process.env.DISCORD_BOT_TOKEN);

 

Run your bot using:

    node index.js

 

This is the basic structure of how to make a bot on Discord using JavaScript. You can extend this code to add more commands and functionalities.

 


 

Other useful articles in our Blog:


    - How to install Discord on Ubuntu: Three Methods

    - Minecraft Hypixel IP Address - Ultimate Hypixel Guide

    - Is Midjourney coming to an end? Google Bard now generates images.

    - Choosing a Web Host for Low Budget Startups

 


 

 

Expanding the Bot: Commands and Events

 

Once the bot is operational, you can structure your code to handle multiple commands. You may use a command handler system that reads all .js files from a commands/ folder and executes them dynamically.

 

Example command file: commands/ping.js

    module.exports = {
      name: 'ping',
      execute(message) {
        message.channel.send('Pong again!');
      }
    };

 

Handler example:

    const fs = require('fs');
    client.commands = new Map();

    const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
    for (const file of commandFiles) {
      const command = require(`./commands/${file}`);
      client.commands.set(command.name, command);
    }

    client.on('messageCreate', message => {
      const args = message.content.slice(1).trim().split(/ +/);
      const commandName = args.shift().toLowerCase();
      const command = client.commands.get(commandName);

      if (command) command.execute(message, args);
    });

 

This modular approach is more maintainable and scalable for larger bots.

 

 

 

 

Hosting the Bot

 

For continuous uptime, you need to host your bot on a server. Options include:

    Self-hosting – Using a VPS with Node.js installed. Ideal for learning and control. This is where understanding how to get bots on Discord crosses into system administration.
    Cloud platforms – Like Heroku, Replit, or Railway. These platforms are beginner-friendly and offer free tiers.
    Docker – Package your bot in a Docker container and deploy using Kubernetes or Docker Compose.

 


Example Dockerfile:

    FROM node:18-alpine
    WORKDIR /app
    COPY . .
    RUN npm install
    CMD ["node", "index.js"]

 

 

 

 

Handling Permissions and Security

 

When you make your own Discord bot, always restrict permissions. Grant only the capabilities the bot absolutely needs. Never hardcode the token into your codebase—use environment variables.

 

To restrict bot commands to admins only:

    if (!message.member.permissions.has("Administrator")) {
      return message.channel.send("You do not have permission to use this command.");
    }

 

Also, implement error handling and logging for production-grade bots.

 

 

 

 

Examples of Popular Features

 

Here are a few ideas to add value to your bot:

    Moderation commands: kick, ban, mute users
    Music player: using packages like discord-player or erela.js
    Custom welcome messages: on guildMemberAdd event
    Polls: users react to messages with emojis
    Integration with external APIs: weather, news, crypto

Once you're familiar with the basics, expanding your bot becomes an exciting creative challenge. You can even interface with databases, schedule tasks, or interact with REST APIs.

 

 

 

 

Deployment Best Practices

 

If your bot gains users, treat it like a production service:

    - Monitor uptime and errors (use tools like PM2, Sentry, or Grafana)
    - Keep your dependencies updated
    - Use version control (GitHub)
    - Write unit tests for your core commands
    - Use linting and formatting tools like ESLint and Prettier
    - Automate deployment with CI/CD pipelines

The more robust and reliable your bot, the more confidence users will have in it.

 

 

 

 

Conclusion

You now know how to make your own Discord bot, from setting up the developer portal to writing modular code, adding commands, and hosting the bot on a server. The process for building a music bot, a moderation assistant, or a bot for fun follows the same technical steps.

This Discord bot tutorial only scratches the surface. There's a thriving community of bot developers, and endless possibilities to innovate. Knowing how to create a Discord bot is a valuable skill to showcase in your developer portfolio.