Brozy123 commited on
Commit
7793fcb
·
verified ·
1 Parent(s): 348f897

Update server.js

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