Creating a Discord bot using discord.js v14 with a modular structure is a great way to maintain and scale your project effectively. Below is a comprehensive guide to setting up a Discord bot that:
- Loads Slash Commands from the
./commands directory.
- Loads Events from the
./events directory.
- Loads configuration data (like tokens) from the
./settings directory.
Table of Contents
- Prerequisites
- Project Structure
- Setup Steps
- Deploying Slash Commands
- Running the Bot
- Complete Example Code
Prerequisites
- Node.js: Ensure you have Node.js installed (v16.9.0 or higher for
discord.js v14).
- Discord Account: You need a Discord account to create a bot.
- Discord Server: (Optional) For testing your bot.
Project Structure
Here's the recommended directory structure for your bot:
your-bot/
├── commands/
│ └── ping.js
├── events/
│ ├── ready.js
│ └── interactionCreate.js
├── settings/
│ └── config.json
├── index.js
├── package.json
└── .gitignore
Setup Steps
1. Initialize the Project
Create a new directory for your bot and navigate into it:
mkdir your-bot
cd your-bot
Initialize a new Node.js project:
npm init -y
2. Install Dependencies
Install discord.js v14 and other necessary packages:
npm install discord.js dotenv
discord.js: The main library for interacting with the Discord API.
dotenv: Loads environment variables from a .env file into process.env (optional but recommended for managing sensitive data).
3. Create Configuration File
Create a settings directory to store your configuration:
mkdir settings
Inside settings, create a config.json file:
// settings/config.json
{
"token": "YOUR_BOT_TOKEN_HERE",
"clientId": "YOUR_CLIENT_ID_HERE",
"guildId": "YOUR_GUILD_ID_HERE" // Optional: For guild-specific commands
}
Important: Replace the placeholder values with your actual bot token and IDs. To keep your token secure, consider using environment variables with a .env file.
Alternatively, using .env (recommended):
-
Install dotenv as shown above.
-
Create a .env file in the root directory:
DISCORD_TOKEN=your-bot-token
CLIENT_ID=your-client-id
GUILD_ID=your-guild-id
-
Modify config.json accordingly or load directly from process.env in your code.
4. Create the Main Bot File (index.js)
Create an index.js file in the root directory:
// index.js
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, IntentsBitField, Events } = require('discord.js');
const config = require('./settings/config.json');
// Create a new client instance
const client = new Client({
intents: [IntentsBitField.Flags.Guilds],
});
// Initialize a collection for commands
client.commands = new Collection();
// Load command files
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);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
// Load event files
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
// Login to Discord with your client's token
client.login(config.token);
5. Setting Up Commands
Create a commands directory:
mkdir commands
Inside commands, create a sample ping.js command:
// commands/ping.js
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply('Pong!');
},
};
You can add more command files in the commands directory following the same structure.
6. Setting Up Events
Create an events directory:
mkdir events
Inside events, create a ready.js event file:
// events/ready.js
module.exports = {
name: 'ready',
once: true,
execute(client) {
console.log(`✅ Logged in as ${client.user.tag}!`);
},
};
Create an interactionCreate.js event file to handle interactions:
// events/interactionCreate.js
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
},
};
Deploying Slash Commands
Before your bot can use slash commands, you need to register them with Discord. This can be done globally or for specific guilds.
1. Create a deploy-commands.js Script
Create a new file named deploy-commands.js in the root directory:
// deploy-commands.js
const fs = require('node:fs');
const path = require('node:path');
const { REST, Routes } = require('discord.js');
const config = require('./settings/config.json');
const commands = [];
// Grab all the command files from the commands directory
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(config.token);
// Deploy commands
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// If you want to deploy commands globally, use Routes.applicationCommands
// If you want to deploy commands to a specific guild, use Routes.applicationGuildCommands
// Here, we'll deploy to a specific guild for faster updates during development
await rest.put(
Routes.applicationGuildCommands(config.clientId, config.guildId),
{ body: commands },
);
console.log(`Successfully reloaded ${commands.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
Note: Deploying commands to a specific guild (Routes.applicationGuildCommands) updates commands instantly, which is ideal for development. For global commands, use Routes.applicationCommands, but note that global updates can take up to an hour to propagate.
2. Run the Deployment Script
Add a script to your package.json for easy deployment:
// package.json
{
// ...
"scripts": {
"deploy-commands": "node deploy-commands.js",
"start": "node index.js"
},
// ...
}
Now, run the deployment script:
npm run deploy-commands
You should see output indicating that the commands have been successfully registered.
Running the Bot
After deploying the commands, start your bot:
npm start
You should see a message in the console like:
✅ Logged in as YourBotName#1234!
Your bot is now online and ready to respond to the /ping command.
Complete Example Code
1. settings/config.json
{
"token": "YOUR_BOT_TOKEN_HERE",
"clientId": "YOUR_CLIENT_ID_HERE",
"guildId": "YOUR_GUILD_ID_HERE"
}
2. index.js
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, IntentsBitField, Events } = require('discord.js');
const config = require('./settings/config.json');
const client = new Client({
intents: [IntentsBitField.Flags.Guilds],
});
client.commands = new Collection();
// Load 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);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
// Load events
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
client.login(config.token);
3. commands/ping.js
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply('Pong!');
},
};
4. events/ready.js
module.exports = {
name: 'ready',
once: true,
execute(client) {
console.log(`✅ Logged in as ${client.user.tag}!`);
},
};
5. events/interactionCreate.js
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
},
};
6. deploy-commands.js
const fs = require('node:fs');
const path = require('node:path');
const { REST, Routes } = require('discord.js');
const config = require('./settings/config.json');
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);
if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
const rest = new REST({ version: '10' }).setToken(config.token);
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// Deploy to a guild
await rest.put(
Routes.applicationGuildCommands(config.clientId, config.guildId),
{ body: commands },
);
console.log(`Successfully reloaded ${commands.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
7. package.json
Ensure your package.json includes the necessary scripts:
{
"name": "your-bot",
"version": "1.0.0",
"description": "A Discord bot using discord.js v14",
"main": "index.js",
"scripts": {
"deploy-commands": "node deploy-commands.js",
"start": "node index.js"
},
"dependencies": {
"discord.js": "^14.11.0",
"dotenv": "^16.3.1"
},
"author": "Your Name",
"license": "ISC"
}
Additional Tips
-
Environment Variables: It's highly recommended to use environment variables to store sensitive information like your bot token. You can achieve this using the dotenv package.
-
Install dotenv (if not already installed):
npm install dotenv
-
Create a .env file in the root directory:
DISCORD_TOKEN=your-bot-token
CLIENT_ID=your-client-id
GUILD_ID=your-guild-id
-
Modify index.js and deploy-commands.js to use dotenv:
// At the very top of index.js and deploy-commands.js
require('dotenv').config();
// Then replace config.token with process.env.DISCORD_TOKEN, etc.
-
Error Handling: Ensure robust error handling, especially when dealing with asynchronous operations like interacting with the Discord API.
-
Further Enhancements:
- Logging: Implement a logging system for better monitoring.
- Permissions: Handle command permissions and scopes as needed.
- Database Integration: If your bot requires persistent storage, consider integrating a database like MongoDB or PostgreSQL.
-
Documentation: Refer to the official discord.js guide for more in-depth tutorials and best practices.
By following this guide, you'll have a solid foundation for your Discord bot using discord.js v14, with a clean and maintainable structure. From here, you can expand your bot's functionality by adding more commands and events as needed.