Brozy123 commited on
Commit
5310077
·
verified ·
1 Parent(s): 7169c60

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +118 -135
index.js CHANGED
@@ -419,120 +419,120 @@ async function logTransaction(client, commandName, user, guild, member) {
419
  }
420
  } catch (e) {
421
  console.error("Log Transaction Error:", e);
422
- }
423
- }
424
-
425
- // --- 3. EVENT HANDLERS ---
426
-
427
- // Message Command Handler (Prefix Support)
428
- client.on('messageCreate', async (message) => {
429
- // Handle DM commands (mute/unmute work in DMs)
430
- if (message.channel.type === 1) { // DM channel
431
- if (message.author.bot) return;
432
- const prefix = '!';
433
- if (!message.content.startsWith(prefix)) return;
434
-
435
- return; // Ignore commands in DM
436
- }
437
-
438
- const prefix = storage.getPrefix(message.guildId);
439
- if (message.author.bot || !message.content.startsWith(prefix)) return;
440
-
441
- const args = message.content.slice(prefix.length).trim().split(/ +/);
442
- const commandName = args.shift().toLowerCase();
443
 
444
- const allCommands = [...commandsData.map(c => c.name), 'sync', 'sync_cmds', 'reboot', 'grantservers', 'servers', 'help', 'motm', 'profileimage', 'swap'];
445
- if (allCommands.includes(commandName)) {
446
- logTransaction(client, commandName, message.author, message.guild, message.member);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
  }
448
 
449
- if (commandName === 'ping') {
450
- const msg = await message.reply('Pinging...');
451
- msg.edit(`Pong! Latency: ${msg.createdTimestamp - message.createdTimestamp}ms`);
 
 
 
452
  }
453
 
454
- if (commandName === 'friendly') {
455
- if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
456
-
457
- const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
 
 
 
 
458
 
459
- let pingType;
460
- let needed = 6; // Default to 6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
 
462
- if (mentionArg === 'here' || mentionArg === 'everyone') {
463
- pingType = mentionArg;
464
- guildFriendlyPingType.set(message.guildId, pingType);
465
- saveLineup();
466
- // Check if there's a number in args[1]
467
- needed = parseInt(args[1]) || 6;
468
- } else if (parseInt(mentionArg)) {
469
- needed = parseInt(mentionArg);
470
- // Check if next arg is 'here' or 'everyone'
471
- if (args[1] === 'here' || args[1] === 'everyone') {
472
- pingType = args[1];
473
- guildFriendlyPingType.set(message.guildId, pingType);
474
- saveLineup();
475
  } else {
476
- pingType = guildFriendlyPingType.get(message.guildId) || 'everyone';
477
  }
478
- } else {
479
- pingType = guildFriendlyPingType.get(message.guildId) || 'everyone';
480
  }
481
-
482
- // Store the needed count for this poll
483
- pollNeededCount.set(message.guildId, needed);
484
-
485
- let content;
486
- if (pingType === 'here') {
487
- content = getFriendlyText(message.guildId, needed).replace('@everyone', '@here');
488
- } else {
489
- content = getFriendlyText(message.guildId, needed);
490
  }
491
- // Debug: show what will be sent
492
- console.log(`[DEBUG] FRIENDLY-MSG: guild=${message.guildId} author=${message.author?.id || 'unknown'} pingType=${pingType} needed=${needed} contentPreview="${content.slice(0,60)}"`);
493
 
494
- // Always use allowedMentions parse = ['everyone'] to avoid invalid enum
495
- const mentionParse = ['everyone'];
496
- const msg = await message.channel.send({ content, allowedMentions: { parse: mentionParse } });
497
- await msg.react('🟩');
498
- await msg.react('🟥');
499
- storage.data.active_polls[message.guildId] = msg.id;
500
- storage.save('active_polls');
 
 
 
 
 
 
 
 
 
501
 
502
- // Wait for players to react - count is dynamic based on 'needed'
503
- const joined = new Set();
504
- const filter = (reaction, user) => (reaction.emoji.name === '🟩' || reaction.emoji.name === "I'm In") && !user.bot;
505
- const collector = msg.createReactionCollector({ filter, time: 600000 });
506
- collector.on('collect', (reaction, user) => {
507
- if (!joined.has(user.id)) {
508
- joined.add(user.id);
509
- msg.edit({ content: content + `\n\n${joined.size}/${needed} players joined. Waiting for more...` });
510
- }
511
- if (joined.size >= needed) {
512
- collector.stop('ready');
513
- }
514
- });
515
- collector.on('end', async (col, reason) => {
516
- if (reason === 'ready') {
517
- // Clear lineup before showing
518
- const lineup = getGuildLineup(message.guildId);
519
- lineup.clear();
520
- saveLineup();
521
 
522
- // Send NEW message with lineup (don't edit the poll message)
523
- const view = createLineupView(message.guildId);
524
- await msg.edit(view);
525
- activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: msg.id });
526
- addToCleanupQueue(message.guildId, message.channelId, msg.id, 'lineup');
527
- } else {
528
- msg.edit({ content: content + `\n\n❌ Canceled: not enough players joined.` });
529
  }
530
- // Clean up
531
- delete storage.data.active_polls[message.guildId];
532
- pollNeededCount.delete(message.guildId);
533
- storage.save('active_polls');
534
- });
535
- addToCleanupQueue(message.guildId, message.channelId, msg.id, 'poll');
536
  } else {
537
  changed = true;
538
  }
@@ -544,6 +544,7 @@ client.on('messageCreate', async (message) => {
544
 
545
  }, 60000); // Check every minute
546
  });
 
547
  function addToCleanupQueue(guildId, channelId, messageId, type = 'poll') {
548
  const config = storage.data.config[guildId] || {};
549
  const hours = type === 'lineup' ? (config.lineupCleanupHours || 2) : (config.cleanupHours || 2);
@@ -553,7 +554,6 @@ function addToCleanupQueue(guildId, channelId, messageId, type = 'poll') {
553
  storage.save('active_polls');
554
  }
555
 
556
-
557
  const inviteCache = new Map();
558
 
559
  async function logTransaction(client, commandName, user, guild, member) {
@@ -618,15 +618,10 @@ async function logTransaction(client, commandName, user, guild, member) {
618
 
619
  // --- 3. EVENT HANDLERS ---
620
 
621
- // Message Command Handler (Prefix Support)
622
  client.on('messageCreate', async (message) => {
623
- // Handle DM commands (mute/unmute work in DMs)
624
  if (message.channel.type === 1) { // DM channel
625
  if (message.author.bot) return;
626
- const prefix = '!';
627
- if (!message.content.startsWith(prefix)) return;
628
-
629
- return; // Ignore commands in DM
630
  }
631
 
632
  const prefix = storage.getPrefix(message.guildId);
@@ -643,25 +638,23 @@ client.on('messageCreate', async (message) => {
643
  if (commandName === 'ping') {
644
  const msg = await message.reply('Pinging...');
645
  msg.edit(`Pong! Latency: ${msg.createdTimestamp - message.createdTimestamp}ms`);
 
646
  }
647
 
648
  if (commandName === 'friendly') {
649
  if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
650
 
651
  const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
652
-
653
  let pingType;
654
- let needed = 6; // Default to 6
655
 
656
  if (mentionArg === 'here' || mentionArg === 'everyone') {
657
  pingType = mentionArg;
658
  guildFriendlyPingType.set(message.guildId, pingType);
659
  saveLineup();
660
- // Check if there's a number in args[1]
661
  needed = parseInt(args[1]) || 6;
662
  } else if (parseInt(mentionArg)) {
663
  needed = parseInt(mentionArg);
664
- // Check if next arg is 'here' or 'everyone'
665
  if (args[1] === 'here' || args[1] === 'everyone') {
666
  pingType = args[1];
667
  guildFriendlyPingType.set(message.guildId, pingType);
@@ -673,27 +666,15 @@ client.on('messageCreate', async (message) => {
673
  pingType = guildFriendlyPingType.get(message.guildId) || 'everyone';
674
  }
675
 
676
- // Store the needed count for this poll
677
  pollNeededCount.set(message.guildId, needed);
 
678
 
679
- let content;
680
- if (pingType === 'here') {
681
- content = getFriendlyText(message.guildId, needed).replace('@everyone', '@here');
682
- } else {
683
- content = getFriendlyText(message.guildId, needed);
684
- }
685
- // Debug: show what will be sent
686
- console.log(`[DEBUG] FRIENDLY-MSG: guild=${message.guildId} author=${message.author?.id || 'unknown'} pingType=${pingType} needed=${needed} contentPreview="${content.slice(0,60)}"`);
687
-
688
- // Always use allowedMentions parse = ['everyone'] to avoid invalid enum
689
- const mentionParse = ['everyone'];
690
- const msg = await message.channel.send({ content, allowedMentions: { parse: mentionParse } });
691
- await msg.react('🟩');
692
- await msg.react('🟥');
693
  storage.data.active_polls[message.guildId] = msg.id;
694
  storage.save('active_polls');
695
 
696
- // Wait for players to react - count is dynamic based on 'needed'
697
  const joined = new Set();
698
  const filter = (reaction, user) => (reaction.emoji.name === '🟩' || reaction.emoji.name === "I'm In") && !user.bot;
699
  const collector = msg.createReactionCollector({ filter, time: 600000 });
@@ -702,31 +683,33 @@ client.on('messageCreate', async (message) => {
702
  joined.add(user.id);
703
  msg.edit({ content: content + `\n\n${joined.size}/${needed} players joined. Waiting for more...` });
704
  }
705
- if (joined.size >= needed) {
706
- collector.stop('ready');
707
- }
708
  });
709
  collector.on('end', async (col, reason) => {
710
  if (reason === 'ready') {
711
- // Clear lineup before showing
712
  const lineup = getGuildLineup(message.guildId);
713
  lineup.clear();
714
  saveLineup();
715
 
716
- // Send NEW message with lineup (don't edit the poll message)
717
  const view = createLineupView(message.guildId);
718
- await msg.edit(view);
719
- activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: msg.id });
720
- addToCleanupQueue(message.guildId, message.channelId, msg.id, 'lineup');
 
 
721
  } else {
722
  msg.edit({ content: content + `\n\n❌ Canceled: not enough players joined.` });
723
  }
724
- // Clean up
725
  delete storage.data.active_polls[message.guildId];
726
  pollNeededCount.delete(message.guildId);
727
  storage.save('active_polls');
728
  });
729
  addToCleanupQueue(message.guildId, message.channelId, msg.id, 'poll');
 
 
 
 
 
730
 
731
  const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
732
  const pingType = mentionArg === 'here' ? 'here' : 'everyone';
 
419
  }
420
  } catch (e) {
421
  console.error("Log Transaction Error:", e);
422
+ console.log(`[SYSTEM] Connected to ${client.guilds.cache.size} servers`);
423
+ console.log(`[SYSTEM] ##########################################`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424
 
425
+ try {
426
+ const guildCount = client.guilds.cache.size;
427
+ if (guildCount === 0) {
428
+ console.log('[*] Bot is in no servers yet — registering global slash commands...');
429
+ await client.application.commands.set(commandsData);
430
+ } else {
431
+ // Per-guild registration so / commands show up immediately (global can take up to ~1 hour).
432
+ console.log(`[*] Syncing slash commands to ${guildCount} server(s)...`);
433
+ await client.application.commands.set([]).catch(() => { });
434
+ for (const guild of client.guilds.cache.values()) {
435
+ await guild.commands.set(commandsData).catch((err) => {
436
+ console.error(`[!] Slash sync failed for "${guild.name}" (${guild.id}):`, err.message);
437
+ });
438
+ }
439
+ }
440
+ console.log('[*] Slash commands synchronized.');
441
+ } catch (e) {
442
+ console.error(`[!] Command Sync Error: ${e.message}`);
443
  }
444
 
445
+ // Auto-Scan Pending Polls & Cleanup
446
+ for (const guild of client.guilds.cache.values()) {
447
+ const backupChannel = guild.channels.cache.find(c => c.name === 'friendlybot-storage');
448
+ if (backupChannel) {
449
+ backupChannel.delete().catch(() => { });
450
+ }
451
  }
452
 
453
+ // Auto-Friendly Background Loop
454
+ setInterval(async () => {
455
+ const now = Date.now();
456
+ for (const guild of client.guilds.cache.values()) {
457
+ const config = storage.data.config[guild.id];
458
+ if (config?.autoFriendlyEnabled && config?.autoFriendlyChannel) {
459
+ const intervalMs = (config.autoFriendlyInterval || 40) * 60000;
460
+ const lastRun = config.lastAutoFriendly || 0;
461
 
462
+ if (now - lastRun >= intervalMs) {
463
+ try {
464
+ const channel = await guild.channels.fetch(config.autoFriendlyChannel).catch(() => null);
465
+ if (channel && channel.isTextBased()) {
466
+ const needed = 7;
467
+ const content = getFriendlyText(guild.id, needed);
468
+ const msg = await channel.send({ content, allowedMentions: { parse: ['everyone'] } });
469
+ await msg.react('🟩');
470
+ await msg.react('🟥');
471
+ storage.data.active_polls[guild.id] = msg.id;
472
+ config.lastAutoFriendly = now;
473
+ storage.save('config');
474
+ storage.save('active_polls');
475
+ }
476
+ } catch (err) {
477
+ console.error(`Auto-friendly error in ${guild.name}:`, err);
478
+ }
479
+ }
480
+ }
481
+ }
482
 
483
+ // --- NEW MAINTENANCE SYSTEM ---
484
+
485
+ // 1. Handle Auto-Cleanup Queue
486
+ const newCleanupQueue = [];
487
+ for (const item of (storage.data.cleanup_queue || [])) {
488
+ if (now >= item.expiry) {
489
+ try {
490
+ const channel = await client.channels.fetch(item.channelId).catch(() => null);
491
+ if (channel) {
492
+ const msg = await channel.messages.fetch(item.messageId).catch(() => null);
493
+ if (msg) await msg.delete().catch(() => { });
494
+ }
495
+ } catch (e) { }
496
  } else {
497
+ newCleanupQueue.push(item);
498
  }
 
 
499
  }
500
+ if (newCleanupQueue.length !== (storage.data.cleanup_queue || []).length) {
501
+ storage.data.cleanup_queue = newCleanupQueue;
502
+ storage.save('active_polls');
 
 
 
 
 
 
503
  }
 
 
504
 
505
+ // 2. Handle Match Reminders
506
+ const newScheduledMatches = [];
507
+ let changed = false;
508
+ for (const match of (storage.data.scheduled_matches || [])) {
509
+ const config = storage.data.config[match.guildId] || {};
510
+ if (config.remindersEnabled && !match.reminded) {
511
+ const leadMs = (config.remindersLead || 30) * 60000;
512
+ // Remind if we are within the window
513
+ if (now >= match.timestamp - leadMs && now < match.timestamp) {
514
+ match.reminded = true;
515
+ changed = true;
516
+ const lineup = getGuildLineup(match.guildId);
517
+ const players = new Set();
518
+ for (const uids of lineup.values()) {
519
+ uids.forEach(uid => players.add(uid));
520
+ }
521
 
522
+ const embed = UI.createEmbed("🕒 MATCH REMINDER", `Your league match against **${match.away}** starts in **${config.remindersLead || 30} minutes**!\n\n🏟️ **Field**: ${match.home}\n🔗 **Link**: ${match.link}`, UI.colors.primary);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
523
 
524
+ for (const uid of players) {
525
+ try {
526
+ const user = await client.users.fetch(uid);
527
+ if (user) await user.send({ embeds: [embed] }).catch(() => { });
528
+ } catch (e) { }
529
+ }
530
+ }
531
  }
532
+
533
+ // Keep matches until 1 hour after kickoff
534
+ if (now < match.timestamp + 3600000) {
535
+ newScheduledMatches.push(match);
 
 
536
  } else {
537
  changed = true;
538
  }
 
544
 
545
  }, 60000); // Check every minute
546
  });
547
+
548
  function addToCleanupQueue(guildId, channelId, messageId, type = 'poll') {
549
  const config = storage.data.config[guildId] || {};
550
  const hours = type === 'lineup' ? (config.lineupCleanupHours || 2) : (config.cleanupHours || 2);
 
554
  storage.save('active_polls');
555
  }
556
 
 
557
  const inviteCache = new Map();
558
 
559
  async function logTransaction(client, commandName, user, guild, member) {
 
618
 
619
  // --- 3. EVENT HANDLERS ---
620
 
 
621
  client.on('messageCreate', async (message) => {
 
622
  if (message.channel.type === 1) { // DM channel
623
  if (message.author.bot) return;
624
+ return;
 
 
 
625
  }
626
 
627
  const prefix = storage.getPrefix(message.guildId);
 
638
  if (commandName === 'ping') {
639
  const msg = await message.reply('Pinging...');
640
  msg.edit(`Pong! Latency: ${msg.createdTimestamp - message.createdTimestamp}ms`);
641
+ return;
642
  }
643
 
644
  if (commandName === 'friendly') {
645
  if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
646
 
647
  const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
 
648
  let pingType;
649
+ let needed = 6;
650
 
651
  if (mentionArg === 'here' || mentionArg === 'everyone') {
652
  pingType = mentionArg;
653
  guildFriendlyPingType.set(message.guildId, pingType);
654
  saveLineup();
 
655
  needed = parseInt(args[1]) || 6;
656
  } else if (parseInt(mentionArg)) {
657
  needed = parseInt(mentionArg);
 
658
  if (args[1] === 'here' || args[1] === 'everyone') {
659
  pingType = args[1];
660
  guildFriendlyPingType.set(message.guildId, pingType);
 
666
  pingType = guildFriendlyPingType.get(message.guildId) || 'everyone';
667
  }
668
 
 
669
  pollNeededCount.set(message.guildId, needed);
670
+ let content = pingType === 'here' ? getFriendlyText(message.guildId, needed).replace('@everyone', '@here') : getFriendlyText(message.guildId, needed);
671
 
672
+ const msg = await message.channel.send({ content, allowedMentions: { parse: ['everyone'] } });
673
+ await msg.react('🟩').catch(() => {});
674
+ await msg.react('🟥').catch(() => {});
 
 
 
 
 
 
 
 
 
 
 
675
  storage.data.active_polls[message.guildId] = msg.id;
676
  storage.save('active_polls');
677
 
 
678
  const joined = new Set();
679
  const filter = (reaction, user) => (reaction.emoji.name === '🟩' || reaction.emoji.name === "I'm In") && !user.bot;
680
  const collector = msg.createReactionCollector({ filter, time: 600000 });
 
683
  joined.add(user.id);
684
  msg.edit({ content: content + `\n\n${joined.size}/${needed} players joined. Waiting for more...` });
685
  }
686
+ if (joined.size >= needed) collector.stop('ready');
 
 
687
  });
688
  collector.on('end', async (col, reason) => {
689
  if (reason === 'ready') {
 
690
  const lineup = getGuildLineup(message.guildId);
691
  lineup.clear();
692
  saveLineup();
693
 
 
694
  const view = createLineupView(message.guildId);
695
+ const lineupMsg = await message.channel.send(view);
696
+ activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: lineupMsg.id });
697
+ addToCleanupQueue(message.guildId, message.channelId, lineupMsg.id, 'lineup');
698
+
699
+ await msg.edit({ content: content + `\n\n✅ **Match is Ready!** Check the board below.` });
700
  } else {
701
  msg.edit({ content: content + `\n\n❌ Canceled: not enough players joined.` });
702
  }
 
703
  delete storage.data.active_polls[message.guildId];
704
  pollNeededCount.delete(message.guildId);
705
  storage.save('active_polls');
706
  });
707
  addToCleanupQueue(message.guildId, message.channelId, msg.id, 'poll');
708
+ return;
709
+ }
710
+
711
+ if (commandName === 'lineup') {
712
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
713
 
714
  const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
715
  const pingType = mentionArg === 'here' ? 'here' : 'everyone';