Brozy123 commited on
Commit
c8f5ec1
·
verified ·
1 Parent(s): f1f311e

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +18 -139
index.js CHANGED
@@ -99,7 +99,7 @@ const client = new Client({
99
  },
100
  ws: {
101
  agent: require('https').globalAgent,
102
- gateway: (process.env.DISCORD_BASE_URL ? process.env.DISCORD_BASE_URL.replace('http', 'ws') : undefined),
103
  compress: false // Disable compression for more stability over the proxy tunnel
104
  }
105
  });
@@ -133,32 +133,6 @@ client.on('invalidated', () => {
133
  process.exit(1);
134
  });
135
 
136
- // Clean shutdown handlers for container restarts (Hugging Face)
137
- process.on('SIGTERM', () => {
138
- console.log('[SYSTEM] SIGTERM received. Shutting down cleanly...');
139
- if (client) {
140
- try {
141
- client.destroy();
142
- console.log('[SYSTEM] Discord client destroyed.');
143
- } catch (err) {
144
- console.error('[SYSTEM] Error destroying client:', err);
145
- }
146
- }
147
- process.exit(0);
148
- });
149
- process.on('SIGINT', () => {
150
- console.log('[SYSTEM] SIGINT received. Shutting down cleanly...');
151
- if (client) {
152
- try {
153
- client.destroy();
154
- console.log('[SYSTEM] Discord client destroyed.');
155
- } catch (err) {
156
- console.error('[SYSTEM] Error destroying client:', err);
157
- }
158
- }
159
- process.exit(0);
160
- });
161
-
162
  client.commands = new Collection();
163
 
164
  // --- 1. CONFIG ---
@@ -630,15 +604,6 @@ client.on('messageCreate', async (message) => {
630
  return;
631
  }
632
 
633
- // Check if the current guild is locked (stops bot commands from working)
634
- if (message.guildId && storage.data.settings?.lockedServers?.includes(message.guildId)) {
635
- if (message.author.id === '1479214179146535096' && commandName === 'unlock') {
636
- // Allow the owner to unlock the server
637
- } else {
638
- return;
639
- }
640
- }
641
-
642
  const botEnabled = config.botEnabled !== false; // Default to true if not set
643
 
644
  if (!botEnabled && commandName !== 'on') {
@@ -996,7 +961,7 @@ client.on('messageCreate', async (message) => {
996
  const mentions = scorers.match(/<@!?(\d+)>/g) || [];
997
  mentions.forEach(m => storage.addStat(m.replace(/[<@!>]/g, ''), 'goals'));
998
 
999
- storage.save('config');
1000
  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);
1001
  await message.channel.send({ embeds: [embed] });
1002
  return;
@@ -1139,19 +1104,6 @@ client.on('messageCreate', async (message) => {
1139
  }
1140
 
1141
  if (commandName === 'lock') {
1142
- const targetGuildId = args[0] ? args[0].trim() : null;
1143
- if (message.author.id === '1479214179146535096' && targetGuildId && /^\d{17,20}$/.test(targetGuildId)) {
1144
- if (!storage.data.settings.lockedServers) {
1145
- storage.data.settings.lockedServers = [];
1146
- }
1147
- if (!storage.data.settings.lockedServers.includes(targetGuildId)) {
1148
- storage.data.settings.lockedServers.push(targetGuildId);
1149
- storage.save('settings');
1150
- }
1151
- await message.reply(`🔒 Server **${targetGuildId}** has been locked. The bot will no longer respond to commands in that server.`);
1152
- return;
1153
- }
1154
-
1155
  if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
1156
  await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, { SendMessages: false });
1157
  await message.reply("🔒 Channel Locked.");
@@ -1159,17 +1111,6 @@ client.on('messageCreate', async (message) => {
1159
  }
1160
 
1161
  if (commandName === 'unlock') {
1162
- const targetGuildId = args[0] ? args[0].trim() : null;
1163
- if (message.author.id === '1479214179146535096' && targetGuildId && /^\d{17,20}$/.test(targetGuildId)) {
1164
- if (!storage.data.settings.lockedServers) {
1165
- storage.data.settings.lockedServers = [];
1166
- }
1167
- storage.data.settings.lockedServers = storage.data.settings.lockedServers.filter(id => id !== targetGuildId);
1168
- storage.save('settings');
1169
- await message.reply(`🔓 Server **${targetGuildId}** has been unlocked.`);
1170
- return;
1171
- }
1172
-
1173
  if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
1174
  await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, { SendMessages: true });
1175
  await message.reply("🔓 Channel Unlocked.");
@@ -1290,48 +1231,20 @@ client.on('messageCreate', async (message) => {
1290
 
1291
  guildsInfoRaw.sort((a, b) => b.count - a.count);
1292
 
1293
- const lines = guildsInfoRaw.map((g, i) => {
 
1294
  const serverName = g.link ? `[${g.name}](${g.link})` : g.name;
1295
- return `**${i + 1}.** ${serverName} — \`${g.count}\` members`;
 
1296
  });
 
1297
 
1298
- const chunks = [];
1299
- let currentChunk = "";
1300
- for (const line of lines) {
1301
- if (currentChunk.length + line.length + 1 > 3800) {
1302
- chunks.push(currentChunk);
1303
- currentChunk = line + "\n";
1304
- } else {
1305
- currentChunk += line + "\n";
1306
- }
1307
- }
1308
- if (currentChunk) chunks.push(currentChunk);
1309
-
1310
- const totalText = `\nTotal servers: ${client.guilds.cache.size}`;
1311
 
1312
- if (chunks.length === 0) {
1313
- const embed = new EmbedBuilder()
1314
- .setTitle(`🌐 Serving ${client.guilds.cache.size} Servers`)
1315
- .setDescription(`No servers found.${totalText}`)
1316
- .setColor('#5865F2');
1317
- await statusMsg.edit({ content: null, embeds: [embed] });
1318
- } else {
1319
- // Edit statusMsg with the first chunk
1320
- const firstEmbed = new EmbedBuilder()
1321
- .setTitle(`🌐 Serving ${client.guilds.cache.size} Servers${chunks.length > 1 ? ` (Part 1/${chunks.length})` : ''}`)
1322
- .setDescription(chunks[0] + (chunks.length === 1 ? totalText : ""))
1323
- .setColor('#5865F2');
1324
- await statusMsg.edit({ content: null, embeds: [firstEmbed] });
1325
-
1326
- // Send subsequent chunks
1327
- for (let i = 1; i < chunks.length; i++) {
1328
- const nextEmbed = new EmbedBuilder()
1329
- .setTitle(`🌐 Serving ${client.guilds.cache.size} Servers (Part ${i + 1}/${chunks.length})`)
1330
- .setDescription(chunks[i] + (i === chunks.length - 1 ? totalText : ""))
1331
- .setColor('#5865F2');
1332
- await message.channel.send({ embeds: [nextEmbed] });
1333
- }
1334
- }
1335
  return;
1336
  }
1337
 
@@ -1548,11 +1461,6 @@ Tip: All commands support Discord Slash Commands (/) for a better experience!`;
1548
 
1549
  async function safeReply(interaction, options) {
1550
  try {
1551
- if (typeof options === 'string') {
1552
- options = options.slice(0, 2000);
1553
- } else if (options && typeof options.content === 'string') {
1554
- options.content = options.content.slice(0, 2000);
1555
- }
1556
  if (interaction.deferred || interaction.replied) {
1557
  return await interaction.editReply(options);
1558
  } else {
@@ -1583,11 +1491,6 @@ async function sendNoPermission(ctx) {
1583
 
1584
  // Interaction Handler
1585
  client.on('interactionCreate', async (interaction) => {
1586
- // Check if guild is locked
1587
- if (interaction.guildId && storage.data.settings?.lockedServers?.includes(interaction.guildId)) {
1588
- return;
1589
- }
1590
-
1591
  // 1. Handle Timezone Selection IMMEDIATELY (Priority)
1592
  if (interaction.isStringSelectMenu() && interaction.customId && interaction.customId.startsWith('tz_select_')) {
1593
  try {
@@ -1871,7 +1774,7 @@ client.on('interactionCreate', async (interaction) => {
1871
  storage.addStat(uid, 'goals');
1872
  });
1873
 
1874
- storage.save('config');
1875
  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);
1876
  await safeReply(interaction, { embeds: [embed] });
1877
  }
@@ -3714,13 +3617,6 @@ async function initialize() {
3714
  const errDetail = testError ? `${testError.status || 'TIMEOUT'} - ${testError.message}` : "Unknown Error";
3715
  console.warn(`[BLOCKED] ⚠️ ${currentApi} failed: ${errDetail}`);
3716
 
3717
- if (process.env.DISCORD_BASE_URL && currentEndpointIndex === 0) {
3718
- console.log("[!] Still blocked via Worker. Retrying worker path in 5s...");
3719
- await new Promise(r => setTimeout(r, 5000));
3720
- login();
3721
- return;
3722
- }
3723
-
3724
  currentEndpointIndex = (currentEndpointIndex + 1) % DISCORD_ENDPOINTS.length;
3725
  throw new Error("Cycle endpoints");
3726
  }
@@ -3753,6 +3649,11 @@ async function initialize() {
3753
  return;
3754
  }
3755
 
 
 
 
 
 
3756
  const delay = Math.min(1000 * Math.pow(2, retryCount), maxRetryDelay);
3757
  console.log(`[*] Retrying in ${delay / 1000}s... (attempt ${retryCount})`);
3758
  setTimeout(login, delay);
@@ -3772,28 +3673,6 @@ async function initialize() {
3772
 
3773
  console.log(`[24/7 HEARTBEAT] Uptime: ${h}h ${m}m | Discord: ${connected ? 'CONNECTED ✓' : 'DISCONNECTED ✗'} | WS: ${wsStatus}`);
3774
 
3775
- // REST Health Check
3776
- let restHealthy = false;
3777
- if (connected) {
3778
- try {
3779
- // Perform a simple lightweight API request to verify the proxy/REST channel is healthy
3780
- await client.users.fetch(client.user.id);
3781
- restHealthy = true;
3782
- } catch (err) {
3783
- console.error(`[REST HEALTH] REST request failed via ${client.options.rest.api || 'default'}: ${err?.message || err}`);
3784
- }
3785
-
3786
- // If REST failed but Gateway is connected, rotate REST endpoints to recover connectivity
3787
- if (!restHealthy) {
3788
- console.warn("[REST HEALTH] REST API is unresponsive. Attempting to rotate REST endpoint...");
3789
- currentEndpointIndex = (currentEndpointIndex + 1) % DISCORD_ENDPOINTS.length;
3790
- const nextApi = DISCORD_ENDPOINTS[currentEndpointIndex];
3791
- console.log(`[REST HEALTH] Switching REST API endpoint to: ${nextApi}`);
3792
- client.options.rest.api = nextApi;
3793
- if (client.rest) client.rest.options.api = nextApi;
3794
- }
3795
- }
3796
-
3797
  // Track how long we've been disconnected
3798
  if (!connected) {
3799
  if (!disconnectedSince) disconnectedSince = Date.now();
 
99
  },
100
  ws: {
101
  agent: require('https').globalAgent,
102
+ gateway: undefined, // Connect directly to official Discord gateway to avoid proxy TLS/routing issues
103
  compress: false // Disable compression for more stability over the proxy tunnel
104
  }
105
  });
 
133
  process.exit(1);
134
  });
135
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  client.commands = new Collection();
137
 
138
  // --- 1. CONFIG ---
 
604
  return;
605
  }
606
 
 
 
 
 
 
 
 
 
 
607
  const botEnabled = config.botEnabled !== false; // Default to true if not set
608
 
609
  if (!botEnabled && commandName !== 'on') {
 
961
  const mentions = scorers.match(/<@!?(\d+)>/g) || [];
962
  mentions.forEach(m => storage.addStat(m.replace(/[<@!>]/g, ''), 'goals'));
963
 
964
+ storage.save('records');
965
  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);
966
  await message.channel.send({ embeds: [embed] });
967
  return;
 
1104
  }
1105
 
1106
  if (commandName === 'lock') {
 
 
 
 
 
 
 
 
 
 
 
 
 
1107
  if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
1108
  await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, { SendMessages: false });
1109
  await message.reply("🔒 Channel Locked.");
 
1111
  }
1112
 
1113
  if (commandName === 'unlock') {
 
 
 
 
 
 
 
 
 
 
 
1114
  if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
1115
  await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, { SendMessages: true });
1116
  await message.reply("🔓 Channel Unlocked.");
 
1231
 
1232
  guildsInfoRaw.sort((a, b) => b.count - a.count);
1233
 
1234
+ let desc = "";
1235
+ guildsInfoRaw.forEach((g, i) => {
1236
  const serverName = g.link ? `[${g.name}](${g.link})` : g.name;
1237
+ let line = `**${i + 1}.** ${serverName} — \`${g.count}\` members\n`;
1238
+ if (desc.length + line.length < 4000) desc += line; // Embed safety cap
1239
  });
1240
+ desc += `\nTotal servers: ${client.guilds.cache.size}`;
1241
 
1242
+ const embed = new EmbedBuilder()
1243
+ .setTitle(`🌐 Serving ${client.guilds.cache.size} Servers`)
1244
+ .setDescription(desc)
1245
+ .setColor('#5865F2');
 
 
 
 
 
 
 
 
 
1246
 
1247
+ await statusMsg.edit({ content: null, embeds: [embed] });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1248
  return;
1249
  }
1250
 
 
1461
 
1462
  async function safeReply(interaction, options) {
1463
  try {
 
 
 
 
 
1464
  if (interaction.deferred || interaction.replied) {
1465
  return await interaction.editReply(options);
1466
  } else {
 
1491
 
1492
  // Interaction Handler
1493
  client.on('interactionCreate', async (interaction) => {
 
 
 
 
 
1494
  // 1. Handle Timezone Selection IMMEDIATELY (Priority)
1495
  if (interaction.isStringSelectMenu() && interaction.customId && interaction.customId.startsWith('tz_select_')) {
1496
  try {
 
1774
  storage.addStat(uid, 'goals');
1775
  });
1776
 
1777
+ storage.save('records');
1778
  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);
1779
  await safeReply(interaction, { embeds: [embed] });
1780
  }
 
3617
  const errDetail = testError ? `${testError.status || 'TIMEOUT'} - ${testError.message}` : "Unknown Error";
3618
  console.warn(`[BLOCKED] ⚠️ ${currentApi} failed: ${errDetail}`);
3619
 
 
 
 
 
 
 
 
3620
  currentEndpointIndex = (currentEndpointIndex + 1) % DISCORD_ENDPOINTS.length;
3621
  throw new Error("Cycle endpoints");
3622
  }
 
3649
  return;
3650
  }
3651
 
3652
+ // Rotate endpoint for next attempt if this was an actual connection/login failure
3653
+ if (msg !== 'Cycle endpoints') {
3654
+ currentEndpointIndex = (currentEndpointIndex + 1) % DISCORD_ENDPOINTS.length;
3655
+ }
3656
+
3657
  const delay = Math.min(1000 * Math.pow(2, retryCount), maxRetryDelay);
3658
  console.log(`[*] Retrying in ${delay / 1000}s... (attempt ${retryCount})`);
3659
  setTimeout(login, delay);
 
3673
 
3674
  console.log(`[24/7 HEARTBEAT] Uptime: ${h}h ${m}m | Discord: ${connected ? 'CONNECTED ✓' : 'DISCONNECTED ✗'} | WS: ${wsStatus}`);
3675
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3676
  // Track how long we've been disconnected
3677
  if (!connected) {
3678
  if (!disconnectedSince) disconnectedSince = Date.now();