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

Update index.js

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