Skip to content
NongThamPublic

About

This library from Xtron Studio will help you create a Handler for Discord.js more easily.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

Β 

History

13 Commits

Folders and files

Repository files navigation

XtonCore Framework v3.0.2 πŸš€

npm version npm downloads License: ISC TypeScript

A comprehensive, production-ready Discord.js framework with powerful optimizations

Features β€’ Installation β€’ Quick Start β€’ Documentation β€’ Examples


✨ Features

⚑ Performance Optimizations

  • Deferred command handlers - Load command handler functions on first use
  • Parallel Loading - Load modules simultaneously (~57% faster initialization)
  • Combined performance - Parallel initialization plus deferred command handlers
  • Hot Reload - Development-friendly file watching and instant reloading

🎯 Core Features

  • Command Handler - Advanced slash command management with autocomplete support
  • Event Handler - Automatic event loading and management
  • Component Handler - Button, select menu, and modal interaction handling
  • Validation System - Flexible command validation pipeline

πŸ—οΈ Advanced Framework Features (v3.0)

  • Middleware Pipeline - Express-style .use() pipeline to intercept commands
  • Cron Job Manager - Built-in scheduled tasks loaded from jobs/
  • Localization (i18n) - Multi-language support with locales/ dynamic loading
  • Persistent Storage - IStorageAdapter for Redis/DB instead of memory caching
  • Automated Pagination - Easy and secure embed paginations out-of-the-box

πŸš€ Enhanced Features

  • Performance Monitoring - Real-time execution tracking and statistics
  • Cooldown Management - Per-user, per-command cooldown system (Persistent)
  • Permission System - Advanced permission checking with caching
  • Rate Limiting - Built-in rate limiting to prevent abuse (Persistent)
  • Input Sanitization - Security-focused input validation
  • Enhanced Logging - Multi-level logging with context

🎨 Utility Classes

  • EnhancedEmbedBuilder - Beautiful preset embeds (success, error, info, etc.)
  • ComponentHelpers - Quick Discord component creation
  • PaginationBuilder - Automated embed scroll wheels with timeouts
  • InputSanitizer - Security-focused input validation
  • CommandBuilder - Simplified command creation

πŸ“¦ Installation

npm install xtoncore discord.js
# or
yarn add xtoncore discord.js

Requirements:

  • Node.js >= 18.0.0
  • Discord.js v14

πŸš€ Quick Start

Basic Setup

import { Client, GatewayIntentBits } from 'discord.js';
import { ClientHandler } from 'xtoncore';

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
});

async function main() {
  const handler = await ClientHandler.create({
    client,
    commandsPath: './commands',
    eventsPath: './events',
    componentsPath: './components',
    jobsPath: './jobs',
    localesPath: './locales',
    defaultLocale: 'en-US',
    ownerIds: ['YOUR_USER_ID'],
    
    // ⚑ Performance optimizations (enabled by default)
    lazyLoading: true, // Defer command handler functions until first use
    preloadCommands: ['ping', 'help'], // Preload frequently used commands
    
    // πŸ”₯ Development features
    enableHotReload: true,
    
    // πŸ›‘οΈ Security features
    rateLimiting: {
      enabled: true,
      defaultLimit: 5,
      defaultWindow: 60,
    },
  });

  await client.login('YOUR_BOT_TOKEN');
}

main();

Project Structure

your-bot/
β”œβ”€β”€ commands/
β”‚   β”œβ”€β”€ utility/
β”‚   β”‚   β”œβ”€β”€ ping.ts
β”‚   β”‚   └── help.ts
β”‚   └── admin/
β”‚       └── stats.ts
β”œβ”€β”€ events/
β”‚   β”œβ”€β”€ ready/
β”‚   β”‚   └── 00-startup.ts
β”‚   └── interactionCreate/
β”‚       └── 01-logging.ts
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ buttons/
β”‚   β”‚   └── confirm-button.ts
β”‚   β”œβ”€β”€ modals/
β”‚   β”‚   └── feedback-modal.ts
β”‚   └── selectmenus/
β”‚       └── role-selector.ts
└── index.ts

πŸ“š Documentation

Command Example

import { SlashCommandBuilder } from 'discord.js';
import { CommandRunOptions } from 'xtoncore';
import { EnhancedEmbedBuilder } from 'xtoncore';

export const data = new SlashCommandBuilder()
  .setName('ping')
  .setDescription('Check bot latency');

export const cooldown = 5; // 5 seconds
export const category = 'utility';

export async function run({ interaction, client, handler }: CommandRunOptions) {
  const embed = EnhancedEmbedBuilder.createInfo(
    'πŸ“ Pong!',
    `Latency: ${client.ws.ping}ms`
  );
  
  await interaction.reply({ embeds: [embed] });
}

Component Example

import { ButtonInteraction } from 'discord.js';
import { ComponentHandler } from 'xtoncore';

export const customId = 'confirm-action';
export const type = 'button';

export async function run(interaction: ButtonInteraction, client: any, handler: any) {
  await interaction.reply({ 
    content: 'βœ… Action confirmed!', 
    ephemeral: true 
  });
}

Event Example

import { Client } from 'discord.js';

export default async function (client: Client) {
  console.log(`βœ… Logged in as ${client.user?.tag}`);
}

⚑ Performance Features

Lazy Loading

Command metadata is indexed at startup and handler functions are loaded on first use:

const handler = await ClientHandler.create({
  client,
  commandsPath: './commands',
  lazyLoading: true, // Default: true
  preloadCommands: ['ping', 'help'], // Preload critical commands
});

// Check lazy loading stats
const stats = handler.getLazyLoadingStats();
console.log(`Loaded: ${stats.loaded}/${stats.total} (${stats.percentage}%)`);

// Preload all commands (useful for production)
await handler.preloadAllCommands();

Command startup and memory usage depend on the command modules and runtime environment. Benchmark your own bot before making performance commitments.

Parallel Loading

Modules load simultaneously for faster initialization:

// Happens automatically!
const handler = await ClientHandler.create({
  client,
  commandsPath: './commands',
  eventsPath: './events',
  componentsPath: './components',
  // All load in parallel
});

Combined Performance

Traditional Loading:  benchmark in your environment
With Optimizations:   benchmark in your environment
Improvement:          depends on command count and module initialization cost

🎨 Utility Classes

EnhancedEmbedBuilder

import { EnhancedEmbedBuilder } from 'xtoncore';

// Preset embeds
const success = EnhancedEmbedBuilder.createSuccess('Success!', 'Operation completed');
const error = EnhancedEmbedBuilder.createError('Error!', 'Something went wrong');
const info = EnhancedEmbedBuilder.createInfo('Info', 'Here is some information');
const warning = EnhancedEmbedBuilder.createWarning('Warning!', 'Be careful');

// Pagination
const paginated = EnhancedEmbedBuilder.createPagination(items, 1, 10, 'Results');

// Progress bar
const progress = EnhancedEmbedBuilder.createProgressBar(75, 100, 20, 'Loading');

// Access preset colors
const custom = EnhancedEmbedBuilder.createBasic(
  'Title',
  'Description',
  EnhancedEmbedBuilder.COLORS.PRIMARY
);

ComponentHelpers

import { ComponentHelpers } from 'xtoncore';

// Buttons
const confirmButtons = ComponentHelpers.createConfirmButtons();
const pagination = ComponentHelpers.createPaginationButtons(1, 5);

// Select menu
const menu = ComponentHelpers.createSelectMenu('menu_id', 'Choose option', [
  { label: 'Option 1', value: 'opt1', emoji: '1️⃣' },
  { label: 'Option 2', value: 'opt2', emoji: '2️⃣' },
]);

// Modal
const modal = ComponentHelpers.createModal('modal_id', 'Feedback Form', [
  {
    customId: 'feedback',
    label: 'Your Feedback',
    style: 2, // Paragraph
    required: true,
  },
]);

InputSanitizer

import { InputSanitizer } from 'xtoncore';

// Sanitize user input
const clean = InputSanitizer.sanitizeString(userInput, {
  maxLength: 1000,
  allowHtml: false,
  trim: true,
});

// Validate IDs
const isValid = InputSanitizer.validateUserId('123456789012345678');

// Sanitize Discord content
const cleanContent = InputSanitizer.sanitizeDiscordContent(message);

πŸ“Š Performance Monitoring

// Access performance manager
const perfManager = handler.performanceManager;

// Get command statistics
const stats = perfManager.getCommandStats('ping');
const topCommands = perfManager.getTopCommands(10);

// Get memory usage
const memory = perfManager.getMemoryUsage();
console.log(`Memory: ${memory.current}MB`);

// Generate report
const report = perfManager.generateReport();
console.log(report);

πŸ”’ Permission Management

// Access permission manager
const permManager = handler.permissionManager;

// Add/remove owners
permManager.addOwner('USER_ID');
permManager.removeOwner('USER_ID');

// Blacklist users/guilds
permManager.blacklistUser('USER_ID');
permManager.blacklistGuild('GUILD_ID');

// Check permissions
const result = await permManager.checkPermissions(interaction, command);
if (!result.allowed) {
  console.log(result.reason);
}

⏱️ Cooldown Management

// Access cooldown manager
const cooldownManager = handler.cooldownManager;

// Set cooldown
cooldownManager.setCooldown('USER_ID', 'command_name', 30);

// Check cooldown
const isOnCooldown = cooldownManager.isOnCooldown('USER_ID', 'command_name');
const remainingTime = cooldownManager.getRemainingTime('USER_ID', 'command_name');

// Remove cooldown
cooldownManager.removeCooldown('USER_ID', 'command_name');

🚦 Rate Limiting

// Access rate limiter
const rateLimiter = handler.rateLimiter;

// Check rate limit
const result = rateLimiter.checkLimit('USER_ID', 'action', 5, 60);
if (!result.allowed) {
  console.log(`Rate limited! Reset in ${result.resetTime - Date.now()}ms`);
}

πŸ”₯ Hot Reload

// Access hot reload manager
const hotReload = handler.hotReloadManager;

// Check if enabled
console.log(hotReload.isEnabled());

// Get watched directories
console.log(hotReload.getWatchedDirectories());

// Manual reload
await handler.reloadCommands();
await handler.reloadComponents();
await handler.reloadAll(); // Reload everything in parallel

οΏ½ Statisstics

// Get comprehensive stats
const stats = handler.getStats();
console.log(stats);
// {
//   commands: 50,
//   performance: {...},
//   cooldowns: 5,
//   components: 10,
//   permissions: {...},
//   rateLimiter: {...},
//   hotReload: {...}
// }

// Generate full report
const report = await handler.generateReport();
console.log(report);

🎯 Configuration Options

interface ClientHandlerOptions {
  client: Client;                    // Discord.js client (required)
  commandsPath?: string;             // Path to commands directory
  eventsPath?: string;               // Path to events directory
  validationsPath?: string;          // Path to validations directory
  componentsPath?: string;           // Path to components directory
  jobsPath?: string;                 // Path to scheduled cron jobs (v3.0)
  localesPath?: string;              // Path to translation JSONs (v3.0)
  defaultLocale?: string;            // Default bot language (v3.0)
  guild?: string;                    // Guild ID for guild-specific commands
  ownerIds?: string[];               // Array of owner user IDs
  
  // ⚑ Performance
  enableHotReload?: boolean;         // Enable hot reload (default: dev mode)
  lazyLoading?: boolean;             // Enable lazy loading (default: true)
  preloadCommands?: string[];        // Commands to preload immediately
  
  // πŸ›‘οΈ Security
  rateLimiting?: {
    enabled: boolean;
    defaultLimit?: number;           // Requests per window
    defaultWindow?: number;          // Window in seconds
  };
  
  // πŸ“Š Monitoring
  performance?: {
    enabled: boolean;
    trackMemory?: boolean;
  };

  // πŸ’Ύ Optional shared storage for cooldowns and rate limits
  storageAdapter?: IStorageAdapter;
}

When omitted, cooldowns and rate limits use separate in-memory adapters. A custom IStorageAdapter can be shared by both managers for persistent storage.


πŸ“– Advanced Examples

Custom Command Data

interface MyCommandData {
  requiredRole: string;
  logChannel: string;
}

export const customData: MyCommandData = {
  requiredRole: '123456789',
  logChannel: '987654321',
};

export async function run({ interaction, customData }: CommandRunOptions<MyCommandData>) {
  // customData is fully typed!
  if (customData?.requiredRole) {
    // Your logic here
  }
}

πŸ›‘ Advanced Middleware Pipeline

// Define custom context types
const handler = await ClientHandler.create({ /* ... */ });

handler.middlewareManager.use(async (ctx, next) => {
  console.log(`Command triggered: ${ctx.command.data.name}`);
  ctx.state.customProperty = "Hello from Middleware!";
  
  if (ctx.interaction.user.bot) {
    return; // Short-circuit, command doesn't run
  }
  
  await next(); // Proceed to the next middleware or command
});

🌐 Localization (i18n) Usage

// Use anywhere using the handler instance
const welcomeMessage = handler.languageManager?.t('messages.welcome', 'th-TH', { 
  user: interaction.user.username 
});
await interaction.reply(welcomeMessage);

πŸ“‘ Easy Pagination

import { PaginationBuilder } from 'xtoncore';

const embed1 = new EmbedBuilder().setTitle('Page 1');
const embed2 = new EmbedBuilder().setTitle('Page 2');

await new PaginationBuilder(interaction, 60000)
  .setEmbeds([embed1, embed2])
  .setEphemeral(true)
  .render();

Production Setup

const handler = await ClientHandler.create({
  client,
  commandsPath: './commands',
  lazyLoading: true,
  preloadCommands: ['ping', 'help'], // Critical commands
});

client.once('ready', async () => {
  // Preload all commands in background
  await handler.preloadAllCommands();
  console.log('All commands ready!');
});

Development Setup

const handler = await ClientHandler.create({
  client,
  commandsPath: './commands',
  lazyLoading: true,              // Fast startup
  enableHotReload: true,          // Auto-reload on changes
  rateLimiting: { enabled: false }, // Disable for testing
});

πŸ“Š Performance

XtonCore defers command handler functions and initializes independent modules in parallel. Startup and memory improvements vary with command count, module side effects, and the host runtime, so benchmark production workloads in your own environment.


πŸ”§ TypeScript Support

Full TypeScript support with complete type definitions:

import { 
  ClientHandler, 
  LocalCommand, 
  CommandRunOptions,
  EnhancedEmbedBuilder,
  ComponentHelpers 
} from 'xtoncore';

// Full IntelliSense and type checking
const handler = await ClientHandler.create({ /* ... */ });
const stats = handler.getStats(); // Fully typed!

The package includes generated TypeScript declarations for IntelliSense and type checking.


πŸ“š Additional Documentation


πŸ› οΈ CLI Tool

Want to scaffold projects quickly? Check out our CLI tool:

npm install -g xton-cli
xton init my-bot

Learn more about xton-cli


🀝 Contributing

Contributions, issues, and feature requests are welcome!

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ Changelog

v2.1.0 - Performance & Feature Update

  • ✨ Added deferred command handler loading
  • ✨ Added parallel initialization
  • ✨ Added component management system
  • ✨ Added advanced permission system
  • ✨ Added rate limiting
  • ✨ Added input sanitization
  • ✨ Added utility classes
  • ✨ Enhanced logging system
  • πŸ”§ Improved TypeScript support
  • πŸ”§ Better error handling
  • πŸ“Š Performance monitoring

πŸ“„ License

This project is licensed under the ISC License - see the LICENSE file for details.


πŸ™ Credits

Created and maintained by Narabordee Wirakkamo


πŸ“ž Support


XtonCore Enhanced v2.1 - Making Discord.js development easier and more powerful! πŸš€

⭐ Star us on GitHub if you find this useful!

About

This library from Xtron Studio will help you create a Handler for Discord.js more easily.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages