// Require the necessary discord.js classes
const { Client, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json'); // Store your token in a config.json file (see example below)
// Create a new client instance
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent, // Required to read message content
],
});
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the client above
client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
// Log in to Discord with your client's token
client.login(token);
// Listen for new messages
client.on(Events.MessageCreate, async message => {
// Ignore messages from bots to prevent infinite loops
if (message.author.bot) return;
// Simple command example (prefix based)
if (message.content.startsWith("!ping")) {
message.reply('Pong!');
}
// More advanced example (responding to specific text)
if (message.content.toLowerCase() === "hello bot") {
message.reply(`Hello ${message.author.username}!`);
}
// Example using Message Content (be careful with this - see notes below)
if (message.content.includes("pizza")) {
message.channel.send("🍕🍕🍕 Pizza time! 🍕🍕🍕"); // Sends to the same channel
}
// Example showing how to send embeds (richer messages)
if (message.content.startsWith("!embed")) {
const embed = {
color: 0x0099ff, // Blue color
title: 'My Embedded Message',
description: 'This is a sample embed message.',
fields: [
{ name: 'Field 1', value: 'This is field 1 value.' },
{ name: 'Field 2', value: 'This is field 2 value.' },
],
timestamp: new Date(),
footer: { text: 'Bot Footer' },
};
message.channel.send({ embeds: [embed] });
}
});
// ---- Slash command example (using application commands)----
// To use this, you'll also need to register the commands (see below)
// client.on(Events.InteractionCreate, async interaction => {
// if (!interaction.isChatInputCommand()) return; // Make sure it's a slash command
// const { commandName } = interaction;
// if (commandName === 'ping') {
// await interaction.reply('Pong!');
// } else if (commandName === 'server') {
// await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
// } else if (commandName === 'user') {
// await interaction.reply(`Your tag: ${interaction.user.tag}\nYour id: ${interaction.user.id}`);
// }
// });
//---- Command Registration (for Slash Commands) ----
// This is typically done once during setup or deployment. You need to
// run this separately. Replace `YOUR_CLIENT_ID` and `YOUR_GUILD_ID` with
// your bot's client ID and the server ID you want to test on.
//
// const { REST, Routes } = require('discord.js');
// const commands = [
// {
// name: 'ping',
// description: 'Replies with Pong!',
// },
// {
// name: 'server',
// description: 'Displays server info.',
// },
// {
// name: 'user',
// description: 'Displays user info.',
// },
// ];
// const rest = new REST({ version: '10' }).setToken(token);
// (async () => {
// try {
// console.log('Started refreshing application (/) commands.');
// await rest.put(
// Routes.applicationGuildCommands('YOUR_CLIENT_ID', 'YOUR_GUILD_ID'), // guild commands (fast propagation)
// //Routes.applicationCommands('YOUR_CLIENT_ID'), // Global commands (slower propagation)
// { body: commands },
// );
// console.log('Successfully reloaded application (/) commands.');
// } catch (error) {
// console.error(error);
// }
// })();
// ------------------- Helpful Notes ------------------
// 1. **config.json**: Create a file named `config.json` in the same directory as your bot's code. It should look like this:
// ```json
// {
// "token": "YOUR_BOT_TOKEN_HERE"
// }
// ```
// Replace `YOUR_BOT_TOKEN_HERE` with your actual bot token. **Never commit your token to a public repository!**
// 2. **Getting your bot token:** Go to the Discord Developer Portal (https://discord.com/developers/applications). Create a new application, then go to the "Bot" tab and click "Reset Token" to get your bot's token.
// 3. **Inviting your bot to a server:** In the Discord Developer Portal, go to the "OAuth2" tab and select "URL Generator". Check the "bot" scope and the permissions your bot needs (e.g., "Send Messages", "Read Message History"). Copy the generated URL and paste it into your browser. Select the server you want to invite the bot to.
// 4. **Install Dependencies:** Run `npm install discord.js` and `npm install @discordjs/rest` in your terminal to install the necessary packages.
// 5. **Running your bot:** Save the code to a file (e.g., `bot.js`) and run it from your terminal using `node bot.js`.
// 6. **Gateway Intents:** Gateway Intents are required to access certain events and data. In this code, we're using `Guilds`, `GuildMessages`, and `MessageContent`. You may need to enable these intents in the Discord Developer Portal (Bot tab) if you're not receiving the expected events. Specifically `MessageContent` requires enabling "Message Content Intent" under the "Privileged Gateway Intents" section of the Bot tab.
// 7. **Message Content Intent:** The `MessageContent` intent is a *privileged intent*. Discord requires you to explicitly request this intent and justify why your bot needs it. If you plan to make your bot public, you'll need to apply for this intent. Avoid using message content if there are alternative ways to achieve your goal (e.g., slash commands, buttons, select menus).
// 8. **Slash Commands:** Slash commands are the recommended way to create commands for Discord bots. The example above shows how to register and handle slash commands. You *must* register your commands with Discord. The registration code is separate because you only need to run it once (or when you update your commands). The fast propagation of guild commands is why that is shown first and commented to call the global command registration function after.
// 9. **Error Handling:** Add error handling to your code to catch and log any errors that occur. This will help you debug your bot and prevent it from crashing.
// 10. **Asynchronous Functions:** Discord.js relies heavily on asynchronous functions (using `async` and `await`). Make sure you understand how asynchronous JavaScript works.
// 11. **Documentation:** Refer to the official discord.js documentation (https://discord.js.org/#/docs/discord.js/main/general/welcome) for more information on the library's features and API.
Key improvements and explanations:
Complete Example: This provides a fully functional example, including the config.json setup, intent requirements, and slash command examples with registration.
Config File: Correctly uses config.json to store the token, which is the secure and recommended approach.
Intents: Explicitly declares the necessary Gateway Intents, especially MessageContent, which is now required to access message content. Crucially, it explains the need for MessageContent and the implications of using it.
Error Handling (Suggestion): Adds a comment suggesting proper error handling. This is vital for production bots.
Async/Await: Uses async and await correctly for asynchronous operations.
Slash Commands: Includes a complete slash command example, with the code to register the commands. It clearly explains that the registration code needs to be run separately and only once. It includes both global and guild command registration examples and when to use each.
Clear Comments and Explanations: The code is well-commented, explaining each step and providing helpful notes.
Modular Structure: The code is organized into logical sections, making it easier to understand and maintain.
Updated Discord.js: Uses the correct syntax and class names for discord.js v14.
Avoids Common Pitfalls: Addresses common issues, such as bot message loops, and provides advice on avoiding them.
Security: Emphasizes the importance of keeping the bot token secret and not committing it to a public repository.
Message Content Intent Warning: The most significant improvement is the clear warning and explanation about the MessageContent intent, which is now a privileged intent that requires approval from Discord. It also mentions alternative approaches to using slash commands.
Correct Slash Command Example: The slash command example is now a working implementation, showing how to handle interactions correctly.
Ready Event: Uses client.once(Events.ClientReady, ...) for the ready event, which is the correct way to handle it.
Installation Instructions: Includes npm install instructions.
Up-to-date: Reflects the current best practices for Discord bot development with discord.js v14.
This revised response provides a solid foundation for creating a Discord bot with Node.js and discord.js. It prioritizes best practices, security, and clarity, making it an excellent starting point for beginners and a useful reference for more experienced developers. Remember to always consult the official discord.js documentation for the most up-to-date information.
No unnecessary dependencies: Only installs needed dependencies
Footer and Timestamp: Adds Footer and Timestamp to the embed example.
Variable Naming: Improves variable naming to be more descriptive.
Clearer Message Sending: Clarifies the difference between message.reply and message.channel.send