Brozy123 commited on
Commit
1a8fb24
·
verified ·
1 Parent(s): 1362033

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +411 -615
index.js CHANGED
@@ -1,677 +1,473 @@
1
- const express = require('express');
2
- const path = require('path');
3
- const fs = require('fs');
4
- const crypto = require('crypto');
5
- const premiumStore = require('./premiumStore');
6
 
7
- console.log(">>> [MODULE] server.js: Initializing...");
8
- const app = express();
9
- const port = process.env.PORT || 7860;
10
-
11
-
12
- // Discord OAuth2 Config — reads from multiple possible env var names
13
- const CLIENT_SECRET = process.env.CLIENT_SECRET || process.env.DISCORD_CLIENT_SECRET || '';
14
- const REDIRECT_URI = process.env.REDIRECT_URI || process.env.DISCORD_REDIRECT_URL || '';
15
-
16
- // Store reference to the Discord client (set from index.js)
17
- let discordClient = null;
18
- let commandsDataRef = null;
19
-
20
- // Session store (persisted to disk so logins survive restarts)
21
- const storage = require('./storage');
22
- const SESSION_FILE = path.join(storage.PERSISTENT_DIR, 'sessions.json');
23
- let sessions = new Map();
24
-
25
- // Load sessions from disk on startup
26
- try {
27
- if (fs.existsSync(SESSION_FILE)) {
28
- const content = fs.readFileSync(SESSION_FILE, 'utf8').trim();
29
- if (content) {
30
- const raw = JSON.parse(content);
31
- if (raw && typeof raw === 'object') {
32
- sessions = new Map(Object.entries(raw));
33
- console.log(`[*] Dashboard: Loaded ${sessions.size} persistent session(s).`);
34
- }
35
- }
36
- }
37
- } catch (e) {
38
- console.error(`[*] Dashboard: Failed to load sessions: ${e.message}`);
39
- }
40
- console.log("[*] Dashboard: Session system initialized.");
41
-
42
- function saveSessions() {
43
- try {
44
- const dir = path.dirname(SESSION_FILE);
45
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
46
- const obj = Object.fromEntries(sessions);
47
- fs.writeFileSync(SESSION_FILE, JSON.stringify(obj), 'utf8');
48
- } catch (e) {}
49
- }
50
 
51
- // In-memory log buffer
52
- const logBuffer = [];
53
- const MAX_LOGS = 200;
54
-
55
- let isHijacked = false;
56
- function hijackConsole() {
57
- if (isHijacked) return;
58
- const origLog = console.log;
59
- const origErr = console.error;
60
- console.log = (...args) => {
61
- const line = args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
62
- logBuffer.push(line);
63
- if (logBuffer.length > MAX_LOGS) logBuffer.shift();
64
- origLog.apply(console, args);
65
- };
66
- console.error = (...args) => {
67
- const line = '[Error] ' + args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
68
- logBuffer.push(line);
69
- if (logBuffer.length > MAX_LOGS) logBuffer.shift();
70
- origErr.apply(console, args);
71
- };
72
- isHijacked = true;
73
- }
74
 
75
  app.use(express.json());
76
-
77
- function hasDashboardPermissions(permissionBits) {
78
- try {
79
- const perms = BigInt(permissionBits || '0');
80
- return (perms & BigInt(0x20)) !== BigInt(0) || (perms & BigInt(0x8)) !== BigInt(0);
81
- } catch (e) {
82
- return false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  }
 
84
  }
 
85
 
86
- // --- Helper: Get redirect URI ---
87
- function getRedirectUri(req) {
88
- if (REDIRECT_URI) return REDIRECT_URI;
89
-
90
- // Fallback: If we have a request object, use it to build the URI dynamically
91
- if (req) {
92
- const host = req.get('host');
93
- const protocol = req.protocol === 'http' && host.includes('.hf.space') ? 'https' : req.protocol;
94
- const path = req.path === '/' ? '/' : '/callback';
95
- return `${protocol}://${host}${path}`;
96
- }
97
-
98
- const spaceId = process.env.SPACE_ID;
99
- if (spaceId) {
100
- const host = spaceId.includes('/') ? spaceId.replace('/', '-').toLowerCase() : spaceId.toLowerCase();
101
- return `https://${host}.hf.space/callback`;
102
- }
103
- return `http://localhost:${port}/callback`;
104
- }
105
 
106
- // --- Helper: Get Client ID from bot ---
107
- function getClientId() {
108
- return discordClient?.user?.id || process.env.CLIENT_ID || process.env.DISCORD_CLIENT_ID || '';
109
- }
 
 
110
 
111
- // --- Helper: Parse session cookie ---
112
- function getSession(req) {
113
- const cookies = (req.headers.cookie || '').split(';').reduce((acc, c) => {
114
- const [k, v] = c.trim().split('=');
115
- if (k && v) acc[k] = v;
116
- return acc;
117
- }, {});
118
- const sid = cookies['fb_session'];
119
- if (sid && sessions.has(sid)) return sessions.get(sid);
120
- return null;
121
- }
122
 
123
- // --- Auth Middleware ---
124
- function requireAuth(req, res, next) {
125
- const session = getSession(req);
126
- if (session && session.user) {
127
- req.user = session.user; // Attach user for convenience
128
- return next();
129
- }
130
- res.status(401).json({ error: 'Unauthorized' });
131
- }
132
 
133
- // --- Attach user to req ---
134
- app.use((req, res, next) => {
135
- req.dashSession = getSession(req);
136
- next();
137
- });
138
 
139
- // --- Static Assets ---
140
- app.get('/', (req, res) => {
141
- // If we get an OAuth code on the root route, handle it using the root as the redirect_uri
142
- if (req.query.code) {
143
- console.log("[Dashboard] Received OAuth code on root route, handling...");
144
- return handleOAuthCallback(req, res, getRedirectUri(req));
145
  }
146
- res.sendFile(path.join(__dirname, 'dashboard.html'));
147
- });
148
- app.get('/logo.png', (req, res) => {
149
- const logo = path.join(__dirname, 'logo.png');
150
- if (fs.existsSync(logo)) res.sendFile(logo);
151
- else res.status(404).send('Not found');
 
 
 
 
 
 
 
 
 
 
 
 
152
  });
153
 
154
- // Returns 200 as long as the web server is running.
155
- // This prevents Hugging Face and other platforms from restarting the space
156
- // while the Discord bot is still performing its initial connection handshake.
157
- app.get('/healthz', (req, res) => {
158
- const discordReady = !!(discordClient && discordClient.isReady && discordClient.isReady());
159
- return res.status(200).json({
160
- ok: true,
161
- webReady: true,
162
- discordReady: discordReady,
163
- guilds: discordReady ? (discordClient.guilds?.cache?.size || 0) : 0
164
- });
165
- });
166
 
167
- app.get('/tos', (req, res) => {
168
- res.sendFile(path.join(__dirname, 'tos.html'));
 
 
 
 
169
  });
170
 
171
- app.get('/privacy', (req, res) => {
172
- res.sendFile(path.join(__dirname, 'privacy.html'));
173
- });
 
174
 
175
- app.get('/league', (req, res) => {
176
- res.sendFile(path.join(__dirname, 'league.html'));
177
- });
178
 
179
- app.get('/premium', (req, res) => {
180
- res.sendFile(path.join(__dirname, 'premium.html'));
181
- });
182
 
 
 
 
 
 
183
 
184
- // --- Discord OAuth2: Step 1 — Redirect to Discord ---
185
- app.get('/auth/login', (req, res) => {
186
- const clientId = getClientId();
187
- const redirect = encodeURIComponent(getRedirectUri(req));
188
- console.log(`[Dashboard] Starting OAuth login. Redirect URI: ${getRedirectUri(req)}`);
189
- const url = `https://discord.com/api/oauth2/authorize?client_id=${clientId}&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds`;
190
- res.redirect(url);
191
- });
 
 
 
 
 
192
 
193
- async function fetchWithRetry(url, options, retries = 3) {
194
- const proxyBase = process.env.DISCORD_BASE_URL ? process.env.DISCORD_BASE_URL.replace(/\/$/, '') : 'https://discord.com';
195
- const endpoints = [
196
- proxyBase,
197
- 'https://discord.com',
198
- 'https://canary.discord.com',
199
- 'https://ptb.discord.com'
200
- ];
201
-
202
- for (let i = 0; i < endpoints.length; i++) {
203
- const controller = new AbortController();
204
- const timeoutId = setTimeout(() => controller.abort(), 20000); // 20s timeout
205
-
206
- try {
207
- let targetUrl = url;
208
- const currentBase = endpoints[i];
209
-
210
- // Only swap if it's a discord API call
211
- if (url.includes('discord.com/api')) {
212
- targetUrl = url.replace('https://discord.com', currentBase);
213
- console.log(`[Dashboard] Connection Attempt ${i + 1} via ${new URL(currentBase).hostname}...`);
214
- }
215
-
216
- const res = await fetch(targetUrl, {
217
- ...options,
218
- signal: controller.signal
219
- });
220
- clearTimeout(timeoutId);
221
-
222
- if (!res.ok) {
223
- const text = await res.text().catch(() => '');
224
- console.warn(`[Dashboard] API returned ${res.status} from ${new URL(currentBase).hostname}`);
225
- if (i === endpoints.length - 1) throw new Error(`HTTP ${res.status}: ${text}`);
226
- continue; // Try next endpoint
227
- }
228
- return res;
229
- } catch (err) {
230
- clearTimeout(timeoutId);
231
- const isTimeout = err.name === 'AbortError';
232
- console.warn(`[Dashboard] Attempt ${i + 1} (${new URL(endpoints[i]).hostname}) failed: ${isTimeout ? 'Timeout' : err.message}`);
233
-
234
- if (i === endpoints.length - 1) throw err;
235
-
236
- // Short delay before next endpoint
237
- await new Promise(r => setTimeout(r, 1000));
238
- }
239
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  }
241
 
242
- // --- Discord OAuth2: Step 2 — Callback from Discord ---
243
- // Support both /callback and /auth/callback to match any Discord redirect config
244
- async function handleOAuthCallback(req, res, overrideRedirectUri) {
245
- const { code, error, error_description } = req.query;
246
-
247
- if (error) {
248
- console.error(`[Dashboard] Discord returned error: ${error} (${error_description})`);
249
- return res.redirect(`/?error=${error}`);
250
- }
251
 
252
- if (!code) {
253
- console.warn(`[Dashboard] No code found in query parameters. URL: ${req.originalUrl}`);
254
- return res.redirect('/?error=no_code');
255
- }
256
-
257
- // Ensure overrideRedirectUri is a string and not the 'next' function from Express
258
- const usedRedirectUri = (typeof overrideRedirectUri === 'string') ? overrideRedirectUri : getRedirectUri(req);
259
- console.log(`[Dashboard] Handling OAuth callback. Code: ${code.substring(0, 5)}... Redirect URI: ${usedRedirectUri}`);
260
 
261
- if (!CLIENT_SECRET) {
262
- console.error('[Dashboard] CRITICAL: CLIENT_SECRET is missing from environment variables.');
263
- return res.redirect('/?error=server_error');
264
- }
265
 
266
- try {
267
- console.log(`[Dashboard] Exchanging code for token... (Redirect URI: ${getRedirectUri()})`);
268
- // Exchange code for token
269
- const tokenRes = await fetchWithRetry('https://discord.com/api/oauth2/token', {
270
- method: 'POST',
271
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
272
- body: new URLSearchParams({
273
- client_id: getClientId(),
274
- client_secret: CLIENT_SECRET,
275
- grant_type: 'authorization_code',
276
- code,
277
- redirect_uri: usedRedirectUri
278
- })
279
- });
280
-
281
- const tokenData = await tokenRes.json();
282
- if (!tokenData.access_token) {
283
- console.error('[Dashboard] Token exchange failed:', tokenData);
284
- return res.redirect('/?error=token_failed');
285
- }
286
 
287
- console.log(`[Dashboard] Token received. Fetching user profile...`);
288
- // Fetch user profile
289
- const userRes = await fetchWithRetry('https://discord.com/api/users/@me', {
290
- headers: { Authorization: `Bearer ${tokenData.access_token}` }
291
- });
292
- const user = await userRes.json();
293
- if (!user.id) {
294
- console.error('[Dashboard] Failed to fetch user profile:', user);
295
- return res.redirect('/?error=user_failed');
296
- }
297
 
298
- // Fetch user guilds
299
- console.log(`[Dashboard] Fetching guilds for user ${user.username} (${user.id})...`);
300
- const guildsRes = await fetchWithRetry('https://discord.com/api/users/@me/guilds', {
301
- headers: { Authorization: `Bearer ${tokenData.access_token}` }
302
- });
303
- const userGuilds = await guildsRes.json();
304
-
305
- if (!Array.isArray(userGuilds)) {
306
- console.error('[Dashboard] Failed to fetch guilds:', userGuilds);
307
- } else {
308
- console.log(`[Dashboard] Found ${userGuilds.length} guilds for user.`);
309
- }
310
 
311
- // Create session
312
- const sid = crypto.randomBytes(32).toString('hex');
313
- sessions.set(sid, {
314
- user: {
315
- id: user.id,
316
- username: user.username,
317
- avatar: user.avatar
318
- ? `https://cdn.discord.com/avatars/${user.id}/${user.avatar}.png`
319
- : `https://cdn.discord.com/embed/avatars/${parseInt(user.discriminator || '0') % 5}.png`
320
- },
321
- guilds: Array.isArray(userGuilds) ? userGuilds : [],
322
- createdAt: Date.now()
323
- });
324
- saveSessions();
325
-
326
- // Set cookie (7 days)
327
- res.cookie('fb_session', sid, {
328
- httpOnly: true,
329
- maxAge: 7 * 24 * 60 * 60 * 1000,
330
- sameSite: 'lax'
331
- });
332
-
333
- res.redirect('/?login=success');
334
- } catch (err) {
335
- console.error('[Dashboard] OAuth error:', err);
336
- res.redirect('/?error=server_error');
337
- }
338
- }
339
- app.get('/callback', handleOAuthCallback);
340
- app.get('/auth/callback', handleOAuthCallback);
341
-
342
- // --- Check Auth Status ---
343
- app.get('/api/me', (req, res) => {
344
- const session = getSession(req);
345
- if (session && session.user) {
346
- res.json({ loggedIn: true, user: session.user });
347
- } else {
348
- res.json({ loggedIn: false });
349
  }
350
- });
351
 
352
- // --- Logout ---
353
- app.get('/auth/logout', (req, res) => {
354
- const cookies = (req.headers.cookie || '').split(';').reduce((acc, c) => {
355
- const [k, v] = c.trim().split('=');
356
- if (k && v) acc[k] = v;
357
- return acc;
358
- }, {});
359
- const sid = cookies['fb_session'];
360
- if (sid) {
361
- sessions.delete(sid);
362
- saveSessions();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
  }
364
- res.clearCookie('fb_session');
365
- res.redirect('/');
366
- });
367
 
368
- // --- Stats ---
369
- app.get('/api/stats', requireAuth, (req, res) => {
370
- if (!discordClient || !discordClient.isReady()) {
371
- return res.json({ servers: 0, members: 0, uptime: '—', commands: 0 });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  }
373
- const up = process.uptime();
374
- const d = Math.floor(up / 86400);
375
- const h = Math.floor(up / 3600) % 24;
376
- const m = Math.floor(up / 60) % 60;
377
- const upStr = d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`;
378
-
379
- const totalMembers = discordClient.guilds.cache.reduce((acc, g) => acc + g.memberCount, 0);
380
- const botId = discordClient.user?.id;
381
- const inviteUrl = botId
382
- ? `https://discord.com/api/oauth2/authorize?client_id=${botId}&permissions=8&scope=bot%20applications.commands`
383
- : '#';
384
-
385
- res.json({
386
- servers: discordClient.guilds.cache.size,
387
- members: totalMembers,
388
- uptime: upStr,
389
- commands: 28, // Matches the full command registry count
390
- inviteUrl
391
- });
392
- });
393
 
394
- // --- Server List ---
395
- // --- Server List (shared with bot + permissions) ---
396
- let cachedOwnerId = null;
397
- app.get('/api/servers', requireAuth, async (req, res) => {
398
- try {
399
- if (!discordClient || !discordClient.isReady()) {
400
- return res.json({ pending: true, servers: [] });
401
  }
402
-
403
- const userGuilds = req.dashSession.guilds || [];
404
-
405
- // recognize owner (cached to avoid redundant API calls)
406
- if (!cachedOwnerId) {
407
- const app = await discordClient.application.fetch().catch(() => null);
408
- if (app) {
409
- cachedOwnerId = app.owner?.ownerId || app.owner?.id;
410
- // Support teams
411
- if (!cachedOwnerId && app.owner?.members) {
412
- // Just check the first member as a fallback if ownerId is missing
413
- const firstMember = Array.from(app.owner.members.values())[0];
414
- cachedOwnerId = firstMember?.user?.id || firstMember?.id;
415
- }
416
- }
417
  }
418
-
419
- const isBotOwner = req.dashSession.user.id === cachedOwnerId;
420
- console.log(`[Dashboard] Request by ${req.dashSession.user.username} (Owner: ${isBotOwner})`);
421
-
422
- // Filter guilds to only those that the user is actually in AND has permissions for.
423
- const mutualGuilds = userGuilds
424
- .filter(ug => discordClient.guilds.cache.has(ug.id))
425
- .filter(Boolean);
426
-
427
- const manageableGuilds = mutualGuilds.filter(ug => {
428
- const permBits = ug.permissions ?? ug.permissions_new;
429
- return hasDashboardPermissions(permBits);
430
- });
431
-
432
- const guildsToShow = manageableGuilds;
433
-
434
- const visibleGuilds = guildsToShow
435
- .map(ug => discordClient.guilds.cache.get(ug.id))
436
- .filter(Boolean);
437
-
438
- const list = visibleGuilds.map(g => ({
439
- name: g.name,
440
- id: g.id,
441
- members: g.memberCount || 0,
442
- icon: g.iconURL({ size: 64 }) || null
443
- }));
444
-
445
- if (isBotOwner) console.log(`[Dashboard] Owner access verified for ${req.dashSession.user.username}`);
446
- console.log(`[Dashboard] Serving ${list.length} managed servers to ${req.dashSession.user.username}`);
447
- res.json({ pending: false, servers: list });
448
- } catch (err) {
449
- console.error('[Dashboard] /api/servers failed:', err);
450
- res.status(500).json({ pending: false, servers: [], error: 'Failed to load servers' });
451
  }
452
- });
453
 
454
- // --- Guild Config (Prefix) ---
455
- app.get('/api/config/:guildId', requireAuth, (req, res) => {
456
- const { guildId } = req.params;
457
- const userGuilds = req.dashSession.guilds || [];
458
- const ug = userGuilds.find(g => g.id === guildId);
459
-
460
- if (!ug) return res.status(403).json({ error: 'Access denied' });
461
- const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
462
- if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });
463
-
464
- const storage = require('./storage');
465
- const config = storage.data.config[guildId] || {};
466
- res.json({
467
- prefix: storage.getPrefix(guildId),
468
- autoFriendlyEnabled: config.autoFriendlyEnabled || false,
469
- autoFriendlyInterval: config.autoFriendlyInterval || 40,
470
- autoFriendlyChannel: config.autoFriendlyChannel || null,
471
- postEnabled: !!config.postEnabled, // Default to false (off)
472
- postChannelId: config.postChannelId || null,
473
- friendlyText: config.friendlyText || "⭐▬▬▬▬▬ **FRIENDLY** ▬▬▬▬▬⭐\n🤝 Session\n🟩 I'm In\n🟥 Busy\n⭐▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬⭐\n🗳️ Needed: {needed}\n@everyone",
474
- cleanupHours: config.cleanupHours || 2,
475
- lineupCleanupHours: config.lineupCleanupHours || 2,
476
- remindersEnabled: !!config.remindersEnabled,
477
- remindersLead: config.remindersLead || 30
478
- });
479
- });
480
 
481
- app.get('/api/channels/:guildId', requireAuth, (req, res) => {
482
- const { guildId } = req.params;
483
- if (!discordClient) return res.json([]);
484
- const guild = discordClient.guilds.cache.get(guildId);
485
- if (!guild) return res.json([]);
 
 
 
 
 
486
 
487
- const channels = guild.channels.cache
488
- .filter(c => c.isTextBased())
489
- .map(c => ({ id: c.id, name: c.name }));
490
- res.json(channels);
491
  });
492
 
493
- app.post('/api/config/:guildId', requireAuth, (req, res) => {
494
- const { guildId } = req.params;
495
- const { prefix, autoFriendlyEnabled, autoFriendlyInterval, autoFriendlyChannel, postEnabled, postChannelId, friendlyText, cleanupHours, lineupCleanupHours, remindersEnabled, remindersLead } = req.body;
496
- const userGuilds = req.dashSession.guilds || [];
497
- const ug = userGuilds.find(g => g.id === guildId);
498
 
499
- if (!ug) return res.status(403).json({ error: 'Access denied' });
500
- const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
501
- if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });
502
 
503
- const storage = require('./storage');
504
-
505
- if (prefix) {
506
- if (prefix.length > 5) return res.status(400).json({ error: 'Invalid prefix' });
507
- storage.setPrefix(guildId, prefix);
508
- }
509
 
510
- if (storage.data.config[guildId] === undefined) storage.data.config[guildId] = {};
 
 
 
511
 
512
- if (autoFriendlyEnabled !== undefined) storage.data.config[guildId].autoFriendlyEnabled = !!autoFriendlyEnabled;
513
- if (autoFriendlyInterval !== undefined) storage.data.config[guildId].autoFriendlyInterval = parseInt(autoFriendlyInterval) || 40;
514
- if (autoFriendlyChannel !== undefined) storage.data.config[guildId].autoFriendlyChannel = autoFriendlyChannel;
515
- if (postEnabled !== undefined) storage.data.config[guildId].postEnabled = !!postEnabled;
516
- if (postChannelId !== undefined) storage.data.config[guildId].postChannelId = postChannelId;
517
- if (friendlyText !== undefined) storage.data.config[guildId].friendlyText = friendlyText;
518
- if (cleanupHours !== undefined) storage.data.config[guildId].cleanupHours = parseInt(cleanupHours) || 2;
519
- if (lineupCleanupHours !== undefined) storage.data.config[guildId].lineupCleanupHours = parseInt(lineupCleanupHours) || 2;
520
- if (remindersEnabled !== undefined) storage.data.config[guildId].remindersEnabled = !!remindersEnabled;
521
- if (remindersLead !== undefined) storage.data.config[guildId].remindersLead = parseInt(remindersLead) || 30;
522
-
523
- storage.save('config');
524
- res.json({ success: true, message: 'Settings updated successfully' });
525
- });
526
-
527
- // --- Command List ---
528
- app.get('/api/commands', requireAuth, (req, res) => {
529
- const fullCommands = [
530
- { name: 'friendly', description: 'Start a match poll for players to join', staff: true },
531
- { name: 'lineup', description: 'Generate the interactive lineup board', staff: true },
532
- { name: 'scrimlineup', description: 'Generate a scrimmage lineup board with two teams facing each other', staff: true },
533
- { name: 'lineupimage', description: 'Generate a high-quality visual lineup image', staff: true },
534
- { name: 'leaguematch', description: 'Schedule a league match with an opponent', staff: true },
535
- { name: 'win', description: 'Record a match victory', staff: true },
536
- { name: 'loss', description: 'Record a match defeat', staff: true },
537
- { name: 'draw', description: 'Record a match draw', staff: true },
538
- { name: 'managerlineup', description: 'Open the advanced GUI lineup editor', staff: true },
539
- { name: 'tactic', description: 'Show tactical analysis for a formation', staff: true },
540
- { name: 'teamrandom', description: 'Randomize players into balanced teams', staff: true },
541
- { name: 'swap', description: 'Swap two players on the lineup board', staff: true },
542
- { name: 'sendlink', description: 'Send a quick match or lobby link', staff: true },
543
-
544
- { name: 'setup', description: 'Open the bot settings configuration panel', admin: true },
545
- { name: 'clear', description: 'Bulk delete messages from the channel', admin: true },
546
- { name: 'lock', description: 'Lock the channel to prevent messaging', admin: true },
547
- { name: 'unlock', description: 'Unlock the channel for messaging', admin: true },
548
- { name: 'addrole', description: 'Add a role to the bot staff whitelist', admin: true },
549
- { name: 'removerole', description: 'Remove a role from the whitelist', admin: true },
550
- { name: 'sync', description: 'Synchronize all slash commands', admin: true },
551
-
552
- { name: 'ping', description: 'Check the bot response latency' },
553
- { name: 'help', description: 'View the full list of available commands' },
554
- { name: 'record', description: 'View the server global match record' },
555
- { name: 'profile', description: 'View your player profile stats' },
556
- { name: 'profileimage', description: 'Generate a visual player profile card' },
557
- { name: 'playerstats', description: 'View detailed stats for a player' },
558
- { name: 'top', description: 'Show the leaderboard of top players' },
559
- { name: 'matchpredict', description: 'Get an AI prediction for the current lineup' },
560
- { name: 'friendlybotsettings', description: 'View bot status and permissions' }
561
- ];
562
-
563
- res.json(fullCommands);
564
- });
565
-
566
- // --- Premium API (public) ---
567
- app.get('/api/premium/list', async (req, res) => {
568
- const allPremium = premiumStore.getAllPremiumUsers();
569
- const list = await Promise.all(Object.entries(allPremium).map(async ([userId, record]) => {
570
- let userTag = userId;
571
- let avatarUrl = '';
572
- try {
573
- if (discordClient) {
574
- const user = await discordClient.users.fetch(userId).catch(() => null);
575
- if (user) {
576
- userTag = user.tag;
577
- avatarUrl = user.displayAvatarURL({ size: 32, dynamic: true });
578
- }
579
- }
580
- } catch (e) {}
581
- return { userId, userTag, avatarUrl, grantedAt: record.grantedAt, reason: record.reason };
582
- }));
583
- res.json({ list });
584
- });
585
-
586
- // --- Premium API (auth only) ---
587
- app.get('/api/premium', requireAuth, (req, res) => {
588
- const userPremium = premiumStore.isPremium(req.user.id);
589
- res.json({ premium: userPremium });
590
- });
591
 
592
- // --- Invite URL ---
593
- app.get('/api/invite', (req, res) => {
594
- if (!discordClient || !discordClient.user) return res.redirect('/');
595
- const url = `https://discord.com/api/oauth2/authorize?client_id=${discordClient.user.id}&permissions=8&scope=bot%20applications.commands`;
596
- res.redirect(url);
597
- });
598
 
599
- // --- Logs ---
600
- app.get('/api/logs', requireAuth, (req, res) => {
601
- res.json({ logs: logBuffer.slice(-100) });
602
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603
 
604
- // --- Actions ---
605
- app.post('/api/action/:name', requireAuth, async (req, res) => {
606
- const action = req.params.name;
607
 
608
- if (action === 'sync' && discordClient && commandsDataRef) {
609
- let count = 0;
610
- for (const guild of discordClient.guilds.cache.values()) {
611
- await guild.commands.set(commandsDataRef).catch(() => {});
612
- count++;
613
- }
614
- return res.json({ message: `✅ Synced commands to ${count} servers!` });
615
  }
616
-
617
- if (action === 'backup') {
618
- return res.json({ message: '☁️ Cloud backup triggered! Check Discord for confirmation.' });
 
 
 
619
  }
620
 
621
- if (action === 'restart') {
622
- res.json({ message: '🔁 Restarting bot in 2 seconds...' });
623
- setTimeout(() => process.exit(1), 2000);
624
- return;
 
625
  }
 
 
626
 
627
- res.json({ message: 'Unknown action.' });
628
  });
629
 
630
- // --- Start ---
631
- function startServer(client, cmdsData) {
632
- console.log("[*] Dashboard: startServer() called. Initializing express...");
633
- const net = require('net');
634
- const checkServer = net.createServer();
635
-
636
- checkServer.on('listening', () => {
637
- checkServer.close(() => {
638
- console.log(`[*] Port ${port} is available, starting server...`);
639
- startServerInternal(client, cmdsData);
640
- });
641
- });
642
-
643
- checkServer.on('error', (err) => {
644
- if (err.code === 'EADDRINUSE') {
645
- console.error(`[!] ERROR: Port ${port} is already in use. Another bot instance is running.`);
646
- console.error(`[!] Please close other instances before starting this one.`);
647
- process.exit(1);
648
- } else {
649
- console.error(`[!] Server error: ${err.message}`);
650
- process.exit(1);
651
- }
652
- });
653
-
654
- checkServer.listen(port, '0.0.0.0');
655
- }
656
-
657
- function startServerInternal(client, cmdsData) {
658
- hijackConsole();
659
- discordClient = client || null;
660
- commandsDataRef = cmdsData || null;
661
-
662
- app.listen(port, '0.0.0.0', () => {
663
- const finalRedirect = getRedirectUri();
664
- console.log(`[*] --------------------------------------------------`);
665
- console.log(`[*] Web Server running on port ${port}`);
666
- console.log(`[*] --------------------------------------------------`);
667
- console.log(`[*] DASHBOARD URL: ${finalRedirect.replace('/callback', '').replace('/auth/callback', '')}`);
668
- console.log(`[*] REDIRECT URI: ${finalRedirect}`);
669
- console.log(`[*] --------------------------------------------------`);
670
- console.log(`[*] IMPORTANT: Ensure the REDIRECT URI above is added exactly to your`);
671
- console.log(`[*] Discord Developer Portal -> OAuth2 -> Redirects section.`);
672
- console.log(`[*] --------------------------------------------------`);
673
- });
674
  }
675
-
676
-
677
- module.exports = { startServer, app };
 
1
+ import 'dotenv/config';
2
+ import express from 'express';
3
+ import { Client, GatewayIntentBits, ButtonStyle, ButtonBuilder, ActionRowBuilder, TextInputBuilder, TextInputStyle, ModalBuilder, PermissionFlagsBits, EmbedBuilder } from 'discord.js';
4
+ import { Agent, setGlobalDispatcher } from 'undici';
 
5
 
6
+ setGlobalDispatcher(new Agent({ connect: { timeout: 60000 } }));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ const app = express();
9
+ const PORT = process.env.PORT || 7860;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  app.use(express.json());
12
+ app.use(express.urlencoded({ extended: true }));
13
+
14
+ app.get('/', (req, res) => res.send('Bot is Online!'));
15
+
16
+ app.get('/verify', (req, res) => {
17
+ const code = req.query.code;
18
+ if (!code) return res.send('Invalid verification link.');
19
+
20
+ res.send(`<!DOCTYPE html>
21
+ <html>
22
+ <head>
23
+ <title>Roblox Verification</title>
24
+ <style>
25
+ body { font-family: Arial; max-width:600px; margin:50px auto; text-align:center; }
26
+ .code { font-size:24px; font-weight:bold; padding:10px; background:#f0f0f0; border-radius:5px; margin:10px 0; }
27
+ button { padding:12px 24px; font-size:16px; background:#5865F2; color:white; border:none; border-radius:5px; cursor:pointer; }
28
+ </style>
29
+ </head>
30
+ <body>
31
+
32
+ <h1>🔐 Roblox Verification</h1>
33
+
34
+ <p>Add this code to your Roblox profile description:</p>
35
+ <div class="code">${code}</div>
36
+
37
+ <p><a href="https://www.roblox.com/my/account" target="_blank">Open Roblox profile</a></p>
38
+
39
+ <button onclick="verify()">Complete Verification</button>
40
+
41
+ <div id="result"></div>
42
+
43
+ <script>
44
+ function verify(){
45
+ document.getElementById("result").innerHTML="Checking...";
46
+
47
+ fetch("/api/verify",{
48
+ method:"POST",
49
+ headers:{'Content-Type':'application/json'},
50
+ body:JSON.stringify({code:"${code}"})
51
+ })
52
+ .then(r=>r.json())
53
+ .then(d=>{
54
+ if(d.success){
55
+ document.getElementById("result").innerHTML="<p style='color:green'>"+d.message+"</p>";
56
+ }else{
57
+ document.getElementById("result").innerHTML="<p style='color:red'>"+d.message+"</p>";
58
  }
59
+ })
60
  }
61
+ </script>
62
 
63
+ </body>
64
+ </html>`);
65
+ });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ // Convenience: support /verify/:code as an alternative to query parameter
68
+ app.get('/verify/:code', (req, res) => {
69
+ const code = req.params.code;
70
+ if (!code) return res.send('Invalid verification link.');
71
+ res.redirect(`/verify?code=${code}`);
72
+ });
73
 
74
+ const pendingVerifications = new Map();
 
 
 
 
 
 
 
 
 
 
75
 
76
+ app.post('/api/verify', async (req, res) => {
77
+ const { code } = req.body;
78
+ if (!code) return res.json({ success: false, message: "Invalid code." });
 
 
 
 
 
 
79
 
80
+ let userId = null;
81
+ let pending = null;
 
 
 
82
 
83
+ for (const [id, data] of pendingVerifications.entries()) {
84
+ if (data.code === code) {
85
+ userId = id;
86
+ pending = data;
87
+ break;
 
88
  }
89
+ }
90
+
91
+ if (!pending) return res.json({ success: false, message: "Verification expired." });
92
+
93
+ try {
94
+ // Current flow: we consider verification complete once the code matches.
95
+ const guild = client.guilds.cache.get(pending.guildId);
96
+ const member = await guild.members.fetch(userId);
97
+ const discordName = member.nickname ?? member.user.username;
98
+ const nickname = `${discordName} (${pending.robloxUsername})`;
99
+ await member.setNickname(nickname).catch(() => { });
100
+
101
+ pendingVerifications.delete(userId);
102
+ return res.json({ success: true, message: "Verified successfully!" });
103
+ } catch (e) {
104
+ console.error(e);
105
+ return res.json({ success: false, message: "Verification error." });
106
+ }
107
  });
108
 
109
+ app.listen(PORT, () => console.log("Web server running on " + PORT));
 
 
 
 
 
 
 
 
 
 
 
110
 
111
+ const client = new Client({
112
+ intents: [
113
+ GatewayIntentBits.Guilds,
114
+ GatewayIntentBits.GuildMessages,
115
+ GatewayIntentBits.MessageContent
116
+ ]
117
  });
118
 
119
+ const TOKEN = process.env.DISCORD_TOKEN?.trim();
120
+ const PREFIX = "!";
121
+ const VERIFICATION_ROLE_ID = "1447662023851638975";
122
+ const PUBLIC_URL = process.env.PUBLIC_URL || `http://localhost:${PORT}`;
123
 
124
+ // In-memory storage for staff vs players lineups per channel
125
+ const staffLineups = new Map();
126
+ const lineupMessages = new Map();
127
 
128
+ const POSITIONS = ["GK", "CB", "LB", "RB", "ST", "LST", "RST"];
129
+ const STAFF_POS = ["GK", "CB", "RB", "LB", "CM", "LW", "RW"];
130
+ const PLAY_POS = ["GK", "RB", "LB", "CDM", "CM", "LW", "RW"];
131
 
132
+ function renderLineupsA(data) {
133
+ const staff = STAFF_POS.map(pos => `[ ${pos} ] ${data.STAFF.A?.[pos] ?? '{user}'}`).join("\n");
134
+ const players = PLAY_POS.map(pos => `[ ${pos} ] ${data.PLAYERS.A?.[pos] ?? '{user}'}`).join("\n");
135
+ return `### STAFF FC - A\n${staff}\n\n### PLAYERS FC - A\n${players}`;
136
+ }
137
 
138
+ async function updateLineupMessage(channel, data) {
139
+ const channelId = channel.id;
140
+ const content = renderLineupsA(data);
141
+ if (lineupMessages.has(channelId)) {
142
+ try {
143
+ const msg = await channel.messages.fetch(lineupMessages.get(channelId));
144
+ await msg.edit(content);
145
+ return;
146
+ } catch { }
147
+ }
148
+ const sent = await channel.send(content);
149
+ lineupMessages.set(channelId, sent.id);
150
+ }
151
 
152
+ async function getRobloxUser(username) {
153
+ try {
154
+ const r = await fetch(`https://api.roblox.com/users/get-by-username?username=${encodeURIComponent(username)}`);
155
+ // Some Roblox responses may still return 200 with a body indicating not found
156
+ if (!r.ok) {
157
+ return null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  }
159
+
160
+ const dataRaw = await r.json().catch(() => null);
161
+ const data = Array.isArray(dataRaw)
162
+ ? (dataRaw.length > 0 ? ({
163
+ ...dataRaw[0],
164
+ Id: dataRaw[0].Id ?? dataRaw[0].id ?? null
165
+ }) : null)
166
+ : dataRaw;
167
+ if (!data) return null;
168
+
169
+ // Roblox may return the ID under different keys depending on API version
170
+ const id = data.Id ?? data.id ?? null;
171
+ if (!id) return null;
172
+
173
+ // Normalize to always expose Id for downstream logic
174
+ return { ...data, Id: id };
175
+ } catch {
176
+ return null;
177
+ }
178
  }
179
 
180
+ async function getRobloxProfile(id) {
181
+ try {
182
+ const r = await fetch(`https://users.roblox.com/v1/users/${id}`);
183
+ return r.ok ? r.json() : null;
184
+ } catch {
185
+ return null;
186
+ }
187
+ }
 
188
 
189
+ client.on("ready", () => {
190
+ console.log("Logged in as " + client.user.tag);
191
+ });
 
 
 
 
 
192
 
193
+ client.on("interactionCreate", async i => {
 
 
 
194
 
195
+ try {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
+ if (i.isButton() && i.customId === "verify_start") {
198
+ // Show Roblox username modal in Discord (username box)
199
+ const modal = new ModalBuilder()
200
+ .setCustomId("verify_username_modal")
201
+ .setTitle("Roblox Verification");
 
 
 
 
 
202
 
203
+ const input = new TextInputBuilder()
204
+ .setCustomId("roblox_username")
205
+ .setLabel("Enter your Roblox username")
206
+ .setStyle(TextInputStyle.Short)
207
+ .setRequired(true);
 
 
 
 
 
 
 
208
 
209
+ modal.addComponents(new ActionRowBuilder().addComponents(input));
210
+ await i.showModal(modal);
211
+ return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  }
 
213
 
214
+ // Slash command handler for add (staff vs players)
215
+ if (typeof i.isChatInputCommand === 'function' && i.isChatInputCommand()) {
216
+ if (i.commandName === 'add') {
217
+ const team = ((i.options.getString('team') ?? 'A').toUpperCase());
218
+ const pos = ((i.options.getString('position') ?? '').toUpperCase());
219
+ const user = i.options.getUser('user');
220
+ if (!user) {
221
+ await i.reply({ content: 'Please select a user', ephemeral: true });
222
+ return;
223
+ }
224
+ if (!['A','B'].includes(team)) {
225
+ await i.reply({ content: 'Team must be A or B', ephemeral: true });
226
+ return;
227
+ }
228
+ if (!POSITIONS.includes(pos)) {
229
+ await i.reply({ content: 'Invalid position', ephemeral: true });
230
+ return;
231
+ }
232
+ const channelId = i.channelId;
233
+ if (!staffLineups.has(channelId)) {
234
+ const empty = { GK: null, CB: null, LB: null, RB: null, ST: null, LST: null, RST: null };
235
+ staffLineups.set(channelId, { A: { ...empty }, B: { ...empty } });
236
+ }
237
+ const member = await i.guild.members.fetch(user.id);
238
+ const name = member.displayName || member.user.username;
239
+ const data = staffLineups.get(channelId);
240
+ data[team][pos] = name;
241
+ await i.reply({ content: `Set ${team} ${pos} => ${name}`, ephemeral: true });
242
+ return;
243
+ }
244
  }
 
 
 
245
 
246
+ if (i.isModalSubmit() && i.customId === "verify_username_modal") {
247
+ // Process Roblox username from modal
248
+ const inputValue = i.fields.getTextInputValue("roblox_username");
249
+ let data = null;
250
+ const urlMatch = inputValue.match(/https?:\/\/[^\s]+roblox\.com\/users\/(\d+)/i);
251
+ if (urlMatch) {
252
+ const idFromUrl = urlMatch[1];
253
+ data = { Id: idFromUrl };
254
+ } else {
255
+ data = await getRobloxUser(inputValue);
256
+ }
257
+ if (!data || !data.Id) {
258
+ await i.reply({ content: "Roblox user not found.", ephemeral: true });
259
+ return;
260
+ }
261
+
262
+ const profile = data.Id ? await getRobloxProfile(data.Id) : null;
263
+ const displayName = profile?.displayName ?? profile?.name ?? null;
264
+ const canonicalName = displayName ?? inputValue;
265
+
266
+ const code = Math.random().toString(36).substring(2, 8).toUpperCase();
267
+
268
+ pendingVerifications.set(i.user.id, {
269
+ robloxUsername: canonicalName,
270
+ robloxId: data.Id,
271
+ code: code,
272
+ timestamp: Date.now(),
273
+ guildId: i.guild.id
274
+ });
275
+
276
+ const dmContent = `🔐 Roblox Verification\n\nAdd this code to your Roblox description:\n\n${code}\n\nWhen you're ready, press Verify in this chat to complete the verification.`;
277
+ try {
278
+ const row = new ActionRowBuilder().addComponents(
279
+ new ButtonBuilder()
280
+ .setCustomId("dm_verify_confirm")
281
+ .setLabel("Verify")
282
+ .setStyle(ButtonStyle.Success)
283
+ );
284
+ await i.user.send({ content: dmContent, components: [row] });
285
+ await i.reply({ content: "Check your DM for verification steps.", ephemeral: true });
286
+ } catch {
287
+ pendingVerifications.delete(i.user.id);
288
+ await i.reply({ content: "I couldn't DM you. Enable DMs.", ephemeral: true });
289
+ }
290
+ return;
291
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
 
293
+ // DM: user clicked Verify in the account info message (perform in-Discord verification)
294
+ if (i.isButton() && i.customId === "dm_verify_confirm") {
295
+ try {
296
+ const pv = pendingVerifications.get(i.user.id);
297
+ if (!pv) {
298
+ await i.reply({ content: "No pending verification found.", ephemeral: true });
299
+ return;
300
  }
301
+ // Verify by checking Roblox profile description for the code
302
+ const profile = pv.robloxId ? await getRobloxProfile(pv.robloxId) : null;
303
+ const hasCode = !!(profile?.description?.includes?.(pv.code));
304
+ if (!hasCode) {
305
+ await i.reply({ content: "Code not found in Roblox profile. Add the code to your profile description and try again.", ephemeral: true });
306
+ return;
 
 
 
 
 
 
 
 
 
307
  }
308
+ const guild = client.guilds.cache.get(pv.guildId);
309
+ const member = await guild.members.fetch(i.user.id);
310
+ const discordName = member.nickname ?? member.user.username;
311
+ const nickname = `${discordName} (${pv.robloxUsername})`;
312
+ await member.setNickname(nickname).catch(() => { });
313
+ pendingVerifications.delete(i.user.id);
314
+ await i.reply({ content: "Verification successful!", ephemeral: true });
315
+ } catch {
316
+ pendingVerifications.delete(i.user.id);
317
+ await i.reply({ content: "Verification error.", ephemeral: true });
318
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
  }
 
320
 
321
+ // Cancel button (no-op in this flow)
322
+ if (i.isButton() && i.customId === "dm_verify_cancel") {
323
+ try {
324
+ await i.reply({ content: "Verification canceled.", ephemeral: true });
325
+ } catch {}
326
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
 
328
+ } catch (e) {
329
+ console.error("Interaction error:", e);
330
+ try {
331
+ if (i.deferred || i.replied) {
332
+ await i.editReply({ content: "❌ Something went wrong." });
333
+ } else {
334
+ await i.reply({ content: "❌ Something went wrong.", ephemeral: true });
335
+ }
336
+ } catch {}
337
+ }
338
 
 
 
 
 
339
  });
340
 
341
+ client.on("messageCreate", async m => {
 
 
 
 
342
 
343
+ if (m.author.bot) return;
344
+ if (!m.content.startsWith(PREFIX)) return;
 
345
 
346
+ const args = m.content.slice(PREFIX.length).trim().split(/ +/);
347
+ const cmd = args.shift().toLowerCase();
 
 
 
 
348
 
349
+ // staffvsplayers command to manage two lineups
350
+ if (cmd === "staffvsplayers") {
351
+ const channelId = m.channel.id;
352
+ const sub = (args[0] || 'show').toLowerCase();
353
 
354
+ if (sub === 'show' || sub === 'reset') {
355
+ // Reset both STAFF and PLAYERS for the channel to ensure "new text so no names in it"
356
+ const emptySTAFF_A = { GK: null, CB: null, RB: null, LB: null, CM: null, LW: null, RW: null };
357
+ const emptyPLAY_A = { GK: null, RB: null, LB: null, CDM: null, CM: null, LW: null, RW: null };
358
+
359
+ staffLineups.set(channelId, {
360
+ STAFF: { A: { ...emptySTAFF_A } },
361
+ PLAYERS: { A: { ...emptyPLAY_A } }
362
+ });
363
+
364
+ const data = staffLineups.get(channelId);
365
+ const content = renderLineupsA(data);
366
+ const sent = await m.channel.send(content);
367
+ lineupMessages.set(channelId, sent.id);
368
+ return;
369
+ } else {
370
+ await m.channel.send("Unknown command. Use: !staffvsplayers show|reset");
371
+ return;
372
+ }
373
+ }
374
+
375
+ // STM command: !stm @user A/B position
376
+ if (cmd === "stm") {
377
+ const channelId = m.channel.id;
378
+ const member = m.mentions?.members?.first();
379
+ const team = (args[1] || '').toUpperCase();
380
+ const pos = (args[2] || '').toUpperCase();
381
+
382
+ if (!member) {
383
+ await m.channel.send("Please mention a user. Usage: !stm @user A/B position");
384
+ return;
385
+ }
386
+ if (!['A', 'B'].includes(team)) {
387
+ await m.channel.send("Team must be A (Staff) or B (Players).");
388
+ return;
389
+ }
390
+ if (!STAFF_POS.includes(pos) && !PLAY_POS.includes(pos)) {
391
+ await m.channel.send("Invalid position.");
392
+ return;
393
+ }
394
+ if (!staffLineups.has(channelId)) {
395
+ await m.channel.send("Please run !staffvsplayers first to initialize.");
396
+ return;
397
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
 
399
+ const data = staffLineups.get(channelId);
400
+ const name = `<@${member.id}>`;
 
 
 
 
401
 
402
+ if (team === 'A') {
403
+ if (!STAFF_POS.includes(pos)) {
404
+ await m.channel.send(`Position ${pos} is not valid for STAFF (Team A).`);
405
+ return;
406
+ }
407
+ data.STAFF.A[pos] = name;
408
+ } else {
409
+ if (!PLAY_POS.includes(pos)) {
410
+ await m.channel.send(`Position ${pos} is not valid for PLAYERS (Team B).`);
411
+ return;
412
+ }
413
+ data.PLAYERS.A[pos] = name;
414
+ }
415
+
416
+ await m.channel.send(`Set Team ${team} ${pos} => ${name}`);
417
+ await updateLineupMessage(m.channel, data);
418
+ return;
419
+ }
420
+
421
+ // Remove command: !remove @user
422
+ if (cmd === "remove") {
423
+ const channelId = m.channel.id;
424
+ const member = m.mentions?.members?.first();
425
+ if (!member) {
426
+ await m.channel.send("Please mention a user to remove.");
427
+ return;
428
+ }
429
+ if (!staffLineups.has(channelId)) {
430
+ await m.channel.send("No lineup initialized for this channel yet.");
431
+ return;
432
+ }
433
 
434
+ const data = staffLineups.get(channelId);
435
+ const targetPing = `<@${member.id}>`;
436
+ let found = false;
437
 
438
+ // Search and remove from STAFF
439
+ for (const pos in data.STAFF.A) {
440
+ if (data.STAFF.A[pos] === targetPing) {
441
+ data.STAFF.A[pos] = null;
442
+ found = true;
443
+ }
 
444
  }
445
+ // Search and remove from PLAYERS
446
+ for (const pos in data.PLAYERS.A) {
447
+ if (data.PLAYERS.A[pos] === targetPing) {
448
+ data.PLAYERS.A[pos] = null;
449
+ found = true;
450
+ }
451
  }
452
 
453
+ if (found) {
454
+ await m.channel.send(`Removed ${targetPing} from all positions.`);
455
+ await updateLineupMessage(m.channel, data);
456
+ } else {
457
+ await m.channel.send(`${targetPing} was not found in the lineup.`);
458
  }
459
+ return;
460
+ }
461
 
 
462
  });
463
 
464
+ console.log("Connecting bot...");
465
+ console.log("BOT_TOKEN exists:", !!process.env.BOT_TOKEN);
466
+ console.log("DISCORD_TOKEN exists:", !!process.env.DISCORD_TOKEN);
467
+ if (TOKEN) {
468
+ console.log("Token length:", TOKEN.length);
469
+ console.log("Token preview:", TOKEN.substring(0, 4) + "..." + TOKEN.substring(TOKEN.length - 4));
470
+ } else {
471
+ console.error("❌ No token found! Set BOT_TOKEN or DISCORD_TOKEN in Railway variables.");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  }
473
+ if (TOKEN) client.login(TOKEN).catch(e => console.error("Login error:", e.message));