Write a discord bot base in discord.js v14
- User
Write a discord bot base in discord.js v14
- 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
-
Create a New Application:
- Go to the Discord Developer Portal.
- Click on "New Application".
- Give your application a name and click "Create".
-
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!".
-
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
-
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.
-
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
-
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
-
-
Install discord.js:
-
Install the discord.js library:
npm install discord.js
-
-
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
-
Create the Bot File:
- In your project directory, create a new file named
index.js.
- In your project directory, create a new file named
-
Set Up the Bot Code:
-
Open
index.jsin 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);
-
-
Create a .env File:
-
In your project directory, create a file named
.env. -
Add your bot token to the
.envfile:DISCORD_TOKEN=your-bot-token-hereReplace
your-bot-token-herewith the token you copied earlier.
-
-
Security Note:
-
Do not commit your
.envfile to any public repository. -
Create a
.gitignorefile and add.envto ensure it's ignored by Git:node_modules .env
-
Step 5: Running Your Bot
-
Start the Bot:
-
In your terminal, run:
node index.js -
You should see a message in the console:
Logged in as YourBotName#1234!
-
-
Test the Bot:
- In your Discord server, type
!pingin any channel where the bot has access. - The bot should respond with
Pong!.
- In your Discord server, type
Step 6: Adding Slash Commands
Discord now encourages the use of slash commands. Let's update your bot to respond to a slash command.
-
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);
-
-
Restart Your Bot:
-
Stop the running bot in your terminal (press
Ctrl + C). -
Start the bot again:
node index.js
-
-
Test the Slash Command:
- In your Discord server, type
/ping. - You should see the
pingcommand appear; select it. - The bot will respond with
Pong!.
- In your Discord server, type
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...catchblocks 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
- discord.js Guide
- discord.js Documentation
- Discord Developer Portal
- Node.js Official Website
- Managing Secrets with dotenv
Feel free to ask if you have any questions or need further assistance!