Spaces:
Runtime error
Runtime error
Update index.js
Browse files2677 unmodified lines2678267926802681268226832684268526862687268826892690269140 unmodified lines273227332734273527362737273816 unmodified lines275527562757275827592760276127622763501 unmodified lines3265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289151 unmodified lines3441344234433444344534463447344834493450345134523453345434553456345734583459346034612677 unmodified lines// Store needed count for each active pollconst pollNeededCount = new Map();// Handle reaction removal to decrease countclient.on('messageReactionRemove', async (reaction, user) => {if (user.bot) return;try {// Handle partials for both reaction and message to ensure content is availableif (reaction.partial) await reaction.fetch();if (reaction.message.partial) await reaction.message.fetch();if (reaction.emoji.name === '🟩') {const guildId = reaction.message.guildId;40 unmodified linesif (storage.data.onboarded[guildId].includes(newMember.id)) return;// Send onboarding DMconst dashboardUrl = `https://${process.env.SPACE_ID || '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);16 unmodified lines}});async function triggerOnboardingForRole(guild, role) {const guildId = guild.id;const dashboardUrl = `https://${process.env.SPACE_ID || 'brozy123-lineup-bot'}.hf.space`;try {// Ensure members are cached to find role holders501 unmodified linesreturn '';}setInterval(async () => {const url = getSpacePublicUrl();if (url) {fetch(url, { method: 'GET' }).catch(() => { });}// Recovery Check: If client is not ready or WS is deadif (client.isReady()) {if (client.ws.status !== 0) {console.log("[!] Gateway issues detected. Status:", client.ws.status);console.log("[*] Performing emergency network rotation and restart...");networkFix.rotateEndpoint();// Attempt to keep session alive or force a new login if really deadif (client.ws.status === 7 || client.ws.status === 9) { // DISCONNECTED or INVALID_SESSIONprocess.exit(1); // Force a full container restart by PM2/HuggingFace}}}}, 2 * 60 * 1000); // Every 2 minutesasync function showAutoFriendlyPanel(interaction) {151 unmodified lines// Runs every 5 minutes (not hourly!) for faster detection of problems.let disconnectedSince = null;setInterval(() => {const up = process.uptime();const h = Math.floor(up / 3600);const m = Math.floor(up / 60) % 60;const connected = client.isReady();console.log(`[24/7 HEARTBEAT] Uptime: ${h}h ${m}m | Discord: ${connected ? 'CONNECTED ✓' : 'DISCONNECTED ✗'}`);// Track how long we've been disconnectedif (!connected) {if (!disconnectedSince) disconnectedSince = Date.now();const disconnectedMs = Date.now() - disconnectedSince;// If disconnected for over 10 minutes, force restart so HF rebuilds the containerif (disconnectedMs > 10 * 60 * 1000) {console.error(`[!] Bot disconnected for ${Math.round(disconnectedMs / 60000)} minutes. Forcing process exit for container restart...`);process.exit(1);}2677 unmodified lines267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270240 unmodified lines274327442745274627472748274916 unmodified lines27662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851501 unmodified lines335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412151 unmodified lines35643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936002677 unmodified lines// Store needed count for each active pollconst 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 countclient.on('messageReactionRemove', async (reaction, user) => {if (user.bot) return;try {// Handle partials for both reaction and message to ensure content is availableif (reaction.partial) await fetchWithRetry(() => reaction.fetch());if (reaction.message.partial) await fetchWithRetry(() => reaction.message.fetch());if (reaction.emoji.name === '🟩') {const guildId = reaction.message.guildId;40 unmodified linesif (storage.data.onboarded[guildId].includes(newMember.id)) return;// Send onboarding DMconst 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);16 unmodified lines}});// Log server join to designated log channelclient.on('guildCreate', async (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 detailslet 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/auditslet 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);}});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 holders501 unmodified linesreturn '';}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 statesconst isReady = client.isReady();const wsStatus = client.ws?.status ?? -1;if (isReady && wsStatus === 0) {// Everything is healthy — reset recovery staterecoveryDisconnectedSince = null;recoveryAttempts = 0;return;}// Something is wrong — either not ready, or gateway is degradedif (!recoveryDisconnectedSince) recoveryDisconnectedSince = Date.now();const downMs = Date.now() - recoveryDisconnectedSince;if (isReady && wsStatus !== 0) {// Client thinks it's ready but gateway is degradedconsole.log(`[!] Gateway degraded. WS status: ${wsStatus}. Down for ${Math.round(downMs / 1000)}s.`);} else {// Client is fully offlineconsole.log(`[!] Bot is OFFLINE. WS status: ${wsStatus}. Down for ${Math.round(downMs / 1000)}s.`);}// After 2 minutes of issues, rotate DNS and attempt reconnectif (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 containerif (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 minutesasync function showAutoFriendlyPanel(interaction) {151 unmodified lines// 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 disconnectedif (!connected) {if (!disconnectedSince) disconnectedSince = Date.now();const disconnectedMs = Date.now() - disconnectedSince;// After 5 minutes disconnected, try to reconnect with fresh DNSif (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 restartif (disconnectedMs > 15 * 60 * 1000) {console.error(`[!] Bot disconnected for ${Math.round(disconnectedMs / 60000)} minutes. Forcing process exit for container restart...`);process.exit(1);}
index.js+157-18