Write a bot base for discord.js v14 using node.js
- User
Write a bot base for discord.js v14 using node.js
- Assistant
Sure! Below is a basic template for a Discord bot using
discord.jsv14 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
- Node.js: Ensure you have Node.js installed. You can download it from nodejs.org.
- Discord Account: You need a Discord account to create and manage your bot.
- Text Editor: Any code editor like VSCode, Sublime Text, or Atom.
Step 1: Create a New Discord Application and Bot
- Go to the Discord Developer Portal and log in.
- Click on "New Application" and give it a name.
- In the application's page, navigate to the "Bot" tab on the left and click "Add Bot".
- Under the "Token" section, click "Copy" to get your bot's token. Keep this token secure.
- Under the "Privileged Gateway Intents" section, enable the "Message Content Intent" if you plan to handle message content.
Step 2: Set Up Your Project
-
Create a Project Directory
mkdir discord-bot cd discord-bot -
Initialize a New Node.js Project
npm init -y -
Install
discord.jsv14npm install discord.js -
Install Additional Dependencies (Optional but Recommended)
For handling environment variables securely:
npm install dotenv
Step 3: Create the Bot Base
-
Create a
.envFileIn the root of your project, create a
.envfile to store your bot token securely.DISCORD_TOKEN=your-bot-token-hereMake sure to add
.envto your.gitignoreif you're using version control to prevent exposing your token. -
Create
index.jsCreate an
index.jsfile 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
-
Start Your Bot
node index.jsIf everything is set up correctly, you should see a message like:
Ready! Logged in as YourBotName#1234 -
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.
-
Test the Bot
In your Discord server, go to a text channel and type
!ping. The bot should reply withPong!.
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.
-
Create a
deploy-commands.jsFile// 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. -
Run the Deployment Script
node deploy-commands.js -
Update
index.jsto 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.
-
Directory Structure
discord-bot/ ├── commands/ │ └── ping.js ├── index.js ├── deploy-commands.js ├── package.json └── .env -
Create
commands/ping.js// commands/ping.js module.exports = { data: { name: 'ping', description: 'Replies with Pong!', }, async execute(interaction) { await interaction.reply('Pong!'); }, }; -
Update
deploy-commands.jsto 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); } })(); -
Update
index.jsto 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.jsv14 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!