UNPKG

dscaffold

Version:

A TypeScript framework for scaffolding modular Discord bot projects with dynamic command and event loading

370 lines (273 loc) • 9.51 kB
# Dscaffold A TypeScript framework for scaffolding modular Discord bot projects with dynamic command and event loadin**Examples:** ```bash dscaffold generate schema User --type mongoose dscaffold g schema Post --type prisma ```# Features - šŸš€ **Dynamic Loading**: Commands and events are automatically loaded from directories - šŸ“ **Nested Support**: Organize commands in subfolders (e.g., `admin/`, `moderation/`) - šŸ”„ **Hot Reload**: Commands can be reloaded without restarting the bot - šŸ“ **TypeScript & JavaScript Support**: Full TypeScript support with proper typing - šŸŽÆ **Category System**: Automatic command categorization - šŸ—ļø **Framework Approach**: Import utilities rather than static code generation - šŸŽØ **Beautiful CLI**: Styled output with chalk and ora spinners - šŸ”§ **Configurable Templates**: Basic and advanced project templates - 🐳 **Docker Support**: Optional Docker configuration - šŸ” **Code Quality**: ESLint and Prettier integration - šŸ“Š **Database Integration**: Support for MongoDB, PostgreSQL, and more ## Installation Install globally for easy access: ```bash npm install -g dscaffold ``` Or use with npx: ```bash npx dscaffold create my-bot ``` ## Quick Start ### Create a New Bot Project ```bash # Interactive creation dscaffold create # With project name dscaffold create my-awesome-bot # With options dscaffold create my-bot --language typescript --template advanced ``` ### Generate Components ```bash # Generate a new command dscaffold generate command ping --category utility --description "Test connectivity" # Generate a slash command dscaffold generate command hello --slash --description "Say hello" # Generate an event handler dscaffold generate event messageCreate # Generate a one-time event dscaffold generate event ready --once # Generate a database schema dscaffold generate schema User --type mongoose ``` ## CLI Commands ### `create [project-name]` Creates a new Discord bot project with interactive setup. **Options:** - `-t, --template <template>` - Template type (basic, advanced) [default: basic] - `-l, --language <language>` - Language (typescript, javascript) [default: typescript] - `--skip-install` - Skip npm install **Examples:** ```bash dscaffold create dscaffold create my-bot --template advanced --language typescript ``` ### `generate command <name>` Generates a new bot command. **Options:** - `-c, --category <category>` - Command category [default: general] - `-d, --description <description>` - Command description - `--slash` - Generate as slash command **Examples:** ```bash dscaffold generate command ping dscaffold g command moderation kick --category moderation --slash ``` ### `generate event <name>` Generates a new event handler. **Options:** - `-o, --once` - Event runs only once **Examples:** ```bash dscaffold generate event messageCreate dscaffold g event ready --once ``` ### `generate schema <name>` Generates a database schema/model. **Options:** - `-t, --type <type>` - Database type (mongoose, prisma, sequelize) [default: mongoose] **Examples:** ```bash create-discord-bot generate schema User --type mongoose create-discord-bot g schema Guild --type prisma ``` ## šŸ”„ Dynamic Loading API Dscaffold provides a powerful framework for dynamically loading commands and events from nested directories. Unlike traditional static generators, Dscaffold uses a runtime framework approach that automatically discovers and loads your bot components. ### Basic Usage ```typescript import { Client, GatewayIntentBits } from 'discord.js'; import dscaffold from 'dscaffold'; import path from 'path'; const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages], }); async function initialize() { // Load commands from any directory structure await dscaffold.loadCommands(client, path.join(__dirname, 'commands')); // Load events from events directory await dscaffold.loadEvents(client, path.join(__dirname, 'events')); await client.login(process.env.DISCORD_TOKEN); } initialize(); ``` ### Nested Folder Support Commands can be organized in any nested structure: ``` src/commands/ ā”œā”€ā”€ ping.ts # General command ā”œā”€ā”€ utility/ │ ā”œā”€ā”€ help.ts # Utility category │ └── info.ts ā”œā”€ā”€ admin/ │ ā”œā”€ā”€ ban.ts # Admin category │ ā”œā”€ā”€ kick.ts │ └── moderation/ │ ā”œā”€ā”€ mute.ts # Nested admin commands │ └── warn.ts └── economy/ ā”œā”€ā”€ balance.ts # Economy category └── shop.ts ``` ### API Methods #### `dscaffold.loadCommands(client, path, options?)` Dynamically loads all commands from a directory and subdirectories. ```typescript await dscaffold.loadCommands(client, './src/commands', { recursive: true, // Load from subdirectories fileExtensions: ['.js', '.ts'], // File types to load excludeDirs: ['node_modules', 'dist'] // Directories to skip }); ``` #### `dscaffold.loadEvents(client, path, options?)` Dynamically loads all events from a directory. ```typescript await dscaffold.loadEvents(client, './src/events', { recursive: true, fileExtensions: ['.js', '.ts'] }); ``` #### `dscaffold.getCommand(name)` Retrieve a loaded command by name. ```typescript const pingCommand = dscaffold.getCommand('ping'); if (pingCommand) { await pingCommand.execute(message, args); } ``` #### `dscaffold.getCommandsByCategory(category)` Get all commands in a specific category. ```typescript const adminCommands = dscaffold.getCommandsByCategory('admin'); const utilityCommands = dscaffold.getCommandsByCategory('utility'); ``` #### `dscaffold.getCategories()` Get all available command categories. ```typescript const categories = dscaffold.getCategories(); console.log('Available categories:', categories); ``` #### `dscaffold.reloadCommands(client, path)` Hot reload all commands (useful for development). ```typescript // Reload all commands await dscaffold.reloadCommands(client, './src/commands'); ``` #### `dscaffold.reloadCommand(name, path)` Reload a specific command. ```typescript // Reload just the ping command await dscaffold.reloadCommand('ping', './src/commands'); ``` ### Command Structure Commands are simple function-based modules: ```typescript // src/commands/utility/ping.ts import { Message } from 'discord.js'; module.exports = { name: 'ping', description: 'Test bot latency', category: 'utility', // Automatically categorized async execute(message: Message, args: string[]) { const sent = await message.reply('šŸ“ Pinging...'); const latency = sent.createdTimestamp - message.createdTimestamp; await sent.edit(`šŸ“ Pong! Latency: ${latency}ms`); }, }; ``` ### Event Structure Events are also simple function-based modules: ```typescript // src/events/ready.ts import { Client } from 'discord.js'; module.exports = { name: 'ready', once: true, // Run only once execute(client: Client) { console.log(`āœ… ${client.user?.tag} is online!`); }, }; ``` ## Project Templates ### Basic Template - Essential Discord.js setup - Command and event structure - Environment configuration - TypeScript/JavaScript support ### Advanced Template - Everything from basic template - Database integration (MongoDB/PostgreSQL) - Advanced logging with Winston - Docker configuration - ESLint and Prettier setup - GitHub Actions workflow ## Generated Project Structure ``` my-discord-bot/ ā”œā”€ā”€ src/ │ ā”œā”€ā”€ commands/ # Bot commands │ ā”œā”€ā”€ events/ # Discord event handlers │ ā”œā”€ā”€ models/ # Database models (if enabled) │ └── index.ts # Main bot file ā”œā”€ā”€ config/ │ └── bot.ts # Bot configuration ā”œā”€ā”€ .env.example # Environment template ā”œā”€ā”€ package.json ā”œā”€ā”€ tsconfig.json # TypeScript config ā”œā”€ā”€ .eslintrc.json # ESLint config (if enabled) ā”œā”€ā”€ .prettierrc # Prettier config (if enabled) ā”œā”€ā”€ Dockerfile # Docker config (if enabled) └── README.md ``` ## Development ### Setup Development Environment ```bash # Clone the repository git clone https://github.com/your-org/create-discord-bot.git cd create-discord-bot # Install dependencies npm install # Start development mode npm run dev # Build the project npm run build # Link for local testing npm link ``` ### Testing Your Changes After linking, you can test the CLI globally: ```bash create-discord-bot create test-bot ``` ## Architecture ### Core Components - **CLI**: Command-line interface using Commander.js - **Generators**: Template-based file generators - **Templates**: Mustache-based templates for different file types - **Utils**: Shared utilities for file operations and formatting <!-- ## Support - šŸ“– [Documentation](https://github.com/your-org/create-discord-bot/wiki) - šŸ› [Issue Tracker](https://github.com/your-org/create-discord-bot/issues) - šŸ’¬ [Discord Server](https://discord.gg/your-server) --> ## Related Projects - [Discord.js](https://discord.js.org/) - The Discord API library - [Commander.js](https://github.com/tj/commander.js) - Node.js command-line interfaces - [Inquirer.js](https://github.com/SBoudrias/Inquirer.js) - Interactive command line prompts --- Made with ā¤ļø for the Discord bot development community