Creating a Discord bot with discord.js v14 in Node.js that loads slash commands from a ./commands directory, events from a ./events directory, and securely loads sensitive data (like the bot token) from an encrypted file in ./settings involves several steps. Below is a comprehensive guide to help you set up this structure.
Table of Contents
- Project Structure
- Prerequisites
- Setup Instructions
- Running the Bot
- Security Considerations
- Complete Code Example
Project Structure
Here's how your project directory will look:
your-bot/
├── commands/
│ └── ping.js
├── events/
│ └── ready.js
├── settings/
│ └── settings.enc
├── utils/
│ └── settings.js
├── index.js
├── package.json
└── .gitignore
Prerequisites
- Node.js: Ensure you have Node.js installed (v16.9.0 or higher is required for
discord.js v14).
- Discord Bot Token: You need to have a Discord bot token. You can obtain one by creating a bot in the Discord Developer Portal.
Setup Instructions
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 the necessary packages:
npm install discord.js dotenv
We'll use the built-in crypto module for encryption, so no need to install additional packages for that.
3. Create Encrypted Settings File
We'll store sensitive information like the bot token in an encrypted JSON file. Here's how to create and manage it.
a. Create a .env File for Encryption Key
First, create a .env file to store your encryption key. This key is crucial for encrypting and decrypting your settings. Ensure this file is kept secret and never committed to version control.
Create a .env file in the root directory:
ENCRYPTION_KEY=your-32-byte-long-secret-key-here!
Note: The encryption key must be 32 bytes (256 bits) for AES-256 encryption. You can generate a secure key using Node.js or other secure methods.
For example, to generate a random 32-byte key using Node.js:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'));"
Copy the generated hex string into your ENCRYPTION_KEY.
b. Create a Script to Encrypt the Settings
Create a utils directory to store utility scripts:
mkdir utils
Inside utils, create a file named encryptSettings.js:
// utils/encryptSettings.js
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
require('dotenv').config();
const algorithm = 'aes-256-cbc';
const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex'); // Ensure key is in hex format
const iv = crypto.randomBytes(16); // Initialization vector
function encrypt(text) {
let cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return { iv: iv.toString('hex'), encryptedData: encrypted };
}
// Example settings data
const settings = {
token: 'YOUR_DISCORD_BOT_TOKEN',
clientId: 'YOUR_CLIENT_ID',
// Add other settings as needed
};
const settingsString = JSON.stringify(settings);
const encrypted = encrypt(settingsString);
// Save the encrypted data to settings.enc
const output = {
iv: encrypted.iv,
data: encrypted.encryptedData,
};
fs.writeFileSync(
path.join(__dirname, '../settings/settings.enc'),
JSON.stringify(output)
);
console.log('Settings have been encrypted and saved to ./settings/settings.enc');
Usage:
- Replace
'YOUR_DISCORD_BOT_TOKEN' and 'YOUR_CLIENT_ID' with your actual bot token and client ID.
- Run the script to generate the encrypted settings file:
node utils/encryptSettings.js
This will create a settings.enc file in the ./settings directory containing the encrypted settings.
Important: After running the script, ensure that your .env file and settings.enc are not committed to version control. Add them to your .gitignore:
Create a .gitignore file:
node_modules/
.env
settings/settings.enc
4. Project Structure
Ensure your project structure looks like this after following the steps:
your-bot/
├── commands/
│ └── ping.js
├── events/
│ └── ready.js
├── settings/
│ └── settings.enc
├── utils/
│ └── encryptSettings.js
├── index.js
├── package.json
├── .env
└── .gitignore
5. Main Bot File
Create the main bot file index.js in the root directory:
// index.js
const fs = require('fs');
const path = require('path');
const { Client, Collection, IntentsBitField, REST, Routes } = require('discord.js');
const { loadSettings } = require('./utils/settings');
require('dotenv').config(); // Load environment variables
(async () => {
const settings = await loadSettings();
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'));
const commands = [];
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);
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
// Register slash commands
const rest = new REST({ version: '10' }).setToken(settings.token);
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
await rest.put(
Routes.applicationCommands(settings.clientId),
{ body: commands },
);
console.log(`Successfully reloaded ${commands.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
// 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));
}
}
// Log in to Discord
client.login(settings.token);
})();
6. Loading Settings
Create a utility function to load and decrypt the settings.
Create a settings.js file inside the utils directory:
// utils/settings.js
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
require('dotenv').config();
const algorithm = 'aes-256-cbc';
const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');
function decrypt(encryptedData, iv) {
let decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(iv, 'hex'));
let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
async function loadSettings() {
const settingsPath = path.join(__dirname, '../settings/settings.enc');
const encrypted = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
const decrypted = decrypt(encrypted.data, encrypted.iv);
const settings = JSON.parse(decrypted);
return settings;
}
module.exports = { loadSettings };
7. Loading Commands
Commands are loaded dynamically from the ./commands directory in the index.js file. Each command should export a data property (using SlashCommandBuilder) and an execute function.
8. Loading Events
Events are loaded dynamically from the ./events directory in the index.js file. Each event file should export name, and execute function, and optionally a once property.
9. Example Command and Event
a. Example Command: ping.js
Create a ping.js file in the ./commands directory:
// 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!');
},
};
b. Example Event: ready.js
Create a ready.js file in the ./events directory:
// events/ready.js
module.exports = {
name: 'ready',
once: true,
execute(client) {
console.log(`Logged in as ${client.user.tag}!`);
},
};
Running the Bot
-
Ensure Environment Variables Are Set:
Your .env file should contain the ENCRYPTION_KEY in hexadecimal format.
-
Encrypt Settings:
Make sure you've run the encryptSettings.js script to generate settings.enc:
node utils/encryptSettings.js
Update the settings.enc whenever you change your settings.
-
Start the Bot:
Run the main bot file:
node index.js
You should see a message indicating that the bot has logged in and the commands have been registered.
Security Considerations
- Protect the Encryption Key: The
ENCRYPTION_KEY in your .env file is critical. Do not expose it publicly or commit it to version control.
- Secure Storage: Ensure that both
.env and settings/settings.enc are stored securely and excluded from version control via .gitignore.
- Regularly Rotate Keys: Periodically change your encryption keys and update your settings accordingly to enhance security.
Complete Code Example
For convenience, here's the complete code structure with all necessary files.
1. .gitignore
node_modules/
.env
settings/settings.enc
2. .env
ENCRYPTION_KEY=your-64-character-hexadecimal-key-here
Replace your-64-character-hexadecimal-key-here with your actual 64-character hex key (32 bytes).
3. utils/encryptSettings.js
// utils/encryptSettings.js
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
require('dotenv').config();
const algorithm = 'aes-256-cbc';
const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex'); // Ensure key is in hex format
const iv = crypto.randomBytes(16); // Initialization vector
function encrypt(text) {
let cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return { iv: iv.toString('hex'), encryptedData: encrypted };
}
// Example settings data
const settings = {
token: 'YOUR_DISCORD_BOT_TOKEN',
clientId: 'YOUR_CLIENT_ID',
// Add other settings as needed
};
const settingsString = JSON.stringify(settings);
const encrypted = encrypt(settingsString);
// Save the encrypted data to settings.enc
const output = {
iv: encrypted.iv,
data: encrypted.encryptedData,
};
fs.writeFileSync(
path.join(__dirname, '../settings/settings.enc'),
JSON.stringify(output, null, 4) // Pretty print with indentation
);
console.log('Settings have been encrypted and saved to ./settings/settings.enc');
4. utils/settings.js
// utils/settings.js
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
require('dotenv').config();
const algorithm = 'aes-256-cbc';
const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');
function decrypt(encryptedData, iv) {
let decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(iv, 'hex'));
let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
async function loadSettings() {
const settingsPath = path.join(__dirname, '../settings/settings.enc');
if (!fs.existsSync(settingsPath)) {
throw new Error('Encrypted settings file not found. Please run encryptSettings.js first.');
}
const encrypted = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
const decrypted = decrypt(encrypted.data, encrypted.iv);
const settings = JSON.parse(decrypted);
return settings;
}
module.exports = { loadSettings };
5. index.js
// index.js
const fs = require('fs');
const path = require('path');
const { Client, Collection, IntentsBitField, REST, Routes } = require('discord.js');
const { loadSettings } = require('./utils/settings');
require('dotenv').config(); // Load environment variables
(async () => {
try {
const settings = await loadSettings();
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'));
const commands = [];
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);
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
// Register slash commands
const rest = new REST({ version: '10' }).setToken(settings.token);
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
await rest.put(
Routes.applicationCommands(settings.clientId),
{ body: commands },
);
console.log(`Successfully reloaded ${commands.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
// 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));
}
}
// Log in to Discord
client.login(settings.token);
} catch (error) {
console.error('Error starting the bot:', error);
}
})();
6. commands/ping.js
// 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!');
},
};
7. events/ready.js
// events/ready.js
module.exports = {
name: 'ready',
once: true,
execute(client) {
console.log(`Logged in as ${client.user.tag}!`);
},
};
Conclusion
By following the steps above, you've set up a scalable Discord bot structure using discord.js v14 that:
- Loads Slash Commands dynamically from the
./commands directory.
- Loads Events dynamically from the
./events directory.
- Secures Sensitive Data by storing it in an encrypted file within the
./settings directory.
This setup promotes modularity, security, and ease of maintenance. You can expand upon this foundation by adding more commands and events as needed.