Step 1: Creating a Discord Bot Application

Before you can write any code, you need to create a bot application through the Discord Developer Portal. This process registers your bot with Discord and provides you with the credentials needed to connect your code to the platform.

Start by visiting the Discord Developer Portal at discord.com/developers/applications. Sign in with your Discord account if you have not already done so. Once logged in, you will see a dashboard showing any applications you have previously created. Click the "New Application" button in the top right corner of the page.

You will be prompted to enter a name for your application. This name will appear as your bot username in Discord, though you can change it later. Choose something descriptive that represents your bot purpose. After entering the name, agree to the Discord Developer Terms of Service and click "Create" to proceed.

Once your application is created, you will be taken to its settings page. Here you can add a description, set an avatar image, and configure various options. Navigate to the "Bot" section in the left sidebar to access bot-specific settings. On this page, you can customise your bot username and avatar independently from the application itself.

You will also need to configure your bot Gateway Intents on this page. Intents control which events your bot receives from Discord. For most bots, you will want to enable the "Message Content" intent so your bot can read message text, and the "Server Members" intent if your bot needs to track member joins and updates. These privileged intents require explicit enabling because they involve accessing sensitive user data.

Step 2: Getting the Bot Token

Your bot token is the authentication credential that allows your code to connect to Discord as your bot. It functions like a password and must be kept completely secret. Anyone who obtains your token can control your bot, so never share it publicly, commit it to a public repository, or include it directly in your source code.

On the Bot settings page in the Developer Portal, you will see a "Token" section. Click "Reset Token" to generate a new token. Discord will display the token once, and you will need to copy it immediately because it cannot be viewed again after you navigate away from the page. Store this token somewhere secure, such as a password manager or a local file that is not tracked by version control.

If you ever suspect that your token has been compromised or accidentally exposed, return to the Developer Portal and click "Reset Token" again. This immediately invalidates the old token and generates a new one. You will need to update the token in your hosting environment before your bot can reconnect.

To invite your bot to a Discord server for testing, go to the "OAuth2" section, then "URL Generator". Select the "bot" scope and choose the permissions your bot needs. Copy the generated URL and open it in your browser to add the bot to a server where you have the Manage Server permission.

Step 3: Writing a Simple Bot (Node.js Example)

With your bot application created and token saved, you can now write the code that brings your bot to life. This tutorial uses Node.js with the discord.js library, the most popular framework for building Discord bots in JavaScript.

First, create a new directory for your bot project and initialise it with npm. Open your terminal and run the following commands:

mkdir my-discord-bot
cd my-discord-bot
npm init -y

This creates a new folder and generates a package.json file that tracks your project dependencies and configuration. The -y flag accepts all default values for the package configuration.

Step 4: Installing Dependencies

Install the discord.js library and dotenv package for managing environment variables:

npm install discord.js dotenv

The discord.js package provides the tools to interact with the Discord API, while dotenv allows you to load your bot token from a .env file rather than hardcoding it in your source code.

Create a .env file in your project root to store your bot token securely:

DISCORD_TOKEN=your-bot-token-here

Replace "your-bot-token-here" with the actual token you copied from the Developer Portal. This file should never be committed to version control.

Create a .gitignore file to prevent accidentally exposing your token:

node_modules/
.env

Now create your main bot file. Create a file called index.js with the following code:

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.author.bot) return;

    if (message.content === '!ping') {
        message.reply('Pong!');
    }

    if (message.content === '!hello') {
        message.reply(`Hello, ${message.author.username}!`);
    }
});

client.login(process.env.DISCORD_TOKEN);

This code creates a bot that responds to two commands: !ping replies with "Pong!" and !hello greets the user by name. The bot loads the token from the .env file, connects to Discord with the necessary intents, and listens for incoming messages. The check for message.author.bot prevents the bot from responding to its own messages or messages from other bots, avoiding potential infinite loops.

Step 5: Uploading Files to a Host

With your bot code written and tested locally, the next step is uploading it to a hosting provider so it can run continuously. This tutorial uses MonkeyBytes Hosting as the example, but the general process is similar across most hosting platforms.

First, create an account on MonkeyBytes Hosting by visiting the dashboard at dash.monkey-network.xyz. After registering and verifying your email, create a new server from the dashboard. Select the appropriate server type for your bot (Node.js for this tutorial) and wait for the server to be provisioned.

Once your server is ready, you can upload files using SFTP. The SFTP connection details are available in your server dashboard. You will need an SFTP client such as FileZilla or WinSCP. Enter the server address, port, username, and password provided in the dashboard to connect.

Upload the following files to the server root directory:

  • index.js — your main bot file
  • package.json — dependency manifest
  • .env — containing your bot token

Do not upload the node_modules folder. The hosting platform will install dependencies automatically when you start the server by running npm install based on your package.json file. This ensures the correct versions of packages are compiled for the server environment.

Step 6: Running the Bot 24/7

After uploading your files, navigate to your server console in the MonkeyBytes dashboard and start the server. The platform will automatically run npm install to install your dependencies, then execute your startup command to launch the bot. You should see your bot login message in the console output, confirming that it has connected to Discord successfully.

MonkeyBytes Hosting automatically manages your bot process, which means it will restart your bot if it crashes due to an unhandled error. The platform monitors resource usage and provides alerts if your bot approaches its memory or CPU limits. You can view real-time console output, restart your bot, and manage files all from the web dashboard.

Your bot will now run continuously without requiring your personal computer to be online. The hosting server maintains the connection to Discord around the clock, ensuring your bot is always available to respond to commands and events in your Discord servers.

To verify everything is working, go to a Discord server where your bot has been invited and type !ping in any text channel. Your bot should reply with "Pong!" almost immediately. If it does not respond, check the console output in your hosting dashboard for error messages.

Step 7: Common Mistakes to Avoid

New bot developers frequently encounter several common issues when deploying their first bot. Being aware of these pitfalls helps you avoid frustration and get your bot running smoothly from the start.

  • Exposing your bot token: The most critical mistake is accidentally sharing your bot token. Never paste it into Discord channels, public code repositories, or screenshots. If exposed, reset it immediately in the Developer Portal.
  • Forgetting Gateway Intents: Discord requires bots to declare which events they want to receive. If you forget to enable the Message Content intent in both your code and the Developer Portal, your bot will not receive message content and commands will not work.
  • Uploading node_modules: Uploading the node_modules directory wastes storage space and can cause compatibility issues if your development machine uses a different operating system than the host server. Always let the host run npm install.
  • Not handling errors: Unhandled promise rejections or uncaught exceptions will crash your bot. Add error handlers to prevent unexpected shutdowns. At minimum, add process.on('unhandledRejection') and client.on('error') handlers.
  • Hardcoding the token: Even for personal projects, always use environment variables for your token. This creates good habits and prevents accidental exposure when sharing code or pushing to repositories.
  • Ignoring rate limits: Discord enforces rate limits on API requests. If your bot sends too many messages or API calls in a short period, it will be temporarily blocked. Design your bot to handle rate limit responses gracefully.
  • Not testing locally first: Always test your bot on your local machine before deploying to a host. This allows you to catch errors quickly and debug with direct access to your development environment.

Step 8: Monitoring Your Bot

Once your bot is deployed, monitoring its health and performance is essential for maintaining a reliable service. Even well-written bots can encounter issues in production that were not apparent during development.

The MonkeyBytes dashboard provides real-time resource monitoring showing your bot memory usage, CPU consumption, and network activity. These metrics help you identify trends and potential problems before they cause outages. If you notice memory usage steadily increasing over time, your bot may have a memory leak that needs to be addressed.

Adding logging to your bot code provides visibility into what your bot is doing and helps diagnose issues when they occur. Use console.log statements to record important events like command executions, errors, and connection status changes. Structured logging with timestamps makes it easier to correlate events and trace problems.

Consider implementing a simple health check that periodically logs the bot uptime, connected guild count, and memory usage. This creates a regular heartbeat in your logs that confirms the bot is functioning normally and provides useful metrics for understanding your bot growth over time.

setInterval(() => {
    const memUsage = process.memoryUsage();
    console.log(`[Health] Uptime: ${Math.floor(client.uptime / 1000)}s | ` +
        `Guilds: ${client.guilds.cache.size} | ` +
        `Memory: ${Math.round(memUsage.heapUsed / 1024 / 1024)}MB`);
}, 300000); // Log every 5 minutes

Step 9: Keeping Your Bot Online

Maintaining long-term uptime for your Discord bot requires attention to several factors beyond initial deployment. Bot libraries receive regular updates that fix bugs, patch security vulnerabilities, and add support for new Discord features. Keeping your dependencies updated ensures your bot remains compatible with the Discord API as it evolves.

Implement proper error handling throughout your bot code to prevent crashes from unexpected situations. Discord connections can drop due to network issues, API changes, or server maintenance. The discord.js library handles reconnection automatically in most cases, but your code should gracefully handle errors that occur during event processing.

Add a process-level error handler to catch any unhandled exceptions that would otherwise crash your bot:

process.on('unhandledRejection', (error) => {
    console.error('Unhandled promise rejection:', error);
});

client.on('error', (error) => {
    console.error('Discord client error:', error);
});

Regularly review your bot console output for warnings or deprecation notices from discord.js and Node.js. These notices indicate upcoming changes that may require modifications to your code. Addressing them proactively prevents breakages when deprecated features are eventually removed.

If your bot grows to serve many servers, consider implementing sharding to distribute the load across multiple connections. The discord.js library provides a built-in ShardingManager that handles this automatically. MonkeyBytes Hosting supports sharded bots, allowing you to scale as your community grows.

For more detailed information about hosting, check our complete hosting guide. If you run into problems, visit the troubleshooting guide for solutions to common issues. Explore our features page to learn about all the tools available on MonkeyBytes, or return to the home page to get started. You can also check our FAQ for answers to frequently asked questions.

Guide Complete Hosting Guide Guide Bot Troubleshooting Guide Comparison Free Hosting Platforms