const fs = require('fs'); const path = require('path'); const os = require('os'); const crypto = require('crypto'); const { GIFEncoder } = require('gif-encoder-2'); const { createCanvas, loadImage } = require('canvas'); // --------------------------------------------------------------------------- // SAFE FILESYSTEM / PATH HELPERS // These wrappers make sure we never hand fs/path a non-string value, which // was the root cause of: // TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string // --------------------------------------------------------------------------- function toSafeString(value, fallback = '') { if (typeof value === 'string') return value; if (value === null || value === undefined) return fallback; try { return String(value); } catch { return fallback; } } function safeJoin(...parts) { const cleanParts = parts .map(p => toSafeString(p, null)) .filter(p => p !== null && p !== ''); if (cleanParts.length === 0) return null; try { return path.join(...cleanParts); } catch (err) { console.error('[safeJoin] Failed to join path parts:', parts, err.message); return null; } } function safeExists(targetPath) { if (typeof targetPath !== 'string' || targetPath.length === 0) return false; try { return fs.existsSync(targetPath); } catch { return false; } } function safeStat(targetPath) { if (!safeExists(targetPath)) return null; try { return fs.statSync(targetPath); } catch (err) { console.error(`[safeStat] Failed to stat ${targetPath}:`, err.message); return null; } } function safeReadDir(targetPath) { if (!safeExists(targetPath)) return []; try { return fs.readdirSync(targetPath); } catch (err) { console.error(`[safeReadDir] Failed to read dir ${targetPath}:`, err.message); return []; } } function safeReadFile(targetPath, encoding = 'utf8') { if (!safeExists(targetPath)) return null; try { return fs.readFileSync(targetPath, encoding); } catch (err) { console.error(`[safeReadFile] Failed to read file ${targetPath}:`, err.message); return null; } } function safeUnlink(targetPath) { if (!safeExists(targetPath)) return false; try { fs.unlinkSync(targetPath); return true; } catch (err) { console.error(`[safeUnlink] Failed to delete file ${targetPath}:`, err.message); return false; } } function safeRequireJson(targetPath, fallback = {}) { if (!safeExists(targetPath)) return fallback; try { delete require.cache[require.resolve(targetPath)]; return require(targetPath); } catch (err) { console.error(`[safeRequireJson] Failed to require ${targetPath}:`, err.message); return fallback; } } module.exports = { name: 'cpannel', aliases: ['qm', 'dash', 'qmonitor', 'nexus'], description: 'Ultra premium quantum holographic live monitor with AI analytics', usage: '!quantummonitor [mode] [theme] [interval]', category: 'Quantum Systems', cooldown: 60, premium: true, adminOnly: true, role: '2', version: '5.1.0', author: 'Badhon-00', config: { modes: ['quantum', 'hologram', 'neural', 'matrix', 'cyber', 'infinity'], themes: ['dark', 'neon', 'cosmic', 'midnight', 'aurora', 'plasma'], intervals: [1, 2, 5, 10, 30, 60], maxHistoryPoints: 100, aiPredictionEnabled: true, holographicMode: true, onStart: true }, async onStart(client) { try { const botInfo = await this.getAdvancedBotInfo(client); console.log(`[QUANTUM MONITOR] System initialized for ${botInfo.name} v${botInfo.version}`); console.log(`[QUANTUM MONITOR] FCA Type: ${botInfo.fca.type}`); console.log(`[QUANTUM MONITOR] Commands: ${botInfo.commands} | Events: ${botInfo.events}`); console.log(`[QUANTUM MONITOR] Author: ${botInfo.author}`); if (!client.quantumSystems) { client.quantumSystems = new Map(); } return true; } catch (error) { console.error('[QUANTUM MONITOR] Failed to initialize:', error); return false; } }, async execute(client, message, args) { try { const safeArgs = Array.isArray(args) ? args.map(a => toSafeString(a, '')) : []; const mode = safeArgs[0] ? safeArgs[0].toLowerCase() : 'quantum'; const theme = safeArgs[1] ? safeArgs[1].toLowerCase() : 'cosmic'; const parsedInterval = parseInt(safeArgs[2], 10); const interval = Math.min(Number.isNaN(parsedInterval) ? 5 : parsedInterval, 60); if (!this.config.modes.includes(mode)) { return message.reply(`āŒ Invalid mode! Available: ${this.config.modes.join(', ')}`); } if (!this.config.themes.includes(theme)) { return message.reply(`āŒ Invalid theme! Available: ${this.config.themes.join(', ')}`); } const quantumSignature = this.generateQuantumSignature(); await this.playLoadingSequence(message); const channelName = `🌌-quantum-nexus-${quantumSignature.slice(0, 8)}`; let monitorChannel = await this.setupMonitorChannel(message, channelName); await this.initializeQuantumSystem(client, monitorChannel, mode, theme, interval, quantumSignature); await this.sendActivationMessage(message, quantumSignature, mode, theme, interval); } catch (error) { console.error('Quantum Monitor Error:', error); await this.sendErrorEmbed(message, error); } }, generateQuantumSignature() { const timestamp = Date.now().toString(36); const entropy = crypto.randomBytes(16).toString('hex'); const quantumHash = crypto.createHash('sha256') .update(timestamp + entropy + os.hostname()) .digest('hex') .toUpperCase(); return `QN-${quantumHash.slice(0, 16)}-${timestamp}`; }, async playLoadingSequence(message) { const loadingStages = [ 'šŸ”® Initializing Quantum Core...', '🌌 Calibrating Holographic Display...', '⚔ Activating Neural Networks...', '🧬 Analyzing Bot DNA...', 'šŸ”¬ Scanning File Structure...', 'šŸ’¾ Loading System Metrics...', 'šŸŽÆ Synchronizing Quantum Entanglement...', '✨ Activating Premium Features...' ]; const loadingMsg = await message.reply('šŸš€ Starting Quantum Monitor...'); try { for (let i = 0; i < loadingStages.length; i++) { const progress = Math.round(((i + 1) / loadingStages.length) * 100); const progressBar = 'ā–ˆ'.repeat(Math.floor(progress / 10)) + 'ā–‘'.repeat(10 - Math.floor(progress / 10)); await loadingMsg.edit({ embeds: [{ color: 0x00ffff, title: '🌌 QUANTUM SYSTEM INITIALIZATION', description: `\`\`\`\n${loadingStages[i]}\n\`\`\`\n**Progress:** ${progress}%\n${progressBar}\n\n**Quantum Signature:** \`Generating...\``, footer: { text: 'Quantum Holographic Monitor System v5.1' } }] }); await new Promise(resolve => setTimeout(resolve, 500)); } } catch (err) { console.error('[playLoadingSequence] Failed to update loading message:', err.message); } finally { await loadingMsg.delete().catch(() => {}); } }, async setupMonitorChannel(message, channelName) { let monitorChannel = message.guild.channels.cache.find(ch => ch.name === channelName); if (!monitorChannel) { monitorChannel = await message.guild.channels.create(channelName, { type: 'GUILD_TEXT', topic: '🌌 Quantum Holographic Monitor - Premium System', permissionOverwrites: [ { id: message.guild.id, deny: ['SEND_MESSAGES', 'ADD_REACTIONS'], allow: ['VIEW_CHANNEL', 'READ_MESSAGE_HISTORY'] }, { id: message.author.id, allow: ['SEND_MESSAGES', 'MANAGE_MESSAGES', 'ADD_REACTIONS'] } ] }); } return monitorChannel; }, async initializeQuantumSystem(client, channel, mode, theme, interval, signature) { try { const messages = await channel.messages.fetch({ limit: 100 }); await channel.bulkDelete(messages).catch(() => {}); } catch (err) { console.error('[initializeQuantumSystem] Failed to clear channel:', err.message); } if (!client.quantumSystems) { client.quantumSystems = new Map(); } // If a monitor already exists for this channel, clear its old interval first const existing = client.quantumSystems.get(channel.id); if (existing && existing.intervalId) { clearInterval(existing.intervalId); } const quantumState = { mode, theme, interval, signature, startTime: Date.now(), history: [], predictions: [], anomalies: [], performanceMetrics: [] }; client.quantumSystems.set(channel.id, quantumState); this.startQuantumLoop(client, channel, quantumState); }, async startQuantumLoop(client, channel, quantumState) { const intervalId = setInterval(async () => { try { await this.updateQuantumDisplay(client, channel, quantumState); } catch (error) { console.error('Quantum Loop Error:', error); } }, quantumState.interval * 1000); quantumState.intervalId = intervalId; await this.updateQuantumDisplay(client, channel, quantumState); }, async updateQuantumDisplay(client, channel, quantumState) { let canvasBuffer = null; try { const botData = await this.collectQuantumData(client); const embed = await this.generateQuantumEmbed(botData, quantumState); const prediction = this.generateAIPredictions(botData, quantumState); try { canvasBuffer = await this.generateQuantumCanvas(botData, quantumState); } catch (canvasErr) { console.error('[updateQuantumDisplay] Canvas generation failed:', canvasErr.message); canvasBuffer = null; } quantumState.history.push(botData); if (quantumState.history.length > this.config.maxHistoryPoints) { quantumState.history.shift(); } quantumState.predictions = prediction; quantumState.anomalies = this.detectAnomalies(botData, quantumState.history); try { const messages = await channel.messages.fetch({ limit: 10 }); await channel.bulkDelete(messages).catch(() => {}); } catch (clearErr) { console.error('[updateQuantumDisplay] Failed to clear old messages:', clearErr.message); } const payload = { embeds: [embed] }; if (canvasBuffer) { payload.files = [{ attachment: canvasBuffer, name: `quantum-${quantumState.mode}-${Date.now()}.png` }]; } await channel.send(payload); if (quantumState.anomalies.length > 0) { await this.sendAnomalyAlerts(channel, quantumState.anomalies); } } catch (error) { console.error('[updateQuantumDisplay] Unexpected failure:', error); } finally { // Nothing persistent to clean up here since we generate PNG buffers // in-memory rather than temp files, but this guarantees we never // leak references if future code starts writing to disk. canvasBuffer = null; } }, async collectQuantumData(client) { const botInfo = await this.getAdvancedBotInfo(client); const systemInfo = this.getAdvancedSystemInfo(); const fileInfo = this.getAdvancedFileInfo(); const networkInfo = await this.getAdvancedNetworkInfo(client); const securityInfo = this.getSecurityInfo(); const analyticsInfo = this.getAnalyticsInfo(botInfo, systemInfo); return { timestamp: Date.now(), bot: botInfo, system: systemInfo, files: fileInfo, network: networkInfo, security: securityInfo, analytics: analyticsInfo, quantum: { entropy: crypto.randomBytes(4).readUInt32LE(0) / 0xFFFFFFFF, coherence: Math.random() * 100, entanglement: Math.random() * 100, superposition: Math.random() * 100 } }; }, async getAdvancedBotInfo(client) { const packageJsonPath = safeJoin(process.cwd(), 'package.json'); const packageJson = safeRequireJson(packageJsonPath, {}); const botName = packageJson.name || 'GoatBot'; const version = packageJson.version || '5.1.0'; const author = packageJson.author || 'Badhon-00'; const fcaInfo = this.detectAdvancedFCA(); const uptime = process.uptime(); const startDate = new Date(Date.now() - uptime * 1000); const botAge = this.calculateBotAge(packageJsonPath); return { name: botName, version, author, fca: fcaInfo, uptime: this.formatUptime(uptime), startDate, botAge, guilds: client?.guilds?.cache?.size ?? 0, users: client?.users?.cache?.size ?? 0, channels: client?.channels?.cache?.size ?? 0, commands: this.countAdvancedCommands(), events: this.countAdvancedEvents(), modules: this.countModules(), features: this.detectFeatures(client) }; }, detectAdvancedFCA() { const fcaTypes = [ 'fca-unofficial', 'fca-horizon', 'fca-remastered', 'fca-advanced', 'fca-premium', 'fca-ultimate', 'facebook-chat-api', 'fca-core' ]; for (const fca of fcaTypes) { const fcaPath = safeJoin(process.cwd(), 'node_modules', fca); if (fcaPath && safeExists(fcaPath)) { const fcaPackagePath = safeJoin(fcaPath, 'package.json'); const fcaPackage = safeRequireJson(fcaPackagePath, {}); return { type: fca, version: fcaPackage.version || 'unknown', author: fcaPackage.author || 'unknown', location: 'node_modules' }; } } const srcPath = safeJoin(process.cwd(), 'src'); if (srcPath && safeExists(srcPath)) { const srcFiles = safeReadDir(srcPath); for (const file of srcFiles) { const safeFile = toSafeString(file, ''); if (safeFile.includes('fca') || safeFile.includes('facebook')) { return { type: `src/${safeFile}`, version: 'custom', author: 'custom', location: 'src' }; } } } const packageJsonPath = safeJoin(process.cwd(), 'package.json'); const packageJson = safeRequireJson(packageJsonPath, {}); const deps = { ...(packageJson.dependencies || {}), ...(packageJson.devDependencies || {}) }; for (const dep of Object.keys(deps)) { if (dep.includes('fca') || dep.includes('facebook')) { return { type: dep, version: deps[dep], author: 'npm', location: 'package.json' }; } } return { type: 'unknown', version: 'N/A', author: 'N/A', location: 'N/A' }; }, calculateBotAge(packageJsonPath) { const safePkgPath = packageJsonPath || safeJoin(process.cwd(), 'package.json'); const stats = safeStat(safePkgPath); if (!stats) { return { days: 0, months: 0, years: 0, created: new Date() }; } const createdDate = stats.birthtime; const ageDays = Math.floor((Date.now() - createdDate.getTime()) / 86400000); return { days: ageDays, months: Math.floor(ageDays / 30), years: Math.floor(ageDays / 365), created: createdDate }; }, formatUptime(uptime) { const days = Math.floor(uptime / 86400); const hours = Math.floor((uptime % 86400) / 3600); const minutes = Math.floor((uptime % 3600) / 60); const seconds = Math.floor(uptime % 60); return { days, hours, minutes, seconds, total: uptime }; }, getAdvancedSystemInfo() { const totalMem = os.totalmem(); const freeMem = os.freemem(); const usedMem = totalMem - freeMem; const cpus = os.cpus() || []; // ROM / disk usage (best-effort, cross-platform safe fallback). // fs.statfsSync is only available on Node 18.15+/19.6+, so we guard it. let disk = { total: 0, free: 0, used: 0, usagePercent: 0, available: false }; try { if (typeof fs.statfsSync === 'function') { const stat = fs.statfsSync(process.cwd()); const total = stat.blocks * stat.bsize; const free = stat.bfree * stat.bsize; disk = { total, free, used: total - free, usagePercent: total > 0 ? ((total - free) / total) * 100 : 0, available: true }; } } catch (err) { console.error('[getAdvancedSystemInfo] Disk stats unavailable:', err.message); } // GPU info: Node.js/os module has no native GPU API. We report // "unavailable" rather than fabricating data, and note how to add // real GPU stats (e.g. via the optional 'systeminformation' package) // if the host environment supports it. let gpu = { available: false, note: 'Install "systeminformation" package for real GPU stats' }; try { // Optional dependency - only used if already installed, never required as a hard dependency. const si = require('systeminformation'); gpu = { available: true, viaSystemInformation: true, module: si }; } catch { // systeminformation not installed - keep the safe fallback above. } return { platform: os.platform(), arch: os.arch(), cpu: cpus[0]?.model || 'Unknown CPU', cores: cpus.length, memory: { total: totalMem, free: freeMem, used: usedMem, usagePercent: totalMem > 0 ? (usedMem / totalMem) * 100 : 0 }, disk, gpu, node: process.version, pid: process.pid, uptime: os.uptime(), load: os.loadavg(), network: os.networkInterfaces() }; }, getAdvancedFileInfo() { const rootDir = toSafeString(process.cwd(), '.'); const allFiles = this.getAllFilesAdvanced(rootDir); const fileInfo = { total: allFiles.length, size: 0, types: {}, folders: {}, commands: [], events: [], configs: [], modules: [], recent: [] }; allFiles.forEach(file => { const stats = safeStat(file); if (!stats) return; const ext = path.extname(file).toLowerCase(); const relative = path.relative(rootDir, file); const folder = path.dirname(relative); fileInfo.size += stats.size; fileInfo.types[ext] = (fileInfo.types[ext] || 0) + 1; fileInfo.folders[folder] = (fileInfo.folders[folder] || 0) + 1; if (relative.includes('command')) fileInfo.commands.push(relative); if (relative.includes('event')) fileInfo.events.push(relative); if (relative.includes('config')) fileInfo.configs.push(relative); if (relative.includes('module')) fileInfo.modules.push(relative); if (Date.now() - stats.mtimeMs < 86400000) { fileInfo.recent.push({ path: relative, modified: stats.mtime, size: stats.size }); } }); fileInfo.sizeMB = (fileInfo.size / 1024 / 1024).toFixed(2); fileInfo.sizeKB = (fileInfo.size / 1024).toFixed(2); return fileInfo; }, getAllFilesAdvanced(dir, depth = 0, maxDepth = 10) { const safeDir = toSafeString(dir, null); if (!safeDir || depth > maxDepth || !safeExists(safeDir)) return []; const files = []; const skipDirs = ['node_modules', '.git', 'dist', 'build', 'coverage', '.cache']; const items = safeReadDir(safeDir); items.forEach(item => { const safeItem = toSafeString(item, null); if (!safeItem) return; const fullPath = safeJoin(safeDir, safeItem); if (!fullPath) return; const stat = safeStat(fullPath); if (!stat) return; if (stat.isDirectory()) { if (!skipDirs.includes(safeItem)) { files.push(...this.getAllFilesAdvanced(fullPath, depth + 1, maxDepth)); } } else { if (!safeItem.startsWith('.')) { files.push(fullPath); } } }); return files; }, async getAdvancedNetworkInfo(client) { const guilds = client?.guilds?.cache; if (!guilds) { return { totalGuilds: 0, totalMembers: 0, avgMembers: 0, topGuilds: [], ping: client?.ws?.ping ?? -1, status: client?.ws?.status ?? 'unknown' }; } const totalMembers = guilds.reduce((acc, guild) => acc + (guild.memberCount || 0), 0); const topGuilds = guilds .sort((a, b) => (b.memberCount || 0) - (a.memberCount || 0)) .first(15) .map((guild, index) => ({ rank: index + 1, name: guild.name, members: guild.memberCount, channels: guild.channels?.cache?.size ?? 0, roles: guild.roles?.cache?.size ?? 0, boostLevel: guild.premiumTier, boostCount: guild.premiumSubscriptionCount, region: guild.preferredLocale, created: guild.createdAt })); return { totalGuilds: guilds.size, totalMembers, avgMembers: guilds.size > 0 ? totalMembers / guilds.size : 0, topGuilds, ping: client.ws?.ping ?? -1, status: client.ws?.status ?? 'unknown' }; }, getSecurityInfo() { const envPath = safeJoin(process.cwd(), '.env'); const configPath = safeJoin(process.cwd(), 'config.json'); return { tokenEncrypted: process.env.TOKEN ? 'āœ… Encrypted' : 'āŒ Not Encrypted', envFile: safeExists(envPath) ? 'āœ… Present' : 'āŒ Missing', configFile: safeExists(configPath) ? 'āœ… Present' : 'āŒ Missing', permissions: this.checkPermissions(), vulnerabilities: this.scanVulnerabilities() }; }, checkPermissions() { const perms = []; const cwd = toSafeString(process.cwd(), '.'); try { fs.accessSync(cwd, fs.constants.W_OK); perms.push('āœ… Write Access'); } catch { perms.push('āŒ No Write Access'); } try { fs.accessSync(cwd, fs.constants.R_OK); perms.push('āœ… Read Access'); } catch { perms.push('āŒ No Read Access'); } return perms; }, scanVulnerabilities() { const vulnerabilities = []; const files = this.getAllFilesAdvanced(process.cwd(), 0, 2); files.forEach(file => { const content = safeReadFile(file, 'utf8'); if (content === null) return; if (content.includes('TOKEN') && !file.includes('.env')) { vulnerabilities.push(`āš ļø Token exposed in ${path.basename(file)}`); } if (content.includes('PASSWORD') && !file.includes('.env')) { vulnerabilities.push(`āš ļø Password exposed in ${path.basename(file)}`); } }); return vulnerabilities; }, getAnalyticsInfo(botInfo, systemInfo) { return { efficiency: this.calculateEfficiency(botInfo), stability: this.calculateStability(systemInfo), growth: this.calculateGrowth(botInfo), performance: this.calculatePerformance(botInfo, systemInfo), score: this.calculateOverallScore(botInfo, systemInfo) }; }, calculateEfficiency(botInfo) { const commandEfficiency = Math.min((botInfo.commands / 100) * 100, 100); const moduleEfficiency = Math.min((botInfo.modules / 50) * 100, 100); return (commandEfficiency + moduleEfficiency) / 2; }, calculateStability(systemInfo) { const memoryStability = 100 - systemInfo.memory.usagePercent; const loadStability = Math.max(0, 100 - (systemInfo.load[0] / 8) * 100); return (memoryStability + loadStability) / 2; }, calculateGrowth(botInfo) { const ageInDays = botInfo.botAge.days || 1; const guildGrowth = (botInfo.guilds / ageInDays) * 10; const userGrowth = (botInfo.users / ageInDays) * 10; return Math.min(guildGrowth + userGrowth, 100); }, calculatePerformance(botInfo, systemInfo) { const uptimeScore = Math.min((botInfo.uptime.total / 86400) * 100, 100); const memoryScore = 100 - systemInfo.memory.usagePercent; return (uptimeScore + memoryScore) / 2; }, calculateOverallScore(botInfo, systemInfo) { const efficiency = this.calculateEfficiency(botInfo); const stability = this.calculateStability(systemInfo); const growth = this.calculateGrowth(botInfo); const performance = this.calculatePerformance(botInfo, systemInfo); return (efficiency + stability + growth + performance) / 4; }, generateAIPredictions(botData, quantumState) { if (!this.config.aiPredictionEnabled || quantumState.history.length < 10) { return []; } const predictions = []; const history = quantumState.history; const guildHistory = history.map(h => h.bot.guilds); const guildTrend = this.calculateTrend(guildHistory); predictions.push({ metric: 'Guild Growth', current: botData.bot.guilds, predicted: botData.bot.guilds + guildTrend * 10, trend: guildTrend > 0 ? 'šŸ“ˆ Increasing' : guildTrend < 0 ? 'šŸ“‰ Decreasing' : 'āž”ļø Stable', confidence: this.calculateConfidence(guildHistory) }); const memHistory = history.map(h => h.system.memory.usagePercent); const memTrend = this.calculateTrend(memHistory); predictions.push({ metric: 'Memory Usage', current: botData.system.memory.usagePercent, predicted: botData.system.memory.usagePercent + memTrend * 10, trend: memTrend > 0 ? 'šŸ“ˆ Increasing' : memTrend < 0 ? 'šŸ“‰ Decreasing' : 'āž”ļø Stable', confidence: this.calculateConfidence(memHistory) }); const cmdHistory = history.map(h => h.bot.commands); const cmdTrend = this.calculateTrend(cmdHistory); predictions.push({ metric: 'Commands', current: botData.bot.commands, predicted: botData.bot.commands + cmdTrend * 5, trend: cmdTrend > 0 ? 'šŸ“ˆ Growing' : cmdTrend < 0 ? 'šŸ“‰ Shrinking' : 'āž”ļø Stable', confidence: this.calculateConfidence(cmdHistory) }); return predictions; }, calculateTrend(history) { if (history.length < 2) return 0; const x = Array.from({ length: history.length }, (_, i) => i); const y = history; const n = x.length; const sumX = x.reduce((a, b) => a + b, 0); const sumY = y.reduce((a, b) => a + b, 0); const sumXY = x.reduce((a, b, i) => a + b * y[i], 0); const sumXX = x.reduce((a, b) => a + b * b, 0); const denominator = (n * sumXX - sumX * sumX); if (denominator === 0) return 0; return (n * sumXY - sumX * sumY) / denominator; }, calculateConfidence(history) { if (history.length < 2) return 0; const mean = history.reduce((a, b) => a + b, 0) / history.length; if (mean === 0) return 0; const variance = history.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / history.length; const stdDev = Math.sqrt(variance); return Math.max(0, Math.min(100, 100 - (stdDev / mean) * 100)); }, detectAnomalies(botData, history) { const anomalies = []; if (history.length < 5) return anomalies; const prevData = history[history.length - 2]; if (!prevData) return anomalies; const memChange = botData.system.memory.usagePercent - prevData.system.memory.usagePercent; if (Math.abs(memChange) > 20) { anomalies.push({ type: 'Memory', severity: 'HIGH', message: `Memory usage changed by ${memChange.toFixed(2)}% suddenly`, timestamp: new Date() }); } const guildChange = botData.bot.guilds - prevData.bot.guilds; if (Math.abs(guildChange) > 10) { anomalies.push({ type: 'Network', severity: 'MEDIUM', message: `Guild count changed by ${guildChange} servers`, timestamp: new Date() }); } if (botData.network.ping > 1000) { anomalies.push({ type: 'Performance', severity: 'HIGH', message: `High ping detected: ${botData.network.ping}ms`, timestamp: new Date() }); } return anomalies; }, async sendAnomalyAlerts(channel, anomalies) { const embed = { color: 0xff0000, title: 'āš ļø QUANTUM ANOMALY DETECTED', description: anomalies.map(a => `**${a.type}** (${a.severity})\n${a.message}\n*Detected: *` ).join('\n\n'), footer: { text: 'Quantum Holographic Monitor System' }, timestamp: new Date() }; await channel.send({ embeds: [embed] }).catch(err => { console.error('[sendAnomalyAlerts] Failed to send alert:', err.message); }); }, async generateQuantumCanvas(botData, quantumState) { const width = 1600; const height = 900; let canvas = null; try { canvas = createCanvas(width, height); const ctx = canvas.getContext('2d'); const theme = this.getThemeColors(quantumState.theme); this.createHolographicBackground(ctx, width, height, theme, quantumState); this.drawQuantumGrid(ctx, width, height, theme); await this.drawQuantumDashboard(ctx, botData, quantumState, theme); this.drawHolographicEffects(ctx, width, height, theme, quantumState); this.drawQuantumParticles(ctx, width, height, theme, quantumState); this.drawQuantumWatermark(ctx, quantumState, theme); return canvas.toBuffer('image/png'); } catch (error) { console.error('[generateQuantumCanvas] Rendering failed:', error.message); throw error; } finally { // node-canvas buffers are garbage collected normally, but we // drop our reference explicitly so a failed render doesn't // keep a half-drawn canvas pinned in memory. canvas = null; } }, getThemeColors(theme) { const themes = { dark: { bg1: '#0a0a0a', bg2: '#1a1a1a', primary: '#ffffff', secondary: '#888888', accent: '#00ff00', glow: 'rgba(0, 255, 0, 0.5)', grid: 'rgba(255, 255, 255, 0.1)' }, neon: { bg1: '#000033', bg2: '#330066', primary: '#00ffff', secondary: '#ff00ff', accent: '#ffff00', glow: 'rgba(0, 255, 255, 0.5)', grid: 'rgba(0, 255, 255, 0.2)' }, cosmic: { bg1: '#0a0020', bg2: '#200040', primary: '#8a2be2', secondary: '#9370db', accent: '#da70d6', glow: 'rgba(138, 43, 226, 0.5)', grid: 'rgba(138, 43, 226, 0.2)' }, midnight: { bg1: '#000010', bg2: '#001030', primary: '#4169e1', secondary: '#6495ed', accent: '#87ceeb', glow: 'rgba(65, 105, 225, 0.5)', grid: 'rgba(65, 105, 225, 0.2)' }, aurora: { bg1: '#001010', bg2: '#003030', primary: '#00ff7f', secondary: '#00ced1', accent: '#7fffd4', glow: 'rgba(0, 255, 127, 0.5)', grid: 'rgba(0, 255, 127, 0.2)' }, plasma: { bg1: '#100010', bg2: '#301030', primary: '#ff00ff', secondary: '#ff1493', accent: '#ff69b4', glow: 'rgba(255, 0, 255, 0.5)', grid: 'rgba(255, 0, 255, 0.2)' } }; return themes[theme] || themes.cosmic; }, createHolographicBackground(ctx, width, height, theme, quantumState) { const gradient = ctx.createLinearGradient(0, 0, width, height); gradient.addColorStop(0, theme.bg1); gradient.addColorStop(1, theme.bg2); ctx.fillStyle = gradient; ctx.fillRect(0, 0, width, height); const time = Date.now() / 1000; for (let i = 0; i < 10; i++) { const y = (height / 10) * i + Math.sin(time + i) * 50; const alpha = 0.05 + (i / 10) * 0.1; ctx.fillStyle = theme.glow.replace('0.5', alpha.toString()); ctx.beginPath(); ctx.moveTo(0, y); for (let x = 0; x <= width; x += 50) { const waveY = y + Math.sin(x * 0.01 + time * 2 + i) * 30; ctx.lineTo(x, waveY); } ctx.lineTo(width, height); ctx.lineTo(0, height); ctx.closePath(); ctx.fill(); } }, drawQuantumGrid(ctx, width, height, theme) { ctx.strokeStyle = theme.grid; ctx.lineWidth = 1; for (let x = 0; x < width; x += 50) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, height); ctx.stroke(); } for (let y = 0; y < height; y += 50) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(width, y); ctx.stroke(); } ctx.strokeStyle = theme.grid.replace('0.2', '0.05'); for (let i = -height; i < width; i += 100) { ctx.beginPath(); ctx.moveTo(i, 0); ctx.lineTo(i + height, height); ctx.stroke(); } }, async drawQuantumDashboard(ctx, botData, quantumState, theme) { ctx.fillStyle = theme.primary; ctx.font = 'bold 44px Arial'; ctx.textAlign = 'center'; ctx.shadowColor = theme.glow; ctx.shadowBlur = 20; ctx.fillText('🌌 QUANTUM HOLOGRAPHIC MONITOR', 800, 55); ctx.shadowBlur = 0; const gb = botData.system.gpu?.available ? 'Available' : 'N/A (needs systeminformation)'; const diskLine = botData.system.disk?.available ? `Disk: ${(botData.system.disk.used / 1024 / 1024 / 1024).toFixed(2)}/${(botData.system.disk.total / 1024 / 1024 / 1024).toFixed(2)} GB (${botData.system.disk.usagePercent.toFixed(1)}%)` : 'Disk: N/A on this platform'; this.drawInfoPanel(ctx, 50, 90, 500, 310, 'BOT INFORMATION', [ `Name: ${botData.bot.name}`, `Version: ${botData.bot.version}`, `Author: ${botData.bot.author}`, `FCA: ${botData.bot.fca.type}`, `Uptime: ${botData.bot.uptime.days}d ${botData.bot.uptime.hours}h ${botData.bot.uptime.minutes}m`, `Age: ${botData.bot.botAge.days} days`, `Commands: ${botData.bot.commands}`, `Events: ${botData.bot.events}`, `Modules: ${botData.bot.modules}` ], theme); this.drawInfoPanel(ctx, 550, 90, 500, 310, 'SYSTEM INFORMATION', [ `Platform: ${botData.system.platform} ${botData.system.arch}`, `CPU: ${botData.system.cpu}`, `Cores: ${botData.system.cores}`, `RAM: ${(botData.system.memory.used / 1024 / 1024 / 1024).toFixed(2)}/${(botData.system.memory.total / 1024 / 1024 / 1024).toFixed(2)} GB`, diskLine, `GPU: ${gb}`, `Node.js: ${botData.system.node}`, `PID: ${botData.system.pid}`, `Load: ${botData.system.load.map(l => l.toFixed(2)).join(', ')}` ], theme); this.drawInfoPanel(ctx, 1050, 90, 500, 310, 'FILE STATISTICS', [ `Total Files: ${botData.files.total}`, `Total Size: ${botData.files.sizeMB} MB`, `Commands: ${botData.files.commands.length}`, `Events: ${botData.files.events.length}`, `Configs: ${botData.files.configs.length}`, `Modules: ${botData.files.modules.length}`, `Recent: ${botData.files.recent.length} files modified` ], theme); this.drawInfoPanel(ctx, 50, 420, 500, 260, 'NETWORK STATISTICS', [ `Servers: ${botData.network.totalGuilds}`, `Members: ${botData.network.totalMembers}`, `Avg Members: ${botData.network.avgMembers.toFixed(0)}`, `Ping: ${botData.network.ping}ms`, `Status: ${botData.network.status}` ], theme); this.drawInfoPanel(ctx, 550, 420, 500, 260, 'SECURITY STATUS', [ `Token: ${botData.security.tokenEncrypted}`, `Env File: ${botData.security.envFile}`, `Config: ${botData.security.configFile}`, ...botData.security.permissions ], theme); this.drawInfoPanel(ctx, 1050, 420, 500, 260, 'AI ANALYTICS', [ `Efficiency: ${botData.analytics.efficiency.toFixed(2)}%`, `Stability: ${botData.analytics.stability.toFixed(2)}%`, `Growth: ${botData.analytics.growth.toFixed(2)}%`, `Performance: ${botData.analytics.performance.toFixed(2)}%`, `Overall Score: ${botData.analytics.score.toFixed(2)}%` ], theme); }, drawInfoPanel(ctx, x, y, width, height, title, lines, theme) { ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'; ctx.fillRect(x, y, width, height); ctx.strokeStyle = theme.glow; ctx.lineWidth = 2; ctx.strokeRect(x, y, width, height); ctx.fillStyle = theme.accent; ctx.font = 'bold 20px Arial'; ctx.textAlign = 'left'; ctx.fillText(title, x + 20, y + 35); ctx.fillStyle = theme.primary; ctx.font = '15px Arial'; lines.forEach((line, index) => { ctx.fillText(line, x + 20, y + 62 + index * 24); }); }, drawHolographicEffects(ctx, width, height, theme, quantumState) { const time = Date.now() / 1000; for (let i = 0; i < 20; i++) { const x = (Math.sin(time + i) + 1) * width / 2; const y = (Math.cos(time * 0.7 + i) + 1) * height / 2; const radius = 2 + Math.sin(time + i) * 1.5; const gradient = ctx.createRadialGradient(x, y, 0, x, y, radius * 3); gradient.addColorStop(0, theme.glow); gradient.addColorStop(1, 'rgba(0, 0, 0, 0)'); ctx.fillStyle = gradient; ctx.beginPath(); ctx.arc(x, y, radius * 3, 0, Math.PI * 2); ctx.fill(); } }, drawQuantumParticles(ctx, width, height, theme, quantumState) { const time = Date.now() / 1000; for (let i = 0; i < 50; i++) { const x = (Math.sin(time * 0.5 + i * 0.7) + 1) * width / 2; const y = (Math.cos(time * 0.3 + i * 0.5) + 1) * height / 2; ctx.fillStyle = theme.accent; ctx.globalAlpha = 0.3 + Math.sin(time + i) * 0.2; ctx.beginPath(); ctx.arc(x, y, 2, 0, Math.PI * 2); ctx.fill(); } ctx.globalAlpha = 1; }, drawQuantumWatermark(ctx, quantumState, theme) { ctx.fillStyle = theme.secondary; ctx.font = '16px Arial'; ctx.textAlign = 'right'; ctx.fillText(`Signature: ${quantumState.signature}`, 1580, 860); ctx.fillText('Created by Badhon-00', 1580, 880); }, async generateQuantumEmbed(botData, quantumState) { const embed = { color: 0x8a2be2, title: '🌌 QUANTUM MONITOR UPDATE', description: `**Signature:** \`${quantumState.signature}\`\n**Mode:** ${quantumState.mode.toUpperCase()}\n**Theme:** ${quantumState.theme.toUpperCase()}`, fields: [ { name: 'šŸ¤– Bot Info', value: `Name: ${botData.bot.name}\nVersion: ${botData.bot.version}\nAuthor: ${botData.bot.author}\nFCA: ${botData.bot.fca.type}`, inline: true }, { name: 'šŸ’» System', value: `Platform: ${botData.system.platform}\nCPU: ${botData.system.cpu}\nCores: ${botData.system.cores}\nNode: ${botData.system.node}`, inline: true }, { name: 'šŸ“Š Stats', value: `Commands: ${botData.bot.commands}\nEvents: ${botData.bot.events}\nFiles: ${botData.files.total}\nPing: ${botData.network.ping}ms`, inline: true } ], footer: { text: 'Quantum Monitor v5.1.0 | Author: Badhon-00' }, timestamp: new Date() }; if (quantumState.predictions.length > 0) { embed.fields.push({ name: 'šŸ”® AI Predictions', value: quantumState.predictions.map(p => `${p.metric}: ${p.trend} (${p.confidence.toFixed(1)}% confidence)` ).join('\n'), inline: false }); } return embed; }, async sendActivationMessage(message, signature, mode, theme, interval) { const embed = { color: 0x00ff00, title: 'āœ… QUANTUM MONITOR ACTIVATED', description: `**Signature:** \`${signature}\`\n**Mode:** ${mode.toUpperCase()}\n**Theme:** ${theme.toUpperCase()}\n**Update Interval:** ${interval} seconds`, fields: [ { name: 'šŸ“Š Monitored Data', value: '• Bot Information\n• System Metrics (CPU, RAM, Disk, GPU)\n• File Statistics\n• Network Status & Ping\n• Security Status\n• AI Analytics' }, { name: '⚔ Premium Features', value: '• Real-time Updates\n• AI Predictions\n• Anomaly Detection\n• Quantum Visualization\n• Holographic Display' } ], footer: { text: 'Quantum Monitor v5.1.0 | Author: Badhon-00' }, timestamp: new Date() }; await message.reply({ embeds: [embed] }); }, async sendErrorEmbed(message, error) { const embed = { color: 0xff0000, title: 'āŒ QUANTUM SYSTEM FAILURE', description: `An error occurred in the quantum monitoring system.\n\n**Error:** ${error?.message || 'Unknown error'}`, footer: { text: 'Check system logs for details' }, timestamp: new Date() }; await message.reply({ embeds: [embed] }).catch(() => {}); }, countAdvancedCommands() { const dirs = ['commands', 'cmd', 'modules/commands', 'src/commands']; for (const dir of dirs) { const fullPath = safeJoin(process.cwd(), dir); if (fullPath && safeExists(fullPath)) { return this.countJSFiles(fullPath); } } return 0; }, countAdvancedEvents() { const dirs = ['events', 'event', 'modules/events', 'src/events']; for (const dir of dirs) { const fullPath = safeJoin(process.cwd(), dir); if (fullPath && safeExists(fullPath)) { return this.countJSFiles(fullPath); } } return 0; }, countModules() { const dirs = ['modules', 'src/modules', 'lib', 'utils']; for (const dir of dirs) { const fullPath = safeJoin(process.cwd(), dir); if (fullPath && safeExists(fullPath)) { return this.countJSFiles(fullPath); } } return 0; }, countJSFiles(dir) { const safeDir = toSafeString(dir, null); if (!safeDir || !safeExists(safeDir)) return 0; let count = 0; const items = safeReadDir(safeDir); items.forEach(item => { const safeItem = toSafeString(item, null); if (!safeItem) return; const fullPath = safeJoin(safeDir, safeItem); if (!fullPath) return; const stat = safeStat(fullPath); if (!stat) return; if (stat.isDirectory()) { count += this.countJSFiles(fullPath); } else if (safeItem.endsWith('.js')) { count++; } }); return count; }, detectFeatures(client) { const features = []; if (!client) return features; if (client.commands) features.push('Command Handler'); if (client.events) features.push('Event Handler'); if (client.database) features.push('Database'); if (client.economy) features.push('Economy System'); if (client.leveling) features.push('Leveling System'); if (client.music) features.push('Music System'); if (client.moderation) features.push('Moderation'); if (client.automod) features.push('Auto Moderation'); if (client.welcome) features.push('Welcome System'); if (client.logging) features.push('Logging System'); if (client.customCommands) features.push('Custom Commands'); if (client.reactionRoles) features.push('Reaction Roles'); if (client.tickets) features.push('Ticket System'); if (client.giveaways) features.push('Giveaway System'); if (client.polls) features.push('Poll System'); return features; } };