Brozy123 commited on
Commit
cc8e604
·
verified ·
1 Parent(s): 4299e64

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +1339 -50
index.js CHANGED
@@ -1,5 +1,5 @@
1
  require('dotenv').config();
2
- const { Client, GatewayIntentBits, Partials, Collection, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, MessageFlags } = require('discord.js');
3
  const storage = require('./storage');
4
  const roleStorage = require('./roleStorage');
5
  const networkFix = require('./network_fix');
@@ -8,8 +8,19 @@ const { UI } = require('./NewBotStyle');
8
  const { createLineupAttachment } = require('./lineupRenderer');
9
  const { createProfileAttachment } = require('./profileRenderer');
10
 
 
11
  networkFix.applyAdvancedFixes();
12
 
 
 
 
 
 
 
 
 
 
 
13
  const client = new Client({
14
  intents: [
15
  GatewayIntentBits.Guilds,
@@ -23,35 +34,62 @@ const client = new Client({
23
  api: `https://${networkFix.getTargetDomain()}/api`,
24
  version: '10',
25
  timeout: 60000
 
 
 
26
  }
27
  });
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  const commandsData = [
30
  { name: 'ping', description: 'Check bot latency' },
31
  { name: 'friendly', description: 'Start a friendly match poll', options: [{ name: 'needed', type: 4, description: 'Players needed', required: false }] },
32
- { name: 'leaguematch', description: 'Schedule a league match', options: [
33
- { name: 'home', type: 3, description: 'Home team', required: true },
34
- { name: 'away', type: 3, description: 'Away team', required: true },
35
- { name: 'link', type: 3, description: 'Match link', required: true },
36
- { name: 'time', type: 3, description: 'Time (e.g. 5pm)', required: false }
37
- ]},
 
 
38
  { name: 'lineup', description: 'Show current lineup board' },
39
  { name: 'clear', description: 'Clear messages', options: [{ name: 'amount', type: 4, description: 'Number of messages', required: true }] },
40
  { name: 'lock', description: 'Lock the current channel' },
41
  { name: 'unlock', description: 'Unlock the current channel' },
42
  { name: 'post', description: 'Broadcast a message to all servers', options: [{ name: 'message', type: 3, description: 'The message to send', required: true }] },
43
- { name: 'win', description: 'Record a win', options: [
44
- { name: 'result', type: 3, description: 'The score', required: true },
45
- { name: 'scorers', type: 3, description: 'Mentions and goals', required: false }
46
- ]},
47
- { name: 'loss', description: 'Record a loss', options: [
48
- { name: 'result', type: 3, description: 'The score', required: true },
49
- { name: 'scorers', type: 3, description: 'Mentions and goals', required: false }
50
- ]},
51
- { name: 'draw', description: 'Record a draw', options: [
52
- { name: 'result', type: 3, description: 'The score', required: true },
53
- { name: 'scorers', type: 3, description: 'Mentions and goals', required: false }
54
- ]},
 
 
 
 
 
 
55
  { name: 'top', description: 'View leaderboard' },
56
  { name: 'record', description: 'View server record' },
57
  { name: 'addrole', description: 'Whitelist a role', options: [{ name: 'role', type: 8, description: 'The role', required: true }] },
@@ -59,98 +97,1349 @@ const commandsData = [
59
  { name: 'setup', description: 'Configure bot features (Admin)' },
60
  { name: 'friendlybotsettings', description: 'View bot status and whitelist' },
61
  { name: 'managerlineup', description: 'Open the GUI editor to draft players interactively' },
62
- { name: 'lineupimage', description: 'Generate a visual lineup' },
63
  { name: 'sendlink', description: 'Send a match link publicly', options: [{ name: 'link', type: 3, description: 'The link to send', required: true }] },
64
  { name: 'profile', description: 'Generate a custom profile card', options: [{ name: 'user', type: 6, description: 'The user to check', required: false }] },
65
- { name: 'profileimage', description: 'Generate a visual profile card', options: [{ name: 'user', type: 6, description: 'The user to check', required: false }] },
66
  { name: 'giverole', description: 'Give a role to members (Admin)', options: [{ name: 'role', type: 8, description: 'The role', required: true }] },
67
- { name: 'uptime', description: 'Show bot uptime' },
68
- { name: 'motm', description: 'Award Man of the Match', options: [{ name: 'player', type: 6, description: 'The player', required: true }] }
69
  ];
70
 
71
  client.once('ready', async () => {
 
72
  console.log(`[SYSTEM] FriendlyBot is ONLINE as ${client.user.tag}`);
73
- await client.application.commands.set(commandsData).catch(e => console.error(e));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  });
75
 
76
  async function safeReply(interaction, options) {
77
  try {
78
- if (interaction.deferred || interaction.replied) return await interaction.editReply(options);
79
- return await interaction.reply(options);
80
- } catch (e) {}
 
 
 
 
 
81
  }
82
 
 
83
  client.on('interactionCreate', async (interaction) => {
84
- // Immediate acknowledgment for non-chat commands
85
- if (interaction.isButton() || interaction.isAnySelectMenu()) {
86
- await interaction.deferUpdate().catch(() => {});
 
 
87
  }
88
-
89
  if (interaction.isChatInputCommand()) {
90
- if (interaction.commandName !== 'ping') await interaction.deferReply().catch(() => {});
91
-
92
  if (interaction.commandName === 'ping') {
93
  await safeReply(interaction, `Latency: ${client.ws.ping}ms`);
94
  }
95
 
96
  if (interaction.commandName === 'friendly') {
 
97
  const needed = interaction.options.getInteger('needed') || 7;
98
  const content = `⭐▬▬▬▬▬ **FRIENDLY** ▬▬▬▬▬⭐\n🤝 Session\n🟩 I'm In\n🟥 Busy\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n🗳️ Needed: ${needed}\n@everyone`;
99
  const msg = await safeReply(interaction, { content, fetchReply: true, allowedMentions: { parse: ['everyone'] } });
100
  if (msg) {
101
- await msg.react('🟩').catch(() => {});
102
- await msg.react('🟥').catch(() => {});
103
  storage.data.active_polls[interaction.guildId] = msg.id;
104
  storage.save('active_polls');
105
  }
106
  }
107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  if (interaction.commandName === 'lineup') {
109
- const formOptions = [
110
- { label: '4-3-3', value: '4-3-3' },
111
- { label: '4-4-2', value: '4-4-2' },
112
- { label: '3-5-2', value: '3-5-2' }
113
- ];
114
  const row = new ActionRowBuilder().addComponents(
115
- new StringSelectMenuBuilder().setCustomId('formation_select_initial').setPlaceholder('Choose Formation...').addOptions(formOptions)
 
 
 
116
  );
117
- await safeReply(interaction, { content: "📋 Select a formation:", components: [row] });
 
118
  }
119
 
120
  if (interaction.commandName === 'clear') {
 
121
  const amount = interaction.options.getInteger('amount');
122
  await interaction.channel.bulkDelete(amount, true);
123
  await safeReply(interaction, { content: `✅ Cleared ${amount} messages.`, ephemeral: true });
124
  }
125
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  if (interaction.commandName === 'post') {
127
  if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
128
  const text = interaction.options.getString('message');
129
  let count = 0;
130
  for (const guild of client.guilds.cache.values()) {
131
- const channel = guild.systemChannel || guild.channels.cache.find(c => c.isTextBased());
132
- if (channel) {
133
- await channel.send(text).catch(() => {});
134
- count++;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  }
136
  }
137
  await interaction.editReply({ content: `📢 Broadcasted to ${count} servers.` });
138
  }
139
 
 
 
 
 
 
 
140
  if (interaction.commandName === 'uptime') {
141
  const up = process.uptime();
142
- await safeReply(interaction, `⏱️ **Uptime**: ${Math.floor(up / 3600)}h ${Math.floor((up % 3600) / 60)}m`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  }
144
  }
145
  });
146
 
147
- const RAW_TOKEN = process.env.BOT_TOKEN || process.env.TOKEN;
148
- const TOKEN = RAW_TOKEN ? RAW_TOKEN.trim() : null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  async function initialize() {
151
  console.log("[*] Starting Web Dashboard...");
152
  server.startServer(client, commandsData);
153
- if (TOKEN) await client.login(TOKEN).catch(e => console.error(e));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  }
155
 
156
  initialize();
 
1
  require('dotenv').config();
2
+ const { Client, GatewayIntentBits, Partials, Collection, EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, StringSelectMenuBuilder, UserSelectMenuBuilder, ChannelSelectMenuBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ComponentType, MessageFlags, ChannelType } = require('discord.js');
3
  const storage = require('./storage');
4
  const roleStorage = require('./roleStorage');
5
  const networkFix = require('./network_fix');
 
8
  const { createLineupAttachment } = require('./lineupRenderer');
9
  const { createProfileAttachment } = require('./profileRenderer');
10
 
11
+ // Apply network fixes early
12
  networkFix.applyAdvancedFixes();
13
 
14
+ console.log(`[SYSTEM] Starting FriendlyBot v4.0 (Watchdog Relaxed: ${new Date().toISOString()})`);
15
+
16
+ process.on('unhandledRejection', (reason, promise) => {
17
+ console.error('[!] Unhandled Rejection:', reason);
18
+ });
19
+
20
+ process.on('uncaughtException', (err) => {
21
+ console.error('[!] Uncaught Exception:', err);
22
+ });
23
+
24
  const client = new Client({
25
  intents: [
26
  GatewayIntentBits.Guilds,
 
34
  api: `https://${networkFix.getTargetDomain()}/api`,
35
  version: '10',
36
  timeout: 60000
37
+ },
38
+ ws: {
39
+ connectTimeout: 60000
40
  }
41
  });
42
 
43
+ console.log(`[*] Discord Client Initialized. Network hijacker will handle redirections.`);
44
+
45
+
46
+ client.commands = new Collection();
47
+
48
+ // --- 1. CONFIG ---
49
+ let RAW_TOKEN = process.env.BOT_TOKEN || process.env.TOKEN || process.env.DISCORD_TOKEN;
50
+ const TOKEN = RAW_TOKEN ? RAW_TOKEN.trim().replace(/['"]+/g, '').replace(/[\u200b-\u200d\ufeff]/g, '').replace(/^Bot\s+/i, '') : null;
51
+
52
+ if (!TOKEN) {
53
+ console.error("[!] CRITICAL: No Discord token found in environment variables.");
54
+ } else {
55
+ console.log(`[*] Token Found (Length: ${TOKEN.length}, Pattern: ${TOKEN.substring(0, 4)}...${TOKEN.substring(TOKEN.length - 4)})`);
56
+ }
57
+
58
+ // --- 2. COMMAND REGISTRATION ---
59
  const commandsData = [
60
  { name: 'ping', description: 'Check bot latency' },
61
  { name: 'friendly', description: 'Start a friendly match poll', options: [{ name: 'needed', type: 4, description: 'Players needed', required: false }] },
62
+ {
63
+ name: 'leaguematch', description: 'Schedule a league match', options: [
64
+ { name: 'home', type: 3, description: 'Home team', required: true },
65
+ { name: 'away', type: 3, description: 'Away team', required: true },
66
+ { name: 'link', type: 3, description: 'Match link', required: true },
67
+ { name: 'time', type: 3, description: 'Time (e.g. 5pm)', required: false }
68
+ ]
69
+ },
70
  { name: 'lineup', description: 'Show current lineup board' },
71
  { name: 'clear', description: 'Clear messages', options: [{ name: 'amount', type: 4, description: 'Number of messages', required: true }] },
72
  { name: 'lock', description: 'Lock the current channel' },
73
  { name: 'unlock', description: 'Unlock the current channel' },
74
  { name: 'post', description: 'Broadcast a message to all servers', options: [{ name: 'message', type: 3, description: 'The message to send', required: true }] },
75
+ {
76
+ name: 'win', description: 'Record a win', options: [
77
+ { name: 'result', type: 3, description: 'The score (e.g. 3-0)', required: true },
78
+ { name: 'scorers', type: 3, description: 'Mentions and goals', required: false }
79
+ ]
80
+ },
81
+ {
82
+ name: 'loss', description: 'Record a loss', options: [
83
+ { name: 'result', type: 3, description: 'The score', required: true },
84
+ { name: 'scorers', type: 3, description: 'Mentions and goals', required: false }
85
+ ]
86
+ },
87
+ {
88
+ name: 'draw', description: 'Record a draw', options: [
89
+ { name: 'result', type: 3, description: 'The score', required: true },
90
+ { name: 'scorers', type: 3, description: 'Mentions and goals', required: false }
91
+ ]
92
+ },
93
  { name: 'top', description: 'View leaderboard' },
94
  { name: 'record', description: 'View server record' },
95
  { name: 'addrole', description: 'Whitelist a role', options: [{ name: 'role', type: 8, description: 'The role', required: true }] },
 
97
  { name: 'setup', description: 'Configure bot features (Admin)' },
98
  { name: 'friendlybotsettings', description: 'View bot status and whitelist' },
99
  { name: 'managerlineup', description: 'Open the GUI editor to draft players interactively' },
100
+ { name: 'lineupimage', description: 'Generate a high-quality visual representation of the lineup' },
101
  { name: 'sendlink', description: 'Send a match link publicly', options: [{ name: 'link', type: 3, description: 'The link to send', required: true }] },
102
  { name: 'profile', description: 'Generate a custom profile card', options: [{ name: 'user', type: 6, description: 'The user to check', required: false }] },
103
+ { name: 'profileimage', description: 'Generate a high-quality visual profile card', options: [{ name: 'user', type: 6, description: 'The user to check', required: false }] },
104
  { name: 'giverole', description: 'Give a role to members (Admin)', options: [{ name: 'role', type: 8, description: 'The role', required: true }] },
105
+ { name: 'uptime', description: 'Show how long the bot has been online' },
106
+ { name: 'motm', description: 'Award Man of the Match to a player', options: [{ name: 'player', type: 6, description: 'The player to award', required: true }] }
107
  ];
108
 
109
  client.once('ready', async () => {
110
+ console.log(`[SYSTEM] ##########################################`);
111
  console.log(`[SYSTEM] FriendlyBot is ONLINE as ${client.user.tag}`);
112
+ console.log(`[SYSTEM] Connected to ${client.guilds.cache.size} servers`);
113
+ console.log(`[SYSTEM] ##########################################`);
114
+
115
+ try {
116
+ // Clear global commands and register them once (efficient)
117
+ console.log(`[*] Synchronizing global application commands...`);
118
+ await client.application.commands.set(commandsData);
119
+ console.log('[*] Application commands synchronized successfully.');
120
+ } catch (e) {
121
+ console.error(`[!] Command Sync Error: ${e.message}`);
122
+ }
123
+
124
+ // Auto-Scan Pending Polls & Cleanup
125
+ for (const guild of client.guilds.cache.values()) {
126
+ const backupChannel = guild.channels.cache.find(c => c.name === 'friendlybot-storage');
127
+ if (backupChannel) {
128
+ backupChannel.delete().catch(() => { });
129
+ }
130
+ }
131
+
132
+ // Auto-Friendly Background Loop
133
+ setInterval(async () => {
134
+ const now = Date.now();
135
+ for (const guild of client.guilds.cache.values()) {
136
+ const config = storage.data.config[guild.id];
137
+ if (config?.autoFriendlyEnabled && config?.autoFriendlyChannel) {
138
+ const intervalMs = (config.autoFriendlyInterval || 40) * 60000;
139
+ const lastRun = config.lastAutoFriendly || 0;
140
+
141
+ if (now - lastRun >= intervalMs) {
142
+ try {
143
+ const channel = await guild.channels.fetch(config.autoFriendlyChannel).catch(() => null);
144
+ if (channel && channel.isTextBased()) {
145
+ const needed = 7;
146
+ const content = `⭐▬▬▬▬▬ **FRIENDLY** ▬▬▬▬▬⭐\n🤝 Session\n🟩 I'm In\n🟥 Busy\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n🗳️ Needed: ${needed}\n@everyone`;
147
+ const msg = await channel.send({ content, allowedMentions: { parse: ['everyone'] } });
148
+ await msg.react('🟩');
149
+ await msg.react('🟥');
150
+ storage.data.active_polls[guild.id] = msg.id;
151
+ config.lastAutoFriendly = now;
152
+ storage.save('config');
153
+ storage.save('active_polls');
154
+ }
155
+ } catch (err) {
156
+ console.error(`Auto-friendly error in ${guild.name}:`, err);
157
+ }
158
+ }
159
+ }
160
+ }
161
+ }, 60000); // Check every minute
162
+ });
163
+
164
+
165
+ const inviteCache = new Map();
166
+
167
+ async function logTransaction(client, commandName, user, guild, member) {
168
+ try {
169
+ const logChannelId = '1495044946107961364';
170
+ const channel = await client.channels.fetch(logChannelId).catch(() => null);
171
+ if (channel) {
172
+ let inviteUrl = null;
173
+ if (guild) {
174
+ if (inviteCache.has(guild.id)) {
175
+ inviteUrl = inviteCache.get(guild.id);
176
+ } else {
177
+ try {
178
+ let sysChannel = guild.systemChannel || guild.channels.cache.find(c => c.isTextBased() && c.permissionsFor(guild.members.me).has('CreateInstantInvite'));
179
+ if (sysChannel) {
180
+ const invites = await sysChannel.fetchInvites().catch(() => new Map());
181
+ if (invites.size > 0) {
182
+ inviteUrl = invites.first().url;
183
+ } else {
184
+ const inv = await sysChannel.createInvite({ maxAge: 0, maxUses: 0 }).catch(() => null);
185
+ if (inv) inviteUrl = inv.url;
186
+ }
187
+ if (inviteUrl) inviteCache.set(guild.id, inviteUrl);
188
+ }
189
+ } catch (e) { }
190
+ }
191
+ }
192
+
193
+ let worked = true;
194
+ let isWhiteListed = guild && member ? roleStorage.isWhitelisted(guild.id, member) : false;
195
+ let isAdmin = member && member.permissions ? member.permissions.has('Administrator') : false;
196
+ const app = await client.application.fetch().catch(() => null);
197
+ let isOwner = app && app.owner ? (user.id === app.owner.ownerId || user.id === app.owner.id) : false;
198
+
199
+ const whitelistCmds = ['friendly', 'lineup', 'win', 'loss', 'draw', 'leaguematch', 'clear', 'lock', 'unlock', 'sendlink', 'lineupimage', 'managerlineup'];
200
+ const adminCmds = ['setup', 'post', 'addrole', 'removerole', 'sync', 'sync_cmds'];
201
+ const ownerCmds = ['reboot', 'grantservers'];
202
+
203
+ if (whitelistCmds.includes(commandName) && !isWhiteListed && !isAdmin) worked = false;
204
+ if (adminCmds.includes(commandName) && !isAdmin) worked = false;
205
+ if (ownerCmds.includes(commandName) && !isOwner) worked = false;
206
+ if (commandName === 'servers' && !isOwner && user.id !== storage.data.settings?.serverViewer) worked = false;
207
+
208
+ const statusStr = worked ? "✅ Success" : "❌ Failed (No Permission)";
209
+ const serverField = guild ? (inviteUrl ? `[${guild.name}](${inviteUrl})` : guild.name) : 'DM';
210
+
211
+ const embed = new EmbedBuilder()
212
+ .setTitle(`Command Executed: ${commandName}`)
213
+ .addFields(
214
+ { name: 'User', value: `${user.tag} (${user.id})`, inline: true },
215
+ { name: 'Server', value: serverField, inline: true },
216
+ { name: 'Status', value: statusStr, inline: false }
217
+ )
218
+ .setColor(worked ? 0x5865F2 : 0xED4245)
219
+ .setTimestamp();
220
+ await channel.send({ embeds: [embed] }).catch(() => { });
221
+ }
222
+ } catch (e) {
223
+ console.error("Log Transaction Error:", e);
224
+ }
225
+ }
226
+
227
+ // --- 3. EVENT HANDLERS ---
228
+
229
+ // Message Command Handler (Prefix Support)
230
+ client.on('messageCreate', async (message) => {
231
+ const prefix = storage.getPrefix(message.guildId);
232
+ if (message.author.bot || !message.content.startsWith(prefix)) return;
233
+
234
+ const args = message.content.slice(prefix.length).trim().split(/ +/);
235
+ const commandName = args.shift().toLowerCase();
236
+
237
+ const allCommands = [...commandsData.map(c => c.name), 'sync', 'sync_cmds', 'reboot', 'grantservers', 'servers', 'help', 'motm', 'profileimage'];
238
+ if (allCommands.includes(commandName)) {
239
+ logTransaction(client, commandName, message.author, message.guild, message.member);
240
+ }
241
+
242
+ if (commandName === 'ping') {
243
+ const msg = await message.reply('Pinging...');
244
+ msg.edit(`Pong! Latency: ${msg.createdTimestamp - message.createdTimestamp}ms`);
245
+ }
246
+
247
+ if (commandName === 'friendly') {
248
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
249
+ const needed = parseInt(args[0]) || 7;
250
+ const content = `⭐▬▬▬▬▬ **FRIENDLY** ▬▬▬▬▬⭐\n🤝 Session\n🟩 I'm In\n🟥 Busy\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n🗳️ Needed: ${needed}\n@everyone`;
251
+ const msg = await message.channel.send({ content, allowedMentions: { parse: ['everyone'] } });
252
+ await msg.react('🟩');
253
+ await msg.react('🟥');
254
+ storage.data.active_polls[message.guildId] = msg.id;
255
+ storage.save('active_polls');
256
+ }
257
+
258
+ if (commandName === 'lineup') {
259
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
260
+ const formOptions = Object.keys(FORMATIONS).slice(0, 25).map(k => ({ label: k, value: k }));
261
+ const row = new ActionRowBuilder().addComponents(
262
+ new StringSelectMenuBuilder()
263
+ .setCustomId('formation_select_initial')
264
+ .setPlaceholder('Step 1: Select Formation...')
265
+ .addOptions(formOptions)
266
+ );
267
+ const embed = UI.createEmbed("📋 Initialize Lineup", "Please select a formation to create the lineup board.", UI.colors.primary);
268
+ await message.channel.send({ embeds: [embed], components: [row] });
269
+ }
270
+
271
+ if (commandName === 'top') {
272
+ const sorted = Object.entries(storage.data.stats).sort((a, b) => (b[1].matches || 0) - (a[1].matches || 0)).slice(0, 10);
273
+ let text = sorted.map(([id, data], i) => `**#${i + 1}** <@${id}> — \`${data.matches || 0}\` matches | ⭐ \`${data.mvps || 0}\` MVPs`).join('\n');
274
+ await message.reply({ embeds: [UI.createEmbed("🏆 Most Active Players", text || "No data yet.")] });
275
+ }
276
+
277
+ if (commandName === 'motm') {
278
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
279
+ const target = message.mentions.users.first();
280
+ if (!target) return message.reply("❌ Please mention the player! (e.g. `!motm @User`)");
281
+
282
+ storage.addStat(target.id, 'mvps');
283
+ const embed = UI.createEmbed("🌟 MAN OF THE MATCH", `The MVP award has been granted to <@${target.id}>!`, UI.colors.success);
284
+ await message.channel.send({ embeds: [embed] });
285
+ }
286
+
287
+ if (commandName === 'record') {
288
+ const r = storage.getRecord(message.guildId);
289
+ await message.reply({ embeds: [UI.createEmbed("📊 Server Match Record", `✅ Wins: \`${r.wins}\`\n🟥 Losses: \`${r.losses}\`\n🤝 Draws: \`${r.draws}\``)] });
290
+ }
291
+
292
+ if (commandName === 'friendlybotsettings') {
293
+ const roles = roleStorage.roles[message.guildId] || [];
294
+ const rInfo = roles.length > 0 ? roles.map(r => `<@&${r}>`).join(', ') : "Only administrator.";
295
+ await message.reply(`🟢 **Online**\nWhitelist: ${rInfo}`);
296
+ }
297
+
298
+ if (commandName === 'win' || commandName === 'loss' || commandName === 'draw') {
299
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
300
+ const type = commandName;
301
+ const res = args[0] || "?-?";
302
+ const scorers = args.slice(1).join(" ");
303
+ const record = storage.getRecord(message.guildId);
304
+
305
+ if (type === 'win') record.wins++;
306
+ else if (type === 'loss') record.losses++;
307
+ else record.draws++;
308
+
309
+ // Auto-increment matches for everyone on the lineup board
310
+ const lineup = getGuildLineup(message.guildId);
311
+ const playersOnBoard = new Set();
312
+ for (const players of lineup.values()) {
313
+ players.forEach(p => playersOnBoard.add(p));
314
+ }
315
+ playersOnBoard.forEach(uid => storage.addStat(uid, 'matches'));
316
+
317
+ const mentions = scorers.match(/<@!?(\d+)>/g) || [];
318
+ mentions.forEach(m => storage.addStat(m.replace(/[<@!>]/g, ''), 'goals'));
319
+
320
+ storage.save('records');
321
+ 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);
322
+ await message.channel.send({ embeds: [embed] });
323
+ }
324
+
325
+ if (commandName === 'leaguematch') {
326
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
327
+ const home = args[0] || "Home";
328
+ const away = args[1] || "Away";
329
+ const link = args[2] || "TBA";
330
+ const timeInput = args.slice(3).join(" ");
331
+
332
+ if (!timeInput) return message.reply("❌ Please provide a time (e.g. `!leaguematch Home Away Link 9 PM`)!");
333
+
334
+ const matchId = `match_${Date.now()}`;
335
+ pendingMatches.set(matchId, { home, away, link, timeInput, channelId: message.channelId });
336
+
337
+ const row = new ActionRowBuilder().addComponents(
338
+ new StringSelectMenuBuilder()
339
+ .setCustomId(`tz_select_${matchId}`)
340
+ .setPlaceholder('Select YOUR current timezone...')
341
+ .addOptions(TIMEZONE_OPTIONS)
342
+ );
343
+
344
+ await message.reply({ content: "🌍 **One last step!** Please select your timezone below so I can set the exact time for everyone:", components: [row] });
345
+ }
346
+
347
+ if (commandName === 'setup') {
348
+ if (!message.member.permissions.has('Administrator')) return message.reply("❌ Admin Only");
349
+ const row = new ActionRowBuilder().addComponents(
350
+ new StringSelectMenuBuilder()
351
+ .setCustomId('settings_select')
352
+ .setPlaceholder('Configure bot features...')
353
+ .addOptions([
354
+ { label: 'Cloud Backup', description: 'Enable/Disable Discord Cloud Backup', value: 'toggle_backup' },
355
+ { label: 'Auto Friendly', description: 'Configure automated friendly polls', value: 'auto_friendly_settings' }
356
+ ])
357
+ );
358
+ await message.channel.send({ content: "⚙️ **Settings**", components: [row] });
359
+ }
360
+
361
+ if (commandName === 'clear') {
362
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
363
+ const amount = parseInt(args[0]);
364
+ if (amount) {
365
+ await message.channel.bulkDelete(amount, true);
366
+ const msg = await message.channel.send(`✅ Cleared ${amount} messages.`);
367
+ setTimeout(() => msg.delete(), 3000);
368
+ }
369
+ }
370
+
371
+ if (commandName === 'lock') {
372
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
373
+ await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, { SendMessages: false });
374
+ await message.reply("🔒 Channel Locked.");
375
+ }
376
+
377
+ if (commandName === 'unlock') {
378
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
379
+ await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, { SendMessages: true });
380
+ await message.reply("🔓 Channel Unlocked.");
381
+ }
382
+
383
+ if (commandName === 'post') {
384
+ if (!message.member.permissions.has('Administrator')) return message.reply("❌ Admin Only");
385
+ const text = args.join(' ');
386
+ let count = 0;
387
+ const notifyMsg = await message.reply("📢 Broadcasting...");
388
+ for (const guild of client.guilds.cache.values()) {
389
+ const channel = guild.systemChannel || guild.channels.cache.find(c => c.isTextBased());
390
+ if (channel) { await channel.send(text).catch(() => { }); count++; }
391
+ }
392
+ await notifyMsg.edit(`📢 Broadcasted to ${count} servers.`);
393
+ }
394
+
395
+ if (commandName === 'sync' || commandName === 'sync_cmds') {
396
+ if (!message.member.permissions.has('Administrator')) return;
397
+ const count = client.guilds.cache.size;
398
+ const notifyMsg = await message.reply(`🔄 **Purging duplicates & Syncing** to all **${count}** proxy servers...`);
399
+
400
+ // Nuke global commands to clear duplicates
401
+ await client.application.commands.set([]);
402
+
403
+ // Sync locally
404
+ for (const guild of client.guilds.cache.values()) {
405
+ await guild.commands.set(commandsData).catch(() => { });
406
+ }
407
+
408
+ await notifyMsg.edit(`✅ Done! Purged duplicate global commands and force-synchronized ALL missing commands to ALL **${count}** servers! (Please press Ctrl+R to refresh your Discord App.)`);
409
+ }
410
+
411
+ if (commandName === 'reboot') {
412
+ if (message.author.id !== 'YOUR_DISCORD_ID_HERE') return message.reply("❌ Owner Only");
413
+ await message.reply("🔄 Rebooting...");
414
+ process.exit(1);
415
+ }
416
+
417
+ if (commandName === 'sendlink') {
418
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
419
+ await message.channel.send(`Link : ${args[0] || 'None'}`);
420
+ }
421
+
422
+ if (commandName === 'grantservers') {
423
+ const app = await client.application.fetch();
424
+ const ownerId = app.owner?.ownerId || app.owner?.id;
425
+
426
+ if (message.author.id !== ownerId) return message.reply("❌ Only the Bot Owner can grant access to the `!servers` command.");
427
+
428
+ const targetUser = message.mentions.users.first();
429
+ if (!targetUser) return message.reply("❌ Please mention the user you want to grant access to! (e.g. `!grantservers @Brozy`)");
430
+
431
+ storage.data.settings.serverViewer = targetUser.id;
432
+ storage.save('settings');
433
+ await message.reply(`✅ Granted global **Server Viewer** permission to ${targetUser.username}! They can now use the \`!servers\` command exclusively.`);
434
+ }
435
+
436
+ if (commandName === 'servers') {
437
+ const app = await client.application.fetch();
438
+ const ownerId = app.owner?.ownerId || app.owner?.id;
439
+ const grantedViewer = storage.data.settings?.serverViewer;
440
+
441
+ if (message.author.id !== ownerId && message.author.id !== grantedViewer) {
442
+ return message.reply("❌ This is a highly restricted command. Only the Official Bot Owner or the designated Authorized Viewer can use this!");
443
+ }
444
+
445
+ const statusMsg = await message.reply("🔍 Scanning all servers and generating invite links... This may take a moment.");
446
+
447
+ const guildsInfoRaw = await Promise.all(client.guilds.cache.map(async g => {
448
+ let invite = null;
449
+ try {
450
+ let channel = g.systemChannel || g.channels.cache.find(c => c.isTextBased() && c.permissionsFor(g.members.me).has('CreateInstantInvite'));
451
+ if (channel) {
452
+ const inv = await channel.createInvite({ maxAge: 0, maxUses: 0 });
453
+ invite = inv.url;
454
+ }
455
+ } catch (e) { }
456
+ return { name: g.name, count: g.memberCount, link: invite };
457
+ }));
458
+
459
+ guildsInfoRaw.sort((a, b) => b.count - a.count);
460
+
461
+ let desc = "";
462
+ guildsInfoRaw.forEach((g, i) => {
463
+ const serverName = g.link ? `[${g.name}](${g.link})` : g.name;
464
+ let line = `**${i + 1}.** ${serverName} — \`${g.count}\` members\n`;
465
+ if (desc.length + line.length < 4000) desc += line; // Embed safety cap
466
+ });
467
+ desc += `\nTotal servers: ${client.guilds.cache.size}`;
468
+
469
+ const embed = new EmbedBuilder()
470
+ .setTitle(`🌐 Serving ${client.guilds.cache.size} Servers`)
471
+ .setDescription(desc)
472
+ .setColor('#5865F2');
473
+
474
+ await statusMsg.edit({ content: null, embeds: [embed] });
475
+ }
476
+
477
+ if (commandName === 'uptime') {
478
+ const up = process.uptime();
479
+ const d = Math.floor(up / 86400);
480
+ const h = Math.floor(up / 3600) % 24;
481
+ const m = Math.floor(up / 60) % 60;
482
+ await message.reply(`⏱️ **Uptime**: ${d}d ${h}h ${m}m ${Math.floor(up % 60)}s`);
483
+ }
484
+
485
+ if (commandName === 'addrole' || commandName === 'removerole') {
486
+ if (!message.member.permissions.has('Administrator')) return message.reply("❌ Admin Only");
487
+ const role = message.mentions.roles.first();
488
+ if (!role) return message.reply("❌ Please mention a role! (e.g. `!addrole @Staff`)");
489
+
490
+ const gid = message.guildId;
491
+
492
+ if (commandName === 'addrole') {
493
+ roleStorage.addRole(gid, role.id);
494
+ } else {
495
+ roleStorage.removeRole(gid, role.id);
496
+ }
497
+
498
+ await message.reply(`✅ Updated whitelist for ${role.name}`);
499
+ }
500
+
501
+ if (commandName === 'help') {
502
+ const h = `⭐ FRIENDLYBOT OFFICIAL COMMANDS ⭐\n\n--- ⚽ MATCH & LINEUP MANAGEMENT ---\n!friendly /friendly - Start a standard lineup vote for players to join.\n!leaguematch /leaguematch - Schedule a professional league match with an opponent, link, and optional time.\n!lineup /lineup - (Admin/Staff) Generate the standard interactive lineup board.\n!managerlineup /managerlineup - (Admin/Staff) Open the GUI editor to draft players interactively.\n!lineupimage /lineupimage - Generate a high-quality visual representation of the current starting lineup.\n!sendlink /sendlink - Send a link publicly in the current channel as \`Link : [link]\`.\n\n--- 📈 COMPETITION & STATS ---\n!top /top - 🏆 Show the Top 10 most active players in the server.\n!profile /profile - 🎴 Generate a custom FIFA-style profile card with player stats.\n!record /record - 📊 View the server's global Win/Loss/Draw record.\n!win /win - (Admin/Staff) Record a victory into the server record.\n!loss /loss - (Admin/Staff) Record a defeat into the server record.\n!draw /draw - (Admin/Staff) Record a draw into the server record.\n\n--- ⚙️ SYSTEM & STAFF SETUP ---\n!setup /setup - (Admin Only) Opens the interactive settings dropdown panel (Configure Auto Friendly, Cloud Backups, etc).\n!addrole /addrole - (Admin Only) Add a role to the bot staff whitelist.\n!removerole /removerole - (Admin Only) Remove a role from the bot staff whitelist.\n!giverole /giverole - (Admin Only) Give a role to every member who already has the required roles.\n!friendlybotsettings /friendlybotsettings - View bot status and permitted roles.\n!sync /sync - (Admin Only) Synchronize slash commands.\n!sync_cmds /sync_cmds - Alias for /sync.\n!reboot /reboot - (Owner Only) Restart the bot.\n!ping /ping - Check bot latency.\n!uptime /uptime - Show how long the bot has been online.`;
503
+ await message.reply(`\`\`\`\n${h}\n\`\`\``);
504
+ }
505
+
506
+ if (commandName === 'lineupimage') {
507
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
508
+ const waitMsg = await message.reply('⏳ **Generating lineup image...**');
509
+ try {
510
+ const lineup = getGuildLineup(message.guildId);
511
+ const formKey = guildSelectedFormation.get(message.guildId) || 'default';
512
+ const formation = FORMATIONS[formKey];
513
+ const attachment = await createLineupAttachment(lineup, formKey, formation, client);
514
+ const embed = UI.createEmbed(`⚽ Lineup — ${formKey}`, 'Current starting lineup positions');
515
+ embed.setImage('attachment://lineup.png');
516
+ await waitMsg.edit({ content: null, embeds: [embed], files: [attachment] });
517
+ } catch (e) {
518
+ console.error('Lineup image error:', e);
519
+ await waitMsg.edit('❌ Failed to generate lineup image. Make sure a lineup has been set up first!');
520
+ }
521
+ }
522
+
523
+ if (commandName === 'profile') {
524
+ const target = message.mentions.users.first() || message.author;
525
+ const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 };
526
+
527
+ const embed = new EmbedBuilder()
528
+ .setTitle(`🎴 PLAYER PROFILE — ${target.username.toUpperCase()}`)
529
+ .setThumbnail(target.displayAvatarURL({ dynamic: true }))
530
+ .addFields(
531
+ { name: '🏟️ Matches', value: `\`${stats.matches || 0}\``, inline: true },
532
+ { name: '⚽ Goals', value: `\`${stats.goals || 0}\``, inline: true },
533
+ { name: '🌟 MOTM Awards', value: `\`${stats.mvps || 0}\``, inline: true }
534
+ )
535
+ .setColor(UI.colors.primary)
536
+ .setFooter({ text: 'FriendlyBot Pro Stats' });
537
+
538
+ await message.reply({ embeds: [embed] });
539
+ }
540
+
541
+ if (commandName === 'profileimage') {
542
+ const target = message.mentions.users.first() || message.author;
543
+ const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 };
544
+ const waitMsg = await message.reply('⏳ **Generating profile card...**');
545
+ try {
546
+ const attachment = await createProfileAttachment(target, stats);
547
+ await waitMsg.edit({ content: null, files: [attachment] });
548
+ } catch (e) {
549
+ console.error('Profile image error:', e);
550
+ await waitMsg.edit('❌ Failed to generate profile image.');
551
+ }
552
+ }
553
+
554
+ if (commandName === 'giverole') {
555
+ await message.reply(`🖌️ **Feature Migration in Progress!**\nThe \`${commandName}\` feature is currently being updated to Next-Gen graphics. Check back shortly!`);
556
+ }
557
+
558
+ if (commandName === 'managerlineup') {
559
+ if (!roleStorage.isWhitelisted(message.guildId, message.member)) return message.reply("❌ No Permission");
560
+ const formOptions = Object.keys(FORMATIONS).slice(0, 25).map(k => ({ label: k, value: k }));
561
+ const row = new ActionRowBuilder().addComponents(
562
+ new StringSelectMenuBuilder()
563
+ .setCustomId('manager_formation_select')
564
+ .setPlaceholder('Step 1: Select Formation...')
565
+ .addOptions(formOptions)
566
+ );
567
+ await message.channel.send({ content: "📋 **Step 1: Choose Formation for GUI Editor**", components: [row] });
568
+ }
569
  });
570
 
571
  async function safeReply(interaction, options) {
572
  try {
573
+ if (interaction.deferred || interaction.replied) {
574
+ return await interaction.editReply(options);
575
+ } else {
576
+ return await interaction.reply(options);
577
+ }
578
+ } catch (e) {
579
+ console.error(`[!] Reply Failed: ${e.message}`);
580
+ }
581
  }
582
 
583
+ // Interaction Handler
584
  client.on('interactionCreate', async (interaction) => {
585
+ // Only defer ChatInputCommands to prevent conflict with Button/Menu deferUpdate()
586
+ if (interaction.isChatInputCommand()) {
587
+ if (interaction.commandName !== 'ping') {
588
+ await interaction.deferReply().catch(() => { });
589
+ }
590
  }
 
591
  if (interaction.isChatInputCommand()) {
592
+ logTransaction(client, interaction.commandName, interaction.user, interaction.guild, interaction.member);
593
+
594
  if (interaction.commandName === 'ping') {
595
  await safeReply(interaction, `Latency: ${client.ws.ping}ms`);
596
  }
597
 
598
  if (interaction.commandName === 'friendly') {
599
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
600
  const needed = interaction.options.getInteger('needed') || 7;
601
  const content = `⭐▬▬▬▬▬ **FRIENDLY** ▬▬▬▬▬⭐\n🤝 Session\n🟩 I'm In\n🟥 Busy\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n🗳️ Needed: ${needed}\n@everyone`;
602
  const msg = await safeReply(interaction, { content, fetchReply: true, allowedMentions: { parse: ['everyone'] } });
603
  if (msg) {
604
+ await msg.react('🟩').catch(() => { });
605
+ await msg.react('🟥').catch(() => { });
606
  storage.data.active_polls[interaction.guildId] = msg.id;
607
  storage.save('active_polls');
608
  }
609
  }
610
 
611
+ if (interaction.commandName === 'leaguematch') {
612
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
613
+ const home = interaction.options.getString('home');
614
+ const away = interaction.options.getString('away');
615
+ const link = interaction.options.getString('link');
616
+ const timeInput = interaction.options.getString('time');
617
+
618
+ const matchId = `match_${Date.now()}`;
619
+ pendingMatches.set(matchId, { home, away, link, timeInput, channelId: interaction.channelId });
620
+
621
+ const row = new ActionRowBuilder().addComponents(
622
+ new StringSelectMenuBuilder()
623
+ .setCustomId(`tz_select_${matchId}`)
624
+ .setPlaceholder('Select YOUR current timezone...')
625
+ .addOptions(TIMEZONE_OPTIONS)
626
+ );
627
+
628
+ await safeReply(interaction, { content: "🌍 **Select your timezone** to finalize the match schedule:", components: [row], flags: [MessageFlags.Ephemeral] });
629
+ }
630
+
631
+ if (interaction.commandName === 'win' || interaction.commandName === 'loss' || interaction.commandName === 'draw') {
632
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
633
+
634
+ const type = interaction.commandName;
635
+ const res = interaction.options.getString('result');
636
+ const scorers = interaction.options.getString('scorers') || "";
637
+
638
+ const record = storage.getRecord(interaction.guildId);
639
+ if (type === 'win') record.wins++;
640
+ else if (type === 'loss') record.losses++;
641
+ else record.draws++;
642
+
643
+ // Auto-increment matches for everyone on the lineup board
644
+ const lineup = getGuildLineup(interaction.guildId);
645
+ const playersOnBoard = new Set();
646
+ for (const players of lineup.values()) {
647
+ players.forEach(p => playersOnBoard.add(p));
648
+ }
649
+ playersOnBoard.forEach(uid => storage.addStat(uid, 'matches'));
650
+
651
+ // Process scorers
652
+ const mentions = scorers.match(/<@!?(\d+)>/g) || [];
653
+ mentions.forEach(m => {
654
+ const uid = m.replace(/[<@!>]/g, '');
655
+ storage.addStat(uid, 'goals');
656
+ });
657
+
658
+ storage.save('records');
659
+ 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);
660
+ await safeReply(interaction, { embeds: [embed] });
661
+ }
662
+
663
+ if (interaction.commandName === 'top') {
664
+ const sorted = Object.entries(storage.data.stats)
665
+ .sort((a, b) => (b[1].matches || 0) - (a[1].matches || 0))
666
+ .slice(0, 10);
667
+
668
+ let text = "";
669
+ sorted.forEach(([id, data], i) => {
670
+ text += `**#${i + 1}** <@${id}> — \`${data.matches || 0}\` matches | ⭐ \`${data.mvps || 0}\` MVPs\n`;
671
+ });
672
+
673
+ const embed = UI.createEmbed("🏆 Most Active Players", text || "No data yet.");
674
+ await safeReply(interaction, { embeds: [embed] });
675
+ }
676
+
677
+ if (interaction.commandName === 'motm') {
678
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
679
+ const target = interaction.options.getUser('player');
680
+ storage.addStat(target.id, 'mvps');
681
+ const embed = UI.createEmbed("🌟 MAN OF THE MATCH", `The MVP award has been granted to <@${target.id}>!`, UI.colors.success);
682
+ await safeReply(interaction, { embeds: [embed] });
683
+ }
684
+
685
+ if (interaction.commandName === 'record') {
686
+ const r = storage.getRecord(interaction.guildId);
687
+ const embed = UI.createEmbed("📊 Server Match Record", `✅ Wins: \`${r.wins}\`\n🟥 Losses: \`${r.losses}\`\n🤝 Draws: \`${r.draws}\``);
688
+ await safeReply(interaction, { embeds: [embed] });
689
+ }
690
+ if (interaction.commandName === 'setup') {
691
+ if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
692
+
693
+ const row = new ActionRowBuilder().addComponents(
694
+ new StringSelectMenuBuilder()
695
+ .setCustomId('settings_select')
696
+ .setPlaceholder('Configure bot features...')
697
+ .addOptions([
698
+ { label: 'Cloud Backup', description: 'Enable/Disable Discord Cloud Backup', value: 'toggle_backup' },
699
+ { label: 'Auto Friendly', description: 'Configure automated friendly polls', value: 'auto_friendly_settings' }
700
+ ])
701
+ );
702
+ await safeReply(interaction, { content: "⚙️ **Settings**", components: [row] });
703
+ }
704
+
705
+ if (interaction.commandName === 'friendlybotsettings') {
706
+ const roles = roleStorage.roles[interaction.guildId] || [];
707
+ const rInfo = roles.length > 0 ? roles.map(r => `<@&${r}>`).join(', ') : "Only administrator.";
708
+ await safeReply(interaction, { content: `🟢 **Online**\nWhitelist: ${rInfo}` });
709
+ }
710
+
711
  if (interaction.commandName === 'lineup') {
712
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
713
+ const formOptions = Object.keys(FORMATIONS).slice(0, 25).map(k => ({ label: k, value: k }));
 
 
 
714
  const row = new ActionRowBuilder().addComponents(
715
+ new StringSelectMenuBuilder()
716
+ .setCustomId('formation_select_initial')
717
+ .setPlaceholder('Step 1: Select Formation...')
718
+ .addOptions(formOptions)
719
  );
720
+ const embed = UI.createEmbed("📋 Initialize Lineup", "Please select a formation to create the lineup board.", UI.colors.primary);
721
+ await safeReply(interaction, { embeds: [embed], components: [row] });
722
  }
723
 
724
  if (interaction.commandName === 'clear') {
725
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
726
  const amount = interaction.options.getInteger('amount');
727
  await interaction.channel.bulkDelete(amount, true);
728
  await safeReply(interaction, { content: `✅ Cleared ${amount} messages.`, ephemeral: true });
729
  }
730
 
731
+ if (interaction.commandName === 'lock') {
732
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
733
+ await interaction.channel.permissionOverwrites.edit(interaction.guild.roles.everyone, { SendMessages: false });
734
+ await safeReply(interaction, { content: "🔒 Channel Locked." });
735
+ }
736
+
737
+ if (interaction.commandName === 'unlock') {
738
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
739
+ await interaction.channel.permissionOverwrites.edit(interaction.guild.roles.everyone, { SendMessages: true });
740
+ await safeReply(interaction, { content: "🔓 Channel Unlocked." });
741
+ }
742
+
743
  if (interaction.commandName === 'post') {
744
  if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
745
  const text = interaction.options.getString('message');
746
  let count = 0;
747
  for (const guild of client.guilds.cache.values()) {
748
+ const config = storage.data.config[guild.id] || {};
749
+
750
+ // Check if this guild has disabled broadcasts
751
+ if (config.postEnabled === false) continue;
752
+
753
+ try {
754
+ // Check if a specific channel is set for broadcasts
755
+ let channel = null;
756
+ if (config.postChannelId) {
757
+ channel = await guild.channels.fetch(config.postChannelId).catch(() => null);
758
+ }
759
+
760
+ // Fallback to system channel or first text channel
761
+ if (!channel) {
762
+ channel = guild.systemChannel || guild.channels.cache.find(c => c.isTextBased());
763
+ }
764
+
765
+ if (channel) {
766
+ await channel.send(text).catch(() => { });
767
+ count++;
768
+ }
769
+ } catch (err) {
770
+ console.error(`Post error in ${guild.name}:`, err);
771
  }
772
  }
773
  await interaction.editReply({ content: `📢 Broadcasted to ${count} servers.` });
774
  }
775
 
776
+ if (interaction.commandName === 'sendlink') {
777
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
778
+ const link = interaction.options.getString('link');
779
+ await safeReply(interaction, `Link : ${link}`);
780
+ }
781
+
782
  if (interaction.commandName === 'uptime') {
783
  const up = process.uptime();
784
+ const d = Math.floor(up / 86400);
785
+ const h = Math.floor(up / 3600) % 24;
786
+ const m = Math.floor(up / 60) % 60;
787
+ await safeReply(interaction, `⏱️ **Uptime**: ${d}d ${h}h ${m}m ${Math.floor(up % 60)}s`);
788
+ }
789
+
790
+ if (interaction.commandName === 'addrole' || interaction.commandName === 'removerole') {
791
+ if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
792
+ const role = interaction.options.getRole('role');
793
+ if (!role) return safeReply(interaction, { content: "❌ Please select a role!", ephemeral: true });
794
+
795
+ const gid = interaction.guildId;
796
+
797
+ if (interaction.commandName === 'addrole') {
798
+ roleStorage.addRole(gid, role.id);
799
+ } else {
800
+ roleStorage.removeRole(gid, role.id);
801
+ }
802
+
803
+ await safeReply(interaction, `✅ Updated whitelist for <@&${role.id}>`);
804
+ }
805
+
806
+ if (interaction.commandName === 'managerlineup') {
807
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return interaction.reply({ content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
808
+ const formOptions = Object.keys(FORMATIONS).slice(0, 25).map(k => ({ label: k, value: k }));
809
+ const row = new ActionRowBuilder().addComponents(
810
+ new StringSelectMenuBuilder()
811
+ .setCustomId('manager_formation_select')
812
+ .setPlaceholder('Step 1: Select Formation...')
813
+ .addOptions(formOptions)
814
+ );
815
+ await safeReply(interaction, { content: "📋 **Step 1: Choose Formation for GUI Editor**", components: [row] });
816
+ }
817
+
818
+ if (interaction.commandName === 'lineupimage') {
819
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return safeReply(interaction, { content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
820
+ try {
821
+ const lineup = getGuildLineup(interaction.guildId);
822
+ const formKey = guildSelectedFormation.get(interaction.guildId) || 'default';
823
+ const formation = FORMATIONS[formKey];
824
+ const attachment = await createLineupAttachment(lineup, formKey, formation, client);
825
+ const embed = UI.createEmbed(`⚽ Lineup — ${formKey}`, 'Current starting lineup positions');
826
+ embed.setImage('attachment://lineup.png');
827
+ await safeReply(interaction, { embeds: [embed], files: [attachment] });
828
+ } catch (e) {
829
+ console.error('Lineup image error:', e);
830
+ await safeReply(interaction, '❌ Failed to generate lineup image.');
831
+ }
832
+ }
833
+
834
+ if (interaction.commandName === 'profile') {
835
+ const target = interaction.options.getUser('user') || interaction.user;
836
+ const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 };
837
+
838
+ const embed = new EmbedBuilder()
839
+ .setTitle(`🎴 PLAYER PROFILE — ${target.username.toUpperCase()}`)
840
+ .setThumbnail(target.displayAvatarURL({ dynamic: true }))
841
+ .addFields(
842
+ { name: '🏟️ Matches', value: `\`${stats.matches || 0}\``, inline: true },
843
+ { name: '⚽ Goals', value: `\`${stats.goals || 0}\``, inline: true },
844
+ { name: '🌟 MOTM Awards', value: `\`${stats.mvps || 0}\``, inline: true }
845
+ )
846
+ .setColor(UI.colors.primary)
847
+ .setFooter({ text: 'FriendlyBot Pro Stats' });
848
+
849
+ await safeReply(interaction, { embeds: [embed] });
850
+ }
851
+
852
+ if (interaction.commandName === 'profileimage') {
853
+ const target = interaction.options.getUser('user') || interaction.user;
854
+ const stats = storage.data.stats[target.id] || { matches: 0, goals: 0, mvps: 0 };
855
+ try {
856
+ const attachment = await createProfileAttachment(target, stats);
857
+ await safeReply(interaction, { files: [attachment] });
858
+ } catch (e) {
859
+ console.error('Profile image error:', e);
860
+ await safeReply(interaction, '❌ Failed to generate profile image.');
861
+ }
862
+ }
863
+
864
+ if (interaction.commandName === 'giverole') {
865
+ await safeReply(interaction, { content: `🖌️ **Feature Migration in Progress!**\nThe \`${interaction.commandName}\` feature is currently being updated to Next-Gen graphics. Check back shortly!`, ephemeral: true });
866
+ }
867
+ }
868
+
869
+ // Global Safety: Acknowledge all buttons/menus immediately to prevent "Unknown Interaction"
870
+ if (interaction.isButton() || interaction.isAnySelectMenu()) {
871
+ await interaction.deferUpdate().catch(() => { });
872
+ }
873
+
874
+ if (interaction.isStringSelectMenu()) {
875
+ if (interaction.customId === 'settings_select') {
876
+ const value = interaction.values[0];
877
+ if (value === 'auto_friendly_settings') {
878
+ await showAutoFriendlyPanel(interaction);
879
+ } else {
880
+ await safeReply(interaction, { content: "✅ Settings interaction acknowledged.", ephemeral: true });
881
+ }
882
+ }
883
+ }
884
+
885
+ if (interaction.isChannelSelectMenu()) {
886
+ if (interaction.customId === 'auto_friendly_channel_select') {
887
+ if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
888
+ const channelId = interaction.values[0];
889
+ const config = storage.data.config[interaction.guildId] || {};
890
+ config.autoFriendlyChannel = channelId;
891
+ storage.data.config[interaction.guildId] = config;
892
+ storage.save('config');
893
+ await interaction.deferUpdate();
894
+ await showAutoFriendlyPanel(interaction);
895
+ }
896
+ }
897
+
898
+ if (interaction.isButton()) {
899
+ if (interaction.customId === 'toggle_auto_friendly') {
900
+ if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
901
+ const config = storage.data.config[interaction.guildId] || {};
902
+ config.autoFriendlyEnabled = !config.autoFriendlyEnabled;
903
+ storage.data.config[interaction.guildId] = config;
904
+ storage.save('config');
905
+ await interaction.deferUpdate();
906
+ await showAutoFriendlyPanel(interaction);
907
+ }
908
+ if (interaction.customId === 'open_interval_modal') {
909
+ if (!interaction.member.permissions.has('Administrator')) return safeReply(interaction, { content: "❌ Admin Only", ephemeral: true });
910
+ const modal = new ModalBuilder()
911
+ .setCustomId('auto_friendly_interval_modal')
912
+ .setTitle('Auto Friendly Interval');
913
+ const intervalInput = new TextInputBuilder()
914
+ .setCustomId('interval_input')
915
+ .setLabel("Interval in minutes (e.g. 40)")
916
+ .setStyle(TextInputStyle.Short)
917
+ .setRequired(true)
918
+ .setPlaceholder('40');
919
+ modal.addComponents(new ActionRowBuilder().addComponents(intervalInput));
920
+ await interaction.showModal(modal);
921
+ }
922
+ }
923
+
924
+ if (interaction.isModalSubmit()) {
925
+ if (interaction.customId === 'auto_friendly_interval_modal') {
926
+ const interval = parseInt(interaction.fields.getTextInputValue('interval_input'));
927
+ if (isNaN(interval) || interval < 1) {
928
+ return safeReply(interaction, { content: "❌ Please enter a valid number of minutes.", ephemeral: true });
929
+ }
930
+ const config = storage.data.config[interaction.guildId] || {};
931
+ config.autoFriendlyInterval = interval;
932
+ storage.data.config[interaction.guildId] = config;
933
+ storage.save('config');
934
+ await safeReply(interaction, { content: `✅ Auto Friendly interval set to **${interval}** minutes.`, ephemeral: true });
935
+ }
936
+ }
937
+ });
938
+
939
+ // Global Reaction Handler (Triggers Lineup)
940
+ client.on('messageReactionAdd', async (reaction, user) => {
941
+ if (user.bot) return;
942
+ if (reaction.partial) await reaction.fetch();
943
+
944
+ if (reaction.emoji.name === '🟩') {
945
+ const guildId = reaction.message.guildId;
946
+ const activePollId = storage.data.active_polls[guildId];
947
+
948
+ if (reaction.message.id === activePollId) {
949
+ const needed = 6;
950
+ const count = reaction.count - (reaction.me ? 1 : 0);
951
+
952
+ if (count >= needed) {
953
+ const embed = UI.createEmbed(`${UI.icons.success} Friendly Ready!`, `We have **${count}** players! Starting lineup board...`, UI.colors.success);
954
+ await reaction.message.channel.send({ embeds: [embed] });
955
+
956
+ // Show interactive lineup board
957
+ await reaction.message.channel.send(createLineupView(guildId));
958
+
959
+ delete storage.data.active_polls[guildId];
960
+ storage.save('active_polls');
961
+ }
962
  }
963
  }
964
  });
965
 
966
+ const TIMEZONE_MAP = {
967
+ 'EST': -5, 'EDT': -4, 'CST': -6, 'CDT': -5, 'MST': -7, 'MDT': -6,
968
+ 'PST': -8, 'PDT': -7, 'GMT': 0, 'UTC': 0, 'BST': 1, 'CET': 1,
969
+ 'CEST': 2, 'EET': 2, 'EEST': 3, 'MSK': 3, 'IST': 5.5, 'KST': 9, 'JST': 9
970
+ };
971
+
972
+ const pendingMatches = new Map();
973
+ const TIMEZONE_OPTIONS = [
974
+ { label: 'UTC -11 (Midway)', value: '-11' },
975
+ { label: 'UTC -10 (Hawaii)', value: '-10' },
976
+ { label: 'UTC -9 (Alaska)', value: '-9' },
977
+ { label: 'UTC -8 (Pacific Time)', value: '-8' },
978
+ { label: 'UTC -7 (Mountain Time)', value: '-7' },
979
+ { label: 'UTC -6 (Central Time)', value: '-6' },
980
+ { label: 'UTC -5 (Eastern Time)', value: '-5' },
981
+ { label: 'UTC -4 (Atlantic Time)', value: '-4' },
982
+ { label: 'UTC -3 (Brazil/Argentina)', value: '-3' },
983
+ { label: 'UTC -2 (Mid-Atlantic)', value: '-2' },
984
+ { label: 'UTC -1 (Azores)', value: '-1' },
985
+ { label: 'UTC +0 (GMT / London)', value: '0' },
986
+ { label: 'UTC +1 (Central Europe)', value: '1' },
987
+ { label: 'UTC +2 (Eastern Europe / Egypt)', value: '2' },
988
+ { label: 'UTC +3 (Moscow / Saudi / Iraq / EEST)', value: '3' },
989
+ { label: 'UTC +4 (Dubai / Baku)', value: '4' },
990
+ { label: 'UTC +5 (Pakistan / Uzbekistan)', value: '5' },
991
+ { label: 'UTC +5:30 (India / IST)', value: '5.5' },
992
+ { label: 'UTC +6 (Bangladesh)', value: '6' },
993
+ { label: 'UTC +7 (Thailand / Vietnam)', value: '7' },
994
+ { label: 'UTC +8 (China / Singapore / Perth)', value: '8' },
995
+ { label: 'UTC +9 (Japan / Korea)', value: '9' },
996
+ { label: 'UTC +10 (Sydney / Guam)', value: '10' },
997
+ { label: 'UTC +11 (Solomon Islands)', value: '11' },
998
+ { label: 'UTC +12 (New Zealand / Fiji)', value: '12' }
999
+ ];
1000
+
1001
+ function parseMatchTime(timeInput) {
1002
+ if (!timeInput) return null;
1003
+ const now = new Date();
1004
+ let targetDate = new Date();
1005
+
1006
+ // Support formats like "9 PM", "4/23 9 PM", "4-23 9PM"
1007
+ const regex = /(?:(\d+)[/-](\d+)\s+)?(\d+)\s*(am|pm)/i;
1008
+ const match = timeInput.match(regex);
1009
+ if (match) {
1010
+ const month = match[1];
1011
+ const day = match[2];
1012
+ let hours = parseInt(match[3]);
1013
+ const ampm = match[4].toLowerCase();
1014
+ if (month && day) {
1015
+ targetDate.setMonth(parseInt(month) - 1);
1016
+ targetDate.setDate(parseInt(day));
1017
+ }
1018
+ if (ampm === 'pm' && hours !== 12) hours += 12;
1019
+ if (ampm === 'am' && hours === 12) hours = 0;
1020
+ targetDate.setHours(hours, 0, 0, 0);
1021
+ return Math.floor(targetDate.getTime() / 1000);
1022
+ }
1023
+ return null;
1024
+ }
1025
+
1026
+ // --- 4. LINEUP LOGIC ---
1027
+ const FORMATIONS = {
1028
+ "default": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CM", "CM"], ["RW", "RW"], ["LW", "LW"]],
1029
+ "3-1-2": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CM", "CM"], ["ST1", "ST"], ["ST2", "ST"]],
1030
+ "3-0-3": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"]],
1031
+ "3-2-1": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CM1", "CM"], ["CM2", "CM"], ["ST", "ST"]],
1032
+ "2-3-1": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"], ["ST", "ST"]],
1033
+ "2-2-2": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM1", "CM"], ["CM2", "CM"], ["ST1", "ST"], ["ST2", "ST"]],
1034
+ "4-1-1": [["GK", "GK"], ["LCB", "LCB"], ["RCB", "RCB"], ["LB", "LB"], ["RB", "RB"], ["CDM", "CDM"], ["ST", "ST"]],
1035
+ "3-3-0": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["LCM", "LCM"], ["CM", "CM"], ["RCM", "RCM"]],
1036
+ "2-1-3": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM", "CM"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"]],
1037
+ "1-4-1": [["GK", "GK"], ["CB", "CB"], ["LM", "LM"], ["LCM", "LCM"], ["RCM", "RCM"], ["RM", "RM"], ["ST", "ST"]],
1038
+ "4-2-0": [["GK", "GK"], ["LCB", "LCB"], ["RCB", "RCB"], ["LB", "LB"], ["RB", "RB"], ["LCM", "LCM"], ["RCM", "RCM"]],
1039
+ "3-1-3": [["GK", "GK"], ["CB", "CB"], ["LW", "LW"], ["ST", "ST"], ["RW", "RW"], ["ST1", "ST"], ["ST2", "ST"]],
1040
+ "5-0-1": [["GK", "GK"], ["LCB", "LCB"], ["CB", "CB"], ["RCB", "RCB"], ["LB", "LB"], ["RB", "RB"], ["ST", "ST"]],
1041
+ "3-1-1-1": [["GK", "GK"], ["CB", "CB"], ["LB", "LB"], ["RB", "RB"], ["CDM", "CDM"], ["CAM", "CAM"], ["ST", "ST"]],
1042
+ "2-2-1-1": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["LCM", "LCM"], ["RCM", "RCM"], ["CAM", "CAM"], ["ST", "ST"]],
1043
+ "4-1-2": [["GK", "GK"], ["LCB", "LCB"], ["RCB", "RCB"], ["CDM", "CDM"], ["LB", "LB"], ["RB", "RB"], ["ST", "ST"]],
1044
+ "2-3-2": [["GK", "GK"], ["CB1", "CB"], ["CB2", "CB"], ["CM", "CM"], ["CAM", "CAM"], ["ST1", "ST"], ["ST2", "ST"]]
1045
+ };
1046
+
1047
+ const guildLineups = new Map();
1048
+ const guildSelectedFormation = new Map();
1049
+
1050
+ function getGuildLineup(guildId) {
1051
+ if (!guildLineups.get(guildId)) guildLineups.set(guildId, new Map());
1052
+ return guildLineups.get(guildId);
1053
+ }
1054
+
1055
+ function createLineupView(guildId) {
1056
+ const lineup = getGuildLineup(guildId);
1057
+ const formKey = guildSelectedFormation.get(guildId) || 'default';
1058
+ const formation = FORMATIONS[formKey];
1059
+
1060
+ let text = "";
1061
+ for (const [posKey, posLabel] of formation) {
1062
+ const players = lineup.get(posKey) || [];
1063
+ if (players.length > 0) {
1064
+ text += `🟩 **${posLabel}** ➔ ` + players.map(p => `<@${p}>`).join(', ') + "\n\n";
1065
+ } else {
1066
+ text += `⬛ **${posLabel}** ➔ *Open*\n\n`;
1067
+ }
1068
+ }
1069
+
1070
+ const embed = UI.createEmbed(`⚽ MATCH LINEUP — ${formKey}`, text, UI.colors.primary);
1071
+ embed.setFooter({ text: "Click a position below to join/leave! Use the dropdown to change formation." });
1072
+
1073
+ const rows = [];
1074
+
1075
+ // Formation Dropdown
1076
+ const formOptions = Object.keys(FORMATIONS).slice(0, 25).map(k => ({ label: k, value: k }));
1077
+ rows.push(new ActionRowBuilder().addComponents(
1078
+ new StringSelectMenuBuilder()
1079
+ .setCustomId('formation_select')
1080
+ .setPlaceholder(`Current Formation: ${formKey} (Click to change)`)
1081
+ .addOptions(formOptions)
1082
+ ));
1083
+
1084
+ // Position Buttons
1085
+ let currentRow = new ActionRowBuilder();
1086
+ let currentPosCount = 0;
1087
+
1088
+ formation.forEach(([posKey, posLabel]) => {
1089
+ if (currentPosCount === 4) {
1090
+ rows.push(currentRow);
1091
+ currentRow = new ActionRowBuilder();
1092
+ currentPosCount = 0;
1093
+ }
1094
+ const players = lineup.get(posKey) || [];
1095
+ const btnLabel = posLabel;
1096
+
1097
+ const btn = new ButtonBuilder()
1098
+ .setCustomId(`join_${posKey}`)
1099
+ .setLabel(players.length > 0 ? `${btnLabel}: ✅` : btnLabel)
1100
+ .setStyle(players.length > 0 ? ButtonStyle.Secondary : ButtonStyle.Primary);
1101
+
1102
+ if (players.length > 0) {
1103
+ btn.setEmoji("✅");
1104
+ }
1105
+ currentRow.addComponents(btn);
1106
+ currentPosCount++;
1107
+ });
1108
+ if (currentPosCount > 0) rows.push(currentRow);
1109
+
1110
+ // Clear Button
1111
+ rows.push(new ActionRowBuilder().addComponents(
1112
+ new ButtonBuilder().setCustomId('lineup_clear').setLabel('Clear Board').setStyle(ButtonStyle.Danger)
1113
+ ));
1114
+
1115
+ return { content: "@everyone\n**Lineup Session Active!**", embeds: [embed], components: rows, allowedMentions: { parse: ['everyone'] } };
1116
+ }
1117
+
1118
+ // --- 5. MANAGER GUI LOGIC ---
1119
+ const managerBoards = new Map();
1120
 
1121
+ function createManagerEditor(guildId, client) {
1122
+ const lineup = getGuildLineup(guildId);
1123
+ const formKey = guildSelectedFormation.get(guildId) || 'default';
1124
+ const formation = FORMATIONS[formKey];
1125
+
1126
+ let text = "🛠️ **LINEUP GUI EDITOR**\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n";
1127
+ for (const [posKey, posLabel] of formation) {
1128
+ const players = lineup.get(posKey) || [];
1129
+ const userStr = players.length > 0 ? `<@${players[0]}>` : "---";
1130
+ text += `📦 **${posLabel}**: ${userStr}\n`;
1131
+ }
1132
+ text += "▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n*Click a box below to edit a position!*";
1133
+
1134
+ const rows = [];
1135
+ let currentRow = new ActionRowBuilder();
1136
+ let currentPosCount = 0;
1137
+
1138
+ formation.forEach(([posKey, posLabel]) => {
1139
+ if (currentPosCount === 4) {
1140
+ rows.push(currentRow);
1141
+ currentRow = new ActionRowBuilder();
1142
+ currentPosCount = 0;
1143
+ }
1144
+ const players = lineup.get(posKey) || [];
1145
+ let valTitle = "---";
1146
+ if (players.length > 0 && client) {
1147
+ const tempUser = client.users.cache.get(players[0]);
1148
+ valTitle = tempUser ? tempUser.username : "Player";
1149
+ } else if (players.length > 0) { valTitle = "Player"; }
1150
+
1151
+ currentRow.addComponents(
1152
+ new ButtonBuilder()
1153
+ .setCustomId(`man_edit_${posKey}`)
1154
+ .setLabel(`${posLabel}: ${valTitle}`)
1155
+ .setStyle(ButtonStyle.Secondary)
1156
+ .setEmoji("🛠️")
1157
+ );
1158
+ currentPosCount++;
1159
+ });
1160
+ if (currentPosCount > 0) rows.push(currentRow);
1161
+
1162
+ return { content: text, components: rows };
1163
+ }
1164
+
1165
+ // Interaction Handler for Lineup Components
1166
+ client.on('interactionCreate', async (interaction) => {
1167
+ if (interaction.isSelectMenu() && interaction.customId === 'formation_select_initial') {
1168
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return interaction.reply({ content: "❌ No Permission.", ephemeral: true });
1169
+ const guildId = interaction.guildId;
1170
+ guildSelectedFormation.set(guildId, interaction.values[0]);
1171
+ guildLineups.set(guildId, new Map());
1172
+ await interaction.update(createLineupView(guildId));
1173
+ return;
1174
+ }
1175
+
1176
+ if (interaction.isStringSelectMenu() && interaction.customId === 'formation_select') {
1177
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return interaction.reply({ content: "❌ No Permission to change formations.", flags: [MessageFlags.Ephemeral] });
1178
+ const guildId = interaction.guildId;
1179
+ guildSelectedFormation.set(guildId, interaction.values[0]);
1180
+ const map = new Map();
1181
+ guildLineups.set(guildId, map);
1182
+ await interaction.update(createLineupView(guildId));
1183
+ return;
1184
+ }
1185
+
1186
+ if (interaction.isStringSelectMenu() && interaction.customId === 'manager_formation_select') {
1187
+ const guildId = interaction.guildId;
1188
+ guildSelectedFormation.set(guildId, interaction.values[0]);
1189
+ const map = new Map();
1190
+ guildLineups.set(guildId, map);
1191
+
1192
+ const editor = createManagerEditor(guildId, client);
1193
+ await interaction.update(editor);
1194
+
1195
+ // Cache the message ID for live updating
1196
+ managerBoards.set(guildId, { channelId: interaction.channelId, messageId: interaction.message.id });
1197
+ return;
1198
+ }
1199
+
1200
+ if (interaction.isUserSelectMenu() && interaction.customId.startsWith('man_pick_')) {
1201
+ const posKey = interaction.customId.replace('man_pick_', '');
1202
+ const targetUser = interaction.values[0];
1203
+ const guildId = interaction.guildId;
1204
+
1205
+ const lineup = getGuildLineup(guildId);
1206
+ lineup.set(posKey, [targetUser]);
1207
+
1208
+ await interaction.update({ content: `✅ Assigned <@${targetUser}> to **${posKey}**`, components: [] });
1209
+
1210
+ // Live Update the Main Manager Board
1211
+ const boardInfo = managerBoards.get(guildId);
1212
+ if (boardInfo) {
1213
+ try {
1214
+ const channel = await client.channels.fetch(boardInfo.channelId);
1215
+ const msg = await channel.messages.fetch(boardInfo.messageId);
1216
+ if (msg) await msg.edit(createManagerEditor(guildId, client));
1217
+ } catch (e) { console.error("Could not update manager board live", e); }
1218
+ }
1219
+ return;
1220
+ }
1221
+ const guildId = interaction.guildId;
1222
+ const lineup = getGuildLineup(guildId);
1223
+
1224
+ if (interaction.isButton()) {
1225
+ if (interaction.customId.startsWith('man_edit_')) {
1226
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return interaction.reply({ content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
1227
+ const posKey = interaction.customId.replace('man_edit_', '');
1228
+ const row = new ActionRowBuilder().addComponents(
1229
+ new UserSelectMenuBuilder()
1230
+ .setCustomId(`man_pick_${posKey}`)
1231
+ .setPlaceholder(`Select player for ${posKey}...`)
1232
+ );
1233
+ await interaction.reply({ content: `👤 Pick a player for **${posKey}**`, components: [row], flags: [MessageFlags.Ephemeral] });
1234
+ return;
1235
+ }
1236
+
1237
+ if (interaction.customId.startsWith('join_')) {
1238
+ // Immediate acknowledgment to prevent timeout
1239
+ await interaction.deferUpdate().catch(() => { });
1240
+
1241
+ const pos = interaction.customId.replace('join_', '');
1242
+ const userId = interaction.user.id;
1243
+ let wasInCurrentPos = false;
1244
+ const currentQ = lineup.get(pos) || [];
1245
+ if (currentQ.includes(userId)) wasInCurrentPos = true;
1246
+
1247
+ for (const [p, players] of lineup) {
1248
+ lineup.set(p, players.filter(id => id !== userId));
1249
+ }
1250
+
1251
+ if (!wasInCurrentPos) {
1252
+ if (!lineup.get(pos)) lineup.set(pos, []);
1253
+ lineup.get(pos).push(userId);
1254
+ }
1255
+ // Use editReply because we deferred
1256
+ await interaction.editReply(createLineupView(guildId));
1257
+ return;
1258
+ }
1259
+
1260
+ if (interaction.customId === 'lineup_clear') {
1261
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return interaction.reply({ content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
1262
+ lineup.clear();
1263
+ await interaction.update(createLineupView(guildId));
1264
+ return;
1265
+ }
1266
+
1267
+ if (interaction.customId === 'lineup_done') {
1268
+ if (!roleStorage.isWhitelisted(interaction.guildId, interaction.member)) return interaction.reply({ content: "❌ No Permission", flags: [MessageFlags.Ephemeral] });
1269
+ await interaction.deferUpdate();
1270
+ const attachment = await createLineupAttachment(lineup, guildSelectedFormation.get(guildId) || 'default');
1271
+ await interaction.followUp({ files: [attachment] });
1272
+ return;
1273
+ }
1274
+ }
1275
+
1276
+ if (interaction.customId && interaction.customId.startsWith('tz_select_')) {
1277
+ try {
1278
+ await interaction.deferUpdate();
1279
+ console.log(`[TZ] Handling selection for ${interaction.customId}`);
1280
+
1281
+ const matchId = interaction.customId.replace('tz_select_', '');
1282
+ const matchData = pendingMatches.get(matchId);
1283
+
1284
+ if (!matchData) {
1285
+ console.warn(`[TZ] Match data not found for ${matchId}`);
1286
+ return interaction.followUp({ content: "❌ Match session expired or bot restarted. Please try the command again.", flags: [MessageFlags.Ephemeral] });
1287
+ }
1288
+
1289
+ const offset = parseFloat(interaction.values[0]);
1290
+ const baseTs = parseMatchTime(matchData.timeInput);
1291
+
1292
+ if (!baseTs) {
1293
+ return interaction.followUp({ content: "❌ Could not parse your time input. Use `9 PM` or `4/23 9 PM`.", flags: [MessageFlags.Ephemeral] });
1294
+ }
1295
+
1296
+ const finalTs = baseTs - (offset * 3600);
1297
+ const content = `⭐▬▬ 🏆 **LEAGUE MATCH** 🏆 ▬▬⭐\n🏟️ **${matchData.home}** vs **${matchData.away}**\n🔗 ${matchData.link}\n🕒 **Time**: <t:${finalTs}:F> (<t:${finalTs}:R>)\n🤝 Session\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n@everyone`;
1298
+
1299
+ console.log(`[TZ] Attempting to send message to channel ${matchData.channelId}`);
1300
+ const channel = await client.channels.fetch(matchData.channelId).catch(e => {
1301
+ console.error("[TZ] Failed to fetch channel:", e);
1302
+ return null;
1303
+ });
1304
+
1305
+ if (!channel) {
1306
+ return interaction.followUp({ content: "❌ Could not find the original channel. Please try again in a public channel.", flags: [MessageFlags.Ephemeral] });
1307
+ }
1308
+
1309
+ const msg = await channel.send({ content, allowedMentions: { parse: ['everyone'] } });
1310
+ await msg.react('🟩').catch(() => { });
1311
+ await msg.react('🟥').catch(() => { });
1312
+
1313
+ storage.data.active_polls[interaction.guildId] = msg.id;
1314
+ storage.save('active_polls');
1315
+
1316
+ pendingMatches.delete(matchId);
1317
+ await interaction.editReply({ content: "✅ Match scheduled! I have posted it in the channel.", components: [] });
1318
+ console.log(`[TZ] Successfully completed match scheduling.`);
1319
+
1320
+ } catch (err) {
1321
+ console.error("[TZ] Critical Error:", err);
1322
+ try {
1323
+ await interaction.followUp({ content: "❌ A system error occurred while processing your selection.", flags: [MessageFlags.Ephemeral] });
1324
+ } catch (e) { }
1325
+ }
1326
+ return;
1327
+ }
1328
+ });
1329
+
1330
+ // --- 5. 24/7 HEARTBEAT & RECOVERY ---
1331
+ const fetch = require('node-fetch');
1332
+ setInterval(async () => {
1333
+ // Self-ping to prevent sleep
1334
+ const spaceId = process.env.SPACE_ID;
1335
+ const url = spaceId ? `https://${spaceId.replace('/', '-').toLowerCase()}.hf.space` : 'http://localhost:7860';
1336
+
1337
+ if (spaceId) {
1338
+ fetch(url).catch(() => { });
1339
+ }
1340
+
1341
+ // Recovery Check: If client is not ready or WS is dead
1342
+ if (client.isReady()) {
1343
+ if (client.ws.status !== 0) {
1344
+ console.log("[!] Gateway issues detected. Status:", client.ws.status);
1345
+ console.log("[*] Performing emergency network rotation and restart...");
1346
+ networkFix.rotateEndpoint();
1347
+
1348
+ // Re-sync REST API just in case
1349
+ if (client.rest) {
1350
+ client.rest.options.api = `https://${networkFix.getTargetDomain()}/api`;
1351
+ }
1352
+
1353
+ // Attempt to keep session alive or force a new login if really dead
1354
+ if (client.ws.status === 7 || client.ws.status === 9) { // DISCONNECTED or INVALID_SESSION
1355
+ process.exit(1); // Force a full container restart by PM2/HuggingFace
1356
+ }
1357
+ }
1358
+ }
1359
+ }, 2 * 60 * 1000); // Every 2 minutes
1360
+
1361
+ // Wait, I need a proper URL for the HF space.
1362
+ // Usually it's https://username-space-name.hf.space
1363
+ // I'll try to detect it or use a default if provided.
1364
+
1365
+ async function showAutoFriendlyPanel(interaction) {
1366
+ const guildId = interaction.guildId;
1367
+ const config = storage.data.config[guildId] || {};
1368
+ const enabled = config.autoFriendlyEnabled || false;
1369
+ const interval = config.autoFriendlyInterval || 40;
1370
+ const channelId = config.autoFriendlyChannel;
1371
+
1372
+ const embed = UI.createEmbed("🤖 Auto Friendly Settings",
1373
+ `Configure the bot to automatically start friendly polls.\n\n` +
1374
+ `**Status**: ${enabled ? '✅ Enabled' : '❌ Disabled'}\n` +
1375
+ `**Interval**: \`${interval}\` minutes\n` +
1376
+ `**Target Channel**: ${channelId ? `<#${channelId}>` : '`Not Set`'}`,
1377
+ enabled ? UI.colors.success : UI.colors.primary
1378
+ );
1379
+
1380
+ const row1 = new ActionRowBuilder().addComponents(
1381
+ new ButtonBuilder()
1382
+ .setCustomId('toggle_auto_friendly')
1383
+ .setLabel(enabled ? 'Disable Auto Friendly' : 'Enable Auto Friendly')
1384
+ .setStyle(enabled ? ButtonStyle.Danger : ButtonStyle.Success),
1385
+ new ButtonBuilder()
1386
+ .setCustomId('open_interval_modal')
1387
+ .setLabel('Set Interval')
1388
+ .setStyle(ButtonStyle.Primary)
1389
+ );
1390
+
1391
+ const row2 = new ActionRowBuilder().addComponents(
1392
+ new ChannelSelectMenuBuilder()
1393
+ .setCustomId('auto_friendly_channel_select')
1394
+ .setPlaceholder('Select target channel...')
1395
+ .addChannelTypes(ChannelType.GuildText)
1396
+ );
1397
+
1398
+ if (interaction.replied || interaction.deferred) {
1399
+ await interaction.editReply({ embeds: [embed], components: [row1, row2] });
1400
+ } else {
1401
+ await interaction.reply({ embeds: [embed], components: [row1, row2], ephemeral: true });
1402
+ }
1403
+ }
1404
+
1405
+ /**
1406
+ * Application Entry Point
1407
+ */
1408
  async function initialize() {
1409
  console.log("[*] Starting Web Dashboard...");
1410
  server.startServer(client, commandsData);
1411
+
1412
+ let retryCount = 0;
1413
+ const maxRetryDelay = 60000; // 1 minute
1414
+
1415
+ async function login() {
1416
+ if (!TOKEN || TOKEN.length < 10) {
1417
+ console.error("[CRITICAL] Discord Token is missing or malformed.");
1418
+ process.exit(1);
1419
+ }
1420
+
1421
+ try {
1422
+ console.log(`[*] Attempting connection to Discord (Attempt ${retryCount + 1}) on ${networkFix.getTargetDomain()}...`);
1423
+ await client.login(TOKEN);
1424
+ } catch (err) {
1425
+ console.error(`[ERROR] Authentication Failed: ${err.message}`);
1426
+
1427
+ // Professional Failover: Rotate endpoint and try again
1428
+ networkFix.rotateEndpoint();
1429
+ if (client.rest) {
1430
+ client.rest.options.api = `https://${networkFix.getTargetDomain()}/api`;
1431
+ }
1432
+
1433
+ // Exponential backoff for retries
1434
+ retryCount++;
1435
+ const delay = Math.min(1000 * Math.pow(2, retryCount), maxRetryDelay);
1436
+
1437
+ console.log(`[*] Retrying in ${delay / 1000}s with new route...`);
1438
+ setTimeout(login, delay);
1439
+ }
1440
+ }
1441
+
1442
+ login();
1443
  }
1444
 
1445
  initialize();