LineUp-Bot / index.js
Brozy123's picture
Update index.js
2a732a9 verified
Raw History Blame Contribute Delete
185 kB
"use strict"; // ------------------------------------------------------------- // DEBUG LOGGING - FIRST LINES // ------------------------------------------------------------- console.log(">>> [BOOT] Application process group starting..."); process.stdout.write(">>> [BOOT] Purity check: Stdout is writeable.\n"); console.error(">>> [BOOT] Purity check: Stderr is writeable."); process.on('unhandledRejection', (reason, promise) => { console.error('>>> [BOOT] UNHANDLED REJECTION:', reason); }); process.on('uncaughtException', (err) => { console.error('>>> [BOOT] UNCAUGHT EXCEPTION:', err); console.error(err.stack); }); console.log(">>> [BOOT] Loading dependencies..."); require('dotenv').config(); const ultimateFix = require('./ultimate_fix'); // High priority fix const networkFix = require('./network_fix'); const { Client, GatewayIntentBits, Partials, Collection, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, UserSelectMenuBuilder, ChannelSelectMenuBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ComponentType, MessageFlags, ChannelType } = require('discord.js'); function sendServerTransaction(type, guild) { if (!guild || !guild.id) return; console.log('SEND_SERVER_TRANSACTION', type, guild.id, guild.name || ''); } function sendJoinTransaction(guild) { sendServerTransaction('join', guild); } function sendLeaveTransaction(guild) { sendServerTransaction('leave', guild); } console.log(">>> [BOOT] Discord.js loaded."); console.log(">>> [BOOT] Loading Storage..."); const storage = require('./storage'); console.log(">>> [BOOT] Storage loaded."); console.log(">>> [BOOT] Loading RoleStorage..."); const roleStorage = require('./roleStorage'); console.log(">>> [BOOT] RoleStorage loaded."); console.log(">>> [BOOT] Loading Web Server module..."); const server = require('./server'); console.log(">>> [BOOT] Web Server module loaded."); const { guildLineups, guildLineupsB, guildScrimMode, guildSelectedFormationA, guildSelectedFormationB, guildSelectedFormation, lineupOwners, activeLineupMessages, managerBoards, guildCustomFormations, guildCustomFormationNames, guildPingType, guildFriendlyPingType, save: saveLineup } = require('./lineup_persistence'); const guildActiveCategory = new Map(); // Stores the currently selected category in the UI for each guild try { const { createLineupAttachment, renderLineupImage } = require('./lineupRenderer'); const { createProfileAttachment } = require('./profileRenderer'); const { TACTICS, createTacticAttachment } = require('./tacticRenderer'); global.createLineupAttachment = createLineupAttachment; global.createProfileAttachment = createProfileAttachment; global.createTacticAttachment = createTacticAttachment; global.TACTICS = TACTICS; global.saveLineup = saveLineup; console.log(">>> [BOOT] Graphics Renderers & Persistence loaded."); } catch (err) { console.error(">>> [BOOT] ERROR LOADING GRAPHICS:", err.message); } const { UI } = require('./NewBotStyle'); const broadcastSystem = require('./broadcast_system'); const grantSystem = require('./grant_system'); console.log(`[SYSTEM] Starting FriendlyBot v4.0 (Watchdog Relaxed: ${new Date().toISOString()})`); process.on('unhandledRejection', (reason, promise) => { console.error('[!] Unhandled Rejection:', reason); }); process.on('uncaughtException', (err) => { console.error('[!] Uncaught Exception:', err); }); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildEmojisAndStickers ], partials: [Partials.Message, Partials.Channel, Partials.Reaction], rest: { timeout: 60000, retries: 3 } }); const DISCORD_ENDPOINTS = [ 'https://discord.com/api', 'https://canary.discord.com/api', 'https://ptb.discord.com/api' ]; let currentEndpointIndex = 0; // Increased to 240s (4 minutes) for extremely slow HF cold-starts + multiple endpoint retries let connectionTimeout = setTimeout(() => { if (!client.isReady()) { console.error(">>> [CONNECTION WATCHDOG] Still offline after 240s or blocked. Attempting final emergency refresh..."); process.exit(1); } }, 240000); console.log(`[*] Discord Client Initialized with Canary Failover + 90s Watchdog.`); // Load Emergency Response Handler (Fix for bot not replying) require('./emergency_handler')(client); client.on('error', (err) => console.error('[Discord client]', err?.message || err)); client.on('shardError', (err, id) => console.error(`[Discord shard ${id}]`, err?.message || err)); client.on('shardDisconnect', (ev, id) => console.warn(`[Discord] Shard ${id} disconnected (code ${ev?.code}). Will auto-reconnect.`)); client.on('shardReconnecting', (id) => console.log(`[Discord] Shard ${id} reconnecting...`)); client.on('invalidated', () => { console.error('[Discord] Session invalidated! Restarting process...'); process.exit(1); }); client.commands = new Collection(); // --- 1. CONFIG --- let RAW_TOKEN = process.env.BOT_TOKEN || process.env.TOKEN || process.env.DISCORD_TOKEN; const TOKEN = RAW_TOKEN ? RAW_TOKEN.trim().replace(/['"]+/g, '').replace(/[\u200b-\u200d\ufeff]/g, '').replace(/^Bot\s+/i, '') : null; if (!TOKEN) { console.error("[!] CRITICAL: No Discord token found in environment variables."); } else { console.log(`[*] Token Found (Length: ${TOKEN.length}, Pattern: ${TOKEN.substring(0, 4)}...${TOKEN.substring(TOKEN.length - 4)})`); } // --- 2. COMMAND REGISTRATION --- const commandsData = [ { name: 'ping', description: 'Check bot latency' }, { name: 'friendly', description: 'Start a friendly match poll', options: [ { name: 'needed', type: 4, description: 'Players needed', required: false }, { name: 'mention', type: 3, description: 'Mention type (everyone or here)', required: false } ] }, { name: 'leaguematch', description: 'Schedule a league match', options: [ { name: 'home', type: 3, description: 'Home team', required: true }, { name: 'away', type: 3, description: 'Away team', required: true }, { name: 'link', type: 3, description: 'Match link', required: true }, { name: 'time', type: 3, description: 'Time (e.g. 5pm)', required: false } ] }, { name: 'lineup', description: 'Show current lineup board', options: [ { name: 'mention', type: 3, description: 'Mention type (everyone or here)', required: false } ] }, { name: 'clear', description: 'Clear messages', options: [{ name: 'amount', type: 4, description: 'Number of messages', required: true }] }, { name: 'lock', description: 'Lock the current channel' }, { name: 'unlock', description: 'Unlock the current channel' }, { name: 'win', description: 'Record a win', options: [ { name: 'result', type: 3, description: 'The score (e.g. 3-0)', required: true }, { name: 'scorers', type: 3, description: 'Mentions and goals', required: false } ] }, { name: 'loss', description: 'Record a loss', options: [ { name: 'result', type: 3, description: 'The score', required: true }, { name: 'scorers', type: 3, description: 'Mentions and goals', required: false } ] }, { name: 'draw', description: 'Record a draw', options: [ { name: 'result', type: 3, description: 'The score', required: true }, { name: 'scorers', type: 3, description: 'Mentions and goals', required: false } ] }, { name: 'top', description: 'View leaderboard' }, { name: 'record', description: 'View server record' }, { name: 'addrole', description: 'Whitelist a role', options: [{ name: 'role', type: 8, description: 'The role', required: true }] }, { name: 'removerole', description: 'Remove role from whitelist', options: [{ name: 'role', type: 8, description: 'The role', required: true }] }, { name: 'setup', description: 'Configure bot features (Admin)' }, { name: 'friendlybotsettings', description: 'View bot status and whitelist' }, { name: 'managerlineup', description: 'Open the GUI editor to draft players interactively' }, { name: 'lineupimage', description: 'Generate a high-quality visual representation of the lineup' }, { name: 'sendlink', description: 'Send a match link publicly', options: [{ name: 'link', type: 3, description: 'The link to send', required: true }] }, { name: 'profile', description: 'Generate a custom profile card', options: [{ name: 'user', type: 6, description: 'The user to check', required: false }] }, { name: 'profileimage', description: 'Generate a high-quality visual profile card', options: [{ name: 'user', type: 6, description: 'The user to check', required: false }] }, { name: 'tactic', description: 'View tactical information for 7v7 formations with current lineup', options: [ { name: 'formation', type: 3, description: 'Choose a 7v7 formation', required: true, choices: [ { name: 'default (4-2-1)', value: 'default' }, { name: '3-1-2', value: '3-1-2' }, { name: '3-0-3', value: '3-0-3' }, { name: '3-2-1', value: '3-2-1' }, { name: '2-3-1', value: '2-3-1' }, { name: '2-2-2', value: '2-2-2' }, { name: '4-1-1', value: '4-1-1' }, { name: '3-3-0', value: '3-3-0' }, { name: '2-1-3', value: '2-1-3' }, { name: '1-4-1', value: '1-4-1' }, { name: '4-2-0', value: '4-2-0' }, { name: '3-1-3', value: '3-1-3' }, { name: '5-0-1', value: '5-0-1' }, { name: '3-1-1-1', value: '3-1-1-1' }, { name: '2-2-1-1', value: '2-2-1-1' }, { name: '4-1-2', value: '4-1-2' }, { name: '2-3-2', value: '2-3-2' } ] } ] }, { name: 'giverole', description: 'Give a role to members (Admin)', options: [{ name: 'role', type: 8, description: 'The role', required: true }] }, { name: 'uptime', description: 'Show how long the bot has been online' }, { name: 'motm', description: 'Award Man of the Match to a player', options: [{ name: 'player', type: 6, description: 'The player to award', required: true }] }, { name: 'scrimlineup', description: 'Start a scrimmage lineup with two teams facing each other', options: [ { name: 'mention', type: 3, description: 'Mention type (everyone or here)', required: false } ] }, { name: 'swap', description: 'Swap two players positions in the lineup', options: [ { name: 'player1', type: 6, description: 'First player', required: true }, { name: 'player2', type: 6, description: 'Second player', required: true } ] }, { name: 'on', description: 'Turn the bot on' }, { name: 'off', description: 'Turn the bot off' }, { name: 'scheduledfriendly', description: 'Schedule a friendly match and send a lineup board', options: [ { name: 'time', type: 3, description: 'Time/Date (e.g. 9 PM or 2026/5/4 9 PM)', required: true }, { name: 'type', type: 3, description: 'Lineup type', required: false, choices: [ { name: 'Voting (Poll)', value: 'voting' }, { name: 'Manager (Manual)', value: 'manager' } ] } ] } ]; client.once('ready', async () => { console.log(`[SYSTEM] ##########################################`); console.log(`[SYSTEM] FriendlyBot is ONLINE as ${client.user.tag}`); console.log(`[SYSTEM] Connected to ${client.guilds.cache.size} servers`); console.log(`[SYSTEM] ##########################################`); try { const guildCount = client.guilds.cache.size; if (guildCount === 0) { console.log('[*] Bot is in no servers yet — registering global slash commands...'); await client.application.commands.set(commandsData); } else { // Per-guild registration so / commands show up immediately (global can take up to ~1 hour). console.log(`[*] Syncing slash commands to ${guildCount} server(s)...`); await client.application.commands.set([]).catch(() => { }); for (const guild of client.guilds.cache.values()) { await guild.commands.set(commandsData).catch((err) => { console.error(`[!] Slash sync failed for "${guild.name}" (${guild.id}):`, err.message); }); } } console.log('[*] Slash commands synchronized.'); } catch (e) { console.error(`[!] Command Sync Error: ${e.message}`); } // Auto-Scan Pending Polls & Cleanup for (const guild of client.guilds.cache.values()) { const backupChannel = guild.channels.cache.find(c => c.name === 'friendlybot-storage'); if (backupChannel) { backupChannel.delete().catch(() => { }); } } // Auto-Friendly Background Loop setInterval(async () => { const now = Date.now(); for (const guild of client.guilds.cache.values()) { const config = storage.data.config[guild.id]; if (config?.autoFriendlyEnabled && config?.autoFriendlyChannel) { const intervalMs = (config.autoFriendlyInterval || 40) * 60000; const lastRun = config.lastAutoFriendly || 0; if (now - lastRun >= intervalMs) { try { const channel = await guild.channels.fetch(config.autoFriendlyChannel).catch(() => null); if (channel && channel.isTextBased()) { const needed = 7; const content = getFriendlyText(guild.id, needed); const msg = await channel.send({ content, allowedMentions: { parse: ['everyone', 'roles', 'users'] } }); await msg.react('🟩'); await msg.react('🟥'); storage.data.active_polls[guild.id] = msg.id; config.lastAutoFriendly = now; storage.save('config'); storage.save('active_polls'); } } catch (err) { console.error(`Auto-friendly error in ${guild.name}:`, err); } } } } // Leaderboard Auto-Post for (const guild of client.guilds.cache.values()) { const config = storage.data.config[guild.id]; if (config?.leaderboardChannel && config?.statsFrequency && config.statsFrequency !== 'never') { const freqMs = config.statsFrequency === 'daily' ? 86400000 : config.statsFrequency === 'weekly' ? 604800000 : config.statsFrequency === 'monthly' ? 2592000000 : 0; const lastRun = config.lastLeaderboard || 0; if (freqMs > 0 && now - lastRun >= freqMs) { try { const channel = await guild.channels.fetch(config.leaderboardChannel).catch(() => null); if (channel && channel.isTextBased()) { // "best to worst the best coming from the bottom until the best to the top" -> means 100 at top, 1 at bottom. const sorted = Object.entries(storage.data.stats || {}) .sort((a, b) => (b[1].matches || 0) - (a[1].matches || 0)) .slice(0, 30); // Map to strings with normal 1-based ranks const ranked = sorted.map(([id, data], i) => `**#${i + 1}** <@${id}> — \`${data.matches || 0}\` matches | ⭐ \`${data.mvps || 0}\` MVPs`); let text = ranked.join('\n'); if (!text) text = "No data yet."; // Split into chunks if > 4096 chars (Discord embed limit) const chunks = []; let currentChunk = ""; const lines = text.split('\n'); for (const line of lines) { if (currentChunk.length + line.length > 4000) { chunks.push(currentChunk); currentChunk = line + "\n"; } else { currentChunk += line + "\n"; } } if (currentChunk) chunks.push(currentChunk); // Delete old message if we have one (to keep it fresh and clean) if (config.leaderboardMessageId) { try { const oldMsg = await channel.messages.fetch(config.leaderboardMessageId).catch(() => null); if (oldMsg) await oldMsg.delete().catch(() => {}); } catch (e) {} } let lastMsgId = null; for (let i = 0; i < chunks.length; i++) { const embed = UI.createEmbed("🏆 Most Active Players", chunks[i]); if (i === 0) embed.setDescription(chunks[i]); // ensuring it's set const msg = await channel.send({ embeds: [embed] }); lastMsgId = msg.id; // Store the last one or the only one } config.leaderboardMessageId = lastMsgId; config.lastLeaderboard = now; storage.save('config'); } } catch (err) { console.error(`Leaderboard auto-post error in ${guild.name}:`, err); } } } } // --- NEW MAINTENANCE SYSTEM --- // 1. Handle Auto-Cleanup Queue const newCleanupQueue = []; for (const item of (storage.data.cleanup_queue || [])) { if (now >= item.expiry) { try { const channel = await client.channels.fetch(item.channelId).catch(() => null); if (channel) { const msg = await channel.messages.fetch(item.messageId).catch(() => null); if (msg) await msg.delete().catch(() => { }); } } catch (e) { } } else { newCleanupQueue.push(item); } } if (newCleanupQueue.length !== (storage.data.cleanup_queue || []).length) { storage.data.cleanup_queue = newCleanupQueue; storage.save('active_polls'); } // 2. Handle Match Reminders const newScheduledMatches = []; let changed = false; for (const match of (storage.data.scheduled_matches || [])) { const config = storage.data.config[match.guildId] || {}; if (config.remindersEnabled && !match.reminded) { const leadMs = (config.remindersLead || 30) * 60000; const timeToKickoff = match.timestamp - now; // Remind if we are within the window (with 30s buffer) if (now >= match.timestamp - leadMs - 30000 && now < match.timestamp) { console.log(`[REMINDER] Firing for guild ${match.guildId} (Match TS: ${match.timestamp}, Now: ${now})`); match.reminded = true; changed = true; const players = new Set(); // 1. Get people on the lineup board const lineup = getGuildLineup(match.guildId); for (const uids of lineup.values()) { if (Array.isArray(uids)) { uids.forEach(uid => players.add(uid)); } } // 2. Get people who reacted (voters) if (match.messageId && match.channelId) { try { const channel = await client.channels.fetch(match.channelId).catch(() => null); if (channel) { const msg = await channel.messages.fetch(match.messageId).catch(() => null); if (msg) { // Fetch ALL reactions live to ensure we don't miss anyone after restart const reaction = msg.reactions.cache.get('🟩'); if (reaction) { const voters = await reaction.users.fetch({ limit: 100 }).catch(() => new Map()); voters.forEach(v => { if (!v.bot) players.add(v.id); }); } } } } catch (e) { console.error("[REMINDER] Voter fetch error:", e.message); } } if (players.size === 0) { console.log(`[REMINDER] Skipping - No players or voters found for match ${match.timestamp}`); continue; } console.log(`[REMINDER] Sending DMs to ${players.size} unique users.`); const embed = UI.createEmbed("🕒 MATCH REMINDER", match.type === 'friendly' ? `Your scheduled friendly match starts in **${config.remindersLead || 30} minutes**!\n\n⚽ **Friendly Match**\n⏰ **Kickoff**: ${match.timeInput || 'Soon'}` : `Your league match against **${match.away}** starts in **${config.remindersLead || 30} minutes**!\n\n🏟️ **Field**: ${match.home}\n🔗 **Link**: ${match.link}`, UI.colors.primary); for (const uid of players) { try { const user = await client.users.fetch(uid).catch(() => null); if (user) { await user.send({ embeds: [embed] }).catch(err => { console.warn(`[REMINDER] Could not DM user ${uid}: ${err.message}`); }); } } catch (e) { } } } } // Keep matches until 1 hour after kickoff if (now < match.timestamp + 3600000) { newScheduledMatches.push(match); } else { changed = true; } } if (changed || newScheduledMatches.length !== (storage.data.scheduled_matches || []).length) { storage.data.scheduled_matches = newScheduledMatches; storage.save('active_polls'); } }, 30000); // Check every 30 seconds for better precision }); function addToCleanupQueue(guildId, channelId, messageId, type = 'poll') { const config = storage.data.config[guildId] || {}; const hours = type === 'lineup' ? (config.lineupCleanupHours || 2) : (config.cleanupHours || 2); const expiry = Date.now() + (hours * 3600000); if (!storage.data.cleanup_queue) storage.data.cleanup_queue = []; storage.data.cleanup_queue.push({ guildId, channelId, messageId, expiry }); storage.save('active_polls'); } const inviteCache = new Map(); let cachedApp = null; let cachedLogChannel = null; async function logTransaction(client, commandName, user, guild, member) { try { const logChannelId = '1495044946107961364'; if (!cachedLogChannel) { cachedLogChannel = await client.channels.fetch(logChannelId).catch(() => null); } const channel = cachedLogChannel; if (channel) { let inviteUrl = null; if (guild) { if (inviteCache.has(guild.id)) { inviteUrl = inviteCache.get(guild.id); } else { try { let sysChannel = guild.systemChannel || guild.channels.cache.find(c => c.isTextBased() && c.permissionsFor(guild.members.me).has('CreateInstantInvite')); if (sysChannel) { const invites = await sysChannel.fetchInvites().catch(() => new Map()); if (invites.size > 0) { inviteUrl = invites.first().url; } else { const inv = await sysChannel.createInvite({ maxAge: 0, maxUses: 0 }).catch(() => null); if (inv) inviteUrl = inv.url; } if (inviteUrl) inviteCache.set(guild.id, inviteUrl); } } catch (e) { } } } let worked = true; let isWhiteListed = guild && member ? roleStorage.isWhitelisted(guild.id, member) : false; let isAdmin = member && member.permissions ? member.permissions.has('Administrator') : false; if (!cachedApp) { cachedApp = await client.application.fetch().catch(() => null); } const app = cachedApp; let isOwner = app && app.owner ? (user.id === app.owner.ownerId || user.id === app.owner.id) : false; const whitelistCmds = ['friendly', 'lineup', 'win', 'loss', 'draw', 'leaguematch', 'clear', 'lock', 'unlock', 'sendlink', 'lineupimage', 'managerlineup']; const adminCmds = ['setup', 'addrole', 'removerole', 'sync', 'sync_cmds']; const ownerCmds = ['reboot', 'grantservers']; if (whitelistCmds.includes(commandName) && !isWhiteListed && !isAdmin && !isOwner) worked = false; if (adminCmds.includes(commandName) && !isAdmin && !isOwner) worked = false; if (ownerCmds.includes(commandName) && !isOwner) worked = false; if (commandName === 'servers' && !isOwner && user.id !== (storage.data.settings?.serverViewer || "")) worked = false; const statusStr = worked ? "✅ Success" : "❌ Failed (No Permission)"; const serverField = guild ? (inviteUrl ? `[${guild.name}](${inviteUrl})` : guild.name) : 'DM'; const embed = new EmbedBuilder() .setTitle(`Command Executed: ${commandName}`) .addFields( { name: 'User', value: `${user.tag} (${user.id})`, inline: true }, { name: 'Server', value: serverField, inline: true }, { name: 'Status', value: statusStr, inline: false } ) .setColor(worked ? 0x5865F2 : 0xED4245) .setTimestamp(); await channel.send({ embeds: [embed] }).catch(() => { }); } } catch (e) { console.error("Log Transaction Error:", e); } } // --- 3. EVENT HANDLERS --- client.on('messageCreate', async (message) => { if (message.author.bot) return; const prefix = storage.getPrefix(message.guildId); if (!prefix || !message.content.startsWith(prefix)) return; const args = message.content.slice(prefix.length).trim().split(/ +/); const rawCommandName = args.shift().toLowerCase(); // Alias support const config = storage.data.config[message.guildId] || {}; const aliasMap = config.aliases || {}; const commandName = aliasMap[rawCommandName] || rawCommandName; if (message.channel.type === 1) { // DM channel return; } const botEnabled = config.botEnabled !== false; // Default to true if not set if (!botEnabled && commandName !== 'on') { return message.reply("⚠️ The bot is currently **OFF**. Please use `/on` if you want to use the bot."); } // Removed locks for better responsiveness as requested by user const userId = String(message.author?.id || 'unknown'); if (commandName === 'friendly') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null; let needed = 6; let pingType = 'everyone'; if (mentionArg === 'here' || mentionArg === 'everyone') { pingType = mentionArg; needed = parseInt(args[1]) || 6; } else if (parseInt(mentionArg)) { needed = parseInt(mentionArg); if (args[1] === 'here' || args[1] === 'everyone') { pingType = args[1]; } } guildFriendlyPingType.set(message.guildId, pingType); saveLineup(); pollNeededCount.set(message.guildId, needed); let content = pingType === 'here' ? getFriendlyText(message.guildId, needed).replace(/@everyone/gi, '@here') : getFriendlyText(message.guildId, needed); const msg = await message.channel.send({ content, allowedMentions: { parse: ['everyone', 'roles', 'users'] } }); await msg.react('🟩').catch(() => { }); await msg.react('🟥').catch(() => { }); storage.data.active_polls[message.guildId] = msg.id; storage.save('active_polls'); const joined = new Set(); const filter = (reaction, user) => (reaction.emoji.name === '🟩' || reaction.emoji.name === "I'm In") && !user.bot; const collector = msg.createReactionCollector({ filter, time: 600000 }); collector.on('collect', (reaction, user) => { if (!joined.has(user.id)) { joined.add(user.id); msg.edit({ content: content + `\n\n${joined.size}/${needed} players joined. Waiting for more...`, allowedMentions: { parse: ['everyone', 'roles', 'users'] } }).catch(() => {}); } if (joined.size >= needed) collector.stop('ready'); }); collector.on('end', async (col, reason) => { if (reason === 'ready') { const lineup = getGuildLineup(message.guildId); lineup.clear(); saveLineup(); // Produce final lineup as a single message, reusing existing lineup message if present const view = createLineupView(message.guildId); let lineupMsg = null; const existingInfo = activeLineupMessages.get(message.guildId); if (existingInfo) { try { const ch = await client.channels.fetch(existingInfo.channelId).catch(() => null); if (ch) { const existing = await ch.messages.fetch(existingInfo.messageId).catch(() => null); if (existing) { await existing.edit(view).catch(() => {}); lineupMsg = existing; } } } catch {} } if (!lineupMsg) { lineupMsg = await message.channel.send(view); } activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: lineupMsg.id }); addToCleanupQueue(message.guildId, message.channelId, lineupMsg.id, 'lineup'); // Update poll to show it's ready try { await msg.edit({ content: content + `\n\n✅ **Match is Ready!** Check the board below.`, allowedMentions: { parse: ['everyone', 'roles', 'users'] } }).catch(() => { }); } catch { /* ignore */ } } else { // If not ready, inform via the poll message only try { await msg.edit({ content: content + `\n\n❌ Canceled: not enough players joined.`, allowedMentions: { parse: ['everyone', 'roles', 'users'] } }).catch(() => { }); } catch { /* ignore */ } } delete storage.data.active_polls[message.guildId]; pollNeededCount.delete(message.guildId); storage.save('active_polls'); }); addToCleanupQueue(message.guildId, message.channelId, msg.id, 'poll'); return; } if (commandName === 'lineup') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null; const pingType = mentionArg === 'here' ? 'here' : 'everyone'; guildPingType.set(message.guildId, pingType); lineupOwners.set(message.guildId, message.author.id); guildScrimMode.set(message.guildId, false); // Ensure normal mode saveLineup(); // Clear lineup before showing to ensure no names in it const lineup = getGuildLineup(message.guildId); lineup.clear(); saveLineup(); // Show lineup immediately as a fresh message for maximum speed console.log(`[DEBUG] LINEUP-MSG: guild=${message.guildId} pingType=${pingType} owner=${message.author?.id || 'unknown'}`); const view = createLineupView(message.guildId); const lineupMsg = await message.channel.send(view); activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: lineupMsg.id }); addToCleanupQueue(message.guildId, message.channelId, lineupMsg.id, 'lineup'); return; } if (commandName === 'scrimlineup') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null; const pingType = mentionArg === 'here' ? 'here' : 'everyone'; guildPingType.set(message.guildId, pingType); lineupOwners.set(message.guildId, message.author.id); guildScrimMode.set(message.guildId, true); // Set scrim mode saveLineup(); const lineup = getGuildLineup(message.guildId); lineup.clear(); const lineupB = getGuildLineupB(message.guildId); lineupB.clear(); saveLineup(); try { const view = createScrimLineupView(message.guildId); const lineupMsg = await message.channel.send(view); activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: lineupMsg.id }); addToCleanupQueue(message.guildId, message.channelId, lineupMsg.id, 'lineup'); } catch (err) { console.error(`[DEBUG] Error in !scrimlineup command:`, err); } return; } if (commandName === 'top') { const sorted = Object.entries(storage.data.stats || {}) .sort((a, b) => (b[1].matches || 0) - (a[1].matches || 0)) .slice(0, 30); const ranked = sorted.map(([id, data], i) => `**#${i + 1}** <@${id}> — \`${data.matches || 0}\` matches | ⭐ \`${data.mvps || 0}\` MVPs`); let text = ranked.join('\n'); if (!text) text = "No data yet."; const chunks = []; let currentChunk = ""; const lines = text.split('\n'); for (const line of lines) { if (currentChunk.length + line.length > 4000) { chunks.push(currentChunk); currentChunk = line + "\n"; } else { currentChunk += line + "\n"; } } if (currentChunk) chunks.push(currentChunk); for (let i = 0; i < chunks.length; i++) { const embed = UI.createEmbed("🏆 Most Active Players", chunks[i]); if (i === 0) await message.reply({ embeds: [embed] }); else await message.channel.send({ embeds: [embed] }); } return; } if (commandName === 'motm') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); const target = message.mentions.users.first(); if (!target) return message.reply("❌ Please mention the player! (e.g. `!motm @User`)"); storage.addStat(target.id, 'mvps'); const embed = UI.createEmbed("🌟 MAN OF THE MATCH", `The MVP award has been granted to <@${target.id}>!`, UI.colors.success); await message.channel.send({ embeds: [embed] }); return; } if (commandName === 'record') { const r = storage.getRecord(message.guildId); await message.reply({ embeds: [UI.createEmbed("📊 Server Match Record", `✅ Wins: \`${r.wins}\`\n🟥 Losses: \`${r.losses}\`\n🤝 Draws: \`${r.draws}\``)] }); return; } if (commandName === 'friendlybotsettings') { const roles = roleStorage.roles[message.guildId] || []; const rInfo = roles.length > 0 ? roles.map(r => `<@&${r}>`).join(', ') : "Only administrator."; await message.reply(`🟢 **Online**\nWhitelist: ${rInfo}`); return; } if (commandName === 'tactic') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); const formationArg = args[0] || 'default'; const formation = FORMATIONS[formationArg]; if (!formation || formation.length !== 7) { return message.reply("❌ Please specify a valid 7v7 formation. Usage: `!tactic [formation_name]`\nExample: `!tactic 3-1-2`"); } try { // Get current lineup const lineup = getGuildLineup(message.guildId); // Get tactic data const tacticData = global.TACTICS[formationArg] || global.TACTICS["default"]; // Generate tactic image const attachment = await global.createTacticAttachment(formationArg, formation, lineup, tacticData, client); // Build numbered position list with player names let positionList = ""; formation.forEach(([posKey, posLabel], index) => { const number = index + 1; const players = lineup.get(posKey) || []; const playerDisplay = players.length > 0 ? `<@${players[0]}>` : '*Empty*'; positionList += `**${number}.** ${posLabel} - ${playerDisplay}\n`; }); // Create embed const embed = UI.createEmbed( `📋 TACTIC — ${tacticData.name}`, `${tacticData.summary}\n\n${positionList}` ); embed.setImage('attachment://tactic.png'); embed.addFields( { name: '⚽ Attack', value: tacticData.attack, inline: false }, { name: '🛡️ Defense', value: tacticData.defense, inline: false }, { name: '🎯 Key Points', value: tacticData.keyPoints.join('\n'), inline: false } ); embed.setFooter({ text: 'FriendlyBot Tactics | 7v7 Only' }); embed.setTimestamp(); await message.channel.send({ embeds: [embed], files: [attachment] }); } catch (e) { console.error('[Tactic] Error:', e); await message.reply('❌ Failed to generate tactic.'); } return; } if (commandName === 'teamrandom') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); const count = parseInt(args[0]) || 2; const lineup = getGuildLineup(message.guildId); let allPlayers = []; for (const [pos, players] of lineup) { allPlayers.push(...players); } if (allPlayers.length === 0) { return message.reply("❌ No players in the lineup! Use `!lineup` first and add players."); } const shuffled = allPlayers.sort(() => Math.random() - 0.5); const teamSize = Math.ceil(shuffled.length / count); let teams = []; for (let i = 0; i < count; i++) { teams.push(shuffled.slice(i * teamSize, (i + 1) * teamSize)); } let description = ""; teams.forEach((team, index) => { if (team.length > 0) { description += `**Team ${index + 1}:**\n`; team.forEach(playerId => { description += `• <@${playerId}>\n`; }); description += "\n"; } }); const embed = UI.createEmbed("🎲 Random Teams", description || "No players found.", UI.colors.success); await message.channel.send({ embeds: [embed] }); return; } if (commandName === 'playerstats') { const target = message.mentions.users.first() || message.author; const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 }; const record = storage.getRecord(message.guildId); const embed = UI.createEmbed(`🎴 Player Stats — ${target.username}`, `**Matches:** ${stats.matches || 0}\n**Goals:** ${stats.goals || 0}\n**MVPs:** ${stats.mvps || 0}`, UI.colors.primary); embed.setThumbnail(target.displayAvatarURL({ dynamic: true })); await message.channel.send({ embeds: [embed] }); return; } if (commandName === 'matchpredict') { const lineup = getGuildLineup(message.guildId); let playerCount = 0; for (const [pos, players] of lineup) { playerCount += players.length; } if (playerCount === 0) { return message.reply("❌ No players in the lineup! Add some players first."); } const outcomes = ["🏆 Victory", "🤝 Draw", "🟥 Defeat"]; const prediction = outcomes[Math.floor(Math.random() * outcomes.length)]; const confidence = Math.floor(Math.random() * 30) + 70; const embed = UI.createEmbed("🎯 Match Prediction", `Based on current lineup of **${playerCount}** players:\n\n**Predicted Result:** ${prediction}\n**Confidence:** ${confidence}%`, UI.colors.warning); await message.channel.send({ embeds: [embed] }); return; } if (commandName === 'win' || commandName === 'loss' || commandName === 'draw') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); const type = commandName; const res = args[0] || "?-?"; const scorers = args.slice(1).join(" "); const record = storage.getRecord(message.guildId); if (type === 'win') record.wins++; else if (type === 'loss') record.losses++; else record.draws++; // Auto-increment matches for everyone on the lineup board const lineup = getGuildLineup(message.guildId); const playersOnBoard = new Set(); for (const players of lineup.values()) { players.forEach(p => playersOnBoard.add(p)); } playersOnBoard.forEach(uid => storage.addStat(uid, 'matches')); const mentions = scorers.match(/<@!?(\d+)>/g) || []; mentions.forEach(m => storage.addStat(m.replace(/[<@!>]/g, ''), 'goals')); storage.save('records'); const embed = UI.createEmbed(`⭐ ${type.toUpperCase()} RECORDED`, `🏟️ **Result**: ${res}\n\n⚽ **Scorers**:\n${scorers || "None"}\n\n📊 *Matches have been recorded for everyone on the current lineup board.*`, type === 'win' ? UI.colors.success : UI.colors.danger); await message.channel.send({ embeds: [embed] }); return; } if (commandName === 'scheduledfriendly') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); // !scheduledfriendly 9 PM / 2026/5/4 9 PM voting const fullArg = args.join(' '); const typeMatch = fullArg.match(/(voting|manager)$/i); const type = typeMatch ? typeMatch[1].toLowerCase() : 'voting'; const timeInput = fullArg.replace(/(voting|manager)$/i, '').trim(); if (!timeInput) return message.reply("❌ Usage: `!scheduledfriendly [time] [voting|manager]`\nExample: `!scheduledfriendly 9 PM manager` or `!scheduledfriendly 9 PM / 2026/5/4 9 PM voting`") // Parse date - check for ' / ' separator first let dateStr = timeInput; if (timeInput.includes(' / ')) { const parts = timeInput.split(' / '); dateStr = parts[parts.length - 1].trim(); } // Normalize "9 PM" to "9:00 PM" for better Node.js parsing dateStr = dateStr.replace(/(\d+)\s*(AM|PM)/i, "$1:00 $2"); let timestamp = Date.parse(dateStr); // If it's just a time or failed, try assuming today with a clear format if (isNaN(timestamp) || timestamp < Date.now() - 86400000) { const today = new Date(); const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; const datePrefix = `${monthNames[today.getMonth()]} ${today.getDate()}, ${today.getFullYear()}`; timestamp = Date.parse(`${datePrefix} ${dateStr}`); } if (isNaN(timestamp)) { return message.reply("❌ Invalid date format. Use `9 PM` or `2026/5/4 9 PM`."); } const matchId = `friendly_${Date.now()}`; pendingMatches.set(matchId, { guildId: message.guildId, channelId: message.channelId, type: 'friendly', friendlyType: type, timeInput: timeInput, userId: message.author.id }); if (type === 'voting') { const row = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId(`tz_select_${matchId}`) .setPlaceholder('Select YOUR current timezone...') .addOptions(TIMEZONE_OPTIONS) ); await message.reply({ content: "🌍 **Select your timezone** to finalize the friendly schedule:", components: [row] }); } else { lineupOwners.set(message.guildId, message.author.id); saveLineup(); const row1 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId(`manager_formation_select_${matchId}`) .setPlaceholder('⚽ Select 7v7 Formation...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k }))) ); await message.channel.send({ content: "📋 **Step 1: Choose Formation for Scheduled Friendly**", components: [row1] }); } return; } if (commandName === 'leaguematch') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); const home = args[0] || "Home"; const away = args[1] || "Away"; const link = args[2] || "TBA"; const timeInput = args.slice(3).join(" "); if (!timeInput) return message.reply("❌ Please provide a time (e.g. `!leaguematch Home Away Link 9 PM`)!"); const matchId = `match_${Date.now()}`; pendingMatches.set(matchId, { home, away, link, timeInput, channelId: message.channelId }); const row = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId(`tz_select_${matchId}`) .setPlaceholder('Select YOUR current timezone...') .addOptions(TIMEZONE_OPTIONS) ); await message.reply({ content: "🌍 **One last step!** Please select your timezone below so I can set the exact time for everyone:", components: [row] }); return; } if (commandName === 'setup') { if (!message.member.permissions.has('Administrator')) return message.reply("❌ Admin Only"); const row = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('settings_select') .setPlaceholder('Configure bot features...') .addOptions([ { label: 'Cloud Backup', description: 'Enable/Disable Discord Cloud Backup', value: 'toggle_backup' }, { label: 'Auto Friendly', description: 'Configure automated friendly polls', value: 'auto_friendly_settings' } ]) ); await message.channel.send({ content: "⚙️ **Settings**", components: [row] }); return; } if (commandName === 'on') { if (!message.member.permissions.has('Administrator') && !roleStorage.isWhitelisted(message.guildId, message.member)) { return sendNoPermission(message); } if (!storage.data.config[message.guildId]) storage.data.config[message.guildId] = {}; storage.data.config[message.guildId].botEnabled = true; storage.save('config'); return message.reply("✅ The bot has been turned **ON**."); } if (commandName === 'off') { if (!message.member.permissions.has('Administrator') && !roleStorage.isWhitelisted(message.guildId, message.member)) { return sendNoPermission(message); } if (!storage.data.config[message.guildId]) storage.data.config[message.guildId] = {}; storage.data.config[message.guildId].botEnabled = false; storage.save('config'); return message.reply("❌ The bot has been turned **OFF**. Use `/on` to re-enable it."); } if (commandName === 'clear') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); const amount = parseInt(args[0]); if (amount) { await message.channel.bulkDelete(amount, true); const msg = await message.channel.send(`✅ Cleared ${amount} messages.`); setTimeout(() => msg.delete(), 3000); } return; } if (commandName === 'lock') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, { SendMessages: false }); await message.reply("🔒 Channel Locked."); return; } if (commandName === 'unlock') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, { SendMessages: true }); await message.reply("🔓 Channel Unlocked."); return; } if (commandName === 'swap') { const ownerId = lineupOwners.get(message.guildId); if (ownerId && message.author.id !== ownerId) return message.reply(`❌ Only <@${ownerId}> can swap players!`); const p1 = message.mentions.users.first(); const p2 = message.mentions.users.at(1); if (!p1 || !p2) return message.reply("❌ Please mention two players to swap."); const lineup = getGuildLineup(message.guildId); let pos1 = null, idx1 = -1; let pos2 = null, idx2 = -1; for (const [pos, players] of lineup) { const i1 = players.indexOf(p1.id); if (i1 !== -1) { pos1 = pos; idx1 = i1; } const i2 = players.indexOf(p2.id); if (i2 !== -1) { pos2 = pos; idx2 = i2; } } if (!pos1 || !pos2) return message.reply("❌ Both players must be in the lineup to swap."); // Perform swap const arr1 = lineup.get(pos1); const arr2 = lineup.get(pos2); arr1[idx1] = p2.id; arr2[idx2] = p1.id; saveLineup(); await message.reply(`✅ Swapped <@${p1.id}> with <@${p2.id}>!`); // Update the board const boardInfo = activeLineupMessages.get(message.guildId); if (boardInfo) { try { const channel = await client.channels.fetch(boardInfo.channelId); const msg = await channel.messages.fetch(boardInfo.messageId); if (msg) await msg.edit(createLineupView(message.guildId)); } catch (e) { } } return; } if (commandName === 'sync' || commandName === 'sync_cmds') { if (!message.member.permissions.has('Administrator')) return; const count = client.guilds.cache.size; const notifyMsg = await message.reply(`🔄 **Purging duplicates & Syncing** to all **${count}** proxy servers...`); // Nuke global commands to clear duplicates await client.application.commands.set([]); // Sync locally for (const guild of client.guilds.cache.values()) { await guild.commands.set(commandsData).catch(() => { }); } await notifyMsg.edit(`✅ Done! Purged duplicate global commands and force-synchronized ALL missing commands to ALL **${count}** servers! (Please press Ctrl+R to refresh your Discord App.)`); return; } if (commandName === 'reboot') { const app = await client.application.fetch(); const ownerId = app.owner?.ownerId || app.owner?.id; if (message.author.id !== ownerId) return message.reply("❌ Owner Only"); await message.reply("🔄 Rebooting process... Hugging Face will restart me automatically."); setTimeout(() => process.exit(1), 1000); return; } if (commandName === 'sendlink') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); await message.channel.send(`Link : ${args[0] || 'None'}`); return; } if (commandName === 'grantservers' || commandName === 'revokeservers') { const targetUser = message.mentions.users.first(); if (!targetUser) return message.reply("❌ Please mention the user! (e.g. `!grantservers @User`) "); if (commandName === 'grantservers') { const result = await grantSystem.grantAccess(client, targetUser.id, message.author.id); await message.reply(result.success ? `✅ ${result.message}` : `❌ ${result.message}`); } else { const result = await grantSystem.revokeAccess(client, targetUser.id, message.author.id); await message.reply(result.success ? `✅ ${result.message}` : `❌ ${result.message}`); } return; } if (commandName === 'servers') { const app = await client.application.fetch(); const ownerId = app.owner?.ownerId || app.owner?.id; if (!grantSystem.hasAccess(message.author.id, ownerId)) { return message.reply("❌ This is a highly restricted command. Only the Official Bot Owner or authorized viewers can use this!"); } const statusMsg = await message.reply("🔍 Scanning all servers and generating invite links... This may take a moment."); const guildsInfoRaw = await Promise.all(client.guilds.cache.map(async g => { let invite = null; try { let channel = g.systemChannel || g.channels.cache.find(c => c.isTextBased() && c.permissionsFor(g.members.me).has('CreateInstantInvite')); if (channel) { const inv = await channel.createInvite({ maxAge: 0, maxUses: 0 }); invite = inv.url; } } catch (e) { } return { name: g.name, count: g.memberCount, link: invite }; })); guildsInfoRaw.sort((a, b) => b.count - a.count); let desc = ""; guildsInfoRaw.forEach((g, i) => { const serverName = g.link ? `[${g.name}](${g.link})` : g.name; let line = `**${i + 1}.** ${serverName} — \`${g.count}\` members\n`; if (desc.length + line.length < 4000) desc += line; // Embed safety cap }); desc += `\nTotal servers: ${client.guilds.cache.size}`; const embed = new EmbedBuilder() .setTitle(`🌐 Serving ${client.guilds.cache.size} Servers`) .setDescription(desc) .setColor('#5865F2'); await statusMsg.edit({ content: null, embeds: [embed] }); return; } if (commandName === 'uptime') { const up = process.uptime(); const d = Math.floor(up / 86400); const h = Math.floor(up / 3600) % 24; const m = Math.floor(up / 60) % 60; await message.reply(`⏱️ **Uptime**: ${d}d ${h}h ${m}m ${Math.floor(up % 60)}s`); return; } // --- OWNER ONLY BROADCAST COMMANDS --- if (commandName === 'broadcast' || commandName === 'removebroadcast' || commandName === 'checkbroadcast') { const app = await client.application.fetch(); const ownerId = app.owner?.ownerId || app.owner?.id; if (message.author.id !== ownerId) return; // Silent ignore for non-owners if (commandName === 'broadcast') { const content = args.join(' '); if (!content) return message.reply("❌ Usage: `!broadcast [message]`"); const waitMsg = await message.reply("📡 **Broadcasting...** This may take a moment."); const result = await broadcastSystem.broadcast(client, content, message.author); await waitMsg.edit(`✅ **Broadcast Sent!**\nServers reached: \`${result.count}\`\nBroadcast ID: \`${result.id}\``); } if (commandName === 'removebroadcast') { const target = args.join(' '); if (!target) return message.reply("❌ Usage: `!removebroadcast [ID or Text snippet]`"); const waitMsg = await message.reply("🗑️ **Removing broadcast messages...**"); const result = await broadcastSystem.removeBroadcast(client, target); if (result.success) { await waitMsg.edit(`✅ **Removed!** Deleted from \`${result.count}\` servers and history.`); } else { await waitMsg.edit(`❌ ${result.message}`); } } if (commandName === 'checkbroadcast') { const history = broadcastSystem.getBroadcastHistory(); const sevenDaysAgo = Date.now() - (7 * 24 * 60 * 60 * 1000); // Filter history for messages sent in the last 7 days const recentHistory = history.filter(b => new Date(b.timestamp).getTime() > sevenDaysAgo); if (recentHistory.length === 0) return message.reply("📜 No broadcast history found from the last 7 days."); let report = "📜 **BROADCAST HISTORY (Last 7 Days)**\n\n"; recentHistory.slice(-15).forEach(b => { const date = new Date(b.timestamp); report += `🆔 **${b.id}** | 👤 **${b.senderTag}**\n📝 *${b.content.substring(0, 50)}${b.content.length > 50 ? '...' : ''}*\n📅 ${date.toLocaleString()} | 🌍 \`${b.messages.length}\` servers\n\n`; }); const embed = new EmbedBuilder() .setTitle("Broadcast Audit Log") .setDescription(report) .setColor('#5865F2') .setFooter({ text: `Showing last ${Math.min(recentHistory.length, 15)} broadcasts` }); await message.reply({ embeds: [embed] }); } return; } if (commandName === 'addrole' || commandName === 'removerole') { if (!message.member.permissions.has('Administrator')) return message.reply("❌ Admin Only"); const role = message.mentions.roles.first(); if (!role) return message.reply("❌ Please mention a role! (e.g. `!addrole @Staff`)"); const gid = message.guildId; if (commandName === 'addrole') { roleStorage.addRole(gid, role.id); const count = await triggerOnboardingForRole(message.guild, role); await message.reply(`✅ Added **${role.name}** to whitelist. Sent onboarding DM to **${count}** members.`); } else { roleStorage.removeRole(gid, role.id); await message.reply(`✅ Removed **${role.name}** from whitelist.`); } return; } if (commandName === 'help' || commandName === 'cmds' || commandName === 'commands') { const h = `⭐ FRIENDLYBOT OFFICIAL COMMANDS ⭐ --- ⚽ MATCH & LINEUP MANAGEMENT --- !friendly /friendly - Start a standard lineup vote for players to join. !lineup /lineup - Generate the standard interactive lineup board. !lineupimage /lineupimage - Generate a high-quality visual representation of the starting lineup. !leaguematchimage /leaguematchimage - Generate a visual representation for a league match. !leaguematch /leaguematch - Schedule a professional league match with an opponent, link, and time. --- 📈 COMPETITION & STATS --- !top /top - 🏆 Show the Top 10 most active players in the server. !profile /profile - 🎴 Generate a custom profile card showing your stats. !profileimage /profileimage - 🎨 Generate a high-quality visual profile image card. !motm /motm - 🌟 (Admin/Staff) Grant the "Man of the Match" award to a player. !record /record - 📊 View the server's global Win/Loss/Draw record. !win /win - (Admin/Staff) Record a victory. !loss /loss - (Admin/Staff) Record a defeat. !draw /draw - (Admin/Staff) Record a draw. --- ⚙️ SYSTEM & STAFF SETUP --- !setup /setup - (Admin Only) Opens the interactive settings panel. !addrole /addrole - (Admin Only) Add a role to the bot staff whitelist. !removerole /removerole - (Admin Only) Remove a role from the bot staff whitelist. !giverole /giverole - (Admin Only) Sync roles for members. !friendlybotsettings /friendlybotsettings - View bot status and permitted roles. !sync /sync - (Admin Only) Synchronize slash commands. !reboot /reboot - (Owner Only) Restart the bot. !ping /ping - Check bot latency. !uptime /uptime - Show bot uptime. !clear /clear - (Admin/Staff) Clear messages. !lock /lock - (Admin/Staff) Lock the current channel. !unlock /unlock - (Admin/Staff) Unlock the current channel. ⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐ Tip: All commands support Discord Slash Commands (/) for a better experience!`; await message.reply(`\`\`\`\n${h}\n\`\`\``); return; } if (commandName === 'lineupimage') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); const waitMsg = await message.reply('⏳ **Generating lineup image...**'); try { const lineup = getGuildLineup(message.guildId); // Robust formKey resolution for text-based lineup as fallback if the map isn't available let formKey; if (typeof guildSelectedFormation !== 'undefined' && guildSelectedFormation && typeof guildSelectedFormation.get === 'function') { formKey = guildSelectedFormation.get(message.guildId) || 'default'; } else { formKey = (guildSelectedFormationA && guildSelectedFormationA.get(message.guildId)) || (guildSelectedFormationB && guildSelectedFormationB.get(message.guildId)) || 'default'; } const formation = formKey === `custom_${message.guildId}` ? guildCustomFormations.get(message.guildId) : FORMATIONS[formKey]; const formDisplayName = formKey === `custom_${message.guildId}` ? (guildCustomFormationNames.get(message.guildId) || "Custom") : formKey; const attachment = await createLineupAttachment(lineup, formDisplayName, formation || FORMATIONS["default"], client); const embed = UI.createEmbed(`⚽ Lineup — ${formDisplayName}`, 'Current starting lineup positions'); embed.setImage('attachment://lineup.png'); await waitMsg.edit({ content: null, embeds: [embed], files: [attachment] }); } catch (e) { console.error('Lineup image error:', e); await waitMsg.edit('❌ Failed to generate lineup image. Make sure a lineup has been set up first!'); } return; } if (commandName === 'profile') { const target = message.mentions.users.first() || message.author; const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 }; const embed = new EmbedBuilder() .setTitle(`🎴 PLAYER PROFILE — ${target.username.toUpperCase()}`) .setThumbnail(target.displayAvatarURL({ dynamic: true })) .addFields( { name: '🏟️ Matches', value: `\`${stats.matches || 0}\``, inline: true }, { name: '⚽ Goals', value: `\`${stats.goals || 0}\``, inline: true }, { name: '🌟 MOTM Awards', value: `\`${stats.mvps || 0}\``, inline: true } ) .setColor(UI.colors.primary) .setFooter({ text: 'FriendlyBot Pro Stats' }); await message.reply({ embeds: [embed] }); return; } if (commandName === 'profileimage') { const target = message.mentions.users.first() || message.author; const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 }; const waitMsg = await message.reply('⏳ **Generating profile card...**'); try { const attachment = await createProfileAttachment(target, stats); await waitMsg.edit({ content: null, files: [attachment] }); } catch (e) { console.error('Profile image error:', e); await waitMsg.edit('❌ Failed to generate profile image.'); } return; } if (commandName === 'giverole') { await message.reply(`🖌️ **Feature Migration in Progress!**\nThe \`${commandName}\` feature is currently being updated to Next-Gen graphics. Check back shortly!`); return; } if (commandName === 'managerlineup') { if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message); lineupOwners.set(message.guildId, message.author.id); saveLineup(); const row1 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('manager_formation_select_7v7') .setPlaceholder('⚽ Select 7v7 Formation...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k }))) ); const row2 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('manager_formation_select_11v11') .setPlaceholder('🏆 Select 11v11 Formation...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11).slice(0, 25).map(k => ({ label: k, value: k }))) ); const row3 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('manager_formation_select_other') .setPlaceholder('🎮 Select Other Sizes...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11).slice(0, 25).map(k => ({ label: k, value: k }))) ); await message.channel.send({ content: "📋 **Step 1: Choose Formation for GUI Editor**", components: [row1, row2, row3] }); return; } }); async function safeReply(interaction, options) { try { if (interaction.deferred || interaction.replied) { return await interaction.editReply(options); } else { return await interaction.reply(options); } } catch (e) { console.error(`[!] Reply Failed: ${e.message}`); } } async function sendNoPermission(ctx) { const msg = "❌ No Permission\n*(Note: Use Slash Commands `/` for private error messages)*"; try { if (ctx.isChatInputCommand || ctx.isButton || ctx.isStringSelectMenu || ctx.isUserSelectMenu) { return await safeReply(ctx, { content: msg, flags: [MessageFlags.Ephemeral] }); } else { const reply = await ctx.reply(msg); setTimeout(() => { reply.delete().catch(() => { }); if (ctx.deletable) ctx.delete().catch(() => { }); }, 3000); } } catch (e) { } } // Simple per-user cooldown: 2 seconds between text commands (hard lock to ensure one reply) // Interaction Handler client.on('interactionCreate', async (interaction) => { // 1. Handle Timezone Selection IMMEDIATELY (Priority) if (interaction.isStringSelectMenu() && interaction.customId && interaction.customId.startsWith('tz_select_')) { try { await interaction.deferUpdate().catch(() => {}); const matchId = interaction.customId.replace('tz_select_', ''); const matchData = pendingMatches.get(matchId); if (!matchData) { return interaction.followUp({ content: "❌ Match session expired or bot restarted. Please try the command again.", flags: [MessageFlags.Ephemeral] }); } const offset = parseFloat(interaction.values[0]); let timeStr = matchData.timeInput; if (timeStr.includes(' / ')) { timeStr = timeStr.split(' / ').pop().trim(); } let normalized = timeStr; // Robustly normalize "9 PM" to "9:00 PM" without breaking "8:30 PM" if (!normalized.includes(':')) { normalized = normalized.replace(/\b(\d+)\s*(AM|PM)\b/i, "$1:00 $2"); } const targetDate = new Date(); // Use word boundaries to ensure we match the start of the time, not just the minutes const hoursMatch = normalized.match(/\b(\d+):(\d+)\s*(am|pm)\b/i) || normalized.match(/\b(\d+)\s*(am|pm)\b/i); if (!hoursMatch) { return interaction.followUp({ content: "❌ Could not parse your time input. Please use a format like `9 PM`.", flags: [MessageFlags.Ephemeral] }); } let hours = parseInt(hoursMatch[1]); const minutes = parseInt(hoursMatch[2] || "0"); const ampm = (hoursMatch[3] || "").toLowerCase(); if (ampm === 'pm' && hours !== 12) hours += 12; if (ampm === 'am' && hours === 12) hours = 0; const dateMatch = normalized.match(/(\d+)[/-](\d+)[/-](\d+)/) || normalized.match(/(\w+)\s+(\d+),?\s+(\d+)/); if (dateMatch) { const d = new Date(normalized); if (!isNaN(d.getTime())) { targetDate.setUTCFullYear(d.getFullYear()); targetDate.setUTCMonth(d.getMonth()); targetDate.setUTCDate(d.getDate()); } } targetDate.setUTCHours(hours, minutes, 0, 0); const finalTs = Math.floor(targetDate.getTime() / 1000) - (offset * 3600); if (matchData.type === 'friendly') { if (!storage.data.scheduled_matches) storage.data.scheduled_matches = []; storage.data.scheduled_matches.push({ guildId: interaction.guildId, type: 'friendly', timeInput: matchData.timeInput, timestamp: finalTs * 1000, reminded: false }); storage.save('active_polls'); await interaction.editReply({ content: `✅ Friendly scheduled for <t:${finalTs}:F>!`, components: [] }); if (matchData.friendlyType === 'voting') { const lineup = getGuildLineup(interaction.guildId); lineup.clear(); saveLineup(); const view = createLineupView(interaction.guildId); const lineupMsg = await interaction.channel.send(view); await lineupMsg.react('🟩').catch(() => { }); await lineupMsg.react('🟥').catch(() => { }); activeLineupMessages.set(interaction.guildId, { channelId: interaction.channelId, messageId: lineupMsg.id }); addToCleanupQueue(interaction.guildId, interaction.channelId, lineupMsg.id, 'lineup'); if (storage.data.scheduled_matches.length > 0) { storage.data.scheduled_matches[storage.data.scheduled_matches.length - 1].messageId = lineupMsg.id; storage.data.scheduled_matches[storage.data.scheduled_matches.length - 1].channelId = interaction.channelId; storage.save('active_polls'); } } else { const guildId = interaction.guildId; guildSelectedFormationA.set(guildId, matchData.selectedFormation); const map = new Map(); guildLineups.set(guildId, map); saveLineup(); const editor = createManagerEditor(guildId, client); const editorMsg = await interaction.channel.send(editor); managerBoards.set(guildId, { channelId: interaction.channelId, messageId: editorMsg.id }); } } else { const content = `⭐▬▬ 🏆 **LEAGUE MATCH** 🏆 ▬▬⭐\n🏟️ **${matchData.home}** vs **${matchData.away}**\n🔗 ${matchData.link}\n🕒 **Time**: <t:${finalTs}:F> (<t:${finalTs}:R>)\n🤝 Session\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n@everyone`; const channel = await client.channels.fetch(matchData.channelId).catch(() => null); if (!channel) return interaction.followUp({ content: "❌ Original channel not found.", flags: [MessageFlags.Ephemeral] }); const msg = await channel.send({ content, allowedMentions: { parse: ['everyone', 'roles', 'users'] } }); await msg.react('🟩').catch(() => { }); await msg.react('🟥').catch(() => { }); // Removed from active_polls to prevent reaction listeners from overwriting it with friendly text // storage.data.active_polls[interaction.guildId] = msg.id; if (!storage.data.scheduled_matches) storage.data.scheduled_matches = []; storage.data.scheduled_matches.push({ guildId: interaction.guildId, home: matchData.home, away: matchData.away, link: matchData.link, timestamp: finalTs * 1000, reminded: false, messageId: msg.id, channelId: interaction.channelId }); storage.save('active_polls'); addToCleanupQueue(interaction.guildId, interaction.channelId, msg.id, 'poll'); await interaction.editReply({ content: "✅ Match scheduled! I have posted it in the channel.", components: [] }); } pendingMatches.delete(matchId); } catch (err) { console.error("[TZ] Priority Error:", err); } return; } // Handle slash commands in DMs if (!interaction.guildId) { if (interaction.isChatInputCommand()) { await interaction.reply({ content: "This command is not available in DMs.", flags: [MessageFlags.Ephemeral] }); return; } return; } // Only defer ChatInputCommands to prevent conflict with Button/Menu deferUpdate() if (interaction.isChatInputCommand()) { const noDeferCmds = ['ping', 'friendly', 'lineup', 'scrimlineup']; if (!noDeferCmds.includes(interaction.commandName)) { await interaction.deferReply().catch(() => { }); } } if (interaction.isChatInputCommand()) { const config = storage.data.config[interaction.guildId] || {}; const botEnabled = config.botEnabled !== false; if (!botEnabled && interaction.commandName !== 'on') { return safeReply(interaction, { content: "⚠️ The bot is currently **OFF**. Please use `/on` if you want to use the bot.", flags: [MessageFlags.Ephemeral] }); } try { logTransaction(client, interaction.commandName, interaction.user, interaction.guild, interaction.member); if (interaction.commandName === 'ping') { await safeReply(interaction, `Latency: ${client.ws.ping}ms`); } if (interaction.commandName === 'friendly') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction); const needed = interaction.options.getInteger('needed') || 7; const mentionArg = interaction.options.getString('mention'); let pingType = 'everyone'; if (mentionArg) { pingType = mentionArg.toLowerCase() === 'here' ? 'here' : 'everyone'; } guildFriendlyPingType.set(interaction.guildId, pingType); saveLineup(); let content; if (pingType === 'here') { content = getFriendlyText(interaction.guildId, needed).replace(/@everyone/gi, '@here'); } else { content = getFriendlyText(interaction.guildId, needed); } // Reply ephemerally to the interaction to prevent timeout and keep interaction response private await safeReply(interaction, { content: "✅ Friendly poll started!", flags: [MessageFlags.Ephemeral] }); const mentionParse = ['everyone', 'roles', 'users']; console.log(`[DEBUG] FRIENDLY-INTERACT: guild=${interaction.guildId} pingType=${pingType} needed=${needed} contentPreview="${(content || '').slice(0, 60)}"`); // Send the actual poll as a normal channel message const msg = await interaction.channel.send({ content, allowedMentions: { parse: mentionParse } }).catch(() => null); if (msg) { await msg.react('🟩').catch(() => { }); await msg.react('🟥').catch(() => { }); storage.data.active_polls[interaction.guildId] = msg.id; pollNeededCount.set(interaction.guildId, needed); storage.save('active_polls'); // Wait for players to react const joined = new Set(); const filter = (reaction, user) => (reaction.emoji.name === '🟩' || reaction.emoji.name === "I'm In") && !user.bot; const collector = msg.createReactionCollector({ filter, time: 600000 }); collector.on('collect', (reaction, user) => { if (!joined.has(user.id)) { joined.add(user.id); msg.edit({ content: content + `\n\n${joined.size}/${needed} players joined. Waiting for more...`, allowedMentions: { parse: mentionParse } }).catch(() => {}); } if (joined.size >= needed) { collector.stop('ready'); } }); collector.on('end', async (col, reason) => { if (reason === 'ready') { const lineup = getGuildLineup(interaction.guildId); lineup.clear(); saveLineup(); const view = createLineupView(interaction.guildId); const lineupMsg = await interaction.channel.send(view); activeLineupMessages.set(interaction.guildId, { channelId: interaction.channelId, messageId: lineupMsg.id }); addToCleanupQueue(interaction.guildId, interaction.channelId, lineupMsg.id, 'lineup'); // Update poll to show it's done await msg.edit({ content: content + `\n\n✅ **Match is Ready!** Check the board below.`, allowedMentions: { parse: mentionParse } }).catch(() => {}); } else { // Canceled await msg.edit({ content: content + `\n\n❌ Canceled: not enough players joined.`, allowedMentions: { parse: mentionParse } }).catch(() => {}); } pollNeededCount.delete(interaction.guildId); delete storage.data.active_polls[interaction.guildId]; storage.save('active_polls'); }); addToCleanupQueue(interaction.guildId, interaction.channelId, msg.id, 'poll'); } } if (interaction.commandName === 'leaguematch') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); const home = interaction.options.getString('home'); const away = interaction.options.getString('away'); const link = interaction.options.getString('link'); const timeInput = interaction.options.getString('time'); const matchId = `match_${Date.now()}`; pendingMatches.set(matchId, { home, away, link, timeInput, channelId: interaction.channelId }); const row = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId(`tz_select_${matchId}`) .setPlaceholder('Select YOUR current timezone...') .addOptions(TIMEZONE_OPTIONS) ); await safeReply(interaction, { content: "🌍 **Select your timezone** to finalize the match schedule:", components: [row], flags: [MessageFlags.Ephemeral] }); } if (interaction.commandName === 'win' || interaction.commandName === 'loss' || interaction.commandName === 'draw') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); const type = interaction.commandName; const res = interaction.options.getString('result'); const scorers = interaction.options.getString('scorers') || ""; const record = storage.getRecord(interaction.guildId); if (type === 'win') record.wins++; else if (type === 'loss') record.losses++; else record.draws++; // Auto-increment matches for everyone on the lineup board const lineup = getGuildLineup(interaction.guildId); const playersOnBoard = new Set(); for (const players of lineup.values()) { players.forEach(p => playersOnBoard.add(p)); } playersOnBoard.forEach(uid => storage.addStat(uid, 'matches')); // Process scorers const mentions = scorers.match(/<@!?(\d+)>/g) || []; mentions.forEach(m => { const uid = m.replace(/[<@!>]/g, ''); storage.addStat(uid, 'goals'); }); storage.save('records'); const embed = UI.createEmbed(`⭐ ${type.toUpperCase()} RECORDED`, `🏟️ **Result**: ${res}\n\n⚽ **Scorers**:\n${scorers || "None"}\n\n📊 *Matches have been recorded for everyone on the current lineup board.*`, type === 'win' ? UI.colors.success : UI.colors.danger); await safeReply(interaction, { embeds: [embed] }); } if (interaction.commandName === 'top') { const sorted = Object.entries(storage.data.stats || {}) .sort((a, b) => (b[1].matches || 0) - (a[1].matches || 0)) .slice(0, 30); const ranked = sorted.map(([id, data], i) => `**#${i + 1}** <@${id}> — \`${data.matches || 0}\` matches | ⭐ \`${data.mvps || 0}\` MVPs`); let text = ranked.join('\n'); if (!text) text = "No data yet."; const chunks = []; let currentChunk = ""; const lines = text.split('\n'); for (const line of lines) { if (currentChunk.length + line.length > 4000) { chunks.push(currentChunk); currentChunk = line + "\n"; } else { currentChunk += line + "\n"; } } if (currentChunk) chunks.push(currentChunk); for (let i = 0; i < chunks.length; i++) { const embed = UI.createEmbed("🏆 Most Active Players", chunks[i]); if (i === 0) await safeReply(interaction, { embeds: [embed] }); else await interaction.channel.send({ embeds: [embed] }); } } if (interaction.commandName === 'motm') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); const target = interaction.options.getUser('player'); storage.addStat(target.id, 'mvps'); const embed = UI.createEmbed("🌟 MAN OF THE MATCH", `The MVP award has been granted to <@${target.id}>!`, UI.colors.success); await safeReply(interaction, { embeds: [embed] }); } if (interaction.commandName === 'record') { const r = storage.getRecord(interaction.guildId); const embed = UI.createEmbed("📊 Server Match Record", `✅ Wins: \`${r.wins}\`\n🟥 Losses: \`${r.losses}\`\n🤝 Draws: \`${r.draws}\``); await safeReply(interaction, { embeds: [embed] }); } if (interaction.commandName === 'setup') { if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true }); const row = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('settings_select') .setPlaceholder('Configure bot features...') .addOptions([ { label: 'Cloud Backup', description: 'Enable/Disable Discord Cloud Backup', value: 'toggle_backup' }, { label: 'Auto Friendly', description: 'Configure automated friendly polls', value: 'auto_friendly_settings' } ]) ); await safeReply(interaction, { content: "⚙️ **Settings**", components: [row] }); } if (interaction.commandName === 'friendlybotsettings') { const roles = roleStorage.roles[interaction.guildId] || []; const rInfo = roles.length > 0 ? roles.map(r => `<@&${r}>`).join(', ') : "Only administrator."; const config = storage.data.config[interaction.guildId] || {}; const status = config.botEnabled !== false ? "🟢 **Online**" : "🔴 **Offline**"; await safeReply(interaction, { content: `${status}\nWhitelist: ${rInfo}` }); } if (interaction.commandName === 'on') { if (!interaction.member.permissions.has('Administrator') && !roleStorage.isWhitelisted(interaction.guildId, interaction.member)) { return sendNoPermission(interaction); } if (!storage.data.config[interaction.guildId]) storage.data.config[interaction.guildId] = {}; storage.data.config[interaction.guildId].botEnabled = true; storage.save('config'); await safeReply(interaction, "✅ The bot has been turned **ON**."); } if (interaction.commandName === 'off') { if (!interaction.member.permissions.has('Administrator') && !roleStorage.isWhitelisted(interaction.guildId, interaction.member)) { return sendNoPermission(interaction); } if (!storage.data.config[interaction.guildId]) storage.data.config[interaction.guildId] = {}; storage.data.config[interaction.guildId].botEnabled = false; storage.save('config'); await safeReply(interaction, "❌ The bot has been turned **OFF**. Use `/on` to re-enable it."); } if (interaction.commandName === 'lineup') { console.log(`[DEBUG] LINEUP-INTERACT: guild=${interaction.guildId} user=${interaction.user?.id} ` + `args=${JSON.stringify(interaction.options?.getString?.('mention'))}`); if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction); const mention = interaction.options.getString('mention') || 'everyone'; const pingType = mention.toLowerCase() === 'here' ? 'here' : 'everyone'; guildPingType.set(interaction.guildId, pingType); lineupOwners.set(interaction.guildId, interaction.user.id); saveLineup(); const row1 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('formation_select_initial_7v7') .setPlaceholder('⚽ Select 7v7 Formation...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k }))) ); const row2 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('formation_select_initial_11v11') .setPlaceholder('🏆 Select 11v11 Formation...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11).slice(0, 25).map(k => ({ label: k, value: k }))) ); const row3 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('formation_select_initial_other') .setPlaceholder('🎮 Select Other Sizes (6v6, 8v8, 9v9, 10v10)...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11).slice(0, 25).map(k => ({ label: k, value: k }))) ); const row4 = new ActionRowBuilder().addComponents( new ButtonBuilder() .setCustomId('open_custom_lineup_modal') .setLabel('Custom Positions / Numbers') .setStyle(ButtonStyle.Primary) .setEmoji("🛠️") ); const embed = UI.createEmbed("📋 Initialize Lineup", "Select a formation from the dropdowns below, or create your own custom layout.", UI.colors.primary); const pingMention = pingType === 'here' ? '@here' : '@everyone'; // Use a robust allowedMentions parse value const mentionParse = ['everyone', 'roles', 'users']; await safeReply(interaction, { content: `${pingMention}\n**Lineup Session Active!**`, embeds: [embed], components: [row1, row2, row3, row4], allowedMentions: { parse: mentionParse } }); } if (interaction.commandName === 'scrimlineup') { console.log(`[DEBUG] SCRIMLINEUP-INTERACT: guild=${interaction.guildId} user=${interaction.user?.id} ` + `args=${JSON.stringify(interaction.options?.getString?.('mention'))}`); if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction); const mention = interaction.options.getString('mention') || 'everyone'; const pingType = mention.toLowerCase() === 'here' ? 'here' : 'everyone'; guildPingType.set(interaction.guildId, pingType); lineupOwners.set(interaction.guildId, interaction.user.id); guildScrimMode.set(interaction.guildId, true); // Set scrim mode saveLineup(); const lineup = getGuildLineup(interaction.guildId); lineup.clear(); const lineupB = getGuildLineupB(interaction.guildId); lineupB.clear(); saveLineup(); const embed = UI.createEmbed("📋 Initialize Scrimmage Lineup", "Select a formation from the dropdowns below to start! Two teams will face each other.", UI.colors.primary); const pingMention = pingType === 'here' ? '@here' : '@everyone'; const mentionParse = ['everyone', 'roles', 'users']; // Re-use the view generator for components const view = createScrimLineupView(interaction.guildId); await safeReply(interaction, { content: `${pingMention}\n**🔥 SCRIMMAGE LINEUP SESSION ACTIVE!**\n*Two teams facing each other!*`, embeds: [embed], components: view.components, allowedMentions: { parse: mentionParse } }); } if (interaction.commandName === 'clear') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); const amount = interaction.options.getInteger('amount'); await interaction.channel.bulkDelete(amount, true); await safeReply(interaction, { content: `✅ Cleared ${amount} messages.`, ephemeral: true }); } if (interaction.commandName === 'lock') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); await interaction.channel.permissionOverwrites.edit(interaction.guild.roles.everyone, { SendMessages: false }); await safeReply(interaction, { content: "🔒 Channel Locked." }); } if (interaction.commandName === 'unlock') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); await interaction.channel.permissionOverwrites.edit(interaction.guild.roles.everyone, { SendMessages: true }); await safeReply(interaction, { content: "🔓 Channel Unlocked." }); } if (interaction.commandName === 'swap') { const ownerId = lineupOwners.get(interaction.guildId); if (ownerId && interaction.user.id !== ownerId) return safeReply(interaction, { content: `❌ Only <@${ownerId}> can swap players!`, flags: [MessageFlags.Ephemeral] }); const p1 = interaction.options.getUser('player1'); const p2 = interaction.options.getUser('player2'); const lineup = getGuildLineup(interaction.guildId); let pos1 = null, idx1 = -1; let pos2 = null, idx2 = -1; for (const [pos, players] of lineup) { const i1 = players.indexOf(p1.id); if (i1 !== -1) { pos1 = pos; idx1 = i1; } const i2 = players.indexOf(p2.id); if (i2 !== -1) { pos2 = pos; idx2 = i2; } } if (!pos1 || !pos2) return safeReply(interaction, { content: "❌ Both players must be in the lineup to swap.", flags: [MessageFlags.Ephemeral] }); // Perform swap const arr1 = lineup.get(pos1); const arr2 = lineup.get(pos2); arr1[idx1] = p2.id; arr2[idx2] = p1.id; saveLineup(); await safeReply(interaction, { content: `✅ Swapped <@${p1.id}> with <@${p2.id}>!`, flags: [MessageFlags.Ephemeral] }); // Update the board const boardInfo = activeLineupMessages.get(interaction.guildId); if (boardInfo) { try { const channel = await client.channels.fetch(boardInfo.channelId); const msg = await channel.messages.fetch(boardInfo.messageId); if (msg) await msg.edit(createLineupView(interaction.guildId)); } catch (e) { } } } if (interaction.commandName === 'sendlink') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); const link = interaction.options.getString('link'); await safeReply(interaction, `Link : ${link}`); } if (interaction.commandName === 'uptime') { const up = process.uptime(); const d = Math.floor(up / 86400); const h = Math.floor(up / 3600) % 24; const m = Math.floor(up / 60) % 60; await safeReply(interaction, `⏱️ **Uptime**: ${d}d ${h}h ${m}m ${Math.floor(up % 60)}s`); } if (interaction.commandName === 'addrole' || interaction.commandName === 'removerole') { if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true }); const role = interaction.options.getRole('role'); if (!role) return safeReply(interaction, { content: "❌ Please select a role!", ephemeral: true }); const gid = interaction.guildId; if (interaction.commandName === 'addrole') { roleStorage.addRole(gid, role.id); const count = await triggerOnboardingForRole(interaction.guild, role); await safeReply(interaction, `✅ Added <@&${role.id}> to whitelist. Sent onboarding DM to **${count}** members.`); } else { roleStorage.removeRole(gid, role.id); await safeReply(interaction, `✅ Removed <@&${role.id}> from whitelist.`); } } if (interaction.commandName === 'managerlineup') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return interaction.reply({ content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); lineupOwners.set(interaction.guildId, interaction.user.id); saveLineup(); const row1 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('manager_formation_select_7v7') .setPlaceholder('⚽ Select 7v7 Formation...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k }))) ); const row2 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('manager_formation_select_11v11') .setPlaceholder('🏆 Select 11v11 Formation...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11).slice(0, 25).map(k => ({ label: k, value: k }))) ); const row3 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('manager_formation_select_other') .setPlaceholder('🎮 Select Other Sizes...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11).slice(0, 25).map(k => ({ label: k, value: k }))) ); await safeReply(interaction, { content: "📋 **Step 1: Choose Formation for GUI Editor**", components: [row1, row2, row3] }); } if (interaction.commandName === 'lineupimage') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); try { const lineup = getGuildLineup(interaction.guildId); const formKey = guildSelectedFormation.get(interaction.guildId) || 'default'; const formation = formKey === `custom_${interaction.guildId}` ? guildCustomFormations.get(interaction.guildId) : FORMATIONS[formKey]; const formDisplayName = formKey === `custom_${interaction.guildId}` ? (guildCustomFormationNames.get(interaction.guildId) || "Custom") : formKey; const attachment = await createLineupAttachment(lineup, formDisplayName, formation || FORMATIONS["default"], client); const embed = UI.createEmbed(`⚽ Lineup — ${formDisplayName}`, 'Current starting lineup positions'); embed.setImage('attachment://lineup.png'); await safeReply(interaction, { embeds: [embed], files: [attachment] }); } catch (e) { console.error('Lineup image error:', e); await safeReply(interaction, '❌ Failed to generate lineup image.'); } } if (interaction.commandName === 'profile') { const target = interaction.options.getUser('user') || interaction.user; const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 }; const embed = new EmbedBuilder() .setTitle(`🎴 PLAYER PROFILE — ${target.username.toUpperCase()}`) .setThumbnail(target.displayAvatarURL({ dynamic: true })) .addFields( { name: '🏟️ Matches', value: `\`${stats.matches || 0}\``, inline: true }, { name: '⚽ Goals', value: `\`${stats.goals || 0}\``, inline: true }, { name: '🌟 MOTM Awards', value: `\`${stats.mvps || 0}\``, inline: true } ) .setColor(UI.colors.primary) .setFooter({ text: 'FriendlyBot Pro Stats' }); await safeReply(interaction, { embeds: [embed] }); } if (interaction.commandName === 'profileimage') { const target = interaction.options.getUser('user') || interaction.user; const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 }; try { const attachment = await createProfileAttachment(target, stats); await safeReply(interaction, { files: [attachment] }); } catch (e) { console.error('Profile image error:', e); await safeReply(interaction, '❌ Failed to generate profile image.'); } } if (interaction.commandName === 'tactic') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); try { const formationName = interaction.options.getString('formation'); const formation = FORMATIONS[formationName]; if (!formation || formation.length !== 7) { return safeReply(interaction, { content: "❌ Please select a valid 7v7 formation.", flags: [MessageFlags.Ephemeral] }); } // Get current lineup const lineup = getGuildLineup(interaction.guildId); // Get tactic data const tacticData = global.TACTICS[formationName] || global.TACTICS["default"]; // Generate tactic image with numbered positions and player names const attachment = await global.createTacticAttachment(formationName, formation, lineup, tacticData, client); // Build numbered position list with player names let positionList = ""; formation.forEach(([posKey, posLabel], index) => { const number = index + 1; const players = lineup.get(posKey) || []; const playerDisplay = players.length > 0 ? `<@${players[0]}>` : '*Empty*'; positionList += `**${number}.** ${posLabel} - ${playerDisplay}\n`; }); // Create embed const embed = UI.createEmbed( `📋 TACTIC — ${tacticData.name}`, `${tacticData.summary}\n\n${positionList}` ); embed.setImage('attachment://tactic.png'); embed.addFields( { name: '⚽ Attack', value: tacticData.attack, inline: false }, { name: '🛡️ Defense', value: tacticData.defense, inline: false }, { name: '🎯 Key Points', value: tacticData.keyPoints.join('\n'), inline: false } ); embed.setFooter({ text: 'FriendlyBot Tactics | 7v7 Only' }); embed.setTimestamp(); await safeReply(interaction, { embeds: [embed], files: [attachment] }); } catch (e) { console.error('[Tactic] Error:', e); await safeReply(interaction, '❌ Failed to generate tactic.'); } } if (interaction.commandName === 'scheduledfriendly') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] }); const timeInput = interaction.options.getString('time'); const type = interaction.options.getString('type') || 'voting'; // Parse date - check for ' / ' separator first let dateStr = timeInput; if (timeInput.includes(' / ')) { const parts = timeInput.split(' / '); dateStr = parts[parts.length - 1].trim(); } // Normalize "9 PM" to "9:00 PM" safely if (!dateStr.includes(':')) { dateStr = dateStr.replace(/\b(\d+)\s*(AM|PM)\b/i, "$1:00 $2"); } let timestamp = Date.parse(dateStr); // If it's just a time or failed, try assuming today with a clear format if (isNaN(timestamp) || timestamp < Date.now() - 86400000) { const today = new Date(); const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; const datePrefix = `${monthNames[today.getMonth()]} ${today.getDate()}, ${today.getFullYear()}`; timestamp = Date.parse(`${datePrefix} ${dateStr}`); } if (isNaN(timestamp)) { return safeReply(interaction, { content: "❌ Invalid date format. Use `9 PM` or `2026/5/4 9 PM`.", flags: [MessageFlags.Ephemeral] }); } const matchId = `friendly_${Date.now()}`; pendingMatches.set(matchId, { guildId: interaction.guildId, channelId: interaction.channelId, type: 'friendly', friendlyType: type, timeInput: timeInput, userId: interaction.user.id }); if (type === 'voting') { const row = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId(`tz_select_${matchId}`) .setPlaceholder('Select YOUR current timezone...') .addOptions(TIMEZONE_OPTIONS) ); await safeReply(interaction, { content: "🌍 **Select your timezone** to finalize the friendly schedule:", components: [row], flags: [MessageFlags.Ephemeral] }); } else { lineupOwners.set(interaction.guildId, interaction.user.id); saveLineup(); const row1 = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId(`manager_formation_select_${matchId}`) .setPlaceholder('⚽ Select 7v7 Formation...') .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k }))) ); await safeReply(interaction, { content: "📋 **Step 1: Choose Formation for Scheduled Friendly**", components: [row1] }); } } if (interaction.commandName === 'giverole') { await safeReply(interaction, { content: `🖌️ **Feature Migration in Progress!**\nThe \`${interaction.commandName}\` feature is currently being updated to Next-Gen graphics. Check back shortly!`, ephemeral: true }); } } catch (err) { console.error(`[INTERACTION ERROR] ${interaction.commandName}:`, err); await safeReply(interaction, { content: "❌ A system error occurred while processing this command.", ephemeral: true }).catch(() => { }); } } if (interaction.isStringSelectMenu()) { if (interaction.customId === 'settings_select') { await interaction.deferUpdate().catch(() => { }); const value = interaction.values[0]; if (value === 'auto_friendly_settings') { await showAutoFriendlyPanel(interaction); } else { await safeReply(interaction, { content: "✅ Settings interaction acknowledged.", ephemeral: true }); } } } if (interaction.isChannelSelectMenu()) { if (interaction.customId === 'auto_friendly_channel_select') { if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true }); const channelId = interaction.values[0]; const config = storage.data.config[interaction.guildId] || {}; config.autoFriendlyChannel = channelId; storage.data.config[interaction.guildId] = config; storage.save('config'); await interaction.deferUpdate(); await showAutoFriendlyPanel(interaction); } } if (interaction.isButton()) { if (interaction.customId === 'open_custom_lineup_modal') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction); const modal = new ModalBuilder() .setCustomId('custom_lineup_modal') .setTitle('Custom Lineup / Other Sizes'); const customInput = new TextInputBuilder() .setCustomId('custom_input') .setLabel("Enter Custom Positions (Comma separated)") .setPlaceholder("Example: GK, LB, CB, CB, RB, CDM, CM, LW, ST, RW") .setStyle(TextInputStyle.Paragraph) .setRequired(true); modal.addComponents( new ActionRowBuilder().addComponents(customInput) ); await interaction.showModal(modal); } if (interaction.customId === 'toggle_auto_friendly') { if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true }); const config = storage.data.config[interaction.guildId] || {}; config.autoFriendlyEnabled = !config.autoFriendlyEnabled; storage.data.config[interaction.guildId] = config; storage.save('config'); await interaction.deferUpdate(); await showAutoFriendlyPanel(interaction); } if (interaction.customId === 'open_interval_modal') { if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true }); const modal = new ModalBuilder() .setCustomId('auto_friendly_interval_modal') .setTitle('Auto Friendly Interval'); const intervalInput = new TextInputBuilder() .setCustomId('interval_input') .setLabel("Interval in minutes (e.g. 40)") .setStyle(TextInputStyle.Short) .setRequired(true) .setPlaceholder('40'); modal.addComponents(new ActionRowBuilder().addComponents(intervalInput)); await interaction.showModal(modal); } } if (interaction.isModalSubmit()) { if (interaction.customId === 'custom_lineup_modal') { const custom = interaction.fields.getTextInputValue('custom_input').trim(); let formation = null; let formName = "Custom"; if (custom) { formation = autoDetectFormation(custom); formName = `Custom (${formation.length}v${formation.length})`; } if (!formation) { return safeReply(interaction, { content: "❌ Could not find that preset or parse your custom positions. Example: `GK, CB, CM, ST`", ephemeral: true }); } const guildId = interaction.guildId; // Store this custom formation and its name persistently guildCustomFormations.set(guildId, formation); guildCustomFormationNames.set(guildId, formName); const tempKey = `custom_${guildId}`; guildSelectedFormation.set(guildId, tempKey); // Clear current lineup as formation changed const map = new Map(); guildLineups.set(guildId, map); saveLineup(); const view = createLineupView(guildId); // If the modal was triggered from a message (like the initial setup message), update it! if (interaction.message) { await interaction.update(view); activeLineupMessages.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id }); addToCleanupQueue(guildId, interaction.channelId, interaction.message.id, 'lineup'); } else { // Otherwise reply ephemerally and send a new message await interaction.reply({ content: `✅ Formation set to **${formName}**!`, ephemeral: true }); const msg = await interaction.channel.send(view); activeLineupMessages.set(guildId, { channelId: interaction.channelId, messageId: msg.id }); addToCleanupQueue(guildId, interaction.channelId, msg.id, 'lineup'); } return; } if (interaction.customId === 'auto_friendly_interval_modal') { const interval = parseInt(interaction.fields.getTextInputValue('interval_input')); if (isNaN(interval) || interval < 1) { return safeReply(interaction, { content: "❌ Please enter a valid number of minutes.", ephemeral: true }); } const config = storage.data.config[interaction.guildId] || {}; config.autoFriendlyInterval = interval; storage.data.config[interaction.guildId] = config; storage.save('config'); await safeReply(interaction, { content: `✅ Auto Friendly interval set to **${interval}** minutes.`, ephemeral: true }); } } if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formation_select_initial_')) { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction); const ownerId = lineupOwners.get(interaction.guildId); if (ownerId && interaction.user.id !== ownerId) { return interaction.reply({ content: `❌ Only <@${ownerId}> can initialize this lineup!`, ephemeral: true }); } const guildId = interaction.guildId; const formKey = interaction.values[0]; guildSelectedFormation.set(guildId, formKey); guildSelectedFormationA.set(guildId, formKey); // Keep in sync for image renderer // Clear current lineup as formation changed const map = new Map(); guildLineups.set(guildId, map); saveLineup(); const view = createLineupView(guildId); await interaction.update(view); activeLineupMessages.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id }); addToCleanupQueue(guildId, interaction.channelId, interaction.message.id, 'lineup'); saveLineup(); return; } if (interaction.isStringSelectMenu()) { if (interaction.customId === 'scrim_join_team_a' || interaction.customId === 'scrim_join_team_b') { await interaction.deferUpdate().catch(() => { }); const isTeamA = interaction.customId === 'scrim_join_team_a'; const selectedValue = interaction.values[0]; const pos = isTeamA ? selectedValue.replace('a_', '') : selectedValue.replace('b_', ''); const lineupGuildId = interaction.guildId; const targetLineup = isTeamA ? getGuildLineup(lineupGuildId) : getGuildLineupB(lineupGuildId); const userId = String(interaction.user.id); let wasInCurrentPos = false; const currentQ = targetLineup.get(pos) || []; if (currentQ.includes(userId)) wasInCurrentPos = true; for (const [p, players] of targetLineup) { targetLineup.set(p, players.filter(id => id !== userId)); } const oppositeLineup = isTeamA ? getGuildLineupB(lineupGuildId) : getGuildLineup(lineupGuildId); for (const [p, players] of oppositeLineup) { oppositeLineup.set(p, players.filter(id => id !== userId)); } if (!wasInCurrentPos) { if (!targetLineup.get(pos)) targetLineup.set(pos, []); targetLineup.get(pos).push(userId); } saveLineup(); const view = createScrimLineupView(lineupGuildId); await interaction.editReply({ embeds: view.embeds, components: view.components }); return; } if (interaction.customId === 'formation_category_select') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction); const ownerId = lineupOwners.get(interaction.guildId); if (ownerId && interaction.user.id !== ownerId) { return interaction.reply({ content: `❌ Only <@${ownerId}> can manage this lineup!`, ephemeral: true }); } const cat = interaction.values[0]; const guildId = interaction.guildId; let filteredKeys = []; let catLabel = ""; if (cat === 'cat_7v7') { filteredKeys = Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7); catLabel = "7v7"; } else if (cat === 'cat_11v11') { filteredKeys = Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11); catLabel = "11v11"; } else { filteredKeys = Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11); catLabel = "Other Sizes"; } const row = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId(`formation_select_ephemeral_${interaction.message.id}`) .setPlaceholder(`⚽ Pick a ${catLabel} Formation...`) .addOptions(filteredKeys.slice(0, 25).map(k => ({ label: k, value: k }))) ); await interaction.reply({ content: `📂 **Browsing ${catLabel} Formations**\nSelect an option below to update the public board.`, components: [row], flags: [MessageFlags.Ephemeral] }); return; } } if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formation_select_ephemeral_')) { const publicMessageId = interaction.customId.replace('formation_select_ephemeral_', ''); const formKey = interaction.values[0]; const guildId = interaction.guildId; guildSelectedFormation.set(guildId, formKey); guildSelectedFormationA.set(guildId, formKey); // Keep in sync for image renderer const map = new Map(); guildLineups.set(guildId, map); saveLineup(); await interaction.update({ content: `✅ Updated public board to **${formKey}**!`, components: [] }); try { const channel = interaction.channel; const publicMsg = await channel.messages.fetch(publicMessageId); await publicMsg.edit(createLineupView(guildId)); } catch (e) { console.error("[!] Failed to update public board from ephemeral menu:", e.message); } return; } if (interaction.isStringSelectMenu() && interaction.customId === 'formation_select_active') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction); const ownerId = lineupOwners.get(interaction.guildId); if (ownerId && interaction.user.id !== ownerId) { return interaction.reply({ content: `❌ Only <@${ownerId}> can change the formation!`, ephemeral: true }); } const guildId = interaction.guildId; if (guildScrimMode.get(guildId)) { guildSelectedFormationA.set(guildId, interaction.values[0]); guildSelectedFormationB.set(guildId, interaction.values[0]); guildSelectedFormation.set(guildId, interaction.values[0]); } else { guildSelectedFormationA.set(guildId, interaction.values[0]); guildSelectedFormation.set(guildId, interaction.values[0]); } const map = new Map(); guildLineups.set(guildId, map); await interaction.update(createLineupView(guildId)); saveLineup(); return; } if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formation_select_')) { if (interaction.customId.includes('_initial_') || interaction.customId.includes('_active')) return; if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction); const ownerId = lineupOwners.get(interaction.guildId); if (ownerId && interaction.user.id !== ownerId) { return interaction.reply({ content: `❌ Only <@${ownerId}> can change the formation!`, ephemeral: true }); } const guildId = interaction.guildId; if (guildScrimMode.get(guildId)) { guildSelectedFormationA.set(guildId, interaction.values[0]); guildSelectedFormationB.set(guildId, interaction.values[0]); guildSelectedFormation.set(guildId, interaction.values[0]); } else { guildSelectedFormationA.set(guildId, interaction.values[0]); guildSelectedFormation.set(guildId, interaction.values[0]); } const map = new Map(); guildLineups.set(guildId, map); await interaction.update(createLineupView(guildId)); saveLineup(); return; } if (interaction.isStringSelectMenu() && interaction.customId.startsWith('manager_formation_select_')) { const guildId = interaction.guildId; const formationKey = interaction.values[0]; // Check if this is part of a scheduled friendly flow const matchId = interaction.customId.replace('manager_formation_select_', ''); if (matchId.startsWith('friendly_')) { const matchData = pendingMatches.get(matchId); if (matchData) { matchData.selectedFormation = formationKey; const row = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId(`tz_select_${matchId}`) .setPlaceholder('Select YOUR current timezone...') .addOptions(TIMEZONE_OPTIONS) ); await interaction.update({ content: "🌍 **Step 2: Select your timezone** to finalize the kickoff time:", components: [row] }); return; } } if (guildScrimMode.get(guildId)) { guildSelectedFormationA.set(guildId, formationKey); guildSelectedFormationB.set(guildId, formationKey); guildSelectedFormation.set(guildId, formationKey); } else { guildSelectedFormationA.set(guildId, formationKey); guildSelectedFormation.set(guildId, formationKey); } const map = new Map(); guildLineups.set(guildId, map); const editor = createManagerEditor(guildId, client); await interaction.update(editor); managerBoards.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id }); saveLineup(); return; } if (interaction.isUserSelectMenu() && interaction.customId.startsWith('man_pick_')) { const posKey = interaction.customId.replace('man_pick_', ''); const targetUser = interaction.values[0]; const guildId = interaction.guildId; const lineup = getGuildLineup(guildId); lineup.set(posKey, [targetUser]); saveLineup(); await interaction.update({ content: `✅ Assigned <@${targetUser}> to **${posKey}**`, components: [] }); const boardInfo = managerBoards.get(guildId); if (boardInfo) { try { const channel = await client.channels.fetch(boardInfo.channelId); const msg = await channel.messages.fetch(boardInfo.messageId); if (msg) await msg.edit(createManagerEditor(guildId, client)); } catch (e) { console.error("Could not update manager board live", e); } } return; } const lineupGuildId = interaction.guildId; const lineupBoard = getGuildLineup(lineupGuildId); if (interaction.isButton()) { if (interaction.customId.startsWith('man_edit_')) { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction); const posKey = interaction.customId.replace('man_edit_', ''); const row = new ActionRowBuilder().addComponents( new UserSelectMenuBuilder() .setCustomId(`man_pick_${posKey}`) .setPlaceholder(`Select player for ${posKey}...`) ); await interaction.reply({ content: `👤 Pick a player for **${posKey}**`, components: [row], flags: [MessageFlags.Ephemeral] }); return; } if (interaction.customId.startsWith('join_')) { await interaction.deferUpdate().catch(() => { }); const isScrim = guildScrimMode.get(lineupGuildId) === true; let targetLineup = lineupBoard; let pos = interaction.customId.replace('join_', ''); if (isScrim && pos.startsWith('scrim_join_a_')) { pos = pos.replace('scrim_join_a_', ''); targetLineup = lineupBoard; } else if (isScrim && pos.startsWith('scrim_join_b_')) { pos = pos.replace('scrim_join_b_', ''); targetLineup = getGuildLineupB(lineupGuildId); } const userId = interaction.user.id; let wasInCurrentPos = false; const currentQ = targetLineup.get(pos) || []; if (currentQ.includes(userId)) wasInCurrentPos = true; for (const [p, players] of targetLineup) { targetLineup.set(p, players.filter(id => id !== userId)); } if (isScrim) { const oppositeLineup = (targetLineup === lineupBoard) ? getGuildLineupB(lineupGuildId) : lineupBoard; for (const [p, players] of oppositeLineup) { oppositeLineup.set(p, players.filter(id => id !== userId)); } } if (!wasInCurrentPos) { if (!targetLineup.get(pos)) targetLineup.set(pos, []); targetLineup.get(pos).push(userId); } saveLineup(); // Re-fetch the lineup to ensure memory view is up to date before rendering const refreshedLineup = getGuildLineup(lineupGuildId); const view = isScrim ? createScrimLineupView(lineupGuildId) : createLineupView(lineupGuildId); await interaction.editReply({ embeds: view.embeds, components: view.components }); return; } if (interaction.customId === 'lineup_clear') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction); const ownerId = lineupOwners.get(interaction.guildId); if (ownerId && interaction.user.id !== ownerId) { return interaction.reply({ content: `❌ Only <@${ownerId}> can clear the board!`, ephemeral: true }); } lineupBoard.clear(); const isScrim = guildScrimMode.get(lineupGuildId) === true; if (isScrim) { const lineupB = getGuildLineupB(lineupGuildId); lineupB.clear(); } saveLineup(); const view = isScrim ? createScrimLineupView(lineupGuildId) : createLineupView(lineupGuildId); await interaction.update({ embeds: view.embeds, components: view.components }); return; } if (interaction.customId === 'lineup_done') { if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) { return sendNoPermission(interaction); } const ownerId = lineupOwners.get(interaction.guildId); if (ownerId && interaction.user.id !== ownerId) { return interaction.reply({ content: `❌ Only <@${ownerId}> can generate the final image!`, flags: [MessageFlags.Ephemeral] }); } await interaction.deferReply().catch(() => { }); try { const isScrim = guildScrimMode.get(lineupGuildId) === true; if (isScrim) { const formKeyA = guildSelectedFormationA.get(lineupGuildId) || 'default'; const formationA = formKeyA === `custom_${lineupGuildId}` ? guildCustomFormations.get(lineupGuildId) : FORMATIONS[formKeyA]; const formDisplayNameA = formKeyA === `custom_${lineupGuildId}` ? (guildCustomFormationNames.get(lineupGuildId) || "Custom") : formKeyA; const effFormationA = formationA || FORMATIONS["default"]; const formKeyB = guildSelectedFormationB.get(lineupGuildId) || 'default'; const formationB = formKeyB === `custom_${lineupGuildId}` ? guildCustomFormations.get(lineupGuildId) : FORMATIONS[formKeyB]; const formDisplayNameB = formKeyB === `custom_${lineupGuildId}` ? (guildCustomFormationNames.get(lineupGuildId) || "Custom") : formKeyB; const effFormationB = formationB || FORMATIONS["default"]; const teamABuffer = await renderLineupImage(lineupBoard, `TEAM A - ${formDisplayNameA}`, effFormationA, client); const lineupB = getGuildLineupB(lineupGuildId); const teamBBuffer = await renderLineupImage(lineupB, `TEAM B - ${formDisplayNameB}`, effFormationB, client, true); const attA = new AttachmentBuilder(teamABuffer, { name: 'team_a.png' }); const attB = new AttachmentBuilder(teamBBuffer, { name: 'team_b.png' }); const embedA = new EmbedBuilder() .setColor('#5865F2') .setTitle(`TEAM A — ${formDisplayNameA}`) .setDescription('Team A lineup (attacking upward)') .setImage('attachment://team_a.png'); const embedB = new EmbedBuilder() .setColor('#ff4444') .setTitle(`TEAM B — ${formDisplayNameB}`) .setDescription('Team B lineup (attacking downward, facing Team A)') .setImage('attachment://team_b.png'); await interaction.editReply({ embeds: [embedA, embedB], files: [attA, attB] }); } else { const formKey = guildSelectedFormationA.get(lineupGuildId) || 'default'; const formation = formKey === `custom_${lineupGuildId}` ? guildCustomFormations.get(lineupGuildId) : FORMATIONS[formKey]; const formDisplayName = formKey === `custom_${lineupGuildId}` ? (guildCustomFormationNames.get(lineupGuildId) || "Custom") : formKey; const effFormation = formation || FORMATIONS["default"]; const attachment = await createLineupAttachment(lineupBoard, formDisplayName, effFormation, client); const embed = UI.createEmbed(`⚽ Final Lineup — ${formDisplayName}`, "Here is the visual representation of the starting lineup."); embed.setImage('attachment://lineup.png'); await interaction.editReply({ embeds: [embed], files: [attachment] }); } } catch (err) { console.error("Failed to generate lineup image:", err); await interaction.editReply({ content: "❌ Failed to generate lineup image. Please try again." }).catch(() => { }); } return; } } }); // Store needed count for each active poll const pollNeededCount = new Map(); async function fetchWithRetry(fetchFn, retries = 3, delay = 1000) { for (let i = 0; i < retries; i++) { try { return await fetchFn(); } catch (err) { if (i === retries - 1) throw err; await new Promise(res => setTimeout(res, delay)); } } } // Handle reaction removal to decrease count client.on('messageReactionRemove', async (reaction, user) => { if (user.bot) return; try { // Handle partials for both reaction and message to ensure content is available if (reaction.partial) await fetchWithRetry(() => reaction.fetch()); if (reaction.message.partial) await fetchWithRetry(() => reaction.message.fetch()); if (reaction.emoji.name === '🟩') { const guildId = reaction.message.guildId; const activePollId = storage.data.active_polls[guildId]; if (reaction.message.id === activePollId) { const content = reaction.message.content || ""; // Safety check: Don't edit if it's a league match or NOT a friendly poll if (content.includes('LEAGUE MATCH')) return; if (!content.includes('FRIENDLY')) return; const count = reaction.count - (reaction.me ? 1 : 0); const needed = pollNeededCount.get(guildId) || 6; // Update the message with current count const baseText = getFriendlyText(guildId, needed); await reaction.message.edit({ content: baseText + `\n\n${count}/${needed} players joined. Waiting for more...` }); } } } catch (err) { console.error("[REACTION-REMOVE] Error handling removal:", err); } }); // Staff Onboarding System client.on('guildMemberUpdate', async (oldMember, newMember) => { try { const guildId = newMember.guild.id; const oldRoles = oldMember.roles.cache; const newRoles = newMember.roles.cache; // Find added roles const addedRoles = newRoles.filter(role => !oldRoles.has(role.id)); if (addedRoles.size === 0) return; // Check if any of the added roles are in the whitelist const whitelist = roleStorage.roles[guildId] || []; const hasNewWhitelistRole = addedRoles.some(role => whitelist.includes(role.id)); if (hasNewWhitelistRole) { // Check if already onboarded if (!storage.data.onboarded[guildId]) storage.data.onboarded[guildId] = []; if (storage.data.onboarded[guildId].includes(newMember.id)) return; // Send onboarding DM const dashboardUrl = getSpacePublicUrl() || 'https://brozy123-lineup-bot.hf.space'; const embed = UI.createEmbed("🎉 Welcome to the Staff Team!", `You have been granted a **Staff Role** in **${newMember.guild.name}**!\n\nYou now have access to manage lineups, record match stats, and use admin commands.`, UI.colors.primary); embed.addFields( { name: "🌐 Management Dashboard", value: `Access settings and logs here:\n[**Open Dashboard**](${dashboardUrl})` }, { name: "⚽ Key Commands", value: "`!friendly` - Start a friendly poll\n`!lineup` - Start a lineup board\n`!lineupimage` - Generate lineup image\n`!leaguematchimage` - Generate match image" }, { name: "📖 Help", value: "If you need any help, check the dashboard or contact the server owner." } ); await newMember.send({ embeds: [embed] }).catch(() => { console.log(`[Onboarding] Could not send DM to ${newMember.user.tag}`); }); // Mark as onboarded storage.data.onboarded[guildId].push(newMember.id); storage.save('active_polls'); } } catch (err) { console.error("[Onboarding] Error:", err); } }); // Log server join to designated log channel client.on('guildCreate', async (guild) => { sendJoinTransaction(guild); try { console.log(`[SYSTEM] Bot joined a new guild: "${guild.name}" (${guild.id})`); const logChannelId = '1508759327731875977'; const channel = await client.channels.fetch(logChannelId).catch(() => null); if (!channel) { console.warn(`[SYSTEM] Could not find the guild-join log channel: ${logChannelId}`); return; } // Fetch owner details let ownerTag = 'Unknown'; let ownerMention = 'Unknown'; try { const owner = await guild.fetchOwner().catch(() => null); if (owner) { ownerTag = owner.user.tag; ownerMention = `<@${owner.id}>`; } else { const ownerUser = await client.users.fetch(guild.ownerId).catch(() => null); if (ownerUser) { ownerTag = ownerUser.tag; ownerMention = `<@${ownerUser.id}>`; } else if (guild.ownerId) { ownerMention = `<@${guild.ownerId}>`; } } } catch (e) { console.error(`[SYSTEM] Error fetching owner for guild ${guild.id}:`, e); } // Try to generate an invite link for logs/audits let inviteUrl = 'N/A'; try { const sysChannel = guild.systemChannel || guild.channels.cache.find(c => c.isTextBased() && c.permissionsFor(guild.members.me).has('CreateInstantInvite')); if (sysChannel) { const invites = await sysChannel.fetchInvites().catch(() => new Map()); if (invites.size > 0) { inviteUrl = invites.first().url; } else { const inv = await sysChannel.createInvite({ maxAge: 0, maxUses: 0 }).catch(() => null); if (inv) inviteUrl = inv.url; } } } catch (e) { console.error(`[SYSTEM] Error creating invite link for guild ${guild.id}:`, e); } const memberCount = guild.memberCount || 0; const iconUrl = guild.iconURL({ dynamic: true }) || null; const currentGuildsCount = client.guilds.cache.size; const embed = new EmbedBuilder() .setTitle(`📥 Bot Joined a New Guild!`) .setThumbnail(iconUrl) .addFields( { name: '🌐 Server Name', value: `**${guild.name}**`, inline: true }, { name: '🆔 Server ID', value: `\`${guild.id}\``, inline: true }, { name: '👑 Owner', value: `${ownerTag} (${ownerMention})`, inline: true }, { name: '👥 Member Count', value: `\`${memberCount}\` members`, inline: true }, { name: '🔗 Server Invite', value: inviteUrl !== 'N/A' ? `[Join Server](${inviteUrl})` : '`No Permission`', inline: true }, { name: '📊 Total Servers Now', value: `\`${currentGuildsCount}\` guilds`, inline: true } ) .setColor(0x57F287) // Green / Success .setTimestamp(); await channel.send({ embeds: [embed] }).catch((err) => { console.error(`[SYSTEM] Failed to send guild join embed log to channel:`, err); }); } catch (err) { console.error("[SYSTEM] Error inside guildCreate event handler:", err); } }); // Log server leave to designated log channel client.on('guildDelete', async (guild) => { sendLeaveTransaction(guild); try { console.log(`[SYSTEM] Bot left a guild: "${guild.name}" (${guild.id})`); const logChannelId = '1508759327731875977'; const channel = await client.channels.fetch(logChannelId).catch(() => null); if (!channel) { console.warn(`[SYSTEM] Could not find the guild-leave log channel: ${logChannelId}`); return; } // Try to find who kicked the bot from audit logs let kickedBy = 'Unknown'; try { const auditLogs = await guild.fetchAuditLogs({ limit: 10 }).catch(() => null); if (auditLogs) { const kickEntry = auditLogs.entries.find(entry => entry.targetId === client.user.id && (entry.action === 'MemberKick' || entry.action === 'MemberBanAdd') ); if (kickEntry && kickEntry.executor) { kickedBy = kickEntry.executor.username; } } } catch (e) { console.warn(`[SYSTEM] Could not fetch audit logs for guild ${guild.id}`); } const embed = new EmbedBuilder() .setTitle(`📤 Bot Left a Guild`) .addFields( { name: '🌐 Server Name', value: `**${guild.name}**`, inline: true }, { name: '🆔 Server ID', value: `\`${guild.id}\``, inline: true }, { name: '👤 Kicked By', value: `**${kickedBy}**`, inline: true }, { name: '👥 Member Count', value: `\`${guild.memberCount || 0}\` members`, inline: true }, { name: '📊 Total Servers Now', value: `\`${client.guilds.cache.size}\` guilds`, inline: true } ) .setColor(0xED4245) // Red / Failure .setTimestamp(); await channel.send({ embeds: [embed] }).catch((err) => { console.error(`[SYSTEM] Failed to send guild leave embed log to channel:`, err); }); } catch (err) { console.error("[SYSTEM] Error inside guildDelete event handler:", err); } }); async function triggerOnboardingForRole(guild, role) { const guildId = guild.id; const dashboardUrl = getSpacePublicUrl() || 'https://brozy123-lineup-bot.hf.space'; try { // Ensure members are cached to find role holders await guild.members.fetch().catch(() => { }); const membersWithRole = guild.members.cache.filter(m => m.roles.cache.has(role.id) && !m.user.bot); if (!storage.data.onboarded[guildId]) storage.data.onboarded[guildId] = []; const onboardingEmbed = UI.createEmbed("🎉 Welcome to the Staff Team!", `Your role **${role.name}** has been whitelisted as a **Staff Role** in **${guild.name}**!\n\nYou now have access to manage lineups, record match stats, and use admin commands.`, UI.colors.primary); onboardingEmbed.addFields( { name: "🌐 Management Dashboard", value: `Access settings and logs here:\n[**Open Dashboard**](${dashboardUrl})` }, { name: "⚽ Key Commands", value: "`!friendly` - Start a friendly poll\n`!lineup` - Start a lineup board\n`!lineupimage` - Generate lineup image\n`!leaguematchimage` - Generate match image" }, { name: "📖 Help", value: "If you need any help, check the dashboard or contact the server owner." } ); let sentCount = 0; for (const [id, member] of membersWithRole) { if (!storage.data.onboarded[guildId].includes(id)) { const success = await member.send({ embeds: [onboardingEmbed] }).then(() => true).catch(() => false); if (success) { storage.data.onboarded[guildId].push(id); sentCount++; } } } if (sentCount > 0) storage.save('active_polls'); return sentCount; } catch (err) { console.error("[Onboarding] Retroactive Error:", err); return 0; } } const TIMEZONE_MAP = { 'EST': -5, 'EDT': -4, 'CST': -6, 'CDT': -5, 'MST': -7, 'MDT': -6, 'PST': -8, 'PDT': -7, 'GMT': 0, 'UTC': 0, 'BST': 1, 'CET': 1, 'CEST': 2, 'EET': 2, 'EEST': 3, 'MSK': 3, 'IST': 5.5, 'KST': 9, 'JST': 9 }; const pendingMatches = new Map(); const TIMEZONE_OPTIONS = [ { label: 'UTC -11 (Midway)', value: '-11' }, { label: 'UTC -10 (Hawaii)', value: '-10' }, { label: 'UTC -9 (Alaska)', value: '-9' }, { label: 'UTC -8 (Pacific Time)', value: '-8' }, { label: 'UTC -7 (Mountain Time)', value: '-7' }, { label: 'UTC -6 (Central Time)', value: '-6' }, { label: 'UTC -5 (Eastern Time)', value: '-5' }, { label: 'UTC -4 (Atlantic Time)', value: '-4' }, { label: 'UTC -3 (Brazil/Argentina)', value: '-3' }, { label: 'UTC -2 (Mid-Atlantic)', value: '-2' }, { label: 'UTC -1 (Azores)', value: '-1' }, { label: 'UTC +0 (GMT / London)', value: '0' }, { label: 'UTC +1 (Central Europe)', value: '1' }, { label: 'UTC +2 (Eastern Europe / Egypt)', value: '2' }, { label: 'UTC +3 (Moscow / Saudi / Iraq / EEST)', value: '3' }, { label: 'UTC +4 (Dubai / Baku)', value: '4' }, { label: 'UTC +5 (Pakistan / Uzbekistan)', value: '5' }, { label: 'UTC +5:30 (India / IST)', value: '5.5' }, { label: 'UTC +6 (Bangladesh)', value: '6' }, { label: 'UTC +7 (Thailand / Vietnam)', value: '7' }, { label: 'UTC +8 (China / Singapore / Perth)', value: '8' }, { label: 'UTC +9 (Japan / Korea)', value: '9' }, { label: 'UTC +10 (Sydney / Guam)', value: '10' }, { label: 'UTC +11 (Solomon Islands)', value: '11' }, { label: 'UTC +12 (New Zealand / Fiji)', value: '12' } ]; function parseMatchTime(timeInput, offsetHours = 0) { if (!timeInput) return null; const now = new Date(); let targetDate = new Date(); // Support formats like "9 PM", "4/23 9 PM", "4-23 9PM" // Use word boundaries for the time part to avoid matching minutes/seconds as hours const regex = /(?:(\d+)[/-](\d+)\s+)?\b(\d+)(?::(\d+))?\s*(am|pm)\b/i; const match = timeInput.match(regex); if (match) { const month = match[1]; const day = match[2]; let hours = parseInt(match[3]); const minutes = parseInt(match[4] || "0"); const ampm = match[5].toLowerCase(); if (month && day) { targetDate.setMonth(parseInt(month) - 1); targetDate.setDate(parseInt(day)); } if (ampm === 'pm' && hours !== 12) hours += 12; if (ampm === 'am' && hours === 12) hours = 0; targetDate.setHours(hours, minutes, 0, 0); // Convert local time (targetDate) to UTC by applying offsetHours const utcSeconds = Math.floor(targetDate.getTime() / 1000) - (offsetHours * 3600); return utcSeconds; } return null; } // --- 4. LINEUP LOGIC --- const FORMATIONS = { // 6v6 Formations "2-2-1 (6v6)": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM1", "CM"], ["CM2", "CM"], ["ST", "ST"]], "3-1-1 (6v6)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["CM", "CM"], ["ST", "ST"]], "2-1-2 (6v6)": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM", "CM"], ["ST1", "ST"], ["ST2", "ST"]], "3-2-0 (6v6)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["LCM", "CM"], ["RCM", "CM"]], // 7v7 Formations (Visible in primary dropdown) "default": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CM", "CM"], ["RW", "RW"], ["LW", "LW"]], "3-1-2": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CM", "CM"], ["ST1", "ST"], ["ST2", "ST"]], "3-0-3": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"]], "3-2-1": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CM1", "CM"], ["CM2", "CM"], ["ST", "ST"]], "2-3-1": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST", "ST"]], "2-2-2": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM1", "CM"], ["CM2", "CM"], ["ST1", "ST"], ["ST2", "ST"]], "4-1-1": [["GK", "GK"], ["LCB", "LCB"], ["RCB", "RCB"], ["LB", "LB"], ["RB", "RB"], ["CDM", "CDM"], ["ST", "ST"]], "3-3-0": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"]], "2-1-3": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM", "CM"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"]], "1-4-1": [["GK", "GK"], ["CB", "CB"], ["LM", "LM"], ["LCM", "LCM"], ["RCM", "RCM"], ["RM", "RM"], ["ST", "ST"]], "4-2-0": [["GK", "GK"], ["LCB", "LCB"], ["RCB", "RCB"], ["LB", "LB"], ["RB", "RB"], ["LCM", "LCM"], ["RCM", "RCM"]], "3-1-3": [["GK", "GK"], ["CB", "CB"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"], ["ST1", "ST"], ["ST2", "ST"]], "5-0-1": [["GK", "GK"], ["LCB", "LCB"], ["CB", "CB"], ["RCB", "RCB"], ["LB", "LB"], ["RB", "RB"], ["ST", "ST"]], "3-1-1-1": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CDM", "CDM"], ["CAM", "CAM"], ["ST", "ST"]], "2-2-1-1": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["LCM", "LCM"], ["RCM", "RCM"], ["CAM", "CAM"], ["ST", "ST"]], "4-1-2": [["GK", "GK"], ["LCB", "LCB"], ["RCB", "RCB"], ["CDM", "CDM"], ["LB", "LB"], ["RB", "RB"], ["ST", "ST"]], "1-3-2": [["GK", "GK"], ["CB", "CB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST1", "ST"], ["ST2", "ST"]], "2-1-1-2": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CDM", "CDM"], ["CAM", "CAM"], ["ST1", "ST"], ["ST2", "ST"]], // 8v8 Formations "3-3-1 (8v8)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST", "ST"]], "3-2-2 (8v8)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["CM1", "CM"], ["CM2", "CM"], ["ST1", "ST"], ["ST2", "ST"]], "2-3-2 (8v8)": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST1", "ST"], ["ST2", "ST"]], "4-2-1 (8v8)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LCM", "CM"], ["RCM", "CM"], ["ST", "ST"]], "2-4-1 (8v8)": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST", "ST"]], // 9v9 Formations "3-3-2 (9v9)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST1", "ST"], ["ST2", "ST"]], "4-3-1 (9v9)": [["GK", "GK"], ["LB", "LB"], ["LCB", "LCB"], ["RCB", "RCB"], ["RB", "RB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST", "ST"]], "3-4-1 (9v9)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST", "ST"]], "4-2-2 (9v9)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LCM", "CM"], ["RCM", "CM"], ["ST1", "ST"], ["ST2", "ST"]], // 10v10 Formations "4-4-1 (10v10)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST", "ST"]], "4-3-2 (10v10)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LCM", "CM"], ["CM", "CM"], ["RCM", "CM"], ["ST1", "ST"], ["ST2", "ST"]], "3-4-2 (10v10)": [["GK", "GK"], ["LB", "LB"], ["CB", "CB"], ["RB", "RB"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST1", "ST"], ["ST2", "ST"]], // 11v11 Formations "4-3-3 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "LCB"], ["RCB", "RCB"], ["RB", "RB"], ["CDM", "CDM"], ["LCM", "LCM"], ["RCM", "RCM"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"]], "4-4-2 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "LCB"], ["RCB", "RCB"], ["RB", "RB"], ["LM", "LM"], ["CM1", "CM"], ["CM2", "CM"], ["RM", "RM"], ["ST1", "ST"], ["ST2", "ST"]], "3-5-2 (11v11)": [["GK", "GK"], ["CB", "CB"], ["LCB", "LCB"], ["RCB", "RCB"], ["LWB", "LWB"], ["RWB", "RWB"], ["CDM", "CDM"], ["LCM", "LCM"], ["RCM", "RCM"], ["ST1", "ST"], ["ST2", "ST"]], "4-2-3-1 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "LCB"], ["RCB", "RCB"], ["RB", "RB"], ["CDM1", "CDM"], ["CDM2", "CDM"], ["CAM", "CAM"], ["LM", "LM"], ["RM", "RM"], ["ST", "ST"]], "4-1-4-1 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["CDM", "CDM"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST", "ST"]], "4-5-1 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LM", "LM"], ["LCM", "CM"], ["CM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["ST", "ST"]], "5-3-2 (11v11)": [["GK", "GK"], ["LB", "LB"], ["LCB", "CB"], ["CB", "CB"], ["RCB", "CB"], ["RB", "RB"], ["LCM", "CM"], ["CM", "CM"], ["RCM", "CM"], ["ST1", "ST"], ["ST2", "ST"]], "3-4-3 (11v11)": [["GK", "GK"], ["LCB", "CB"], ["CB", "CB"], ["RCB", "CB"], ["LM", "LM"], ["LCM", "CM"], ["RCM", "CM"], ["RM", "RM"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"]] }; /** * Auto-detects positions from a formation string (like "4-3-3") or a comma-separated list. */ function autoDetectFormation(input) { if (!input) return FORMATIONS["default"]; // 1. Check for numeric formation pattern (e.g. 4-3-3 or 4-2-3-1) const numRegex = /^(\d)-(\d)-(\d)(?:-(\d))?$/; const numMatch = input.trim().match(numRegex); if (numMatch) { const result = [['GK', 'GK']]; const dfCount = parseInt(numMatch[1]); const mid1Count = parseInt(numMatch[2]); const mid2Count = parseInt(numMatch[3]); const fwCount = numMatch[4] ? parseInt(numMatch[4]) : 0; // --- Assign Defenders --- if (dfCount === 1) result.push(['CB', 'CB']); else if (dfCount === 2) result.push(['LCB', 'CB'], ['RCB', 'CB']); else if (dfCount === 3) result.push(['LB', 'LB'], ['CB', 'CB'], ['RB', 'RB']); else if (dfCount === 4) result.push(['LB', 'LB'], ['LCB', 'CB'], ['RCB', 'CB'], ['RB', 'RB']); else if (dfCount === 5) result.push(['LB', 'LB'], ['LCB', 'CB'], ['CB', 'CB'], ['RCB', 'CB'], ['RB', 'RB']); if (!numMatch[4]) { // 3-PART FORMATION (DF-MF-FW) // Midfielders if (mid1Count === 1) result.push(['CM', 'CM']); else if (mid1Count === 2) result.push(['LCM', 'CM'], ['RCM', 'CM']); else if (mid1Count === 3) result.push(['LCM', 'CM'], ['CM', 'CM'], ['RCM', 'CM']); else if (mid1Count === 4) result.push(['LM', 'LM'], ['LCM', 'CM'], ['RCM', 'CM'], ['RM', 'RM']); else if (mid1Count === 5) result.push(['LM', 'LM'], ['LCM', 'CM'], ['CM', 'CM'], ['RCM', 'CM'], ['RM', 'RM']); // Forwards if (mid2Count === 1) result.push(['ST', 'ST']); else if (mid2Count === 2) result.push(['ST1', 'ST'], ['ST2', 'ST']); else if (mid2Count === 3) result.push(['LW', 'LW'], ['ST', 'ST'], ['RW', 'RW']); else if (mid2Count === 4) result.push(['LW', 'LW'], ['ST1', 'ST'], ['ST2', 'ST'], ['RW', 'RW']); } else { // 4-PART FORMATION (DF-DM-AM-FW) // CDMs if (mid1Count === 1) result.push(['CDM', 'CDM']); else if (mid1Count === 2) result.push(['CDM1', 'CDM'], ['CDM2', 'CDM']); // AMs if (mid2Count === 1) result.push(['CAM', 'CAM']); else if (mid2Count === 2) result.push(['CAM1', 'CAM'], ['CAM2', 'CAM']); else if (mid2Count === 3) result.push(['LM', 'LM'], ['CAM', 'CAM'], ['RM', 'RM']); // Forwards if (fwCount === 1) result.push(['ST', 'ST']); else if (fwCount === 2) result.push(['ST1', 'ST'], ['ST2', 'ST']); } return result; } // 2. Fallback to comma/space separated list of positions const parts = input.split(/[,|\s]+/).map(s => s.trim().toUpperCase()).filter(s => s.length > 0); const counts = {}; const result = []; parts.forEach(pos => { counts[pos] = (counts[pos] || 0) + 1; let key = pos; const totalCount = parts.filter(p => p === pos).length; if (totalCount > 1) { key = `${pos}${counts[pos]}`; if (totalCount === 2) { if (pos === 'CB') key = counts[pos] === 1 ? 'LCB' : 'RCB'; if (pos === 'CM') key = counts[pos] === 1 ? 'LCM' : 'RCM'; if (pos === 'ST') key = counts[pos] === 1 ? 'ST1' : 'ST2'; if (pos === 'CDM') key = counts[pos] === 1 ? 'CDM1' : 'CDM2'; if (pos === 'CAM') key = counts[pos] === 1 ? 'CAM1' : 'CAM2'; } } else { key = pos; } result.push([key, pos]); }); if (!result.some(r => r[1] === 'GK')) { result.unshift(['GK', 'GK']); } return result; } // Persistence is now handled by lineup_persistence.js function getGuildLineup(guildId) { if (!guildLineups.get(guildId)) { guildLineups.set(guildId, new Map()); saveLineup(); } return guildLineups.get(guildId); } function getGuildLineupB(guildId) { if (!guildLineupsB.get(guildId)) { guildLineupsB.set(guildId, new Map()); saveLineup(); } return guildLineupsB.get(guildId); } function resolveEmojis(text, guildId) { if (!text || typeof text !== 'string') return text; const guild = client.guilds.cache.get(guildId); return text.replace(/:([a-zA-Z0-9_]+):/g, (match, name) => { // 1. Try finding in current guild (case-insensitive) let emoji = guild?.emojis.cache.find(e => e.name.toLowerCase() === name.toLowerCase()); // 2. Try finding globally if not found in guild if (!emoji && client) { emoji = client.emojis.cache.find(e => e.name.toLowerCase() === name.toLowerCase()); } return emoji ? emoji.toString() : match; }); } function getFriendlyText(guildId, needed) { const config = storage.data.config[guildId] || {}; let text = config.friendlyText || "⭐▬▬▬▬▬ **FRIENDLY** ▬▬▬▬▬⭐\n🤝 Session\n🟩 I'm In\n🟥 Busy\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n🗳️ Needed: {needed}\n@everyone"; // Replace {needed} placeholder text = text.replace('{needed}', needed); // Resolve custom emojis return resolveEmojis(text, guildId); } function createLineupView(guildId) { const lineup = getGuildLineup(guildId); // Prefer explicit map if present; otherwise fall back to A/B maps or default let formKey; if (typeof guildSelectedFormation !== 'undefined' && guildSelectedFormation && typeof guildSelectedFormation.get === 'function') { formKey = guildSelectedFormation.get(guildId) || 'default'; } else { const kb = (guildSelectedFormationA && guildSelectedFormationA.get(guildId)) || null; const kb2 = (guildSelectedFormationB && guildSelectedFormationB.get(guildId)) || null; formKey = kb || kb2 || 'default'; } const formation = formKey === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKey]; const formDisplayName = formKey === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKey; if (!formation) return { content: "❌ Error: Formation not found." }; let text = ""; for (const [posKey, posLabel] of formation) { const players = lineup.get(posKey) || []; const resolvedLabel = resolveEmojis(posLabel, guildId); if (players.length > 0) { const starter = players[0]; const subs = players.slice(1); let line = `🟩 **${resolvedLabel}** ➔ <@${starter}>`; if (subs.length > 0) { line += ` (Substitute: ` + subs.map(p => `<@${p}>`).join(', ') + `)`; } text += line + "\n\n"; } else { text += `⬛ **${resolvedLabel}** ➔ *Open*\n\n`; } } const embed = UI.createEmbed(`⚽ MATCH LINEUP — ${resolveEmojis(formDisplayName, guildId)}`, text, UI.colors.primary); embed.setFooter({ text: "Click a position below to join/leave! Use the dropdown to change formation." }); const rows = []; const categoryRow = new ActionRowBuilder().addComponents( new StringSelectMenuBuilder() .setCustomId('formation_category_select') .setPlaceholder('📂 Change Formation Size (7v7, 11v11, others...)') .addOptions([ { label: '⚽ 7v7 Formations', value: 'cat_7v7', emoji: '⚽' }, { label: '🏆 11v11 Formations', value: 'cat_11v11', emoji: '🏆' }, { label: '🎮 Other Sizes (6v6, 8v8, 9v9, 10v10)', value: 'cat_other', emoji: '🎮' } ]) ); rows.push(categoryRow); let currentRow = new ActionRowBuilder(); let currentPosCount = 0; formation.forEach(([posKey, posLabel]) => { if (currentPosCount === 5) { rows.push(currentRow); currentRow = new ActionRowBuilder(); currentPosCount = 0; } const players = lineup.get(posKey) || []; const btnLabel = posLabel; const btn = new ButtonBuilder() .setCustomId(`join_${posKey}`) .setLabel(players.length > 0 ? `${btnLabel}: ✅` : btnLabel) .setStyle(players.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Primary); if (players.length > 0) btn.setEmoji("✅"); currentRow.addComponents(btn); currentPosCount++; }); if (currentPosCount > 0) rows.push(currentRow); rows.push(new ActionRowBuilder().addComponents( new ButtonBuilder().setCustomId('lineup_done').setLabel('Show Final Image').setStyle(ButtonStyle.Success).setEmoji("🖼️"), new ButtonBuilder().setCustomId('open_custom_lineup_modal').setLabel('Custom / Other Sizes').setStyle(ButtonStyle.Primary).setEmoji("🛠️"), new ButtonBuilder().setCustomId('lineup_clear').setLabel('Clear Board').setStyle(ButtonStyle.Danger) )); const pingType = guildPingType.get(guildId) || 'everyone'; const pingMention = pingType === 'here' ? '@here' : '@everyone'; const mentionParse = ['everyone', 'roles', 'users']; const content = `${pingMention}\n**Lineup Session Active!**`; return { content, embeds: [embed], components: rows, allowedMentions: { parse: mentionParse } }; } function createScrimLineupView(guildId) { const lineupA = getGuildLineup(guildId); const lineupB = getGuildLineupB(guildId); const formKeyA = guildSelectedFormationA.get(guildId) || 'default'; const formationA = formKeyA === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKeyA]; const formDisplayNameA = formKeyA === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKeyA; const formKeyB = guildSelectedFormationB.get(guildId) || 'default'; const formationB = formKeyB === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKeyB]; const formDisplayNameB = formKeyB === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKeyB; if (!formationA || !formationB) return { content: "❌ Error: Formation not found." }; let textA = ""; let textB = ""; for (const [posKey, posLabel] of formationA) { const resolvedLabel = resolveEmojis(posLabel, guildId); const playersA = lineupA.get(posKey) || []; if (playersA.length > 0) { const starter = playersA[0]; const subs = playersA.slice(1); let line = `🟩 **${resolvedLabel}** ➔ <@${starter}>`; if (subs.length > 0) line += ` (Sub: ` + subs.map(p => `<@${p}>`).join(', ') + `)`; textA += line + "\n\n"; } else { textA += `⬛ **${resolvedLabel}** ➔ *Open*\n\n`; } } for (const [posKey, posLabel] of formationB) { const resolvedLabel = resolveEmojis(posLabel, guildId); const playersB = lineupB.get(posKey) || []; if (playersB.length > 0) { const starter = playersB[0]; const subs = playersB.slice(1); let line = `🟩 **${resolvedLabel}** ➔ <@${starter}>`; if (subs.length > 0) line += ` (Sub: ` + subs.map(p => `<@${p}>`).join(', ') + `)`; textB += line + "\n\n"; } else { textB += `⬛ **${resolvedLabel}** ➔ *Open*\n\n`; } } const embedA = UI.createEmbed(`🔵 TEAM A — ${resolveEmojis(formDisplayNameA, guildId)}`, textA, UI.colors.primary); embedA.setFooter({ text: "Click buttons below to join Team A" }); const embedB = UI.createEmbed(`🔴 TEAM B — ${resolveEmojis(formDisplayNameB, guildId)}`, textB, 0xff4444); embedB.setFooter({ text: "Click buttons below to join Team B" }); const allButtons = []; formationA.forEach(([pk, pl]) => { const pA = lineupA.get(pk) || []; allButtons.push(new ButtonBuilder().setCustomId(`scrim_join_a_${pk}`).setLabel(pA.length > 0 ? `${pl}: ✅` : pl).setStyle(pA.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Primary).setEmoji(pA.length > 0 ? "✅" : null)); }); formationB.forEach(([pk, pl]) => { const pB = lineupB.get(pk) || []; allButtons.push(new ButtonBuilder().setCustomId(`scrim_join_b_${pk}`).setLabel(pB.length > 0 ? `${pl}: ✅` : pl).setStyle(pB.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Primary).setEmoji(pB.length > 0 ? "✅" : null)); }); allButtons.push(new ButtonBuilder().setCustomId('lineup_done').setLabel('Show Image').setStyle(ButtonStyle.Success).setEmoji("🖼️")); allButtons.push(new ButtonBuilder().setCustomId('open_custom_lineup_modal').setLabel('Custom').setStyle(ButtonStyle.Primary).setEmoji("🛠️")); allButtons.push(new ButtonBuilder().setCustomId('lineup_clear').setLabel('Clear').setStyle(ButtonStyle.Danger)); let rows = []; for (let i = 0; i < allButtons.length; i += 5) { rows.push(new ActionRowBuilder().addComponents(allButtons.slice(i, i + 5))); } // Limit to 5 rows to prevent Discord API error if (rows.length > 5) rows = rows.slice(0, 5); const pingType = guildPingType.get(guildId) || 'everyone'; const pingMention = pingType === 'here' ? '@here' : '@everyone'; const mentionParse = ['everyone', 'roles', 'users']; const content = `${pingMention}\n**🔥 SCRIMMAGE LINEUP SESSION ACTIVE!**\n*Two teams facing each other!*`; return { content, embeds: [embedA, embedB], components: rows, allowedMentions: { parse: mentionParse } }; } function createManagerEditor(guildId, client) { const lineup = getGuildLineup(guildId); const formKey = guildSelectedFormation.get(guildId) || 'default'; const formation = formKey === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKey]; const formDisplayName = formKey === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKey; if (!formation) return { content: "❌ Error: Formation not found." }; let text = `🛠️ **LINEUP GUI EDITOR** — ${resolveEmojis(formDisplayName, guildId)}\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n`; for (const [posKey, posLabel] of formation) { const players = lineup.get(posKey) || []; const userStr = players.length > 0 ? `<@${players[0]}>` : "---"; text += `📦 **${resolveEmojis(posLabel, guildId)}**: ${userStr}\n`; } text += "▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n*Click a box below to edit a position!*"; const rows = []; let currentRow = new ActionRowBuilder(); let currentPosCount = 0; formation.forEach(([posKey, posLabel]) => { if (currentPosCount === 4) { rows.push(currentRow); currentRow = new ActionRowBuilder(); currentPosCount = 0; } const players = lineup.get(posKey) || []; let valTitle = "---"; if (players.length > 0 && client) { const tempUser = client.users.cache.get(players[0]); valTitle = tempUser ? tempUser.username : "Player"; } else if (players.length > 0) { valTitle = "Player"; } currentRow.addComponents( new ButtonBuilder() .setCustomId(`man_edit_${posKey}`) .setLabel(`${posLabel}: ${valTitle}`) .setStyle(ButtonStyle.Secondary) .setEmoji("🛠️") ); currentPosCount++; }); if (currentPosCount > 0) rows.push(currentRow); // Add a Done/Submit button at the bottom rows.push(new ActionRowBuilder().addComponents( new ButtonBuilder().setCustomId('lineup_done').setLabel('Generate Final Image').setStyle(ButtonStyle.Success).setEmoji("🖼️") )); return { content: text, components: rows }; } // --- 5. 24/7 HEARTBEAT & RECOVERY --- const fetch = require('node-fetch'); /** Public Space URL for keep-alive pings (HF injects these at runtime). */ function getSpacePublicUrl() { const host = (process.env.SPACE_HOST || '').trim(); if (host) return host.startsWith('http') ? host : `https://${host}`; const spaceId = (process.env.SPACE_ID || '').trim(); if (spaceId) return `https://${spaceId.replace('/', '-').toLowerCase()}.hf.space`; const author = (process.env.SPACE_AUTHOR_NAME || '').trim(); const repo = (process.env.SPACE_REPO_NAME || '').trim(); if (author && repo) return `https://${author}-${repo}`.toLowerCase().replace(/\s+/g, '') + '.hf.space'; return ''; } let recoveryDisconnectedSince = null; let recoveryAttempts = 0; setInterval(async () => { const url = getSpacePublicUrl(); if (url) { fetch(url, { method: 'GET' }).catch(() => { }); } // Recovery Check: Handle BOTH online-but-degraded AND fully offline states const isReady = client.isReady(); const wsStatus = client.ws?.status ?? -1; if (isReady && wsStatus === 0) { // Everything is healthy — reset recovery state recoveryDisconnectedSince = null; recoveryAttempts = 0; return; } // Something is wrong — either not ready, or gateway is degraded if (!recoveryDisconnectedSince) recoveryDisconnectedSince = Date.now(); const downMs = Date.now() - recoveryDisconnectedSince; if (isReady && wsStatus !== 0) { // Client thinks it's ready but gateway is degraded console.log(`[!] Gateway degraded. WS status: ${wsStatus}. Down for ${Math.round(downMs / 1000)}s.`); } else { // Client is fully offline console.log(`[!] Bot is OFFLINE. WS status: ${wsStatus}. Down for ${Math.round(downMs / 1000)}s.`); } // After 2 minutes of issues, rotate DNS and attempt reconnect if (downMs > 2 * 60 * 1000 && recoveryAttempts < 3) { recoveryAttempts++; console.log(`[RECOVERY] Attempt ${recoveryAttempts}/3: Rotating DNS and attempting re-login...`); networkFix.rotateEndpoint(); try { client.destroy(); await new Promise(r => setTimeout(r, 2000)); await client.login(TOKEN); console.log('[RECOVERY] Re-login successful!'); recoveryDisconnectedSince = null; recoveryAttempts = 0; } catch (err) { console.error(`[RECOVERY] Re-login failed: ${err?.message || err}`); } } // After 3 failed recovery attempts (~6+ minutes), force restart the container if (recoveryAttempts >= 3 && downMs > 6 * 60 * 1000) { console.error('[RECOVERY] All recovery attempts exhausted. Forcing process exit for container restart...'); process.exit(1); } }, 2 * 60 * 1000); // Every 2 minutes async function showAutoFriendlyPanel(interaction) { const guildId = interaction.guildId; const config = storage.data.config[guildId] || {}; const enabled = config.autoFriendlyEnabled || false; const interval = config.autoFriendlyInterval || 40; const channelId = config.autoFriendlyChannel; const embed = UI.createEmbed("🤖 Auto Friendly Settings", `Configure the bot to automatically start friendly polls.\n\n` + `**Status**: ${enabled ? '✅ Enabled' : '❌ Disabled'}\n` + `**Interval**: \`${interval}\` minutes\n` + `**Target Channel**: ${channelId ? `<#${channelId}>` : '`Not Set`'}`, enabled ? UI.colors.success : UI.colors.primary ); const row1 = new ActionRowBuilder().addComponents( new ButtonBuilder() .setCustomId('toggle_auto_friendly') .setLabel(enabled ? 'Disable Auto Friendly' : 'Enable Auto Friendly') .setStyle(enabled ? ButtonStyle.Danger : ButtonStyle.Success), new ButtonBuilder() .setCustomId('open_interval_modal') .setLabel('Set Interval') .setStyle(ButtonStyle.Primary) ); const row2 = new ActionRowBuilder().addComponents( new ChannelSelectMenuBuilder() .setCustomId('auto_friendly_channel_select') .setPlaceholder('Select target channel...') .addChannelTypes(ChannelType.GuildText) ); if (interaction.replied || interaction.deferred) { await interaction.editReply({ embeds: [embed], components: [row1, row2] }); } else { await interaction.reply({ embeds: [embed], components: [row1, row2], ephemeral: true }); } } /** * Application Entry Point */ async function initialize() { let retryCount = 0; const maxRetryDelay = 60000; // Cap at 1 minute between retries // STEP 1: Start the web server FIRST. // HF will kill the container if port 7860 doesn't respond quickly. console.log("[*] Starting Web Dashboard..."); server.startServer(client, commandsData); // STEP 2: Give the container's network stack a moment to settle. // On HF cold-starts, the outbound network may not be ready immediately. console.log("[*] Waiting 3s for network stack to stabilize..."); await new Promise(r => setTimeout(r, 3000)); // STEP 3: Start the Discord login loop. login(); async function login() { if (!TOKEN || TOKEN.length < 10) { console.error("[CRITICAL] Discord Token is missing or malformed."); process.exit(1); } retryCount++; try { const currentApi = DISCORD_ENDPOINTS[currentEndpointIndex]; console.log(`[*] 📡 VERIFYING: ${currentApi}...`); // Manual Force-Fetch to bypass Discord.js token-not-present error const { request } = require('undici'); let testRes = null; let testError = null; try { const response = await request(`${currentApi}/v10/users/@me`, { method: 'GET', headers: { 'Authorization': `Bot ${TOKEN}`, 'User-Agent': 'DiscordBot (FriendlyBot, 4.0)' } }); if (response.statusCode === 200) testRes = { ok: true }; else if (response.statusCode === 401) testRes = { status: 401 }; else testError = { status: response.statusCode, message: "Blocked or Rate Limited" }; } catch (e) { testError = e; } if (testRes && testRes.status === 401) { console.error("[CRITICAL] ❌ TOKEN INVALID (401). Check Discord Dev Portal!"); return; } else if (testRes) { console.log(`[SUCCESS] ✅ Connected via ${currentApi}`); client.token = TOKEN; } else { const errDetail = testError ? `${testError.status || 'TIMEOUT'} - ${testError.message}` : "Unknown Error"; console.warn(`[BLOCKED] ⚠️ ${currentApi} failed: ${errDetail}`); currentEndpointIndex = (currentEndpointIndex + 1) % DISCORD_ENDPOINTS.length; throw new Error("Cycle endpoints"); } console.log(`[*] Attempting connection to Discord (Attempt ${retryCount}) using ${currentApi}...`); // Destroy any stale connection before retrying if (retryCount > 1) { try { client.destroy(); } catch (_) { } await new Promise(r => setTimeout(r, 1000)); } await client.login(TOKEN); console.log('[*] Discord login() resolved successfully.'); if (connectionTimeout) clearTimeout(connectionTimeout); retryCount = 0; // Reset on success } catch (err) { const msg = err && err.message ? err.message : String(err); console.error(`[ERROR] Discord login failed: ${msg}`); if (/intent|disallowed|4014|privileg/i.test(msg)) { console.error('[HINT] https://discord.com/developers/applications → your app → Bot → Privileged Gateway Intents: turn ON "Server Members Intent" and "Message Content Intent", then restart this Space.'); } // Token errors are fatal — don't retry forever if (/token|unauthorized|authentication|403|401/i.test(msg) && retryCount >= 3) { console.error('[CRITICAL] Token appears invalid after 3 attempts. Stopping retries.'); return; } // Rotate endpoint for next attempt if this was an actual connection/login failure if (msg !== 'Cycle endpoints') { currentEndpointIndex = (currentEndpointIndex + 1) % DISCORD_ENDPOINTS.length; } const delay = Math.min(1000 * Math.pow(2, retryCount), maxRetryDelay); console.log(`[*] Retrying in ${delay / 1000}s... (attempt ${retryCount})`); setTimeout(login, delay); } } // --- 24/7 Heartbeat + Self-Healing --- // Runs every 5 minutes (not hourly!) for faster detection of problems. let disconnectedSince = null; setInterval(async () => { const up = process.uptime(); const h = Math.floor(up / 3600); const m = Math.floor(up / 60) % 60; const connected = client.isReady(); const wsStatus = client.ws?.status ?? -1; console.log(`[24/7 HEARTBEAT] Uptime: ${h}h ${m}m | Discord: ${connected ? 'CONNECTED ✓' : 'DISCONNECTED ✗'} | WS: ${wsStatus}`); // Track how long we've been disconnected if (!connected) { if (!disconnectedSince) disconnectedSince = Date.now(); const disconnectedMs = Date.now() - disconnectedSince; // After 5 minutes disconnected, try to reconnect with fresh DNS if (disconnectedMs > 5 * 60 * 1000 && disconnectedMs <= 6 * 60 * 1000) { console.warn(`[HEARTBEAT] Bot disconnected for ${Math.round(disconnectedMs / 60000)} minutes. Attempting DNS rotation + re-login...`); networkFix.rotateEndpoint(); try { client.destroy(); await new Promise(r => setTimeout(r, 2000)); await client.login(TOKEN); console.log('[HEARTBEAT] Re-login successful!'); disconnectedSince = null; } catch (err) { console.error(`[HEARTBEAT] Re-login failed: ${err?.message || err}`); } } // If disconnected for over 15 minutes even after reconnect attempts, force restart if (disconnectedMs > 15 * 60 * 1000) { console.error(`[!] Bot disconnected for ${Math.round(disconnectedMs / 60000)} minutes. Forcing process exit for container restart...`); process.exit(1); } } else { disconnectedSince = null; } // Ping own public URL to prevent HF from sleeping the Space const spaceHost = process.env.SPACE_HOST; if (spaceHost) { fetch(`https://${spaceHost}/healthz`).catch(() => { }); } // Also ping localhost as fallback fetch(`http://0.0.0.0:${process.env.PORT || 7860}/healthz`).catch(() => { }); }, 5 * 60 * 1000); // Every 5 minutes } initialize().catch(err => { console.error(">>> [BOOT] CRITICAL INITIALIZATION ERROR:", err); process.exit(1); });
"use strict";
// -------------------------------------------------------------
// DEBUG LOGGING - FIRST LINES
// -------------------------------------------------------------
console.log(">>> [BOOT] Application process group starting...");
process.stdout.write(">>> [BOOT] Purity check: Stdout is writeable.\n");
console.error(">>> [BOOT] Purity check: Stderr is writeable.");
process.on('unhandledRejection', (reason, promise) => {
console.error('>>> [BOOT] UNHANDLED REJECTION:', reason);
});
process.on('uncaughtException', (err) => {
console.error('>>> [BOOT] UNCAUGHT EXCEPTION:', err);
console.error(err.stack);
});
console.log(">>> [BOOT] Loading dependencies...");
require('dotenv').config();
const ultimateFix = require('./ultimate_fix'); // High priority fix
const networkFix = require('./network_fix');
const { Client, GatewayIntentBits, Partials, Collection, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, UserSelectMenuBuilder, ChannelSelectMenuBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ComponentType, MessageFlags, ChannelType } = require('discord.js');
function sendServerTransaction(type, guild) {
if (!guild || !guild.id) return;
console.log('SEND_SERVER_TRANSACTION', type, guild.id, guild.name || '');
}
function sendJoinTransaction(guild) {
sendServerTransaction('join', guild);
}
function sendLeaveTransaction(guild) {
sendServerTransaction('leave', guild);
}
console.log(">>> [BOOT] Discord.js loaded.");
console.log(">>> [BOOT] Loading Storage...");
const storage = require('./storage');
console.log(">>> [BOOT] Storage loaded.");
console.log(">>> [BOOT] Loading RoleStorage...");
const roleStorage = require('./roleStorage');
console.log(">>> [BOOT] RoleStorage loaded.");
console.log(">>> [BOOT] Loading Web Server module...");
const server = require('./server');
console.log(">>> [BOOT] Web Server module loaded.");
const { guildLineups, guildLineupsB, guildScrimMode, guildSelectedFormationA, guildSelectedFormationB, guildSelectedFormation, lineupOwners, activeLineupMessages, managerBoards, guildCustomFormations, guildCustomFormationNames, guildPingType, guildFriendlyPingType, save: saveLineup } = require('./lineup_persistence');
const guildActiveCategory = new Map(); // Stores the currently selected category in the UI for each guild
try {
const { createLineupAttachment, renderLineupImage } = require('./lineupRenderer');
const { createProfileAttachment } = require('./profileRenderer');
const { TACTICS, createTacticAttachment } = require('./tacticRenderer');
global.createLineupAttachment = createLineupAttachment;
global.createProfileAttachment = createProfileAttachment;
global.createTacticAttachment = createTacticAttachment;
global.TACTICS = TACTICS;
global.saveLineup = saveLineup;
console.log(">>> [BOOT] Graphics Renderers & Persistence loaded.");
} catch (err) {
console.error(">>> [BOOT] ERROR LOADING GRAPHICS:", err.message);
}
const { UI } = require('./NewBotStyle');
const broadcastSystem = require('./broadcast_system');
const grantSystem = require('./grant_system');
console.log(`[SYSTEM] Starting FriendlyBot v4.0 (Watchdog Relaxed: ${new Date().toISOString()})`);
process.on('unhandledRejection', (reason, promise) => {
console.error('[!] Unhandled Rejection:', reason);
});
process.on('uncaughtException', (err) => {
console.error('[!] Uncaught Exception:', err);
});
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildEmojisAndStickers
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
rest: {
timeout: 60000,
retries: 3
}
});