Brozy123 commited on
Commit
303244a
·
verified ·
1 Parent(s): 236c6fa

Update index.js

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