A comprehensive, production-ready Discord.js framework with powerful optimizations
Features β’ Installation β’ Quick Start β’ Documentation β’ Examples
- 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
- 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
- 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 -
IStorageAdapterfor Redis/DB instead of memory caching - Automated Pagination - Easy and secure embed paginations out-of-the-box
- 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
- 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
npm install xtoncore discord.js
# or
yarn add xtoncore discord.jsRequirements:
- Node.js >= 18.0.0
- Discord.js v14
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();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
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] });
}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
});
}import { Client } from 'discord.js';
export default async function (client: Client) {
console.log(`β
Logged in as ${client.user?.tag}`);
}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.
Modules load simultaneously for faster initialization:
// Happens automatically!
const handler = await ClientHandler.create({
client,
commandsPath: './commands',
eventsPath: './events',
componentsPath: './components',
// All load in parallel
});Traditional Loading: benchmark in your environment
With Optimizations: benchmark in your environment
Improvement: depends on command count and module initialization cost
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
);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,
},
]);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);// 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);// 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);
}// 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');// 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`);
}// 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// 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);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.
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
}
}// 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
});// Use anywhere using the handler instance
const welcomeMessage = handler.languageManager?.t('messages.welcome', 'th-TH', {
user: interaction.user.username
});
await interaction.reply(welcomeMessage);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();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!');
});const handler = await ClientHandler.create({
client,
commandsPath: './commands',
lazyLoading: true, // Fast startup
enableHotReload: true, // Auto-reload on changes
rateLimiting: { enabled: false }, // Disable for testing
});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.
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.
- examples/ - Practical code examples
Want to scaffold projects quickly? Check out our CLI tool:
npm install -g xton-cli
xton init my-botContributions, issues, and feature requests are welcome!
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- β¨ 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
This project is licensed under the ISC License - see the LICENSE file for details.
Created and maintained by Narabordee Wirakkamo
- π§ Email: [[email protected]]
- π Issues: GitHub Issues
- π¬ Discord: [Your Discord Server]
XtonCore Enhanced v2.1 - Making Discord.js development easier and more powerful! π
β Star us on GitHub if you find this useful!