UNPKG

rashi-discord-bot-lib

Version:

šŸš€ Powerful Discord bot framework with built-in database, event handling, and utilities

207 lines • 7.59 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BotStatistics = void 0; const cli_table3_1 = __importDefault(require("cli-table3")); const Logger_1 = require("./Logger"); async function loadChalk() { try { const imp = new Function("m", "return import(m)"); const mod = await imp("chalk"); const chalk = mod.default ?? mod; return { bold: { blue: (s) => chalk.bold.blue(s), green: (s) => chalk.bold.green(s), magenta: (s) => chalk.bold.magenta(s), yellow: (s) => chalk.bold.yellow(s), cyan: (s) => chalk.bold.cyan(s), red: (s) => chalk.bold.red(s), }, blue: (s) => chalk.blue(s), green: (s) => chalk.green(s), magenta: (s) => chalk.magenta(s), cyan: (s) => chalk.cyan(s), yellow: (s) => chalk.yellow(s), red: (s) => chalk.red(s), white: (s) => chalk.white(s), }; } catch { const id = (x) => x; return { bold: { blue: id, green: id, magenta: id, yellow: id, cyan: id, red: id }, blue: id, green: id, magenta: id, cyan: id, yellow: id, red: id, white: id, }; } } /* -------------------------------------------------------------------------- */ /* CLASS */ /* -------------------------------------------------------------------------- */ class BotStatistics { logger; startTime; commandUsage; eventTriggers; printedOnce = false; totalCommandsExecuted = 0; totalEventsTriggered = 0; responseTimes = []; errorCount = 0; totalRequests = 0; loadedSlashCommands = 0; loadedPrefixCommands = 0; loadedEvents = 0; dbStats; dbStores = []; constructor(logger) { this.logger = logger ?? new Logger_1.Logger(); this.startTime = new Date(); this.commandUsage = new Map(); this.eventTriggers = new Map(); } /* ------------ SETTERS ---------------- */ setDatabaseStats(stats) { this.dbStats = stats; } setDatabaseStores(stores) { this.dbStores = stores ?? []; } resetPrintedFlag() { this.printedOnce = false; } async loadDatabaseStatsFrom(db) { if (!db) { this.dbStats = undefined; return; } try { const stats = await db.getStats?.(); if (!stats) return; this.dbStats = { keys: stats.keys ?? 0, size: stats.size ?? 0, adapter: stats.adapter ?? "unknown", }; } catch { this.dbStats = undefined; } } /* ------------ LIFECYCLE --------------- */ initialize(client) { this.setupEventTracking(client); } setLoadedCommands(slashCount, prefixCount) { this.loadedSlashCommands = slashCount; this.loadedPrefixCommands = prefixCount; } setLoadedEvents(eventCount) { this.loadedEvents = eventCount; } /* ------------ TRACKING ---------------- */ trackCommand(commandName, type, responseTime) { const current = this.commandUsage.get(commandName) ?? { count: 0, type }; this.commandUsage.set(commandName, { count: current.count + 1, type }); this.totalCommandsExecuted++; this.totalRequests++; if (typeof responseTime === "number") { this.responseTimes.push(responseTime); if (this.responseTimes.length > 100) this.responseTimes.shift(); } } trackEvent(eventName) { const current = this.eventTriggers.get(eventName) ?? 0; this.eventTriggers.set(eventName, current + 1); this.totalEventsTriggered++; } trackError() { this.errorCount++; this.totalRequests++; } /* ------------ RENDER ------------------ */ pushRow(table, row) { table.push(row); } async generateTableStats(client, options, databaseStats) { if (this.printedOnce) return; this.printedOnce = true; const chalk = await loadChalk(); const dbStats = databaseStats ?? this.dbStats; try { const botInfoTable = new cli_table3_1.default({ head: [chalk.bold.blue("Bot Information"), chalk.bold.green("Value")], colWidths: [25, 40], }); const statsTable = new cli_table3_1.default({ head: [chalk.bold.magenta("Statistics"), chalk.bold.cyan("Count")], colWidths: [25, 40], }); const musicTable = new cli_table3_1.default({ head: [chalk.bold.green("Music"), chalk.bold.blue("Value")], colWidths: [25, 55], }); /* ---- BOT INFO ---- */ this.pushRow(botInfoTable, [ chalk.cyan("Name"), chalk.white(client.user?.username ?? "Unknown"), ]); this.pushRow(botInfoTable, [chalk.cyan("ID"), chalk.white(client.user?.id ?? "Unknown")]); this.pushRow(botInfoTable, [chalk.cyan("Uptime"), chalk.green(this.formatUptime(Date.now() - this.startTime.getTime()))]); /* ---- STATS ---- */ this.pushRow(statsTable, [chalk.magenta("Guilds"), String(client.guilds.cache.size)]); this.pushRow(statsTable, ["Slash Commands", String(this.loadedSlashCommands)]); this.pushRow(statsTable, ["Prefix Commands", String(this.loadedPrefixCommands)]); this.pushRow(statsTable, ["Events Loaded", String(this.loadedEvents)]); this.pushRow(statsTable, ["Commands Executed", String(this.totalCommandsExecuted)]); console.log(chalk.blue("\nšŸ¤– Bot Information:\n")); console.log(botInfoTable.toString()); console.log(chalk.magenta("\nšŸ“Š Statistics:\n")); console.log(statsTable.toString()); console.log(chalk.cyan("\nšŸŽ¶ Music:\n")); console.log(musicTable.toString()); } catch (err) { this.logger.warn("cli-table3/chalk not available, fallback display"); console.log(await this.generateStatsDisplay(client)); } } async generateStatsDisplay(client) { const uptime = this.formatUptime(Date.now() - this.startTime.getTime()); return `BOT up: ${uptime}`; } /* ------------ HELPERS ---------------- */ setupEventTracking(client) { const originalEmit = client.emit.bind(client); client.emit = (event, ...args) => { this.trackEvent(event); return originalEmit(event, ...args); }; } formatUptime(ms) { const sec = Math.floor(ms / 1000); const min = Math.floor(sec / 60); const hr = Math.floor(min / 60); const d = Math.floor(hr / 24); if (d > 0) return `${d}d ${hr % 24}h ${min % 60}m`; if (hr > 0) return `${hr}h ${min % 60}m ${sec % 60}s`; if (min > 0) return `${min}m ${sec % 60}s`; return `${sec}s`; } } exports.BotStatistics = BotStatistics; //# sourceMappingURL=BotStatistics.js.map