const { Client, GatewayIntentBits, REST, Routes, Collection, EmbedBuilder, ChannelType, PermissionFlagsBits, } = require("discord.js"); const { createClient } = require("@supabase/supabase-js"); const http = require("http"); const fs = require("fs"); const path = require("path"); // Dashboard HTML path const dashboardPath = path.join(__dirname, "public", "dashboard.html"); require("dotenv").config(); // ============================================================================= // ENVIRONMENT VALIDATION (Modified: Supabase now optional) // ============================================================================= const token = process.env.DISCORD_BOT_TOKEN; const clientId = process.env.DISCORD_CLIENT_ID; if (!token) { console.error("Missing DISCORD_BOT_TOKEN environment variable"); process.exit(1); } if (!clientId) { console.error("Missing DISCORD_CLIENT_ID environment variable"); process.exit(1); } console.log("[Token] Bot token loaded (length: " + token.length + " chars)"); // ============================================================================= // DISCORD CLIENT SETUP (Modified: Added intents for Sentinel) // ============================================================================= const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildModeration, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.DirectMessages, ], }); // ============================================================================= // SUPABASE SETUP (Modified: Now optional) // ============================================================================= let supabase = null; if (process.env.SUPABASE_URL && process.env.SUPABASE_SERVICE_ROLE) { supabase = createClient( process.env.SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE ); console.log("Supabase connected"); } else { console.log("Supabase not configured - community features will be limited"); } // ============================================================================= // SENTINEL: HEAT TRACKING SYSTEM (New) // ============================================================================= const heatMap = new Map(); const HEAT_THRESHOLD = 3; const HEAT_WINDOW_MS = 10000; const whitelistedUsers = (process.env.WHITELISTED_USERS || '').split(',').filter(Boolean); function addHeat(userId, action) { if (whitelistedUsers.includes(userId)) return 0; const now = Date.now(); if (!heatMap.has(userId)) { heatMap.set(userId, []); } const userEvents = heatMap.get(userId); userEvents.push({ action, timestamp: now }); const recentEvents = userEvents.filter(e => now - e.timestamp < HEAT_WINDOW_MS); heatMap.set(userId, recentEvents); return recentEvents.length; } function getHeat(userId) { const now = Date.now(); const userEvents = heatMap.get(userId) || []; return userEvents.filter(e => now - e.timestamp < HEAT_WINDOW_MS).length; } client.heatMap = heatMap; client.addHeat = addHeat; client.getHeat = getHeat; client.HEAT_THRESHOLD = HEAT_THRESHOLD; // ============================================================================= // SENTINEL: FEDERATION MAPPINGS (New) // ============================================================================= const federationMappings = new Map(); client.federationMappings = federationMappings; async function loadFederationMappings() { if (!supabase) return; try { const { data, error } = await supabase .from('federation_mappings') .select('*'); if (error) throw error; for (const mapping of data || []) { federationMappings.set(mapping.role_id, { name: mapping.role_name, guildId: mapping.guild_id, guildName: mapping.guild_name, linkedAt: new Date(mapping.linked_at).getTime(), }); } console.log(`[Federation] Loaded ${federationMappings.size} mappings from database`); } catch (e) { console.warn('[Federation] Could not load mappings:', e.message); } } async function saveFederationMapping(roleId, data) { if (!supabase) return; try { await supabase.from('federation_mappings').upsert({ role_id: roleId, role_name: data.name, guild_id: data.guildId, guild_name: data.guildName, linked_at: new Date(data.linkedAt).toISOString(), }); } catch (e) { console.warn('[Federation] Could not save mapping:', e.message); } } async function deleteFederationMapping(roleId) { if (!supabase) return; try { await supabase.from('federation_mappings').delete().eq('role_id', roleId); } catch (e) { console.warn('[Federation] Could not delete mapping:', e.message); } } client.saveFederationMapping = saveFederationMapping; client.deleteFederationMapping = deleteFederationMapping; const REALM_GUILDS = { hub: process.env.HUB_GUILD_ID, labs: process.env.LABS_GUILD_ID, gameforge: process.env.GAMEFORGE_GUILD_ID, corp: process.env.CORP_GUILD_ID, foundation: process.env.FOUNDATION_GUILD_ID, }; client.REALM_GUILDS = REALM_GUILDS; // ============================================================================= // GUILD WHITELIST SYSTEM // ============================================================================= const WHITELISTED_GUILDS = [ '373713073594302464', // AeThex | Corporation '515711457946632232', // AeThex (Main) '525971009313046529', // AeThex | Nexus '1245619208805416970', // AeThex | GameForge '1275962459596783686', // AeThex | LABS '1284290638564687925', // AeThex | DevOps '1338564560277344287', // AeThex | Foundation ...(process.env.EXTRA_WHITELISTED_GUILDS || '').split(',').filter(Boolean), ]; client.WHITELISTED_GUILDS = WHITELISTED_GUILDS; client.on('guildCreate', async (guild) => { if (!WHITELISTED_GUILDS.includes(guild.id)) { console.log(`[Whitelist] Unauthorized server detected: ${guild.name} (${guild.id}) - Leaving...`); try { const owner = await guild.fetchOwner(); await owner.send(`Your server "${guild.name}" is not authorized to use AeThex Bot. The bot has automatically left. Contact the AeThex team if you believe this is an error.`).catch(() => {}); } catch (e) {} await guild.leave(); console.log(`[Whitelist] Left unauthorized server: ${guild.name}`); return; } console.log(`[Whitelist] Joined authorized server: ${guild.name} (${guild.id})`); }); // ============================================================================= // SENTINEL: TICKET TRACKING (New) // ============================================================================= const activeTickets = new Map(); client.activeTickets = activeTickets; async function loadActiveTickets() { if (!supabase) return; try { const { data, error } = await supabase .from('tickets') .select('*') .eq('status', 'open'); if (error) throw error; for (const ticket of data || []) { activeTickets.set(ticket.channel_id, { odId: ticket.id, userId: ticket.user_id, guildId: ticket.guild_id, reason: ticket.reason, createdAt: new Date(ticket.created_at).getTime(), }); } console.log(`[Tickets] Loaded ${activeTickets.size} active tickets from database`); } catch (e) { console.warn('[Tickets] Could not load tickets:', e.message); } } async function saveTicket(channelId, data) { if (!supabase) return; try { await supabase.from('tickets').insert({ channel_id: channelId, user_id: data.userId, guild_id: data.guildId, reason: data.reason, status: 'open', }); } catch (e) { console.warn('[Tickets] Could not save ticket:', e.message); } } async function closeTicket(channelId) { if (!supabase) return; try { await supabase .from('tickets') .update({ status: 'closed', closed_at: new Date().toISOString() }) .eq('channel_id', channelId); } catch (e) { console.warn('[Tickets] Could not close ticket:', e.message); } } client.saveTicket = saveTicket; client.closeTicket = closeTicket; // ============================================================================= // SENTINEL: ALERT SYSTEM (New) // ============================================================================= let alertChannelId = process.env.ALERT_CHANNEL_ID; client.alertChannelId = alertChannelId; async function sendAlert(message, embed = null) { if (!alertChannelId) return; try { const channel = await client.channels.fetch(alertChannelId); if (channel) { if (embed) { await channel.send({ content: message, embeds: [embed] }); } else { await channel.send(message); } } } catch (err) { console.error("Failed to send alert:", err.message); } } client.sendAlert = sendAlert; // ============================================================================= // COMMAND LOADING // ============================================================================= client.commands = new Collection(); const commandsPath = path.join(__dirname, "commands"); if (fs.existsSync(commandsPath)) { const commandFiles = fs.readdirSync(commandsPath).filter((file) => file.endsWith(".js")); for (const file of commandFiles) { const filePath = path.join(commandsPath, file); const command = require(filePath); if ("data" in command && "execute" in command) { client.commands.set(command.data.name, command); console.log(`Loaded command: ${command.data.name}`); } } } // ============================================================================= // EVENT LOADING // ============================================================================= const eventsPath = path.join(__dirname, "events"); if (fs.existsSync(eventsPath)) { const eventFiles = fs.readdirSync(eventsPath).filter((file) => file.endsWith(".js")); for (const file of eventFiles) { const filePath = path.join(eventsPath, file); const event = require(filePath); if ("name" in event && "execute" in event) { client.on(event.name, (...args) => event.execute(...args, client, supabase)); console.log(`Loaded event: ${event.name}`); } } } // ============================================================================= // SENTINEL LISTENER LOADING (New) // ============================================================================= const sentinelPath = path.join(__dirname, "listeners", "sentinel"); if (fs.existsSync(sentinelPath)) { const sentinelFiles = fs.readdirSync(sentinelPath).filter((file) => file.endsWith(".js")); for (const file of sentinelFiles) { const filePath = path.join(sentinelPath, file); const listener = require(filePath); if ("name" in listener && "execute" in listener) { client.on(listener.name, (...args) => listener.execute(...args, client)); console.log(`Loaded sentinel listener: ${listener.name}`); } } } // ============================================================================= // GENERAL LISTENER LOADING (Welcome, Goodbye, XP Tracker) // ============================================================================= const listenersPath = path.join(__dirname, "listeners"); const generalListenerFiles = ['welcome.js', 'goodbye.js', 'xpTracker.js']; for (const file of generalListenerFiles) { const filePath = path.join(listenersPath, file); if (fs.existsSync(filePath)) { const listener = require(filePath); if ("name" in listener && "execute" in listener) { client.on(listener.name, (...args) => listener.execute(...args, client, supabase)); console.log(`Loaded listener: ${file}`); } } } // ============================================================================= // SERVER CONFIGS MAP // ============================================================================= const serverConfigs = new Map(); client.serverConfigs = serverConfigs; async function loadServerConfigs() { if (!supabase) return; try { const { data, error } = await supabase .from('server_config') .select('*'); if (error) throw error; for (const config of data || []) { serverConfigs.set(config.guild_id, config); } console.log(`[Config] Loaded ${serverConfigs.size} server configurations`); } catch (e) { console.warn('[Config] Could not load server configs:', e.message); } } // ============================================================================= // FEED SYNC SETUP (Modified: Guard for missing Supabase) // ============================================================================= let feedSyncModule = null; let setupFeedListener = null; let sendPostToDiscord = null; let getFeedChannelId = () => null; try { feedSyncModule = require("./listeners/feedSync"); setupFeedListener = feedSyncModule.setupFeedListener; sendPostToDiscord = feedSyncModule.sendPostToDiscord; getFeedChannelId = feedSyncModule.getFeedChannelId; } catch (e) { console.log("Feed sync module not available"); } // ============================================================================= // INTERACTION HANDLER (Modified: Added button handling for tickets) // ============================================================================= client.on("interactionCreate", async (interaction) => { console.log(`[Interaction] Received: type=${interaction.type}, commandName=${interaction.commandName || 'N/A'}, user=${interaction.user?.tag}, guild=${interaction.guildId}`); if (interaction.isChatInputCommand()) { console.log(`[Command] Processing: ${interaction.commandName}`); const command = client.commands.get(interaction.commandName); if (!command) { console.warn(`No command matching ${interaction.commandName} was found.`); return; } try { console.log(`[Command] Executing: ${interaction.commandName}`); await command.execute(interaction, supabase, client); console.log(`[Command] Completed: ${interaction.commandName}`); } catch (error) { console.error(`Error executing ${interaction.commandName}:`, error); try { const errorEmbed = new EmbedBuilder() .setColor(0xff0000) .setTitle("Command Error") .setDescription("There was an error while executing this command.") .setFooter({ text: "Contact support if this persists" }); if (interaction.replied || interaction.deferred) { await interaction.followUp({ embeds: [errorEmbed], ephemeral: true }).catch(() => {}); } else { await interaction.reply({ embeds: [errorEmbed], ephemeral: true }).catch(() => {}); } } catch (replyError) { console.error("Failed to send error response:", replyError.message); } } } if (interaction.isButton()) { const [action, ...params] = interaction.customId.split('_'); if (action === 'ticket') { const ticketAction = params[0]; if (ticketAction === 'close') { try { const channel = interaction.channel; if (channel && channel.type === ChannelType.GuildText) { await interaction.reply({ content: 'Closing ticket...', ephemeral: true }); activeTickets.delete(channel.id); await closeTicket(channel.id); setTimeout(() => channel.delete().catch(console.error), 3000); } } catch (err) { console.error('Ticket close error:', err); } } } } }); // ============================================================================= // COMMANDS FOR REGISTRATION (Uses actual command file definitions) // ============================================================================= function getCommandsToRegister() { return Array.from(client.commands.values()).map(cmd => cmd.data.toJSON()); } // ============================================================================= // COMMAND REGISTRATION FUNCTION // ============================================================================= async function registerDiscordCommands() { try { const rest = new REST({ version: "10" }).setToken( process.env.DISCORD_BOT_TOKEN, ); const commandsToRegister = getCommandsToRegister(); console.log( `Registering ${commandsToRegister.length} slash commands...`, ); try { const data = await rest.put( Routes.applicationCommands(process.env.DISCORD_CLIENT_ID), { body: commandsToRegister }, ); console.log(`Successfully registered ${data.length} slash commands`); return { success: true, count: data.length, results: null }; } catch (bulkError) { if (bulkError.code === 50240) { console.warn( "Error 50240: Entry Point detected. Registering individually...", ); const results = []; let successCount = 0; let skipCount = 0; for (const command of commandsToRegister) { try { const posted = await rest.post( Routes.applicationCommands(process.env.DISCORD_CLIENT_ID), { body: command }, ); results.push({ name: command.name, status: "registered", id: posted.id, }); successCount++; } catch (postError) { if (postError.code === 50045) { results.push({ name: command.name, status: "already_exists", }); skipCount++; } else { results.push({ name: command.name, status: "error", error: postError.message, }); } } } console.log( `Registration complete: ${successCount} new, ${skipCount} already existed`, ); return { success: true, count: successCount, skipped: skipCount, results, }; } throw bulkError; } } catch (error) { console.error("Failed to register commands:", error); return { success: false, error: error.message }; } } // ============================================================================= // HTTP SERVER (Modified: Added Sentinel stats to health endpoint) // ============================================================================= const healthPort = process.env.HEALTH_PORT || 8080; const ADMIN_TOKEN = process.env.DISCORD_ADMIN_TOKEN || "aethex-bot-admin"; const checkAdminAuth = (req) => { const authHeader = req.headers.authorization; return authHeader === `Bearer ${ADMIN_TOKEN}`; }; http .createServer((req, res) => { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); res.setHeader("Content-Type", "application/json"); if (req.method === "OPTIONS") { res.writeHead(200); res.end(); return; } if (req.url === "/" || req.url === "/dashboard") { res.setHeader("Content-Type", "text/html"); try { const html = fs.readFileSync(dashboardPath, "utf8"); res.writeHead(200); res.end(html); } catch (e) { res.writeHead(404); res.end("
Click to register all ${client.commands.size} slash commands