Creating a Discord bot with JavaScript and hosting it

Discord bots are a great way to automate tasks and make your server more fun. This guide will show you how to make a discord bot with JavaScript and host it for free. You will need some basic knowledge of JavaScript and Node.js to follow along with this guide.

Getting Started

First, we need to get the discord bot token. Go to the Discord Developer Portal. And create an application.

Now, once you have created the application, the page will get redirected to the application page. You can edit the bot details here.

Now go to the bot section and click on add bot. You will get a confirmation message. Click on yes, do it!

Now click on the Reset Token button. This will reset the bot token. You will get a confirmation message. Accept it and you will get the bot token. Copy the token and create a .env file in the project directory and add the following contents.

TOKEN=YOUR_TOKEN_HERE

Make sure to replace YOUR_TOKEN_HERE with your bot token.

Also, scroll bottom and toggle all the permissions to true.

image

Lastly, we should add the bot to a Discord server, to do this, we go to the Developer portal again and go to the Oauth2->Url Generator. Then, check on the bot checkbox and check Administrator on the bottom checkboxes list.

Now scroll to the bottom of the page and copy the URL.

After that, open it in a new tab and select the server you want to add the bot to. Click on authorize and you are done.

Yaay! You have added the bot to your server.

But, the bot is offline. We need to make it online. To do that, we need to code the bot. Let's get started.

Creating the bot

Now that we have the bot token, we can create the bot. We will be using the discord.js library to create the bot. Install the library using the following command.

npm install discord.js # or pnpm install discord.js / yarn add discord.js

And for getting the token from the .env file, we will be using the dotenv package. Install it using the following command.

npm install dotenv

After that, open the package.json file and add the following scripts.

{
    "scripts": {
        "start": "node index.js"
    }
}

Also, make sure to add the type field to the package.json file.

{
    "type": "module"
}

Now, create a file named index.js and add the following contents.

// Require the necessary discord.js classes
import { Client, Events, GatewayIntentBits } from "discord.js";
import { config } from "dotenv";

// Load environment variables from .env file
config();

const { TOKEN } = process.env;

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

// When the client is ready, run this code (only once)
client.once(Events.ClientReady, (c) => {
    console.log(`Ready! Logged in as ${c.user.tag}`);
});

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

This will create a new instance of the client and log in to the discord bot. Now, run the following command to start the bot.

npm start

The bot should be online now! 🥳

Adding commands

We'll add a simple ping command to the bot. Add the following code to the index.js file.

// Command handler
const prefix = "!"; // Prefix for commands

client.on(Events.MessageCreate, (message) => {
    const content = message.content.trim();
    if (!content.startsWith(prefix)) return; // Ignore messages that don't start with the prefix

    const args = content.slice(prefix.length).trim().split(/ +/); // Split the message into arguments
    const command = args.shift().toLowerCase(); // Get the command name

    const commands = {
        ping: () => {
            message.reply(
                `Pong! Latency is ${Date.now() - message.createdTimestamp}ms.`
            );
        },
    };

    if (command in commands) {
        commands[command]();
    }
});

Restart the bot and try the command by typing !ping in the server.

Nice! We have created a simple ping command. Now, if you want to add more commands, you can add them to the commands object. Let's add a simple help command.

const commands = {
    // ...
    help: () => {
        message.reply(`Available commands: ${Object.keys(commands).join(", ")}`);
    },
};

It also works!

So, if you want to add more commands, you can add them to the commands object.

Hosting the bot

Now that we have created the bot, we need to host it. You can use Railway to host the bot. Create an account and open the dashboard. Click on the New Project.

Then select the Create from GitHub option. After that, select the repository with the bot code and click on Create Project.

Then select edit variables and add the TOKEN variable. Paste the bot token in the value field.

Now after some time, the bot should be online.

And if you test the bot, it should work pretty fast.

Conclusion

You have successfully created a discord bot and hosted it. You can add more commands to the bot and make it more useful.

The code for this tutorial is available here

Connect with me