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

Write a discord bot base in discord.js v14

  1. User

    Write a discord bot base in discord.js v14

  2. Assistant

    Sure! I'll guide you through creating a basic Discord bot using discord.js v14. This bot will connect to your Discord server and respond to simple commands.


    Prerequisites

    • Node.js v16.9.0 or higher installed on your machine.
    • A Discord account.
    • Basic knowledge of JavaScript and using the command line.
    • A text editor (e.g., Visual Studio Code).

    Step 1: Setting Up Your Discord Bot Application

    1. Create a New Application:

    2. Add a Bot to Your Application:

      • In your application's dashboard, navigate to the "Bot" tab on the left sidebar.
      • Click on "Add Bot".
      • Confirm by clicking "Yes, do it!".
    3. Retrieve Your Bot Token:

      • Under the "Bot" tab, you'll see your bot's information.
      • Click on "Reset Token" and then "Yes, do it!" to generate a token.
      • Copy the token and keep it somewhere safe. Do not share this token publicly.

    Step 2: Inviting Your Bot to Your Server

    1. Generate an Invite Link:

      • Navigate to the "OAuth2" section, then to the "URL Generator".
      • Under Scopes, select "bot" and "applications.commands".
      • Under Bot Permissions, select the permissions you want your bot to have. For basic functionality, you might select:
        • Send Messages
        • Read Messages/View Channels
        • Use Slash Commands
      • A Generated URL will appear at the bottom.
    2. Invite the Bot:

      • Copy the generated URL.
      • Paste it into your browser and select the server where you want to add the bot.
      • Follow the prompts to authorize the bot.

    Step 3: Setting Up Your Project

    1. Initialize Your Project:

      • Open your command prompt or terminal.

      • Create a new directory for your bot project and navigate into it:

        mkdir my-discord-bot
        cd my-discord-bot
        
      • Initialize a new Node.js project:

        npm init -y
        
    2. Install discord.js:

      • Install the discord.js library:

        npm install discord.js
        
    3. Install dotenv (for Environment Variables):

      • This helps keep your bot token secure by storing it in an environment variable:

        npm install dotenv
        

    Step 4: Writing Your Bot's Code

    1. Create the Bot File:

      • In your project directory, create a new file named index.js.
    2. Set Up the Bot Code:

      • Open index.js in your text editor and add the following code:

        // Load environment variables from a .env file into process.env
        require('dotenv').config();
        
        // Import the Client and Intents classes from discord.js
        const { Client, GatewayIntentBits } = require('discord.js');
        
        // 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('ready', () => {
          console.log(`Logged in as ${client.user.tag}!`);
        });
        
        // Listen for messages
        client.on('messageCreate', (message) => {
          // Ignore messages from bots
          if (message.author.bot) return;
        
          // If the message content is '!ping', respond with 'Pong!'
          if (message.content === '!ping') {
            message.channel.send('Pong!');
          }
        });
        
        // Log in to Discord with your bot's token
        client.login(process.env.DISCORD_TOKEN);
        
    3. Create a .env File:

      • In your project directory, create a file named .env.

      • Add your bot token to the .env file:

        DISCORD_TOKEN=your-bot-token-here
        

        Replace your-bot-token-here with the token you copied earlier.

    4. Security Note:

      • Do not commit your .env file to any public repository.

      • Create a .gitignore file and add .env to ensure it's ignored by Git:

        node_modules
        .env
        

    Step 5: Running Your Bot

    1. Start the Bot:

      • In your terminal, run:

        node index.js
        
      • You should see a message in the console:

        Logged in as YourBotName#1234!
        
    2. Test the Bot:

      • In your Discord server, type !ping in any channel where the bot has access.
      • The bot should respond with Pong!.

    Step 6: Adding Slash Commands

    Discord now encourages the use of slash commands. Let's update your bot to respond to a slash command.

    1. Register a Slash Command:

      • Install necessary packages:

        npm install @discordjs/rest discord-api-types
        
      • Update your index.js:

        // Load environment variables
        require('dotenv').config();
        
        // Import necessary classes
        const { Client, GatewayIntentBits } = require('discord.js');
        const { REST } = require('@discordjs/rest');
        const { Routes } = require('discord-api-types/v10');
        const { SlashCommandBuilder } = require('@discordjs/builders');
        
        // Create a new client instance
        const client = new Client({ intents: [GatewayIntentBits.Guilds] });
        
        // Create a new slash command
        const commands = [
          new SlashCommandBuilder()
            .setName('ping')
            .setDescription('Replies with Pong!'),
        ].map(command => command.toJSON());
        
        // Register slash commands when the client is ready
        client.once('ready', async () => {
          console.log(`Logged in as ${client.user.tag}!`);
        
          const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
        
          try {
            console.log('Started refreshing application (/) commands.');
        
            await rest.put(
              Routes.applicationCommands(client.user.id),
              { body: commands },
            );
        
            console.log('Successfully reloaded application (/) commands.');
          } catch (error) {
            console.error(error);
          }
        });
        
        // Respond to slash commands
        client.on('interactionCreate', async interaction => {
          if (!interaction.isCommand()) return;
        
          if (interaction.commandName === 'ping') {
            await interaction.reply('Pong!');
          }
        });
        
        // Log in to Discord with your bot's token
        client.login(process.env.DISCORD_TOKEN);
        
    2. Restart Your Bot:

      • Stop the running bot in your terminal (press Ctrl + C).

      • Start the bot again:

        node index.js
        
    3. Test the Slash Command:

      • In your Discord server, type /ping.
      • You should see the ping command appear; select it.
      • The bot will respond with Pong!.

    Congratulations!

    You've successfully created a basic Discord bot using discord.js v14 that can respond to both traditional and slash commands.


    Next Steps and Tips

    • Explore More Events and Commands:

      • Check out the discord.js documentation for more events and methods.
      • Learn how to handle other interactions like buttons, selects, and modals.
    • Error Handling:

      • Add error handling to your bot to make it more robust.
      • Use try...catch blocks where appropriate.
    • Organize Your Code:

      • As your bot grows, consider organizing commands and events into separate folders and files.
      • Use a command handler to dynamically load commands.
    • Stay Updated:

      • Keep your discord.js library up-to-date to take advantage of new features and bug fixes.
    • Join Developer Communities:

      • Participate in Discord developer communities for support and collaboration.

    Resources


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