🤖
Let's create a digital companion that can chat, play games, and help manage your Discord server! Perfect for first-time coders.
🧭 Getting Started: What You'll Need
| Tool | What It Does | 
|---|---|
| Node.js | Runs JavaScript outside browsers | 
| discord.js v14 | Makes bot creation easier | 
| Code Editor | Where we'll write our magic (VS Code recommended) | 
| Discord Account | To create and test your bot | 
🚀 Step 1: Creating Your Bot Identity
- Go to Discord Developer Portal
- Click "New Application" and name your bot
- Navigate to "Bot" > "Add Bot"
🔒
Your bot token is like a password! Save it in a .env file and never share it.
⚙️ Setting Up Your Project
Create a new folder and run these commands in your terminal:
pnpm init -y              # Creates package.json
pnpm install discord.js   # Main bot library
pnpm install dotenv       # Keeps secrets safe📁 File Structure Basics
your-bot/
├── bot.js            # Main bot code
├── commands/         # Slash commands folder
│   └── ping.js       # Example command
├── .env              # Stores your bot token
└── package.json      # Project dependencies💡 Core Bot Code Explained
Create bot.js with this starter code:
// Load environment variables from .env file
require('dotenv').config();
// Import necessary Discord.js components
const { Client, GatewayIntentBits } = require('discord.js');
// Create our bot client with required permissions
const bot = new Client({
  intents: [
    GatewayIntentBits.Guilds,          // Access server info
    GatewayIntentBits.GuildMessages,   // Read messages
    GatewayIntentBits.MessageContent   // See message content
  ]
});
// Bot startup confirmation
bot.on('ready', () => {
  console.log(`✅ ${bot.user.tag} is online!`);
});
// Basic message response
bot.on('messageCreate', async (message) => {
  if (message.content === '!hello') {
    await message.reply('👋 Hey there!');
  }
});
// Start the bot using our token
bot.login(process.env.DISCORD_TOKEN);🔌
Create a .env file with:
DISCORD_TOKEN=your-bot-token-here
🎨 Creating Your First Slash Command
Make commands/ping.js:
const { SlashCommandBuilder } = require('discord.js');
module.exports = {
  data: new SlashCommandBuilder()
    .setName('ping')         // Command name
    .setDescription('Check bot latency'), // Description
    
  // What happens when command is used
  async execute(interaction) {
    const start = Date.now();
    await interaction.reply('🏓 Pinging...');
    const latency = Date.now() - start;
    
    await interaction.editReply(
      `🏓 Pong! Latency: ${latency}ms`
    );
  }
};🚀 Deploying Commands
Create deploy-commands.js:
const { REST, Routes } = require('discord.js');
require('dotenv').config();
// List all your commands here
const commands = [
  require('./commands/ping.js').data.toJSON()
];
// Prepare REST client
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
// Deployment script
(async () => {
  try {
    console.log('🔄 Deploying commands...');
    
    // Update commands globally
    await rest.put(
      Routes.applicationCommands(process.env.CLIENT_ID),
      { body: commands }
    );
    
    console.log('✅ Commands deployed successfully!');
  } catch (error) {
    console.error('❌ Deployment failed:', error);
  }
})();💡
Find your CLIENT_ID in Discord Developer Portal > Application > General Information
🌟 Creative Command Ideas
🎮 Rock-Paper-Scissors Game
// commands/rps.js
const { SlashCommandBuilder } = require('discord.js');
const choices = ['🪨 Rock', '📄 Paper', '✂️ Scissors'];
module.exports = {
  data: new SlashCommandBuilder()
    .setName('rps')
    .setDescription('Play Rock-Paper-Scissors!'),
    
  async execute(interaction) {
    const botChoice = choices[Math.floor(Math.random() * 3)];
    const userChoice = choices[Math.floor(Math.random() * 3)];
    
    await interaction.reply(
      `🤖 ${botChoice} vs ${userChoice} 🧑💻\n` +
      (botChoice === userChoice ? "It's a tie!" : 
      ((botChoice === '🪨 Rock' && userChoice === '✂️ Scissors') ||
       (botChoice === '📄 Paper' && userChoice === '🪨 Rock') ||
       (botChoice === '✂️ Scissors' && userChoice === '📄 Paper')) 
       ? "I win! 😎" : "You win! 🎉")
    );
  }
};🐱 Random Cat Fact
// commands/catfact.js
const { SlashCommandBuilder } = require('discord.js');
const facts = [
  "Cats can jump 5 times their height!",
  "A group of cats is called a clowder",
  "Cats sleep 12-16 hours daily",
  "Cats have 32 muscles in each ear"
];
module.exports = {
  data: new SlashCommandBuilder()
    .setName('catfact')
    .setDescription('Get a random cat fact'),
    
  async execute(interaction) {
    const fact = facts[Math.floor(Math.random() * facts.length)];
    await interaction.reply(`🐱 Did you know? ${fact}`);
  }
};🛠️ Hosting Your Bot 24/7
| Platform | Best For | 
|---|---|
| Railway.app | Easy deployment with free tier | 
| AWS EC2 | Full control and scalability | 
| Raspberry Pi | Always-on home hosting | 
🚨 Common Issues & Fixes
⚠️
Troubleshooting Guide:
- Bot not responding? Check if it's added to your server
- Commands not showing? Redeploy with deploy-commands.js
- Getting errors? Restart the bot with node bot.js
- Permission issues? Check bot roles in server settings
🌈 What's Next?
💡
Future Project Ideas:
- Server member count tracker
- Music player with YouTube integration
- Auto-moderation system
- Trivia game with score leaderboards
- Weather command using OpenWeather API
// Keep your bot running forever
bot.on('disconnect', () => {
  console.log('🔌 Bot disconnected... Reconnecting');
  bot.login(process.env.DISCORD_TOKEN);
});🎉
Congratulations! You've just created your first Discord bot. The coding journey never ends - what will you create next?
👋
Stuck or want to show off your creation? Join the official Discord.js support Server for help and inspiration!