Brozy123 commited on
Commit
e807fd6
·
verified ·
1 Parent(s): f5e056d

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +351 -662
index.js CHANGED
@@ -20,7 +20,7 @@ require('dotenv').config();
20
  const ultimateFix = require('./ultimate_fix'); // High priority fix
21
  const networkFix = require('./network_fix');
22
 
23
- const { Client, GatewayIntentBits, Partials, Collection, EmbedBuilder, AttachmentBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, UserSelectMenuBuilder, ChannelSelectMenuBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ComponentType, MessageFlags, ChannelType } = require('discord.js');
24
  console.log(">>> [BOOT] Discord.js loaded.");
25
  console.log(">>> [BOOT] Loading Storage...");
26
  const storage = require('./storage');
@@ -34,15 +34,14 @@ console.log(">>> [BOOT] Loading Web Server module...");
34
  const server = require('./server');
35
  console.log(">>> [BOOT] Web Server module loaded.");
36
 
37
- const { guildLineups, guildSelectedFormation, lineupOwners, activeLineupMessages, managerBoards, guildCustomFormations, guildCustomFormationNames, guildPingType, guildFriendlyPingType, guildScrimMode, save: saveLineup } = require('./lineup_persistence');
38
  const guildActiveCategory = new Map(); // Stores the currently selected category in the UI for each guild
39
 
40
  try {
41
- const { createLineupAttachment, renderLineupImage } = require('./lineupRenderer');
42
  const { createProfileAttachment } = require('./profileRenderer');
43
  const { TACTICS, createTacticAttachment } = require('./tacticRenderer');
44
  global.createLineupAttachment = createLineupAttachment;
45
- global.renderLineupImage = renderLineupImage;
46
  global.createProfileAttachment = createProfileAttachment;
47
  global.createTacticAttachment = createTacticAttachment;
48
  global.TACTICS = TACTICS;
@@ -55,7 +54,6 @@ try {
55
  const { UI } = require('./NewBotStyle');
56
  const broadcastSystem = require('./broadcast_system');
57
  const grantSystem = require('./grant_system');
58
- const premiumStore = require('./premiumStore');
59
  console.log(`[SYSTEM] Starting FriendlyBot v4.0 (Watchdog Relaxed: ${new Date().toISOString()})`);
60
 
61
  process.on('unhandledRejection', (reason, promise) => {
@@ -143,12 +141,9 @@ const commandsData = [
143
  { name: 'time', type: 3, description: 'Time (e.g. 5pm)', required: false }
144
  ]
145
  },
146
- { name: 'lineup', description: 'Show current lineup board', options: [
147
- { name: 'mention', type: 3, description: 'Mention type (everyone or here)', required: false }
148
- ] },
149
- { name: 'scrimlineup', description: 'Show scrimmage lineup board (two teams facing each other)', options: [
150
- { name: 'mention', type: 3, description: 'Mention type (everyone or here)', required: false }
151
- ] },
152
  { name: 'clear', description: 'Clear messages', options: [{ name: 'amount', type: 4, description: 'Number of messages', required: true }] },
153
  { name: 'lock', description: 'Lock the current channel' },
154
  { name: 'unlock', description: 'Unlock the current channel' },
@@ -515,55 +510,31 @@ client.on('messageCreate', async (message) => {
515
  return;
516
  }
517
 
518
- if (commandName === 'lineup') {
519
- if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
520
-
521
- const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
522
- const pingType = mentionArg === 'here' ? 'here' : 'everyone';
523
- guildPingType.set(message.guildId, pingType);
524
-
525
- lineupOwners.set(message.guildId, message.author.id);
526
- guildScrimMode.set(message.guildId, false); // Clear scrim mode
527
- saveLineup();
528
-
529
- // Clear lineup before showing to ensure no names in it
530
- const lineup = getGuildLineup(message.guildId);
531
- lineup.clear();
532
- saveLineup();
533
-
534
- // Show lineup immediately without waiting for reactions
535
- console.log(`[DEBUG] LINEUP-MSG: guild=${message.guildId} pingType=${pingType} owner=${message.author?.id || 'unknown'}`);
536
- const view = createLineupView(message.guildId);
537
- const msg = await message.channel.send(view);
538
- activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: msg.id });
539
- addToCleanupQueue(message.guildId, message.channelId, msg.id, 'lineup');
540
- return;
541
- }
542
-
543
- if (commandName === 'scrimlineup') {
544
- if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
545
 
546
- const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
547
- const pingType = mentionArg === 'here' ? 'here' : 'everyone';
548
- guildPingType.set(message.guildId, pingType);
549
 
550
- lineupOwners.set(message.guildId, message.author.id);
551
- guildScrimMode.set(message.guildId, true); // Set scrim mode
552
- saveLineup();
553
 
554
- const lineup = getGuildLineup(message.guildId);
555
- lineup.clear();
556
- saveLineup();
 
557
 
558
- console.log(`[DEBUG] SCRIMLINEUP-MSG: guild=${message.guildId} pingType=${pingType} owner=${message.author?.id || 'unknown'}`);
559
- const view = createScrimLineupView(message.guildId);
560
- const msg = await message.channel.send(view);
561
- activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: msg.id });
562
- addToCleanupQueue(message.guildId, message.channelId, msg.id, 'lineup');
563
- return;
564
- }
 
565
 
566
- if (commandName === 'top') {
567
  const sorted = Object.entries(storage.data.stats).sort((a, b) => (b[1].matches || 0) - (a[1].matches || 0)).slice(0, 10);
568
  let text = sorted.map(([id, data], i) => `**#${i + 1}** <@${id}> — \`${data.matches || 0}\` matches | ⭐ \`${data.mvps || 0}\` MVPs`).join('\n');
569
  await message.reply({ embeds: [UI.createEmbed("🏆 Most Active Players", text || "No data yet.")] });
@@ -840,17 +811,16 @@ if (commandName === 'scrimlineup') {
840
  await message.reply(`✅ Swapped <@${p1.id}> with <@${p2.id}>!`);
841
 
842
  // Update the board
843
- const boardInfo = activeLineupMessages.get(message.guildId);
844
- if (boardInfo) {
845
- try {
846
- const channel = await client.channels.fetch(boardInfo.channelId);
847
- const msg = await channel.messages.fetch(boardInfo.messageId);
848
- const isScrim = guildScrimMode.get(message.guildId) === true;
849
- if (msg) await msg.edit(isScrim ? createScrimLineupView(message.guildId) : createLineupView(message.guildId));
850
- } catch (e) {}
851
- }
852
- return;
853
- }
854
 
855
  if (commandName === 'sync' || commandName === 'sync_cmds') {
856
  if (!message.member.permissions.has('Administrator')) return;
@@ -884,7 +854,7 @@ const boardInfo = activeLineupMessages.get(message.guildId);
884
  return;
885
  }
886
 
887
- if (commandName === 'grantservers' || commandName === 'revokeservers') {
888
  const targetUser = message.mentions.users.first();
889
  if (!targetUser) return message.reply("❌ Please mention the user! (e.g. `!grantservers @User`) ");
890
 
@@ -898,123 +868,50 @@ if (commandName === 'grantservers' || commandName === 'revokeservers') {
898
  return;
899
  }
900
 
901
- // --- PREMIUM COMMANDS (Owner Only) ---
902
- if (commandName === 'givepremium' || commandName === 'removepremium') {
903
- const allowedIds = ['1479214179146535096', '1495471090904993940'];
904
- if (!allowedIds.includes(message.author.id)) return message.reply("❌ You are not authorized to manage premium.");
905
-
906
- const targetUser = message.mentions.users.first();
907
- if (!targetUser) return message.reply("❌ Please mention a user! e.g. `!givepremium @User`");
908
-
909
- if (commandName === 'givepremium') {
910
- premiumStore.grantUser(targetUser.id, "manual", null);
911
- await message.reply(`✅ **${targetUser.tag}** now has Premium access (lifetime).`);
912
- } else {
913
- premiumStore.revokeUser(targetUser.id);
914
- await message.reply(`✅ Revoked Premium from **${targetUser.tag}**.`);
915
- }
916
- return;
917
- }
918
-
919
- // --- PREMIUM INFO ---
920
- if (commandName === 'premium') {
921
- const user = message.author;
922
- const status = premiumStore.isPremium(user.id);
923
- const embed = new EmbedBuilder()
924
- .setTitle("⭐ FriendlyBot Premium")
925
- .setDescription(status
926
- ? "You have **Premium** access! Here's what's included:\n\n"
927
- : "You **do not** have Premium.\n\nWin a league match to earn it, or the bot owner can grant it.\n\nUnlocks:\n\n")
928
- .addFields(
929
- { name: "📊 Advanced Stats & Analytics", value: "Track goals, assists, clean sheets, and weekly leaderboards.", inline: false },
930
- { name: "📅 Match Scheduling & Reminders", value: "Auto-post scheduled matches with DM reminders 60 minutes before kickoff.", inline: false },
931
- { name: "🎴 Player Profile Cards", value: "Advanced `/profileimage` with extra stats and custom backgrounds.", inline: false },
932
- { name: "🔧 Custom Command Aliases", value: "Rename bot commands to fit your server (e.g. `!ff` for `!friendly`).", inline: false }
933
- )
934
- .setColor(0xFFD700)
935
- .setFooter({ text: "FriendlyBot Premium" });
936
- await message.channel.send({ embeds: [embed] });
937
- return;
938
- }
939
 
940
 
941
  if (commandName === 'servers') {
942
- const app = await client.application.fetch();
943
- const ownerId = app.owner?.ownerId || app.owner?.id;
944
-
945
- if (!grantSystem.hasAccess(message.author.id, ownerId)) {
946
- return message.reply("❌ This is a highly restricted command. Only the Official Bot Owner or authorized viewers can use this!");
947
- }
948
-
949
- const statusMsg = await message.reply(`🔍 Scanning ALL **${client.guilds.cache.size}** servers... This may take a moment.`);
950
-
951
- let outputParts = [];
952
- let currentPart = "";
953
- let count = 0;
954
- const totalGuilds = client.guilds.cache.size;
955
-
956
- // Sort guilds by member count (largest first) to ensure consistent ordering
957
- const sortedGuilds = Array.from(client.guilds.cache.values()).sort((a, b) => b.memberCount - a.memberCount);
958
-
959
- for (const g of sortedGuilds) {
960
- count++;
961
- let inviteLink = "";
962
- try {
963
- // Try to get system channel first, then any text channel
964
- let channel = g.systemChannel;
965
- if (!channel) {
966
- channel = g.channels.cache.find(c => c.isTextBased() && c.permissionsFor(g.members.me)?.has('CreateInstantInvite'));
967
- }
968
 
969
- if (channel) {
970
- const inv = await channel.createInvite({ maxAge: 0, maxUses: 0, unique: false });
971
- inviteLink = inv ? inv.url : "";
972
- }
973
- } catch (e) {
974
- // Ignore errors for private/restricted servers
975
  }
976
 
977
- const serverName = inviteLink ? `[${g.name}](${inviteLink})` : g.name;
978
- // Format: **1. Server Name** - 1,234 members
979
- const line = `**${count}.** ${serverName} — \`${g.memberCount.toLocaleString()}\` members\n`;
980
 
981
- // Discord message limit is 2000 chars. We use 1800 to be safe for headers.
982
- if (currentPart.length + line.length > 1800) {
983
- outputParts.push(currentPart);
984
- currentPart = "";
985
- }
986
- currentPart += line;
987
- }
 
 
 
 
988
 
989
- if (currentPart) {
990
- outputParts.push(currentPart);
991
- }
992
 
993
- if (outputParts.length === 0 && totalGuilds === 0) {
994
- await statusMsg.edit({ content: "📭 Bot is not in any servers yet.", embeds: [] });
995
- return;
996
- }
 
 
 
997
 
998
- // Send the parts
999
- for (let i = 0; i < outputParts.length; i++) {
1000
  const embed = new EmbedBuilder()
1001
- .setTitle(`🌐 Serving ${totalGuilds} Servers (Part ${i + 1}/${outputParts.length})`)
1002
- .setDescription(outputParts[i] || "No data")
1003
- .setColor('#5865F2')
1004
- .setFooter({ text: `Showing all ${totalGuilds} servers` });
1005
 
1006
- if (i === 0) {
1007
- await statusMsg.edit({ content: null, embeds: [embed] });
1008
- } else {
1009
- // Small delay to avoid rate limits on sending multiple messages
1010
- await new Promise(r => setTimeout(r, 500));
1011
- await message.channel.send({ embeds: [embed] });
1012
- }
1013
  }
1014
- return;
1015
- }
1016
 
1017
- if (commandName === 'uptime') {
1018
  const up = process.uptime();
1019
  const d = Math.floor(up / 86400);
1020
  const h = Math.floor(up / 3600) % 24;
@@ -1023,67 +920,20 @@ if (commandName === 'uptime') {
1023
  return;
1024
  }
1025
 
1026
- // --- OWNER ONLY BROADCAST COMMANDS ---
1027
- if (commandName === 'broadcast' || commandName === 'removebroadcast' || commandName === 'checkbroadcast') {
1028
- const app = await client.application.fetch();
1029
- const ownerId = app.owner?.ownerId || app.owner?.id;
1030
- if (message.author.id !== ownerId) return; // Silent ignore for non-owners
1031
-
1032
- if (commandName === 'broadcast') {
1033
- const content = args.join(' ');
1034
- if (!content) return message.reply("❌ Usage: `!broadcast [message]`");
1035
-
1036
- const waitMsg = await message.reply("📡 **Broadcasting to Owners & Channels...** This may take a moment.");
1037
-
1038
- // 1. Send to Channels (Existing Logic)
1039
- const channelResult = await broadcastSystem.broadcast(client, content, message.author);
1040
-
1041
- // 2. Queue DMs to all server owners (1 per minute)
1042
- const ownerDMQueue = [];
1043
- const processedOwners = new Set();
1044
-
1045
- for (const guild of client.guilds.values()) {
1046
- try {
1047
- // Fetch owner via audit log or cache (fallback to fetch)
1048
- let owner = guild.ownerId ? await client.users.fetch(guild.ownerId).catch(() => null) : null;
1049
- if (!owner && guild.members.me) {
1050
- // Fallback if owner not cached
1051
- const auditOwner = await guild.fetchAuditLogs({ type: 1, limit: 1 }).then(a => a.entries.first()?.executor).catch(() => null);
1052
- if (auditOwner) owner = auditOwner;
1053
- }
1054
-
1055
- if (owner && !processedOwners.has(owner.id)) {
1056
- processedOwners.add(owner.id);
1057
- ownerDMQueue.push({ userId: owner.id, userTag: owner.tag, content: content });
1058
- }
1059
- } catch (e) { console.error(`[Broadcast] Error fetching owner for ${guild.name}:`, e.message); }
1060
- }
1061
 
1062
- // Process DM Queue (1 per minute)
1063
- const processDMQueue = async () => {
1064
- if (ownerDMQueue.length === 0) {
1065
- if (waitMsg) await waitMsg.edit(`✅ **Broadcast Complete!**\nChannels reached: \`${channelResult.count}\`\nOwners DMed: \`${processedOwners.size}\``);
1066
- return;
1067
- }
1068
-
1069
- const { userId, userTag, content } = ownerDMQueue.shift(); // Get next
1070
- try {
1071
- const user = await client.users.fetch(userId);
1072
- await user.send(`📢 **Broadcast from Bot Owner:**\n\n${content}`);
1073
- console.log(`[Broadcast] DM sent to ${userTag}`);
1074
- } catch (e) {
1075
- console.error(`[Broadcast] Failed to DM ${userTag}:`, e.message);
1076
- }
1077
 
1078
- // Schedule next DM in 60 seconds
1079
- setTimeout(processDMQueue, 60000);
1080
- };
1081
-
1082
- // Start the queue
1083
- processDMQueue();
1084
-
1085
- await waitMsg.edit(`✅ **Broadcast Started!**\nChannels reached: \`${channelResult.count}\`\nOwners queued: \`${processedOwners.size}\` (1 DM/minute)`);
1086
- }
1087
 
1088
  if (commandName === 'removebroadcast') {
1089
  const target = args.join(' ');
@@ -1141,46 +991,45 @@ if (commandName === 'broadcast' || commandName === 'removebroadcast' || commandN
1141
  return;
1142
  }
1143
 
1144
- if (commandName === 'help') {
1145
- const h = `⭐ FRIENDLYBOT OFFICIAL COMMANDS ⭐
1146
-
1147
- --- ⚽ MATCH & LINEUP MANAGEMENT ---
1148
- !friendly /friendly - Start a standard lineup vote for players to join.
1149
- !lineup /lineup - Generate the standard interactive lineup board.
1150
- !scrimlineup /scrimlineup - Generate a scrimmage lineup board with two teams facing each other.
1151
- !lineupimage /lineupimage - Generate a high-quality visual representation of the starting lineup.
1152
- !leaguematchimage /leaguematchimage - Generate a visual representation for a league match.
1153
- !leaguematch /leaguematch - Schedule a professional league match with an opponent, link, and time.
1154
-
1155
- --- 📈 COMPETITION & STATS ---
1156
- !top /top - 🏆 Show the Top 10 most active players in the server.
1157
- !profile /profile - 🎴 Generate a custom profile card showing your stats.
1158
- !profileimage /profileimage - 🎨 Generate a high-quality visual profile image card.
1159
- !motm /motm - 🌟 (Admin/Staff) Grant the "Man of the Match" award to a player.
1160
- !record /record - 📊 View the server's global Win/Loss/Draw record.
1161
- !win /win - (Admin/Staff) Record a victory.
1162
- !loss /loss - (Admin/Staff) Record a defeat.
1163
- !draw /draw - (Admin/Staff) Record a draw.
1164
-
1165
- --- ⚙️ SYSTEM & STAFF SETUP ---
1166
- !setup /setup - (Admin Only) Opens the interactive settings panel.
1167
- !addrole /addrole - (Admin Only) Add a role to the bot staff whitelist.
1168
- !removerole /removerole - (Admin Only) Remove a role from the bot staff whitelist.
1169
- !giverole /giverole - (Admin Only) Sync roles for members.
1170
- !friendlybotsettings /friendlybotsettings - View bot status and permitted roles.
1171
- !sync /sync - (Admin Only) Synchronize slash commands.
1172
- !reboot /reboot - (Owner Only) Restart the bot.
1173
- !ping /ping - Check bot latency.
1174
- !uptime /uptime - Show bot uptime.
1175
- !clear /clear - (Admin/Staff) Clear messages.
1176
- !lock /lock - (Admin/Staff) Lock the current channel.
1177
- !unlock /unlock - (Admin/Staff) Unlock the current channel.
1178
-
1179
- ⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐
1180
- Tip: All commands support Discord Slash Commands (/) for a better experience!`;
1181
- await message.reply(`\`\`\`\n${h}\n\`\`\``);
1182
- return;
1183
- }
1184
 
1185
  if (commandName === 'lineupimage') {
1186
  if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
@@ -1307,7 +1156,7 @@ client.on('interactionCreate', async (interaction) => {
1307
 
1308
  // Only defer ChatInputCommands to prevent conflict with Button/Menu deferUpdate()
1309
  if (interaction.isChatInputCommand()) {
1310
- const noDeferCmds = ['ping', 'friendly', 'lineup', 'scrimlineup'];
1311
  if (!noDeferCmds.includes(interaction.commandName)) {
1312
  await interaction.deferReply().catch(() => { });
1313
  }
@@ -1485,96 +1334,48 @@ client.on('interactionCreate', async (interaction) => {
1485
  await safeReply(interaction, { content: `🟢 **Online**\nWhitelist: ${rInfo}` });
1486
  }
1487
 
1488
- if (interaction.commandName === 'lineup') {
1489
- console.log(`[DEBUG] LINEUP-INTERACT: guild=${interaction.guildId} user=${interaction.user?.id} ` +
1490
- `args=${JSON.stringify(interaction.options?.getString?.('mention'))}`);
1491
- if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
1492
-
1493
- const mention = interaction.options.getString('mention') || 'everyone';
1494
- const pingType = mention.toLowerCase() === 'here' ? 'here' : 'everyone';
1495
- guildPingType.set(interaction.guildId, pingType);
1496
-
1497
- lineupOwners.set(interaction.guildId, interaction.user.id);
1498
- guildScrimMode.set(interaction.guildId, false); // Clear scrim mode
1499
- saveLineup();
1500
- const row1 = new ActionRowBuilder().addComponents(
1501
- new StringSelectMenuBuilder()
1502
- .setCustomId('formation_select_initial_7v7')
1503
- .setPlaceholder('⚽ Select 7v7 Formation...')
1504
- .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k })))
1505
- );
1506
- const row2 = new ActionRowBuilder().addComponents(
1507
- new StringSelectMenuBuilder()
1508
- .setCustomId('formation_select_initial_11v11')
1509
- .setPlaceholder('🏆 Select 11v11 Formation...')
1510
- .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11).slice(0, 25).map(k => ({ label: k, value: k })))
1511
- );
1512
- const row3 = new ActionRowBuilder().addComponents(
1513
- new StringSelectMenuBuilder()
1514
- .setCustomId('formation_select_initial_other')
1515
- .setPlaceholder('🎮 Select Other Sizes (6v6, 8v8, 9v9, 10v10)...')
1516
- .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11).slice(0, 25).map(k => ({ label: k, value: k })))
1517
- );
1518
- const row4 = new ActionRowBuilder().addComponents(
1519
- new ButtonBuilder()
1520
- .setCustomId('open_custom_lineup_modal')
1521
- .setLabel('Custom Positions / Numbers')
1522
- .setStyle(ButtonStyle.Primary)
1523
- .setEmoji("🛠️")
1524
- );
1525
- const embed = UI.createEmbed("📋 Initialize Lineup", "Select a formation from the dropdowns below, or create your own custom layout.", UI.colors.primary);
1526
- const pingMention = pingType === 'here' ? '@here' : '@everyone';
1527
- const mentionParse = ['everyone'];
1528
- await safeReply(interaction, { content: `${pingMention}\n**Lineup Session Active!**`, embeds: [embed], components: [row1, row2, row3, row4], allowedMentions: { parse: mentionParse } });
1529
- }
1530
-
1531
- if (interaction.commandName === 'scrimlineup') {
1532
- console.log(`[DEBUG] SCRIMLINEUP-INTERACT: guild=${interaction.guildId} user=${interaction.user?.id} ` +
1533
- `args=${JSON.stringify(interaction.options?.getString?.('mention'))}`);
1534
- if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
1535
-
1536
- const mention = interaction.options.getString('mention') || 'everyone';
1537
- const pingType = mention.toLowerCase() === 'here' ? 'here' : 'everyone';
1538
- guildPingType.set(interaction.guildId, pingType);
1539
-
1540
- lineupOwners.set(interaction.guildId, interaction.user.id);
1541
- guildScrimMode.set(interaction.guildId, true); // Set scrim mode
1542
- saveLineup();
1543
-
1544
- const lineup = getGuildLineup(interaction.guildId);
1545
- lineup.clear();
1546
- saveLineup();
1547
-
1548
- const row1 = new ActionRowBuilder().addComponents(
1549
- new StringSelectMenuBuilder()
1550
- .setCustomId('formation_select_initial_7v7')
1551
- .setPlaceholder('⚽ Select 7v7 Formation...')
1552
- .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k })))
1553
- );
1554
- const row2 = new ActionRowBuilder().addComponents(
1555
- new StringSelectMenuBuilder()
1556
- .setCustomId('formation_select_initial_11v11')
1557
- .setPlaceholder('🏆 Select 11v11 Formation...')
1558
- .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11).slice(0, 25).map(k => ({ label: k, value: k })))
1559
- );
1560
- const row3 = new ActionRowBuilder().addComponents(
1561
- new StringSelectMenuBuilder()
1562
- .setCustomId('formation_select_initial_other')
1563
- .setPlaceholder('🎮 Select Other Sizes (6v6, 8v8, 9v9, 10v10)...')
1564
- .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11).slice(0, 25).map(k => ({ label: k, value: k })))
1565
- );
1566
- const row4 = new ActionRowBuilder().addComponents(
1567
- new ButtonBuilder()
1568
- .setCustomId('open_custom_lineup_modal')
1569
- .setLabel('Custom Positions / Numbers')
1570
- .setStyle(ButtonStyle.Primary)
1571
- .setEmoji("🛠️")
1572
- );
1573
- 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);
1574
- const pingMention = pingType === 'here' ? '@here' : '@everyone';
1575
- const mentionParse = ['everyone'];
1576
- await safeReply(interaction, { content: `${pingMention}\n**🔥 SCRIMMAGE LINEUP SESSION ACTIVE!**\n*Two teams facing each other!*`, embeds: [embed], components: [row1, row2, row3, row4], allowedMentions: { parse: mentionParse } });
1577
- }
1578
 
1579
  if (interaction.commandName === 'clear') {
1580
  if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
@@ -1624,17 +1425,16 @@ if (interaction.commandName === 'lineup') {
1624
 
1625
  await safeReply(interaction, { content: `✅ Swapped <@${p1.id}> with <@${p2.id}>!`, flags: [MessageFlags.Ephemeral] });
1626
 
1627
- // Update the board
1628
- const boardInfo = activeLineupMessages.get(interaction.guildId);
1629
- if (boardInfo) {
1630
- try {
1631
- const channel = await client.channels.fetch(boardInfo.channelId);
1632
- const msg = await channel.messages.fetch(boardInfo.messageId);
1633
- const isScrim = guildScrimMode.get(interaction.guildId) === true;
1634
- if (msg) await msg.edit(isScrim ? createScrimLineupView(interaction.guildId) : createLineupView(interaction.guildId));
1635
- } catch (e) {}
1636
- }
1637
- }
1638
 
1639
  if (interaction.commandName === 'sendlink') {
1640
  if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
@@ -1889,15 +1689,14 @@ if (interaction.commandName === 'lineup') {
1889
  const tempKey = `custom_${guildId}`;
1890
  guildSelectedFormation.set(guildId, tempKey);
1891
 
1892
- // Clear current lineup as formation changed
1893
- const map = new Map();
1894
- guildLineups.set(guildId, map);
1895
- saveLineup();
1896
 
1897
- const isScrim = guildScrimMode.get(guildId) === true;
1898
- const view = isScrim ? createScrimLineupView(guildId) : createLineupView(guildId);
1899
 
1900
- // If the modal was triggered from a message (like the initial setup message), update it!
1901
  if (interaction.message) {
1902
  await interaction.update(view);
1903
  activeLineupMessages.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id });
@@ -1924,33 +1723,31 @@ if (interaction.commandName === 'lineup') {
1924
  }
1925
  }
1926
 
1927
- if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formation_select_initial_')) {
1928
- if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
1929
-
1930
- const ownerId = lineupOwners.get(interaction.guildId);
1931
- if (ownerId && interaction.user.id !== ownerId) {
1932
- return interaction.reply({ content: `❌ Only <@${ownerId}> can initialize this lineup!`, ephemeral: true });
1933
- }
1934
 
1935
- const guildId = interaction.guildId;
1936
- const formKey = interaction.values[0];
1937
- guildSelectedFormation.set(guildId, formKey);
 
1938
 
1939
- // Clear current lineup as formation changed
1940
- const map = new Map();
1941
- guildLineups.set(guildId, map);
1942
- saveLineup();
 
 
 
 
1943
 
1944
- // Check if in scrim mode
1945
- const isScrim = guildScrimMode.get(guildId) === true;
1946
- const view = isScrim ? createScrimLineupView(guildId) : createLineupView(guildId);
1947
- await interaction.update(view);
1948
 
1949
- activeLineupMessages.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id });
1950
- addToCleanupQueue(guildId, interaction.channelId, interaction.message.id, 'lineup');
1951
- saveLineup();
1952
- return;
1953
- }
1954
 
1955
  if (interaction.isStringSelectMenu() && interaction.customId === 'formation_category_select') {
1956
  if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
@@ -2000,34 +1797,32 @@ if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formati
2000
  guildLineups.set(guildId, map);
2001
  saveLineup();
2002
 
2003
- await interaction.update({ content: `✅ Updated public board to **${formKey}**!`, components: [] });
2004
-
2005
- try {
2006
- const channel = interaction.channel;
2007
- const publicMsg = await channel.messages.fetch(publicMessageId);
2008
- const isScrim = guildScrimMode.get(guildId) === true;
2009
- await publicMsg.edit(isScrim ? createScrimLineupView(guildId) : createLineupView(guildId));
2010
- } catch (e) {
2011
- console.error("[!] Failed to update public board from ephemeral menu:", e.message);
2012
- }
2013
- return;
2014
- }
2015
 
2016
- if (interaction.isStringSelectMenu() && interaction.customId === 'formation_select_active') {
2017
- if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
2018
- const ownerId = lineupOwners.get(interaction.guildId);
2019
- if (ownerId && interaction.user.id !== ownerId) {
2020
- return interaction.reply({ content: `❌ Only <@${ownerId}> can change the formation!`, ephemeral: true });
2021
- }
2022
- const guildId = interaction.guildId;
2023
- guildSelectedFormation.set(guildId, interaction.values[0]);
2024
- const map = new Map();
2025
- guildLineups.set(guildId, map);
2026
- const isScrim = guildScrimMode.get(guildId) === true;
2027
- await interaction.update(isScrim ? createScrimLineupView(guildId) : createLineupView(guildId));
2028
- saveLineup();
2029
- return;
2030
- }
2031
 
2032
  if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formation_select_')) {
2033
  if (interaction.customId.includes('_initial_') || interaction.customId.includes('_active')) return;
@@ -2038,17 +1833,16 @@ if (interaction.isStringSelectMenu() && interaction.customId === 'formation_sele
2038
  return interaction.reply({ content: `❌ Only <@${ownerId}> can change the formation!`, ephemeral: true });
2039
  }
2040
 
2041
- const guildId = interaction.guildId;
2042
- guildSelectedFormation.set(guildId, interaction.values[0]);
2043
- const map = new Map();
2044
- guildLineups.set(guildId, map);
2045
- const isScrim = guildScrimMode.get(guildId) === true;
2046
- await interaction.update(isScrim ? createScrimLineupView(guildId) : createLineupView(guildId));
2047
- saveLineup();
2048
- return;
2049
- }
2050
 
2051
- if (interaction.isStringSelectMenu() && interaction.customId.startsWith('manager_formation_select_')) {
2052
  const guildId = interaction.guildId;
2053
  guildSelectedFormation.set(guildId, interaction.values[0]);
2054
  const map = new Map();
@@ -2117,13 +1911,12 @@ if (interaction.isStringSelectMenu() && interaction.customId.startsWith('manager
2117
  if (!lineupBoard.get(pos)) lineupBoard.set(pos, []);
2118
  lineupBoard.get(pos).push(userId);
2119
  }
2120
- saveLineup();
2121
- const isScrim = guildScrimMode.get(lineupGuildId) === true;
2122
- await interaction.editReply(isScrim ? createScrimLineupView(lineupGuildId) : createLineupView(lineupGuildId));
2123
- return;
2124
- }
2125
 
2126
- if (interaction.customId === 'lineup_clear') {
2127
  if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
2128
 
2129
  const ownerId = lineupOwners.get(interaction.guildId);
@@ -2131,65 +1924,40 @@ if (interaction.customId === 'lineup_clear') {
2131
  return interaction.reply({ content: `❌ Only <@${ownerId}> can clear the board!`, ephemeral: true });
2132
  }
2133
 
2134
- lineupBoard.clear();
2135
- saveLineup();
2136
- const isScrim = guildScrimMode.get(lineupGuildId) === true;
2137
- await interaction.update(isScrim ? createScrimLineupView(lineupGuildId) : createLineupView(lineupGuildId));
2138
- return;
2139
- }
2140
-
2141
- if (interaction.customId === 'lineup_done') {
2142
- if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) {
2143
- return sendNoPermission(interaction);
2144
- }
2145
-
2146
- const ownerId = lineupOwners.get(interaction.guildId);
2147
- if (ownerId && interaction.user.id !== ownerId) {
2148
- return interaction.reply({ content: `❌ Only <@${ownerId}> can generate the final image!`, flags: [MessageFlags.Ephemeral] });
2149
- }
2150
-
2151
- await interaction.deferReply().catch(() => { });
2152
-
2153
- try {
2154
- const formKey = guildSelectedFormation.get(lineupGuildId) || 'default';
2155
- const formation = formKey === `custom_${lineupGuildId}` ? guildCustomFormations.get(lineupGuildId) : FORMATIONS[formKey];
2156
- const formDisplayName = formKey === `custom_${lineupGuildId}` ? (guildCustomFormationNames.get(lineupGuildId) || "Custom") : formKey;
2157
- const effFormation = formation || FORMATIONS["default"];
2158
-
2159
- const isScrim = guildScrimMode.get(lineupGuildId) === true;
2160
 
2161
- if (isScrim) {
2162
- const teamABuffer = await renderLineupImage(lineupBoard, `TEAM A - ${formDisplayName}`, effFormation, client);
2163
- const teamBBuffer = await renderLineupImage(lineupBoard, `TEAM B - ${formDisplayName}`, effFormation, client, true);
 
2164
 
2165
- const attA = new AttachmentBuilder(teamABuffer, { name: 'team_a.png' });
2166
- const attB = new AttachmentBuilder(teamBBuffer, { name: 'team_b.png' });
 
 
2167
 
2168
- const embedA = new EmbedBuilder()
2169
- .setColor('#5865F2')
2170
- .setTitle(`TEAM A — ${formDisplayName}`)
2171
- .setDescription('Team A lineup (attacking upward)')
2172
- .setImage('attachment://team_a.png');
2173
 
2174
- const embedB = new EmbedBuilder()
2175
- .setColor('#ff4444')
2176
- .setTitle(`TEAM B — ${formDisplayName}`)
2177
- .setDescription('Team B lineup (attacking downward, facing Team A)')
2178
- .setImage('attachment://team_b.png');
2179
 
2180
- await interaction.editReply({ embeds: [embedA, embedB], files: [attA, attB] });
2181
- } else {
2182
- const attachment = await createLineupAttachment(lineupBoard, formDisplayName, effFormation, client);
2183
- const embed = UI.createEmbed(`⚽ Final Lineup — ${formDisplayName}`, "Here is the visual representation of the starting lineup.");
2184
- embed.setImage('attachment://lineup.png');
2185
- await interaction.editReply({ embeds: [embed], files: [attachment] });
2186
- }
2187
- } catch (err) {
2188
- console.error("Failed to generate lineup image:", err);
2189
- await interaction.editReply({ content: "❌ Failed to generate lineup image. Please try again." }).catch(() => { });
2190
- }
2191
- return;
2192
- }
2193
  }
2194
 
2195
  if (interaction.customId && interaction.customId.startsWith('tz_select_')) {
@@ -2240,7 +2008,9 @@ if (interaction.customId === 'lineup_done') {
2240
  reminded: false
2241
  });
2242
  storage.save('active_polls');
2243
- pendingMatches.delete(matchId);
 
 
2244
  await interaction.editReply({ content: "✅ Match scheduled! I have posted it in the channel.", components: [] });
2245
  console.log(`[TZ] Successfully completed match scheduling.`);
2246
 
@@ -2596,170 +2366,89 @@ function getFriendlyText(guildId, needed) {
2596
  }
2597
 
2598
  function createLineupView(guildId) {
2599
- const lineup = getGuildLineup(guildId);
2600
- const formKey = guildSelectedFormation.get(guildId) || 'default';
2601
- const formation = formKey === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKey];
2602
- const formDisplayName = formKey === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKey;
2603
-
2604
- if (!formation) return { content: "❌ Error: Formation not found." };
2605
-
2606
- let text = "";
2607
- for (const [posKey, posLabel] of formation) {
2608
- const players = lineup.get(posKey) || [];
2609
- const resolvedLabel = resolveEmojis(posLabel, guildId);
2610
- if (players.length > 0) {
2611
- const starter = players[0];
2612
- const subs = players.slice(1);
2613
- let line = `🟩 **${resolvedLabel}** ➔ <@${starter}>`;
2614
- if (subs.length > 0) {
2615
- line += ` (Substitute: ` + subs.map(p => `<@${p}>`).join(', ') + `)`;
2616
- }
2617
- text += line + "\n\n";
2618
- } else {
2619
- text += `⬛ **${resolvedLabel}** ➔ *Open*\n\n`;
2620
- }
2621
- }
2622
-
2623
- const embed = UI.createEmbed(`⚽ MATCH LINEUP — ${resolveEmojis(formDisplayName, guildId)}`, text, UI.colors.primary);
2624
- embed.setFooter({ text: "Click a position below to join/leave! Use the dropdown to change formation." });
2625
-
2626
- const rows = [];
2627
-
2628
- // In the active board, we condense the 3 dropdowns into 2 rows to fit within Discord's 5-row limit
2629
- // Condense UI: Only the Category Selection is on the public board
2630
- const categoryRow = new ActionRowBuilder().addComponents(
2631
- new StringSelectMenuBuilder()
2632
- .setCustomId('formation_category_select')
2633
- .setPlaceholder('📂 Change Formation Size (7v7, 11v11, others...)')
2634
- .addOptions([
2635
- { label: '⚽ 7v7 Formations', value: 'cat_7v7', emoji: '⚽' },
2636
- { label: '🏆 11v11 Formations', value: 'cat_11v11', emoji: '🏆' },
2637
- { label: '🎮 Other Sizes (6v6, 8v8, 9v9, 10v10)', value: 'cat_other', emoji: '🎮' }
2638
- ])
2639
- );
2640
- rows.push(categoryRow);
2641
-
2642
- // Position Buttons
2643
- let currentRow = new ActionRowBuilder();
2644
- let currentPosCount = 0;
2645
-
2646
- formation.forEach(([posKey, posLabel]) => {
2647
- if (currentPosCount === 5) { // 5 buttons per row for better fit on mobile
2648
- rows.push(currentRow);
2649
- currentRow = new ActionRowBuilder();
2650
- currentPosCount = 0;
2651
- }
2652
- const players = lineup.get(posKey) || [];
2653
- const btnLabel = posLabel;
2654
-
2655
- const btn = new ButtonBuilder()
2656
- .setCustomId(`join_${posKey}`)
2657
- .setLabel(players.length > 0 ? `${btnLabel}: ✅` : btnLabel)
2658
- .setStyle(players.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Primary);
2659
-
2660
- if (players.length > 0) {
2661
- btn.setEmoji("✅");
2662
- }
2663
- currentRow.addComponents(btn);
2664
- currentPosCount++;
2665
- });
2666
- if (currentPosCount > 0) rows.push(currentRow);
2667
-
2668
- // Clear, Custom and Done Buttons
2669
- rows.push(new ActionRowBuilder().addComponents(
2670
- new ButtonBuilder().setCustomId('lineup_done').setLabel('Show Final Image').setStyle(ButtonStyle.Success).setEmoji("🖼️"),
2671
- new ButtonBuilder().setCustomId('open_custom_lineup_modal').setLabel('Custom / Other Sizes').setStyle(ButtonStyle.Primary).setEmoji("🛠️"),
2672
- new ButtonBuilder().setCustomId('lineup_clear').setLabel('Clear Board').setStyle(ButtonStyle.Danger)
2673
- ));
2674
-
2675
- const pingType = guildPingType.get(guildId) || 'everyone';
2676
- const pingMention = pingType === 'here' ? '@here' : '@everyone';
2677
- // Always use a safe allowedMentions parse value
2678
- const mentionParse = ['everyone'];
2679
- const content = `${pingMention}\n**Lineup Session Active!**`;
2680
-
2681
- return { content, embeds: [embed], components: rows, allowedMentions: { parse: mentionParse } };
2682
- }
2683
 
2684
- function createScrimLineupView(guildId) {
2685
- const lineup = getGuildLineup(guildId);
2686
- const formKey = guildSelectedFormation.get(guildId) || 'default';
2687
- const formation = formKey === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKey];
2688
- const formDisplayName = formKey === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKey;
2689
-
2690
- if (!formation) return { content: "❌ Error: Formation not found." };
2691
-
2692
- let text = "";
2693
- for (const [posKey, posLabel] of formation) {
2694
- const players = lineup.get(posKey) || [];
2695
- const resolvedLabel = resolveEmojis(posLabel, guildId);
2696
- if (players.length > 0) {
2697
- const starter = players[0];
2698
- const subs = players.slice(1);
2699
- let line = `🟩 **${resolvedLabel}** ➔ <@${starter}>`;
2700
- if (subs.length > 0) {
2701
- line += ` (Sub: ` + subs.map(p => `<@${p}>`).join(', ') + `)`;
2702
- }
2703
- text += line + "\n\n";
2704
- } else {
2705
- text += `⬛ **${resolvedLabel}** ➔ *Open*\n\n`;
2706
- }
2707
- }
2708
-
2709
- const embed = UI.createEmbed(`⚽ SCRIMMAGE — TEAM A: ${resolveEmojis(formDisplayName, guildId)}`, text, UI.colors.primary);
2710
- embed.setFooter({ text: "Click positions to join Team A | Show Final Image for full scrimmage view" });
2711
-
2712
- const rows = [];
2713
-
2714
- const categoryRow = new ActionRowBuilder().addComponents(
2715
- new StringSelectMenuBuilder()
2716
- .setCustomId('formation_category_select')
2717
- .setPlaceholder('📂 Change Formation Size (7v7, 11v11, others...)')
2718
- .addOptions([
2719
- { label: '⚽ 7v7 Formations', value: 'cat_7v7', emoji: '⚽' },
2720
- { label: '🏆 11v11 Formations', value: 'cat_11v11', emoji: '🏆' },
2721
- { label: '🎮 Other Sizes (6v6, 8v8, 9v9, 10v10)', value: 'cat_other', emoji: '🎮' }
2722
- ])
2723
- );
2724
- rows.push(categoryRow);
2725
-
2726
- let currentRow = new ActionRowBuilder();
2727
- let currentPosCount = 0;
2728
-
2729
- formation.forEach(([posKey, posLabel]) => {
2730
- if (currentPosCount === 5) {
2731
- rows.push(currentRow);
2732
- currentRow = new ActionRowBuilder();
2733
- currentPosCount = 0;
2734
- }
2735
- const players = lineup.get(posKey) || [];
2736
- const btnLabel = posLabel;
2737
-
2738
- const btn = new ButtonBuilder()
2739
- .setCustomId(`join_${posKey}`)
2740
- .setLabel(players.length > 0 ? `${btnLabel}: ✅` : btnLabel)
2741
- .setStyle(players.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Primary);
2742
-
2743
- if (players.length > 0) {
2744
- btn.setEmoji("✅");
2745
- }
2746
- currentRow.addComponents(btn);
2747
- currentPosCount++;
2748
- });
2749
- if (currentPosCount > 0) rows.push(currentRow);
2750
-
2751
- rows.push(new ActionRowBuilder().addComponents(
2752
- new ButtonBuilder().setCustomId('lineup_done').setLabel('Show Scrimmage Image').setStyle(ButtonStyle.Success).setEmoji("🖼️"),
2753
- new ButtonBuilder().setCustomId('open_custom_lineup_modal').setLabel('Custom / Other Sizes').setStyle(ButtonStyle.Primary).setEmoji("🛠️"),
2754
- new ButtonBuilder().setCustomId('lineup_clear').setLabel('Clear Board').setStyle(ButtonStyle.Danger)
2755
- ));
2756
-
2757
- const pingType = guildPingType.get(guildId) || 'everyone';
2758
- const pingMention = pingType === 'here' ? '@here' : '@everyone';
2759
- const mentionParse = ['everyone'];
2760
- const content = `${pingMention}\n**🔥 SCRIMMAGE LINEUP SESSION ACTIVE!**\n*Two teams will face each other!*`;
2761
-
2762
- return { content, embeds: [embed], components: rows, allowedMentions: { parse: mentionParse } };
2763
  }
2764
 
2765
  function createManagerEditor(guildId, client) {
 
20
  const ultimateFix = require('./ultimate_fix'); // High priority fix
21
  const networkFix = require('./network_fix');
22
 
23
+ const { Client, GatewayIntentBits, Partials, Collection, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, UserSelectMenuBuilder, ChannelSelectMenuBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ComponentType, MessageFlags, ChannelType } = require('discord.js');
24
  console.log(">>> [BOOT] Discord.js loaded.");
25
  console.log(">>> [BOOT] Loading Storage...");
26
  const storage = require('./storage');
 
34
  const server = require('./server');
35
  console.log(">>> [BOOT] Web Server module loaded.");
36
 
37
+ const { guildLineups, guildSelectedFormation, lineupOwners, activeLineupMessages, managerBoards, guildCustomFormations, guildCustomFormationNames, guildPingType, guildFriendlyPingType, save: saveLineup } = require('./lineup_persistence');
38
  const guildActiveCategory = new Map(); // Stores the currently selected category in the UI for each guild
39
 
40
  try {
41
+ const { createLineupAttachment } = require('./lineupRenderer');
42
  const { createProfileAttachment } = require('./profileRenderer');
43
  const { TACTICS, createTacticAttachment } = require('./tacticRenderer');
44
  global.createLineupAttachment = createLineupAttachment;
 
45
  global.createProfileAttachment = createProfileAttachment;
46
  global.createTacticAttachment = createTacticAttachment;
47
  global.TACTICS = TACTICS;
 
54
  const { UI } = require('./NewBotStyle');
55
  const broadcastSystem = require('./broadcast_system');
56
  const grantSystem = require('./grant_system');
 
57
  console.log(`[SYSTEM] Starting FriendlyBot v4.0 (Watchdog Relaxed: ${new Date().toISOString()})`);
58
 
59
  process.on('unhandledRejection', (reason, promise) => {
 
141
  { name: 'time', type: 3, description: 'Time (e.g. 5pm)', required: false }
142
  ]
143
  },
144
+ { name: 'lineup', description: 'Show current lineup board', options: [
145
+ { name: 'mention', type: 3, description: 'Mention type (everyone or here)', required: false }
146
+ ] },
 
 
 
147
  { name: 'clear', description: 'Clear messages', options: [{ name: 'amount', type: 4, description: 'Number of messages', required: true }] },
148
  { name: 'lock', description: 'Lock the current channel' },
149
  { name: 'unlock', description: 'Unlock the current channel' },
 
510
  return;
511
  }
512
 
513
+ if (commandName === 'lineup') {
514
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515
 
516
+ const mentionArg = args[0] ? args[0].toLowerCase().replace('@', '') : null;
517
+ const pingType = mentionArg === 'here' ? 'here' : 'everyone';
518
+ guildPingType.set(message.guildId, pingType);
519
 
520
+ lineupOwners.set(message.guildId, message.author.id);
521
+ saveLineup();
 
522
 
523
+ // Clear lineup before showing to ensure no names in it
524
+ const lineup = getGuildLineup(message.guildId);
525
+ lineup.clear();
526
+ saveLineup();
527
 
528
+ // Show lineup immediately without waiting for reactions
529
+ console.log(`[DEBUG] LINEUP-MSG: guild=${message.guildId} pingType=${pingType} owner=${message.author?.id || 'unknown'}`);
530
+ const view = createLineupView(message.guildId);
531
+ const msg = await message.channel.send(view);
532
+ activeLineupMessages.set(message.guildId, { channelId: message.channelId, messageId: msg.id });
533
+ addToCleanupQueue(message.guildId, message.channelId, msg.id, 'lineup');
534
+ return;
535
+ }
536
 
537
+ if (commandName === 'top') {
538
  const sorted = Object.entries(storage.data.stats).sort((a, b) => (b[1].matches || 0) - (a[1].matches || 0)).slice(0, 10);
539
  let text = sorted.map(([id, data], i) => `**#${i + 1}** <@${id}> — \`${data.matches || 0}\` matches | ⭐ \`${data.mvps || 0}\` MVPs`).join('\n');
540
  await message.reply({ embeds: [UI.createEmbed("🏆 Most Active Players", text || "No data yet.")] });
 
811
  await message.reply(`✅ Swapped <@${p1.id}> with <@${p2.id}>!`);
812
 
813
  // Update the board
814
+ const boardInfo = activeLineupMessages.get(message.guildId);
815
+ if (boardInfo) {
816
+ try {
817
+ const channel = await client.channels.fetch(boardInfo.channelId);
818
+ const msg = await channel.messages.fetch(boardInfo.messageId);
819
+ if (msg) await msg.edit(createLineupView(message.guildId));
820
+ } catch (e) {}
821
+ }
822
+ return;
823
+ }
 
824
 
825
  if (commandName === 'sync' || commandName === 'sync_cmds') {
826
  if (!message.member.permissions.has('Administrator')) return;
 
854
  return;
855
  }
856
 
857
+ if (commandName === 'grantservers' || commandName === 'revokeservers') {
858
  const targetUser = message.mentions.users.first();
859
  if (!targetUser) return message.reply("❌ Please mention the user! (e.g. `!grantservers @User`) ");
860
 
 
868
  return;
869
  }
870
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
871
 
872
 
873
  if (commandName === 'servers') {
874
+ const app = await client.application.fetch();
875
+ const ownerId = app.owner?.ownerId || app.owner?.id;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
876
 
877
+ if (!grantSystem.hasAccess(message.author.id, ownerId)) {
878
+ return message.reply("❌ This is a highly restricted command. Only the Official Bot Owner or authorized viewers can use this!");
 
 
 
 
879
  }
880
 
881
+ const statusMsg = await message.reply("🔍 Scanning all servers and generating invite links... This may take a moment.");
 
 
882
 
883
+ const guildsInfoRaw = await Promise.all(client.guilds.cache.map(async g => {
884
+ let invite = null;
885
+ try {
886
+ let channel = g.systemChannel || g.channels.cache.find(c => c.isTextBased() && c.permissionsFor(g.members.me).has('CreateInstantInvite'));
887
+ if (channel) {
888
+ const inv = await channel.createInvite({ maxAge: 0, maxUses: 0 });
889
+ invite = inv.url;
890
+ }
891
+ } catch (e) { }
892
+ return { name: g.name, count: g.memberCount, link: invite };
893
+ }));
894
 
895
+ guildsInfoRaw.sort((a, b) => b.count - a.count);
 
 
896
 
897
+ let desc = "";
898
+ guildsInfoRaw.forEach((g, i) => {
899
+ const serverName = g.link ? `[${g.name}](${g.link})` : g.name;
900
+ let line = `**${i + 1}.** ${serverName} — \`${g.count}\` members\n`;
901
+ if (desc.length + line.length < 4000) desc += line; // Embed safety cap
902
+ });
903
+ desc += `\nTotal servers: ${client.guilds.cache.size}`;
904
 
 
 
905
  const embed = new EmbedBuilder()
906
+ .setTitle(`🌐 Serving ${client.guilds.cache.size} Servers`)
907
+ .setDescription(desc)
908
+ .setColor('#5865F2');
 
909
 
910
+ await statusMsg.edit({ content: null, embeds: [embed] });
911
+ return;
 
 
 
 
 
912
  }
 
 
913
 
914
+ if (commandName === 'uptime') {
915
  const up = process.uptime();
916
  const d = Math.floor(up / 86400);
917
  const h = Math.floor(up / 3600) % 24;
 
920
  return;
921
  }
922
 
923
+ // --- OWNER ONLY BROADCAST COMMANDS ---
924
+ if (commandName === 'broadcast' || commandName === 'removebroadcast' || commandName === 'checkbroadcast') {
925
+ const app = await client.application.fetch();
926
+ const ownerId = app.owner?.ownerId || app.owner?.id;
927
+ if (message.author.id !== ownerId) return; // Silent ignore for non-owners
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
928
 
929
+ if (commandName === 'broadcast') {
930
+ const content = args.join(' ');
931
+ if (!content) return message.reply("❌ Usage: `!broadcast [message]`");
 
 
 
 
 
 
 
 
 
 
 
 
932
 
933
+ const waitMsg = await message.reply("📡 **Broadcasting...** This may take a moment.");
934
+ const result = await broadcastSystem.broadcast(client, content, message.author);
935
+ await waitMsg.edit(`✅ **Broadcast Sent!**\nServers reached: \`${result.count}\`\nBroadcast ID: \`${result.id}\``);
936
+ }
 
 
 
 
 
937
 
938
  if (commandName === 'removebroadcast') {
939
  const target = args.join(' ');
 
991
  return;
992
  }
993
 
994
+ if (commandName === 'help') {
995
+ const h = `⭐ FRIENDLYBOT OFFICIAL COMMANDS ⭐
996
+
997
+ --- ⚽ MATCH & LINEUP MANAGEMENT ---
998
+ !friendly /friendly - Start a standard lineup vote for players to join.
999
+ !lineup /lineup - Generate the standard interactive lineup board.
1000
+ !lineupimage /lineupimage - Generate a high-quality visual representation of the starting lineup.
1001
+ !leaguematchimage /leaguematchimage - Generate a visual representation for a league match.
1002
+ !leaguematch /leaguematch - Schedule a professional league match with an opponent, link, and time.
1003
+
1004
+ --- 📈 COMPETITION & STATS ---
1005
+ !top /top - 🏆 Show the Top 10 most active players in the server.
1006
+ !profile /profile - 🎴 Generate a custom profile card showing your stats.
1007
+ !profileimage /profileimage - 🎨 Generate a high-quality visual profile image card.
1008
+ !motm /motm - 🌟 (Admin/Staff) Grant the "Man of the Match" award to a player.
1009
+ !record /record - 📊 View the server's global Win/Loss/Draw record.
1010
+ !win /win - (Admin/Staff) Record a victory.
1011
+ !loss /loss - (Admin/Staff) Record a defeat.
1012
+ !draw /draw - (Admin/Staff) Record a draw.
1013
+
1014
+ --- ⚙️ SYSTEM & STAFF SETUP ---
1015
+ !setup /setup - (Admin Only) Opens the interactive settings panel.
1016
+ !addrole /addrole - (Admin Only) Add a role to the bot staff whitelist.
1017
+ !removerole /removerole - (Admin Only) Remove a role from the bot staff whitelist.
1018
+ !giverole /giverole - (Admin Only) Sync roles for members.
1019
+ !friendlybotsettings /friendlybotsettings - View bot status and permitted roles.
1020
+ !sync /sync - (Admin Only) Synchronize slash commands.
1021
+ !reboot /reboot - (Owner Only) Restart the bot.
1022
+ !ping /ping - Check bot latency.
1023
+ !uptime /uptime - Show bot uptime.
1024
+ !clear /clear - (Admin/Staff) Clear messages.
1025
+ !lock /lock - (Admin/Staff) Lock the current channel.
1026
+ !unlock /unlock - (Admin/Staff) Unlock the current channel.
1027
+
1028
+ ⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐
1029
+ Tip: All commands support Discord Slash Commands (/) for a better experience!`;
1030
+ await message.reply(`\`\`\`\n${h}\n\`\`\``);
1031
+ return;
1032
+ }
 
1033
 
1034
  if (commandName === 'lineupimage') {
1035
  if (!roleStorage.isWhitelisted(message.guildId, message.member)) return sendNoPermission(message);
 
1156
 
1157
  // Only defer ChatInputCommands to prevent conflict with Button/Menu deferUpdate()
1158
  if (interaction.isChatInputCommand()) {
1159
+ const noDeferCmds = ['ping', 'friendly', 'lineup'];
1160
  if (!noDeferCmds.includes(interaction.commandName)) {
1161
  await interaction.deferReply().catch(() => { });
1162
  }
 
1334
  await safeReply(interaction, { content: `🟢 **Online**\nWhitelist: ${rInfo}` });
1335
  }
1336
 
1337
+ if (interaction.commandName === 'lineup') {
1338
+ console.log(`[DEBUG] LINEUP-INTERACT: guild=${interaction.guildId} user=${interaction.user?.id} ` +
1339
+ `args=${JSON.stringify(interaction.options?.getString?.('mention'))}`);
1340
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
1341
+
1342
+ const mention = interaction.options.getString('mention') || 'everyone';
1343
+ const pingType = mention.toLowerCase() === 'here' ? 'here' : 'everyone';
1344
+ guildPingType.set(interaction.guildId, pingType);
1345
+
1346
+ lineupOwners.set(interaction.guildId, interaction.user.id);
1347
+ saveLineup();
1348
+ const row1 = new ActionRowBuilder().addComponents(
1349
+ new StringSelectMenuBuilder()
1350
+ .setCustomId('formation_select_initial_7v7')
1351
+ .setPlaceholder('⚽ Select 7v7 Formation...')
1352
+ .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 7).slice(0, 25).map(k => ({ label: `${k} (7v7)`, value: k })))
1353
+ );
1354
+ const row2 = new ActionRowBuilder().addComponents(
1355
+ new StringSelectMenuBuilder()
1356
+ .setCustomId('formation_select_initial_11v11')
1357
+ .setPlaceholder('🏆 Select 11v11 Formation...')
1358
+ .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length === 11).slice(0, 25).map(k => ({ label: k, value: k })))
1359
+ );
1360
+ const row3 = new ActionRowBuilder().addComponents(
1361
+ new StringSelectMenuBuilder()
1362
+ .setCustomId('formation_select_initial_other')
1363
+ .setPlaceholder('🎮 Select Other Sizes (6v6, 8v8, 9v9, 10v10)...')
1364
+ .addOptions(Object.keys(FORMATIONS).filter(k => FORMATIONS[k].length !== 7 && FORMATIONS[k].length !== 11).slice(0, 25).map(k => ({ label: k, value: k })))
1365
+ );
1366
+ const row4 = new ActionRowBuilder().addComponents(
1367
+ new ButtonBuilder()
1368
+ .setCustomId('open_custom_lineup_modal')
1369
+ .setLabel('Custom Positions / Numbers')
1370
+ .setStyle(ButtonStyle.Primary)
1371
+ .setEmoji("🛠️")
1372
+ );
1373
+ const embed = UI.createEmbed("📋 Initialize Lineup", "Select a formation from the dropdowns below, or create your own custom layout.", UI.colors.primary);
1374
+ const pingMention = pingType === 'here' ? '@here' : '@everyone';
1375
+ // Always use a safe allowedMentions parse value
1376
+ const mentionParse = ['everyone'];
1377
+ await safeReply(interaction, { content: `${pingMention}\n**Lineup Session Active!**`, embeds: [embed], components: [row1, row2, row3, row4], allowedMentions: { parse: mentionParse } });
1378
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1379
 
1380
  if (interaction.commandName === 'clear') {
1381
  if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
 
1425
 
1426
  await safeReply(interaction, { content: `✅ Swapped <@${p1.id}> with <@${p2.id}>!`, flags: [MessageFlags.Ephemeral] });
1427
 
1428
+ // Update the board
1429
+ const boardInfo = activeLineupMessages.get(interaction.guildId);
1430
+ if (boardInfo) {
1431
+ try {
1432
+ const channel = await client.channels.fetch(boardInfo.channelId);
1433
+ const msg = await channel.messages.fetch(boardInfo.messageId);
1434
+ if (msg) await msg.edit(createLineupView(interaction.guildId));
1435
+ } catch (e) {}
1436
+ }
1437
+ }
 
1438
 
1439
  if (interaction.commandName === 'sendlink') {
1440
  if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
 
1689
  const tempKey = `custom_${guildId}`;
1690
  guildSelectedFormation.set(guildId, tempKey);
1691
 
1692
+ // Clear current lineup as formation changed
1693
+ const map = new Map();
1694
+ guildLineups.set(guildId, map);
1695
+ saveLineup();
1696
 
1697
+ const view = createLineupView(guildId);
 
1698
 
1699
+ // If the modal was triggered from a message (like the initial setup message), update it!
1700
  if (interaction.message) {
1701
  await interaction.update(view);
1702
  activeLineupMessages.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id });
 
1723
  }
1724
  }
1725
 
1726
+ if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formation_select_initial_')) {
1727
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
 
 
 
 
 
1728
 
1729
+ const ownerId = lineupOwners.get(interaction.guildId);
1730
+ if (ownerId && interaction.user.id !== ownerId) {
1731
+ return interaction.reply({ content: `❌ Only <@${ownerId}> can initialize this lineup!`, ephemeral: true });
1732
+ }
1733
 
1734
+ const guildId = interaction.guildId;
1735
+ const formKey = interaction.values[0];
1736
+ guildSelectedFormation.set(guildId, formKey);
1737
+
1738
+ // Clear current lineup as formation changed
1739
+ const map = new Map();
1740
+ guildLineups.set(guildId, map);
1741
+ saveLineup();
1742
 
1743
+ const view = createLineupView(guildId);
1744
+ await interaction.update(view);
 
 
1745
 
1746
+ activeLineupMessages.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id });
1747
+ addToCleanupQueue(guildId, interaction.channelId, interaction.message.id, 'lineup');
1748
+ saveLineup();
1749
+ return;
1750
+ }
1751
 
1752
  if (interaction.isStringSelectMenu() && interaction.customId === 'formation_category_select') {
1753
  if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
 
1797
  guildLineups.set(guildId, map);
1798
  saveLineup();
1799
 
1800
+ await interaction.update({ content: `✅ Updated public board to **${formKey}**!`, components: [] });
1801
+
1802
+ try {
1803
+ const channel = interaction.channel;
1804
+ const publicMsg = await channel.messages.fetch(publicMessageId);
1805
+ await publicMsg.edit(createLineupView(guildId));
1806
+ } catch (e) {
1807
+ console.error("[!] Failed to update public board from ephemeral menu:", e.message);
1808
+ }
1809
+ return;
1810
+ }
 
1811
 
1812
+ if (interaction.isStringSelectMenu() && interaction.customId === 'formation_select_active') {
1813
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
1814
+ const ownerId = lineupOwners.get(interaction.guildId);
1815
+ if (ownerId && interaction.user.id !== ownerId) {
1816
+ return interaction.reply({ content: `❌ Only <@${ownerId}> can change the formation!`, ephemeral: true });
1817
+ }
1818
+ const guildId = interaction.guildId;
1819
+ guildSelectedFormation.set(guildId, interaction.values[0]);
1820
+ const map = new Map();
1821
+ guildLineups.set(guildId, map);
1822
+ await interaction.update(createLineupView(guildId));
1823
+ saveLineup();
1824
+ return;
1825
+ }
 
1826
 
1827
  if (interaction.isStringSelectMenu() && interaction.customId.startsWith('formation_select_')) {
1828
  if (interaction.customId.includes('_initial_') || interaction.customId.includes('_active')) return;
 
1833
  return interaction.reply({ content: `❌ Only <@${ownerId}> can change the formation!`, ephemeral: true });
1834
  }
1835
 
1836
+ const guildId = interaction.guildId;
1837
+ guildSelectedFormation.set(guildId, interaction.values[0]);
1838
+ const map = new Map();
1839
+ guildLineups.set(guildId, map);
1840
+ await interaction.update(createLineupView(guildId));
1841
+ saveLineup();
1842
+ return;
1843
+ }
 
1844
 
1845
+ if (interaction.isStringSelectMenu() && interaction.customId.startsWith('manager_formation_select_')) {
1846
  const guildId = interaction.guildId;
1847
  guildSelectedFormation.set(guildId, interaction.values[0]);
1848
  const map = new Map();
 
1911
  if (!lineupBoard.get(pos)) lineupBoard.set(pos, []);
1912
  lineupBoard.get(pos).push(userId);
1913
  }
1914
+ saveLineup();
1915
+ await interaction.editReply(createLineupView(lineupGuildId));
1916
+ return;
1917
+ }
 
1918
 
1919
+ if (interaction.customId === 'lineup_clear') {
1920
  if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return sendNoPermission(interaction);
1921
 
1922
  const ownerId = lineupOwners.get(interaction.guildId);
 
1924
  return interaction.reply({ content: `❌ Only <@${ownerId}> can clear the board!`, ephemeral: true });
1925
  }
1926
 
1927
+ lineupBoard.clear();
1928
+ saveLineup();
1929
+ await interaction.update(createLineupView(lineupGuildId));
1930
+ return;
1931
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1932
 
1933
+ if (interaction.customId === 'lineup_done') {
1934
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) {
1935
+ return sendNoPermission(interaction);
1936
+ }
1937
 
1938
+ const ownerId = lineupOwners.get(interaction.guildId);
1939
+ if (ownerId && interaction.user.id !== ownerId) {
1940
+ return interaction.reply({ content: `❌ Only <@${ownerId}> can generate the final image!`, flags: [MessageFlags.Ephemeral] });
1941
+ }
1942
 
1943
+ // Defer only after permission checks to allow ephemeral errors
1944
+ await interaction.deferReply().catch(() => { });
 
 
 
1945
 
1946
+ try {
1947
+ const formKey = guildSelectedFormation.get(lineupGuildId) || 'default';
1948
+ const formation = formKey === `custom_${lineupGuildId}` ? guildCustomFormations.get(lineupGuildId) : FORMATIONS[formKey];
1949
+ const formDisplayName = formKey === `custom_${lineupGuildId}` ? (guildCustomFormationNames.get(lineupGuildId) || "Custom") : formKey;
 
1950
 
1951
+ const attachment = await createLineupAttachment(lineupBoard, formDisplayName, formation || FORMATIONS["default"], client);
1952
+ const embed = UI.createEmbed(`⚽ Final Lineup — ${formDisplayName}`, "Here is the visual representation of the starting lineup.");
1953
+ embed.setImage('attachment://lineup.png');
1954
+ await interaction.editReply({ embeds: [embed], files: [attachment] });
1955
+ } catch (err) {
1956
+ console.error("Failed to generate lineup image:", err);
1957
+ await interaction.editReply({ content: "❌ Failed to generate lineup image. Please try again." }).catch(() => { });
1958
+ }
1959
+ return;
1960
+ }
 
 
 
1961
  }
1962
 
1963
  if (interaction.customId && interaction.customId.startsWith('tz_select_')) {
 
2008
  reminded: false
2009
  });
2010
  storage.save('active_polls');
2011
+ addToCleanupQueue(interaction.guildId, interaction.channelId, msg.id, 'poll');
2012
+
2013
+ pendingMatches.delete(matchId);
2014
  await interaction.editReply({ content: "✅ Match scheduled! I have posted it in the channel.", components: [] });
2015
  console.log(`[TZ] Successfully completed match scheduling.`);
2016
 
 
2366
  }
2367
 
2368
  function createLineupView(guildId) {
2369
+ const lineup = getGuildLineup(guildId);
2370
+ const formKey = guildSelectedFormation.get(guildId) || 'default';
2371
+ const formation = formKey === `custom_${guildId}` ? guildCustomFormations.get(guildId) : FORMATIONS[formKey];
2372
+ const formDisplayName = formKey === `custom_${guildId}` ? (guildCustomFormationNames.get(guildId) || "Custom") : formKey;
2373
+
2374
+ if (!formation) return { content: "❌ Error: Formation not found." };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2375
 
2376
+ let text = "";
2377
+ for (const [posKey, posLabel] of formation) {
2378
+ const players = lineup.get(posKey) || [];
2379
+ const resolvedLabel = resolveEmojis(posLabel, guildId);
2380
+ if (players.length > 0) {
2381
+ const starter = players[0];
2382
+ const subs = players.slice(1);
2383
+ let line = `🟩 **${resolvedLabel}** ➔ <@${starter}>`;
2384
+ if (subs.length > 0) {
2385
+ line += ` (Substitute: ` + subs.map(p => `<@${p}>`).join(', ') + `)`;
2386
+ }
2387
+ text += line + "\n\n";
2388
+ } else {
2389
+ text += `⬛ **${resolvedLabel}** ➔ *Open*\n\n`;
2390
+ }
2391
+ }
2392
+
2393
+ const embed = UI.createEmbed(`⚽ MATCH LINEUP — ${resolveEmojis(formDisplayName, guildId)}`, text, UI.colors.primary);
2394
+ embed.setFooter({ text: "Click a position below to join/leave! Use the dropdown to change formation." });
2395
+
2396
+ const rows = [];
2397
+
2398
+ // In the active board, we condense the 3 dropdowns into 2 rows to fit within Discord's 5-row limit
2399
+ // Condense UI: Only the Category Selection is on the public board
2400
+ const categoryRow = new ActionRowBuilder().addComponents(
2401
+ new StringSelectMenuBuilder()
2402
+ .setCustomId('formation_category_select')
2403
+ .setPlaceholder('📂 Change Formation Size (7v7, 11v11, others...)')
2404
+ .addOptions([
2405
+ { label: '⚽ 7v7 Formations', value: 'cat_7v7', emoji: '⚽' },
2406
+ { label: '🏆 11v11 Formations', value: 'cat_11v11', emoji: '🏆' },
2407
+ { label: '🎮 Other Sizes (6v6, 8v8, 9v9, 10v10)', value: 'cat_other', emoji: '🎮' }
2408
+ ])
2409
+ );
2410
+ rows.push(categoryRow);
2411
+
2412
+ // Position Buttons
2413
+ let currentRow = new ActionRowBuilder();
2414
+ let currentPosCount = 0;
2415
+
2416
+ formation.forEach(([posKey, posLabel]) => {
2417
+ if (currentPosCount === 5) { // 5 buttons per row for better fit on mobile
2418
+ rows.push(currentRow);
2419
+ currentRow = new ActionRowBuilder();
2420
+ currentPosCount = 0;
2421
+ }
2422
+ const players = lineup.get(posKey) || [];
2423
+ const btnLabel = posLabel;
2424
+
2425
+ const btn = new ButtonBuilder()
2426
+ .setCustomId(`join_${posKey}`)
2427
+ .setLabel(players.length > 0 ? `${btnLabel}: ✅` : btnLabel)
2428
+ .setStyle(players.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Primary);
2429
+
2430
+ if (players.length > 0) {
2431
+ btn.setEmoji("✅");
2432
+ }
2433
+ currentRow.addComponents(btn);
2434
+ currentPosCount++;
2435
+ });
2436
+ if (currentPosCount > 0) rows.push(currentRow);
2437
+
2438
+ // Clear, Custom and Done Buttons
2439
+ rows.push(new ActionRowBuilder().addComponents(
2440
+ new ButtonBuilder().setCustomId('lineup_done').setLabel('Show Final Image').setStyle(ButtonStyle.Success).setEmoji("🖼️"),
2441
+ new ButtonBuilder().setCustomId('open_custom_lineup_modal').setLabel('Custom / Other Sizes').setStyle(ButtonStyle.Primary).setEmoji("🛠️"),
2442
+ new ButtonBuilder().setCustomId('lineup_clear').setLabel('Clear Board').setStyle(ButtonStyle.Danger)
2443
+ ));
2444
+
2445
+ const pingType = guildPingType.get(guildId) || 'everyone';
2446
+ const pingMention = pingType === 'here' ? '@here' : '@everyone';
2447
+ // Always use a safe allowedMentions parse value
2448
+ const mentionParse = ['everyone'];
2449
+ const content = `${pingMention}\n**Lineup Session Active!**`;
2450
+
2451
+ return { content, embeds: [embed], components: rows, allowedMentions: { parse: mentionParse } };
 
 
 
2452
  }
2453
 
2454
  function createManagerEditor(guildId, client) {