Getting Started

    Getting Started

    Discord.js Version TypeScript

    This guide will help you set up and start developing with the Discord bot framework, a powerful TypeScript-based Discord bot template using the latest Discord.js v14.

    Table of Contents

    ✨ Features

    • Modular Architecture - Clean, maintainable code structure
    • TypeScript - Type-safe development experience
    • Discord.js v14 - Latest Discord API support
    • ESM Modules - Modern JavaScript module system
    • Sharding Support - Built-in clustering via discord-hybrid-sharding
    • Command System
      • Slash commands with automatic registration
      • Traditional prefix commands
      • Command cooldowns
      • Command categories
      • Command aliases
    • Component System
      • Type-safe button interactions
      • Select menus (string, user, role, channel)
      • Modal forms with validation
      • Pattern-based custom ID matching
      • Component cooldowns
    • Event System - Type-safe event handling
    • Logging - Beautiful console logging with colors
    • Configuration - Easy setup via environment variables

    Prerequisites

    Before you begin, make sure you have the following installed:

    • Node.js (v18.0.0 or higher)
    • npm (usually comes with Node.js)
    • A code editor (Visual Studio Code recommended for TypeScript support)
    • Git (optional, for version control)

    You'll also need:

    • A Discord account
    • A Discord application and bot token (created through the Discord Developer Portal)
    • Appropriate permissions and a server to test your bot

    Installation

    1. Clone the repository:
    git clone https://github.com/Joniii11/discord-bot-template.git
    cd discord-bot-template
    
    1. Install dependencies:
    npm install
    
    1. Create environment file:

    Copy the example environment file to create your own:

    cp .env.example .env
    

    Configuration

    Edit the .env file with your Discord bot token and other settings:

    # Whether to use Sharding or not
    USE_SHARDING = true
    
    # The token for your bot (from Discord Developer Portal)
    TOKEN = "your-token-goes-here"
    
    # Whether to show debug information in the console
    SHOW_DEBUG = true
    
    # The prefix for traditional message commands
    PREFIX = -
    

    Bot Permissions

    When adding your bot to a server, make sure it has the necessary permissions:

    • Send Messages - Basic message sending
    • Embed Links - For rich embeds
    • Use Slash Commands - For slash commands
    • Other permissions depending on your bot's functionality

    The recommended invite URL format is:

    https://discord.com/api/oauth2/authorize?client_id=YOUR_CLIENT_ID&permissions=PERMISSION_INTEGER&scope=bot%20applications.commands
    

    You can use the Discord Permission Calculator to determine the correct permission integer.

    Running the Bot

    Development Mode

    For development with automatic reloading:

    npm run dev
    

    Production Mode

    To build and start the bot for production:

    npm run build
    npm start
    

    Development Workflow

    Creating a Command

    Create a new file in src/commands/[Category]/ with the following structure:

    // src/commands/Utility/example.ts
    import { SlashCommandBuilder } from "discord.js";
    import { commandFile } from "../../utils/types/commandManager.js";
    
    export const data = commandFile({
        data: new SlashCommandBuilder()
            .setName("example")
            .setDescription("An example command"),
        
        options: {
            cooldown: 5,
            aliases: ["ex"],  // Command aliases for prefix commands
        },
        
        execute: async (cmdExecutor) => {
            await cmdExecutor.reply("This is an example command!");
        }
    });
    

    The command will be automatically loaded and registered on bot startup.

    Creating a Component Handler

    Create a new file in src/components/:

    // src/components/Buttons/exampleButton.ts
    import { ButtonInteraction } from "discord.js";
    import { buttonComponent } from "../../utils/types/componentManager.js";
    
    export const data = buttonComponent({
        id: "example_button",
        
        execute: async (client, interaction: ButtonInteraction) => {
            await interaction.reply({
                content: "You clicked the example button!",
                ephemeral: true
            });
        }
    });
    

    The component handler will be automatically loaded on bot startup.

    Creating an Event Handler

    Create a new file in the appropriate folder in src/events/:

    // src/events/client/guildCreate.ts
    import { eventFile } from "../../utils/types/eventTypes.js";
    
    export const data = eventFile({
        name: "guildCreate",
        once: false,       // Set to true for one-time events
        
        execute: async (client, guild) => {
            client.logger.info(`Bot joined a new server: ${guild.name} (ID: ${guild.id})`);
        }
    });
    

    The event handler will be automatically loaded on bot startup.

    Advanced Usage

    Command Executor

    The template provides a unified CommandExecutor class that handles both slash commands and traditional message commands:

    execute: async (cmdExecutor) => {
        // Check if interaction or message command
        if (cmdExecutor.isInteraction()) {
            // Slash command logic
        } else if (cmdExecutor.isMessage()) {
            // Message command logic
        }
        
        // Common logic for both types
        await cmdExecutor.reply("Response works for both types!");
    }
    

    Cooldowns

    Cooldowns are automatically managed through the CooldownManager class:

    options: {
        cooldown: 10, // 10 seconds cooldown
    }
    

    Project Structure

    discord-bot/
    ├── src/                  # Source code
    │   ├── commands/         # Bot commands organized by category
    │   ├── events/           # Event handlers
    │   │   ├── client/       # Discord.js client events
    │   │   └── cluster/      # Sharding cluster events
    │   ├── utils/
    │   │   ├── classes/      # Utility classes
    │   │   ├── embeds/       # Discord embed templates
    │   │   ├── managers/     # System managers
    │   │   ├── structures/   # Core structures
    │   │   └── types/        # TypeScript type definitions
    │   ├── components/       # Component system files
    │   ├── Bot.ts            # Bot initialization
    │   └── index.ts          # Entry point with sharding setup
    └── dist/                 # Compiled JavaScript
    

    For more details, see the Project Structure documentation.

    Next Steps

    Once you have the bot running, here are some ways to continue development:

    1. Explore the Documentation:

    2. Add Features:

      • Create commands for your specific needs
      • Implement interactive components
      • Add custom event handlers
    3. Learn About Discord.js:

    4. Connect External Services:

      • Add a database for persistent storage
      • Integrate with APIs for additional functionality
      • Implement a web dashboard
    5. Deploy Your Bot:

      • Set up hosting on a VPS, Heroku, or other service
      • Configure for production environment
      • Set up monitoring and logging

    📜 License

    ISC

    👨‍💻 Author

    Joniii (https://github.com/Joniii11)


    Made with ❤️ using Discord.js and TypeScript