Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Write a bot base for discord.js v14 using node.js

  1. User

    Write a bot base for discord.js v14 using node.js

  2. Assistant

    Sure! Below is a basic template for a Discord bot using discord.js v14 and Node.js. This guide will walk you through setting up your project, installing necessary dependencies, and providing a simple bot base that you can expand upon.

    Prerequisites

    1. Node.js: Ensure you have Node.js installed. You can download it from nodejs.org.
    2. Discord Account: You need a Discord account to create and manage your bot.
    3. Text Editor: Any code editor like VSCode, Sublime Text, or Atom.

    Step 1: Create a New Discord Application and Bot

    1. Go to the Discord Developer Portal and log in.
    2. Click on "New Application" and give it a name.
    3. In the application's page, navigate to the "Bot" tab on the left and click "Add Bot".
    4. Under the "Token" section, click "Copy" to get your bot's token. Keep this token secure.
    5. Under the "Privileged Gateway Intents" section, enable the "Message Content Intent" if you plan to handle message content.

    Step 2: Set Up Your Project

    1. Create a Project Directory

      mkdir discord-bot
      cd discord-bot
      
    2. Initialize a New Node.js Project

      npm init -y
      
    3. Install discord.js v14

      npm install discord.js
      
    4. Install Additional Dependencies (Optional but Recommended)

      For handling environment variables securely:

      npm install dotenv
      

    Step 3: Create the Bot Base

    1. Create a .env File

      In the root of your project, create a .env file to store your bot token securely.

      DISCORD_TOKEN=your-bot-token-here
      

      Make sure to add .env to your .gitignore if you're using version control to prevent exposing your token.

    2. Create index.js

      Create an index.js file in your project directory and add the following code:

      // index.js
      const { Client, IntentsBitField, Events, GatewayIntentBits } = require('discord.js');
      require('dotenv').config();
      
      // Create a new client 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}`);
      });
      
      // Listen for message events
      client.on(Events.MessageCreate, message => {
        // Ignore messages from bots
        if (message.author.bot) return;
      
        // Example command: !ping
        if (message.content === '!ping') {
          message.reply('Pong!');
        }
      });
      
      // Log in to Discord with your client's token
      client.login(process.env.DISCORD_TOKEN);
      

    Step 4: Running the Bot

    1. Start Your Bot

      node index.js
      

      If everything is set up correctly, you should see a message like:

      Ready! Logged in as YourBotName#1234
      
    2. Invite the Bot to Your Server

      • Go back to the Discord Developer Portal and select your application.
      • Navigate to the "OAuth2" tab and then "URL Generator".
      • Under "Scopes", select bot.
      • Under "Bot Permissions", select the permissions your bot needs (e.g., Send Messages).
      • A URL will be generated at the bottom. Open this URL in your browser, select the server you want to add the bot to, and authorize it.
    3. Test the Bot

      In your Discord server, go to a text channel and type !ping. The bot should reply with Pong!.

    Additional Features

    Handling Slash Commands

    Discord now encourages the use of slash commands for better user experience. Here's how to set up a basic slash command.

    1. Create a deploy-commands.js File

      // deploy-commands.js
      const { REST, Routes } = require('discord.js');
      require('dotenv').config();
      
      const commands = [
        {
          name: 'ping',
          description: 'Replies with Pong!',
        },
        // Add more commands here
      ];
      
      const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
      
      (async () => {
        try {
          console.log('Started refreshing application (/) commands.');
      
          await rest.put(
            Routes.applicationCommands('YOUR_CLIENT_ID'),
            { body: commands },
          );
      
          console.log('Successfully reloaded application (/) commands.');
        } catch (error) {
          console.error(error);
        }
      })();
      

      Replace 'YOUR_CLIENT_ID' with your bot's client ID found in the Developer Portal.

    2. Run the Deployment Script

      node deploy-commands.js
      
    3. Update index.js to Handle Slash Commands

      // index.js (continued)
      client.on(Events.InteractionCreate, async interaction => {
        if (!interaction.isCommand()) return;
      
        const { commandName } = interaction;
      
        if (commandName === 'ping') {
          await interaction.reply('Pong!');
        }
      });
      

    Using Command Files

    As your bot grows, organizing commands into separate files can help maintainability.

    1. Directory Structure

      discord-bot/
      ├── commands/
      │   └── ping.js
      ├── index.js
      ├── deploy-commands.js
      ├── package.json
      └── .env
      
    2. Create commands/ping.js

      // commands/ping.js
      module.exports = {
        data: {
          name: 'ping',
          description: 'Replies with Pong!',
        },
        async execute(interaction) {
          await interaction.reply('Pong!');
        },
      };
      
    3. Update deploy-commands.js to Dynamically Load Commands

      // deploy-commands.js
      const fs = require('node:fs');
      const path = require('node:path');
      const { REST, Routes } = require('discord.js');
      require('dotenv').config();
      
      const commands = [];
      const commandsPath = path.join(__dirname, 'commands');
      const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
      
      for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        const command = require(filePath);
        commands.push(command.data);
      }
      
      const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
      
      (async () => {
        try {
          console.log('Started refreshing application (/) commands.');
      
          await rest.put(
            Routes.applicationCommands('YOUR_CLIENT_ID'),
            { body: commands },
          );
      
          console.log('Successfully reloaded application (/) commands.');
        } catch (error) {
          console.error(error);
        }
      })();
      
    4. Update index.js to Load Commands Dynamically

      // index.js
      const fs = require('node:fs');
      const path = require('node:path');
      const { Client, IntentsBitField, Events, GatewayIntentBits } = require('discord.js');
      require('dotenv').config();
      
      const client = new Client({
        intents: [
          GatewayIntentBits.Guilds,
          GatewayIntentBits.GuildMessages,
          GatewayIntentBits.MessageContent,
        ],
      });
      
      client.commands = new Map();
      const commandsPath = path.join(__dirname, 'commands');
      const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
      
      for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        const command = require(filePath);
        client.commands.set(command.data.name, command);
      }
      
      client.once(Events.ClientReady, c => {
        console.log(`Ready! Logged in as ${c.user.tag}`);
      });
      
      client.on(Events.InteractionCreate, async interaction => {
        if (!interaction.isCommand()) return;
      
        const command = client.commands.get(interaction.commandName);
      
        if (!command) return;
      
        try {
          await command.execute(interaction);
        } catch (error) {
          console.error(error);
          await interaction.reply({ content: 'There was an error executing that command!', ephemeral: true });
        }
      });
      
      client.login(process.env.DISCORD_TOKEN);
      

    Conclusion

    You now have a basic Discord bot setup using discord.js v14 with Node.js. This setup includes:

    • Handling message-based commands (!ping).
    • Setting up and handling slash commands (/ping).
    • Organizing commands into separate files for scalability.

    From here, you can expand your bot by adding more commands, integrating APIs, handling events, and more!

    Useful Resources

    Feel free to ask if you have any questions or need further assistance!