Spaces:
Runtime error

Brozy123 commited on
Commit
faf81ad
·
verified ·
1 Parent(s): d8395b9

Update server.js

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