dscaffold
Version:
A TypeScript framework for scaffolding modular Discord bot projects with dynamic command and event loading
370 lines (273 loc) ⢠9.51 kB
Markdown
# 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