Getting Started with Your First Discord Bot Using Node.js

Getting Started with Your First Discord Bot Using Node.js

Creating a Discord bot can be a fun and rewarding project, especially if you're looking to add some automation or interactivity to your Discord server. In this blog, we'll walk you through the steps to create a simple Discord bot using Node.js and add a basic command (/echo) that echoes back what the user says.

Prerequisites

Before we get started, make sure you have the following:

  • Node.js installed on your machine. You can download it from Node.js.

  • A Discord account and a server where you can test your bot. If you don't have a server, you can create one by clicking the "+" icon on the left sidebar of the Discord app.

Step 1: Set Up Your Bot on the Discord Developer Portal

  1. Go to the Discord Developer Portal.

  2. Click on the "New Application" button and give your application a name.

  3. Navigate to the "Bot" tab on the left sidebar and click "Add Bot".

  4. You'll see a token generated for your bot. Keep this token safe, as you'll need it later to connect your bot to Discord.

Step 2: Create Your Project

  1. Open your terminal or command prompt and create a new directory for your project:
  •     mkdir my-discord-bot
        cd my-discord-bot
    
  • Initialize a new Node.js project:

  •     npm init -y
    
  • Install the necessary dependencies:

  1.   npm install discord.js
    

Step 3: Write Your Bot's Code

Create a new file named index.js in your project directory and add the following code:

const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'YOUR_BOT_TOKEN';

client.once('ready', () => {
    console.log('Bot is online!');
});

client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

    const { commandName } = interaction;

    if (commandName === 'echo') {
        await interaction.reply(interaction.options.getString('input'));
    }
});

client.login(token);

Replace 'YOUR_BOT_TOKEN' with the token you got from the Discord Developer Portal.

Step 4: Add Your Command to Discord

In order for your bot to recognize the /echo command, you need to define it in Discord. Create a new file named deploy-commands.js in your project directory and add the following code:

const { SlashCommandBuilder } = require('@discordjs/builders');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const clientId = 'YOUR_CLIENT_ID';
const guildId = 'YOUR_GUILD_ID';
const token = 'YOUR_BOT_TOKEN';

const commands = [
    new SlashCommandBuilder().setName('echo').setDescription('Replies with your input')
        .addStringOption(option => option.setName('input').setDescription('The input to echo back')),
].map(command => command.toJSON());

const rest = new REST({ version: '9' }).setToken(token);

(async () => {
    try {
        console.log('Started refreshing application (/) commands.');

        await rest.put(
            Routes.applicationGuildCommands(clientId, guildId),
            { body: commands },
        );

        console.log('Successfully reloaded application (/) commands.');
    } catch (error) {
        console.error(error);
    }
})();

Replace 'YOUR_CLIENT_ID', 'YOUR_GUILD_ID', and 'YOUR_BOT_TOKEN' with your bot's client ID, your server's ID, and your bot's token, respectively.

Run the script to register the command with Discord:

node deploy-commands.js

Step 5: Run Your Bot

Start your bot by running:

node index.js

Your bot should now be online in your Discord server. Try using the /echo command followed by some text, and the bot should echo back your message.

Conclusion

Congratulations! You've just created your first Discord bot using Node.js. This is just the beginning, and there's a lot more you can do with Discord bots. Feel free to experiment and add more functionality to your bot.

Did you find this article valuable?

Support Denny Wang by becoming a sponsor. Any amount is appreciated!