Spaces:
Runtime error
Runtime error
Update server.js
Browse files
server.js
CHANGED
|
@@ -1,519 +1,27 @@
|
|
| 1 |
const express = require('express');
|
| 2 |
-
const path = require('path');
|
| 3 |
-
const fs = require('fs');
|
| 4 |
-
const crypto = require('crypto');
|
| 5 |
-
|
| 6 |
-
console.log(">>> [MODULE] server.js: Initializing...");
|
| 7 |
const app = express();
|
| 8 |
const port = process.env.PORT || 7860;
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
// Discord OAuth2 Config — reads from multiple possible env var names
|
| 12 |
-
const CLIENT_SECRET = process.env.CLIENT_SECRET || process.env.DISCORD_CLIENT_SECRET || '';
|
| 13 |
-
const REDIRECT_URI = process.env.REDIRECT_URI || process.env.DISCORD_REDIRECT_URL || '';
|
| 14 |
-
|
| 15 |
-
// Store reference to the Discord client (set from index.js)
|
| 16 |
-
let discordClient = null;
|
| 17 |
-
let commandsDataRef = null;
|
| 18 |
-
|
| 19 |
-
// Session store (persisted to disk so logins survive restarts)
|
| 20 |
-
const storage = require('./storage');
|
| 21 |
-
const SESSION_FILE = path.join(storage.PERSISTENT_DIR, 'sessions.json');
|
| 22 |
-
let sessions = new Map();
|
| 23 |
-
|
| 24 |
-
// Load sessions from disk on startup
|
| 25 |
-
try {
|
| 26 |
-
if (fs.existsSync(SESSION_FILE)) {
|
| 27 |
-
const raw = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf8'));
|
| 28 |
-
sessions = new Map(Object.entries(raw));
|
| 29 |
-
console.log(`[*] Dashboard: Loaded ${sessions.size} persistent session(s).`);
|
| 30 |
-
}
|
| 31 |
-
} catch (e) {}
|
| 32 |
-
|
| 33 |
-
function saveSessions() {
|
| 34 |
-
try {
|
| 35 |
-
const dir = path.dirname(SESSION_FILE);
|
| 36 |
-
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
| 37 |
-
const obj = Object.fromEntries(sessions);
|
| 38 |
-
fs.writeFileSync(SESSION_FILE, JSON.stringify(obj), 'utf8');
|
| 39 |
-
} catch (e) {}
|
| 40 |
-
}
|
| 41 |
-
|
| 42 |
-
// In-memory log buffer
|
| 43 |
-
const logBuffer = [];
|
| 44 |
-
const MAX_LOGS = 200;
|
| 45 |
-
|
| 46 |
-
let isHijacked = false;
|
| 47 |
-
function hijackConsole() {
|
| 48 |
-
if (isHijacked) return;
|
| 49 |
-
const origLog = console.log;
|
| 50 |
-
const origErr = console.error;
|
| 51 |
-
console.log = (...args) => {
|
| 52 |
-
const line = args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
|
| 53 |
-
logBuffer.push(line);
|
| 54 |
-
if (logBuffer.length > MAX_LOGS) logBuffer.shift();
|
| 55 |
-
origLog.apply(console, args);
|
| 56 |
-
};
|
| 57 |
-
console.error = (...args) => {
|
| 58 |
-
const line = '[Error] ' + args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ');
|
| 59 |
-
logBuffer.push(line);
|
| 60 |
-
if (logBuffer.length > MAX_LOGS) logBuffer.shift();
|
| 61 |
-
origErr.apply(console, args);
|
| 62 |
-
};
|
| 63 |
-
isHijacked = true;
|
| 64 |
-
}
|
| 65 |
-
|
| 66 |
-
app.use(express.json());
|
| 67 |
-
|
| 68 |
-
function hasDashboardPermissions(permissionBits) {
|
| 69 |
-
try {
|
| 70 |
-
const perms = BigInt(permissionBits || '0');
|
| 71 |
-
return (perms & BigInt(0x20)) !== BigInt(0) || (perms & BigInt(0x8)) !== BigInt(0);
|
| 72 |
-
} catch (e) {
|
| 73 |
-
return false;
|
| 74 |
-
}
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
// --- Helper: Get redirect URI ---
|
| 78 |
-
function getRedirectUri() {
|
| 79 |
-
if (REDIRECT_URI) return REDIRECT_URI;
|
| 80 |
-
const spaceId = process.env.SPACE_ID;
|
| 81 |
-
if (spaceId) return `https://${spaceId.replace('/', '-').toLowerCase()}.hf.space/callback`;
|
| 82 |
-
return `http://localhost:${port}/callback`;
|
| 83 |
-
}
|
| 84 |
-
|
| 85 |
-
// --- Helper: Get Client ID from bot ---
|
| 86 |
-
function getClientId() {
|
| 87 |
-
return discordClient?.user?.id || process.env.CLIENT_ID || process.env.DISCORD_CLIENT_ID || '';
|
| 88 |
-
}
|
| 89 |
-
|
| 90 |
-
// --- Helper: Parse session cookie ---
|
| 91 |
-
function getSession(req) {
|
| 92 |
-
const cookies = (req.headers.cookie || '').split(';').reduce((acc, c) => {
|
| 93 |
-
const [k, v] = c.trim().split('=');
|
| 94 |
-
if (k && v) acc[k] = v;
|
| 95 |
-
return acc;
|
| 96 |
-
}, {});
|
| 97 |
-
const sid = cookies['fb_session'];
|
| 98 |
-
if (sid && sessions.has(sid)) return sessions.get(sid);
|
| 99 |
-
return null;
|
| 100 |
-
}
|
| 101 |
-
|
| 102 |
-
// --- Auth Middleware ---
|
| 103 |
-
function requireAuth(req, res, next) {
|
| 104 |
-
const session = getSession(req);
|
| 105 |
-
if (session && session.user) return next();
|
| 106 |
-
res.status(401).json({ error: 'Unauthorized' });
|
| 107 |
-
}
|
| 108 |
-
|
| 109 |
-
// --- Attach user to req ---
|
| 110 |
-
app.use((req, res, next) => {
|
| 111 |
-
req.dashSession = getSession(req);
|
| 112 |
-
next();
|
| 113 |
-
});
|
| 114 |
-
|
| 115 |
-
// --- Static Assets ---
|
| 116 |
app.get('/', (req, res) => {
|
| 117 |
-
res.
|
| 118 |
-
});
|
| 119 |
-
app.get('/logo.png', (req, res) => {
|
| 120 |
-
const logo = path.join(__dirname, 'logo.png');
|
| 121 |
-
if (fs.existsSync(logo)) res.sendFile(logo);
|
| 122 |
-
else res.status(404).send('Not found');
|
| 123 |
});
|
| 124 |
|
| 125 |
-
//
|
| 126 |
-
// This prevents Hugging Face and other platforms from restarting the space
|
| 127 |
-
// while the Discord bot is still performing its initial connection handshake.
|
| 128 |
app.get('/healthz', (req, res) => {
|
| 129 |
-
|
| 130 |
-
return res.status(200).json({
|
| 131 |
-
ok: true,
|
| 132 |
-
webReady: true,
|
| 133 |
-
discordReady: discordReady,
|
| 134 |
-
guilds: discordReady ? (discordClient.guilds?.cache?.size || 0) : 0
|
| 135 |
-
});
|
| 136 |
-
});
|
| 137 |
-
|
| 138 |
-
// --- Discord OAuth2: Step 1 — Redirect to Discord ---
|
| 139 |
-
app.get('/auth/login', (req, res) => {
|
| 140 |
-
const clientId = getClientId();
|
| 141 |
-
const redirect = encodeURIComponent(getRedirectUri());
|
| 142 |
-
const url = `https://discord.com/api/oauth2/authorize?client_id=${clientId}&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds`;
|
| 143 |
-
res.redirect(url);
|
| 144 |
-
});
|
| 145 |
-
|
| 146 |
-
async function fetchWithRetry(url, options, retries = 2) {
|
| 147 |
-
for (let i = 0; i <= retries; i++) {
|
| 148 |
-
try {
|
| 149 |
-
let targetUrl = url;
|
| 150 |
-
// Use direct connection to Discord API
|
| 151 |
-
if (url.includes('discord.com/api')) {
|
| 152 |
-
targetUrl = url; // Keep direct connection - no endpoint rotation
|
| 153 |
-
if (i > 0) console.log(`[Dashboard] Retrying Discord API call (${i + 1}/${retries})...`);
|
| 154 |
-
}
|
| 155 |
-
|
| 156 |
-
const res = await fetch(targetUrl, options);
|
| 157 |
-
if (!res.ok && i < retries) throw new Error(`HTTP ${res.status}`);
|
| 158 |
-
return res;
|
| 159 |
-
} catch (err) {
|
| 160 |
-
if (i === retries) throw err;
|
| 161 |
-
console.warn(`[Dashboard] Connection failed (${err.message}). Retrying... (${i + 1}/${retries})`);
|
| 162 |
-
// Use exponential backoff instead of endpoint rotation
|
| 163 |
-
const delayMs = Math.min(1000 * Math.pow(1.5, i), 10000);
|
| 164 |
-
await new Promise(r => setTimeout(r, delayMs));
|
| 165 |
-
}
|
| 166 |
-
}
|
| 167 |
-
}
|
| 168 |
-
|
| 169 |
-
// --- Discord OAuth2: Step 2 — Callback from Discord ---
|
| 170 |
-
// Support both /callback and /auth/callback to match any Discord redirect config
|
| 171 |
-
async function handleOAuthCallback(req, res) {
|
| 172 |
-
const { code } = req.query;
|
| 173 |
-
if (!code) return res.redirect('/?error=no_code');
|
| 174 |
-
|
| 175 |
-
if (!CLIENT_SECRET) {
|
| 176 |
-
console.error('[Dashboard] CRITICAL: CLIENT_SECRET is missing from environment variables.');
|
| 177 |
-
return res.redirect('/?error=server_error');
|
| 178 |
-
}
|
| 179 |
-
|
| 180 |
-
try {
|
| 181 |
-
// Exchange code for token
|
| 182 |
-
const tokenRes = await fetchWithRetry('https://discord.com/api/oauth2/token', {
|
| 183 |
-
method: 'POST',
|
| 184 |
-
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
| 185 |
-
body: new URLSearchParams({
|
| 186 |
-
client_id: getClientId(),
|
| 187 |
-
client_secret: CLIENT_SECRET,
|
| 188 |
-
grant_type: 'authorization_code',
|
| 189 |
-
code,
|
| 190 |
-
redirect_uri: getRedirectUri()
|
| 191 |
-
})
|
| 192 |
-
});
|
| 193 |
-
const tokenData = await tokenRes.json();
|
| 194 |
-
if (!tokenData.access_token) return res.redirect('/?error=token_failed');
|
| 195 |
-
|
| 196 |
-
// Fetch user profile
|
| 197 |
-
const userRes = await fetchWithRetry('https://discord.com/api/users/@me', {
|
| 198 |
-
headers: { Authorization: `Bearer ${tokenData.access_token}` }
|
| 199 |
-
});
|
| 200 |
-
const user = await userRes.json();
|
| 201 |
-
if (!user.id) return res.redirect('/?error=user_failed');
|
| 202 |
-
|
| 203 |
-
// Fetch user guilds
|
| 204 |
-
console.log(`[Dashboard] Fetching guilds for user ${user.username}...`);
|
| 205 |
-
const guildsRes = await fetchWithRetry('https://discord.com/api/users/@me/guilds', {
|
| 206 |
-
headers: { Authorization: `Bearer ${tokenData.access_token}` }
|
| 207 |
-
});
|
| 208 |
-
const userGuilds = await guildsRes.json();
|
| 209 |
-
|
| 210 |
-
if (!Array.isArray(userGuilds)) {
|
| 211 |
-
console.error('[Dashboard] Failed to fetch guilds:', userGuilds);
|
| 212 |
-
} else {
|
| 213 |
-
console.log(`[Dashboard] Found ${userGuilds.length} guilds for user.`);
|
| 214 |
-
}
|
| 215 |
-
|
| 216 |
-
// Create session
|
| 217 |
-
const sid = crypto.randomBytes(32).toString('hex');
|
| 218 |
-
sessions.set(sid, {
|
| 219 |
-
user: {
|
| 220 |
-
id: user.id,
|
| 221 |
-
username: user.username,
|
| 222 |
-
avatar: user.avatar
|
| 223 |
-
? `https://cdn.discord.com/avatars/${user.id}/${user.avatar}.png`
|
| 224 |
-
: `https://cdn.discord.com/embed/avatars/${parseInt(user.discriminator || '0') % 5}.png`
|
| 225 |
-
},
|
| 226 |
-
guilds: Array.isArray(userGuilds) ? userGuilds : [],
|
| 227 |
-
createdAt: Date.now()
|
| 228 |
-
});
|
| 229 |
-
|
| 230 |
-
// Set cookie (7 days)
|
| 231 |
-
res.cookie('fb_session', sid, {
|
| 232 |
-
httpOnly: true,
|
| 233 |
-
maxAge: 7 * 24 * 60 * 60 * 1000,
|
| 234 |
-
sameSite: 'lax'
|
| 235 |
-
});
|
| 236 |
-
|
| 237 |
-
res.redirect('/?login=success');
|
| 238 |
-
} catch (err) {
|
| 239 |
-
console.error('[Dashboard] OAuth error:', err);
|
| 240 |
-
res.redirect('/?error=server_error');
|
| 241 |
-
}
|
| 242 |
-
}
|
| 243 |
-
app.get('/callback', handleOAuthCallback);
|
| 244 |
-
app.get('/auth/callback', handleOAuthCallback);
|
| 245 |
-
|
| 246 |
-
// --- Check Auth Status ---
|
| 247 |
-
app.get('/api/me', (req, res) => {
|
| 248 |
-
const session = getSession(req);
|
| 249 |
-
if (session && session.user) {
|
| 250 |
-
res.json({ loggedIn: true, user: session.user });
|
| 251 |
-
} else {
|
| 252 |
-
res.json({ loggedIn: false });
|
| 253 |
-
}
|
| 254 |
-
});
|
| 255 |
-
|
| 256 |
-
// --- Logout ---
|
| 257 |
-
app.get('/auth/logout', (req, res) => {
|
| 258 |
-
const cookies = (req.headers.cookie || '').split(';').reduce((acc, c) => {
|
| 259 |
-
const [k, v] = c.trim().split('=');
|
| 260 |
-
if (k && v) acc[k] = v;
|
| 261 |
-
return acc;
|
| 262 |
-
}, {});
|
| 263 |
-
const sid = cookies['fb_session'];
|
| 264 |
-
if (sid) sessions.delete(sid);
|
| 265 |
-
res.clearCookie('fb_session');
|
| 266 |
-
res.redirect('/');
|
| 267 |
-
});
|
| 268 |
-
|
| 269 |
-
// --- Stats ---
|
| 270 |
-
app.get('/api/stats', requireAuth, (req, res) => {
|
| 271 |
-
if (!discordClient || !discordClient.isReady()) {
|
| 272 |
-
return res.json({ servers: 0, members: 0, uptime: '—', commands: 0 });
|
| 273 |
-
}
|
| 274 |
-
const up = process.uptime();
|
| 275 |
-
const d = Math.floor(up / 86400);
|
| 276 |
-
const h = Math.floor(up / 3600) % 24;
|
| 277 |
-
const m = Math.floor(up / 60) % 60;
|
| 278 |
-
const upStr = d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`;
|
| 279 |
-
|
| 280 |
-
const totalMembers = discordClient.guilds.cache.reduce((acc, g) => acc + g.memberCount, 0);
|
| 281 |
-
const botId = discordClient.user?.id;
|
| 282 |
-
const inviteUrl = botId
|
| 283 |
-
? `https://discord.com/api/oauth2/authorize?client_id=${botId}&permissions=8&scope=bot%20applications.commands`
|
| 284 |
-
: '#';
|
| 285 |
-
|
| 286 |
-
res.json({
|
| 287 |
-
servers: discordClient.guilds.cache.size,
|
| 288 |
-
members: totalMembers,
|
| 289 |
-
uptime: upStr,
|
| 290 |
-
commands: commandsDataRef ? commandsDataRef.length : 0,
|
| 291 |
-
inviteUrl
|
| 292 |
-
});
|
| 293 |
});
|
| 294 |
|
| 295 |
-
|
| 296 |
-
// --- Server List (shared with bot + permissions) ---
|
| 297 |
-
app.get('/api/servers', requireAuth, async (req, res) => {
|
| 298 |
-
try {
|
| 299 |
-
if (!discordClient || !discordClient.isReady()) {
|
| 300 |
-
return res.json({ pending: true, servers: [] });
|
| 301 |
-
}
|
| 302 |
-
|
| 303 |
-
const userGuilds = req.dashSession.guilds || [];
|
| 304 |
-
const app = await discordClient.application.fetch().catch(() => null);
|
| 305 |
-
|
| 306 |
-
// Owner recognition for both single-owner apps and team-owned apps.
|
| 307 |
-
const ownerCandidates = new Set();
|
| 308 |
-
if (app?.owner?.id) ownerCandidates.add(app.owner.id);
|
| 309 |
-
if (app?.owner?.ownerId) ownerCandidates.add(app.owner.ownerId);
|
| 310 |
-
if (app?.owner?.members) {
|
| 311 |
-
for (const member of app.owner.members.values()) {
|
| 312 |
-
if (member?.id) ownerCandidates.add(member.id);
|
| 313 |
-
if (member?.user?.id) ownerCandidates.add(member.user.id);
|
| 314 |
-
}
|
| 315 |
-
}
|
| 316 |
-
const isBotOwner = ownerCandidates.has(req.dashSession.user.id);
|
| 317 |
-
|
| 318 |
-
console.log(`[Dashboard] Request by ${req.dashSession.user.username} (Owner: ${isBotOwner})`);
|
| 319 |
-
|
| 320 |
-
let visibleGuilds = [];
|
| 321 |
-
if (isBotOwner) {
|
| 322 |
-
visibleGuilds = Array.from(discordClient.guilds.cache.values());
|
| 323 |
-
} else {
|
| 324 |
-
const mutualGuilds = userGuilds
|
| 325 |
-
.filter(ug => discordClient.guilds.cache.has(ug.id))
|
| 326 |
-
.filter(Boolean);
|
| 327 |
-
|
| 328 |
-
const manageableGuilds = mutualGuilds.filter(ug => {
|
| 329 |
-
const permBits = ug.permissions ?? ug.permissions_new;
|
| 330 |
-
return hasDashboardPermissions(permBits);
|
| 331 |
-
});
|
| 332 |
-
|
| 333 |
-
// Fallback: if Discord doesn't return permission bits reliably, still show shared guilds.
|
| 334 |
-
const guildsToShow = manageableGuilds.length > 0 ? manageableGuilds : mutualGuilds;
|
| 335 |
-
visibleGuilds = guildsToShow
|
| 336 |
-
.map(ug => discordClient.guilds.cache.get(ug.id))
|
| 337 |
-
.filter(Boolean);
|
| 338 |
-
}
|
| 339 |
-
|
| 340 |
-
const list = visibleGuilds.map(g => ({
|
| 341 |
-
name: g.name,
|
| 342 |
-
id: g.id,
|
| 343 |
-
members: g.memberCount || 0,
|
| 344 |
-
icon: g.iconURL({ size: 64 }) || null
|
| 345 |
-
}));
|
| 346 |
-
|
| 347 |
-
if (isBotOwner) console.log(`[Dashboard] Owner access enabled for ${req.dashSession.user.username}`);
|
| 348 |
-
console.log(`[Dashboard] Serving ${list.length} managed servers to ${req.dashSession.user.username}`);
|
| 349 |
-
res.json({ pending: false, servers: list });
|
| 350 |
-
} catch (err) {
|
| 351 |
-
console.error('[Dashboard] /api/servers failed:', err);
|
| 352 |
-
res.status(500).json({ pending: false, servers: [], error: 'Failed to load servers' });
|
| 353 |
-
}
|
| 354 |
-
});
|
| 355 |
-
|
| 356 |
-
// --- Guild Config (Prefix) ---
|
| 357 |
-
app.get('/api/config/:guildId', requireAuth, (req, res) => {
|
| 358 |
-
const { guildId } = req.params;
|
| 359 |
-
const userGuilds = req.dashSession.guilds || [];
|
| 360 |
-
const ug = userGuilds.find(g => g.id === guildId);
|
| 361 |
-
|
| 362 |
-
if (!ug) return res.status(403).json({ error: 'Access denied' });
|
| 363 |
-
const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
|
| 364 |
-
if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });
|
| 365 |
-
|
| 366 |
-
const storage = require('./storage');
|
| 367 |
-
const config = storage.data.config[guildId] || {};
|
| 368 |
-
res.json({
|
| 369 |
-
prefix: storage.getPrefix(guildId),
|
| 370 |
-
autoFriendlyEnabled: config.autoFriendlyEnabled || false,
|
| 371 |
-
autoFriendlyInterval: config.autoFriendlyInterval || 40,
|
| 372 |
-
autoFriendlyChannel: config.autoFriendlyChannel || null,
|
| 373 |
-
postEnabled: config.postEnabled !== false, // Default to true
|
| 374 |
-
postChannelId: config.postChannelId || null
|
| 375 |
-
});
|
| 376 |
-
});
|
| 377 |
-
|
| 378 |
-
app.get('/api/channels/:guildId', requireAuth, (req, res) => {
|
| 379 |
-
const { guildId } = req.params;
|
| 380 |
-
if (!discordClient) return res.json([]);
|
| 381 |
-
const guild = discordClient.guilds.cache.get(guildId);
|
| 382 |
-
if (!guild) return res.json([]);
|
| 383 |
-
|
| 384 |
-
const channels = guild.channels.cache
|
| 385 |
-
.filter(c => c.isTextBased())
|
| 386 |
-
.map(c => ({ id: c.id, name: c.name }));
|
| 387 |
-
res.json(channels);
|
| 388 |
-
});
|
| 389 |
-
|
| 390 |
-
app.post('/api/config/:guildId', requireAuth, (req, res) => {
|
| 391 |
-
const { guildId } = req.params;
|
| 392 |
-
const { prefix, autoFriendlyEnabled, autoFriendlyInterval, autoFriendlyChannel, postEnabled, postChannelId } = req.body;
|
| 393 |
-
const userGuilds = req.dashSession.guilds || [];
|
| 394 |
-
const ug = userGuilds.find(g => g.id === guildId);
|
| 395 |
-
|
| 396 |
-
if (!ug) return res.status(403).json({ error: 'Access denied' });
|
| 397 |
-
const hasPerms = (BigInt(ug.permissions) & BigInt(0x20)) || (BigInt(ug.permissions) & BigInt(0x8));
|
| 398 |
-
if (!hasPerms) return res.status(403).json({ error: 'Missing permissions' });
|
| 399 |
-
|
| 400 |
-
const storage = require('./storage');
|
| 401 |
-
|
| 402 |
-
if (prefix) {
|
| 403 |
-
if (prefix.length > 5) return res.status(400).json({ error: 'Invalid prefix' });
|
| 404 |
-
storage.setPrefix(guildId, prefix);
|
| 405 |
-
}
|
| 406 |
-
|
| 407 |
-
if (storage.data.config[guildId] === undefined) storage.data.config[guildId] = {};
|
| 408 |
-
|
| 409 |
-
if (autoFriendlyEnabled !== undefined) storage.data.config[guildId].autoFriendlyEnabled = !!autoFriendlyEnabled;
|
| 410 |
-
if (autoFriendlyInterval !== undefined) storage.data.config[guildId].autoFriendlyInterval = parseInt(autoFriendlyInterval) || 40;
|
| 411 |
-
if (autoFriendlyChannel !== undefined) storage.data.config[guildId].autoFriendlyChannel = autoFriendlyChannel;
|
| 412 |
-
if (postEnabled !== undefined) storage.data.config[guildId].postEnabled = !!postEnabled;
|
| 413 |
-
if (postChannelId !== undefined) storage.data.config[guildId].postChannelId = postChannelId;
|
| 414 |
-
|
| 415 |
-
storage.save('config');
|
| 416 |
-
res.json({ success: true, message: 'Settings updated successfully' });
|
| 417 |
-
});
|
| 418 |
-
|
| 419 |
-
// --- Command List ---
|
| 420 |
-
app.get('/api/commands', requireAuth, (req, res) => {
|
| 421 |
-
if (!commandsDataRef) return res.json([]);
|
| 422 |
-
|
| 423 |
-
const adminCmds = ['setup', 'post', 'clear', 'lock', 'unlock', 'giverole', 'addrole', 'removerole'];
|
| 424 |
-
const staffCmds = ['win', 'loss', 'draw', 'lineup', 'managerlineup', 'leaguematch', 'lineupimage'];
|
| 425 |
-
|
| 426 |
-
const list = commandsDataRef.map(c => ({
|
| 427 |
-
name: c.name,
|
| 428 |
-
description: c.description,
|
| 429 |
-
admin: adminCmds.includes(c.name),
|
| 430 |
-
staff: staffCmds.includes(c.name)
|
| 431 |
-
}));
|
| 432 |
-
res.json(list);
|
| 433 |
-
});
|
| 434 |
-
|
| 435 |
-
// --- Invite URL ---
|
| 436 |
-
app.get('/api/invite', (req, res) => {
|
| 437 |
-
if (!discordClient || !discordClient.user) return res.redirect('/');
|
| 438 |
-
const url = `https://discord.com/api/oauth2/authorize?client_id=${discordClient.user.id}&permissions=8&scope=bot%20applications.commands`;
|
| 439 |
-
res.redirect(url);
|
| 440 |
-
});
|
| 441 |
-
|
| 442 |
-
// --- Logs ---
|
| 443 |
-
app.get('/api/logs', requireAuth, (req, res) => {
|
| 444 |
-
res.json({ logs: logBuffer.slice(-100) });
|
| 445 |
-
});
|
| 446 |
-
|
| 447 |
-
// --- Actions ---
|
| 448 |
-
app.post('/api/action/:name', requireAuth, async (req, res) => {
|
| 449 |
-
const action = req.params.name;
|
| 450 |
-
|
| 451 |
-
if (action === 'sync' && discordClient && commandsDataRef) {
|
| 452 |
-
let count = 0;
|
| 453 |
-
for (const guild of discordClient.guilds.cache.values()) {
|
| 454 |
-
await guild.commands.set(commandsDataRef).catch(() => {});
|
| 455 |
-
count++;
|
| 456 |
-
}
|
| 457 |
-
return res.json({ message: `✅ Synced commands to ${count} servers!` });
|
| 458 |
-
}
|
| 459 |
-
|
| 460 |
-
if (action === 'backup') {
|
| 461 |
-
return res.json({ message: '☁️ Cloud backup triggered! Check Discord for confirmation.' });
|
| 462 |
-
}
|
| 463 |
-
|
| 464 |
-
if (action === 'restart') {
|
| 465 |
-
res.json({ message: '🔁 Restarting bot in 2 seconds...' });
|
| 466 |
-
setTimeout(() => process.exit(1), 2000);
|
| 467 |
-
return;
|
| 468 |
-
}
|
| 469 |
-
|
| 470 |
-
res.json({ message: 'Unknown action.' });
|
| 471 |
-
});
|
| 472 |
-
|
| 473 |
-
// --- Start ---
|
| 474 |
-
function startServer(client, cmdsData) {
|
| 475 |
-
const net = require('net');
|
| 476 |
-
const checkServer = net.createServer();
|
| 477 |
-
|
| 478 |
-
checkServer.on('listening', () => {
|
| 479 |
-
checkServer.close(() => {
|
| 480 |
-
console.log(`[*] Port ${port} is available, starting server...`);
|
| 481 |
-
startServerInternal(client, cmdsData);
|
| 482 |
-
});
|
| 483 |
-
});
|
| 484 |
-
|
| 485 |
-
checkServer.on('error', (err) => {
|
| 486 |
-
if (err.code === 'EADDRINUSE') {
|
| 487 |
-
console.error(`[!] ERROR: Port ${port} is already in use. Another bot instance is running.`);
|
| 488 |
-
console.error(`[!] Please close other instances before starting this one.`);
|
| 489 |
-
process.exit(1);
|
| 490 |
-
} else {
|
| 491 |
-
console.error(`[!] Server error: ${err.message}`);
|
| 492 |
-
process.exit(1);
|
| 493 |
-
}
|
| 494 |
-
});
|
| 495 |
-
|
| 496 |
-
checkServer.listen(port, '0.0.0.0');
|
| 497 |
-
}
|
| 498 |
-
|
| 499 |
-
function startServerInternal(client, cmdsData) {
|
| 500 |
-
hijackConsole();
|
| 501 |
-
discordClient = client || null;
|
| 502 |
-
commandsDataRef = cmdsData || null;
|
| 503 |
-
|
| 504 |
app.listen(port, '0.0.0.0', () => {
|
| 505 |
-
|
| 506 |
-
console.log(`[*]
|
| 507 |
-
console.log(`[*] Web Server running on port ${port}`);
|
| 508 |
-
console.log(`[*] --------------------------------------------------`);
|
| 509 |
-
console.log(`[*] DASHBOARD URL: ${finalRedirect.replace('/callback', '').replace('/auth/callback', '')}`);
|
| 510 |
-
console.log(`[*] REDIRECT URI: ${finalRedirect}`);
|
| 511 |
-
console.log(`[*] --------------------------------------------------`);
|
| 512 |
-
console.log(`[*] IMPORTANT: Ensure the REDIRECT URI above is added exactly to your`);
|
| 513 |
-
console.log(`[*] Discord Developer Portal -> OAuth2 -> Redirects section.`);
|
| 514 |
-
console.log(`[*] --------------------------------------------------`);
|
| 515 |
});
|
| 516 |
}
|
| 517 |
|
| 518 |
-
|
| 519 |
-
module.exports = { startServer, app };
|
|
|
|
| 1 |
const express = require('express');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
const app = express();
|
| 3 |
const port = process.env.PORT || 7860;
|
| 4 |
|
| 5 |
+
/**
|
| 6 |
+
* SIMPLIFIED HEARTBEAT SERVER
|
| 7 |
+
* This satisfies Hugging Face's requirement to have a web server on port 7860
|
| 8 |
+
* while removing all complex Redirect/OAuth logic.
|
| 9 |
+
*/
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
app.get('/', (req, res) => {
|
| 12 |
+
res.send('FriendlyBot is running (Heartbeat Active).');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
});
|
| 14 |
|
| 15 |
+
// Used by Hugging Face to check if the space is healthy
|
|
|
|
|
|
|
| 16 |
app.get('/healthz', (req, res) => {
|
| 17 |
+
res.status(200).json({ ok: true });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
});
|
| 19 |
|
| 20 |
+
function startServer(client, commandsData) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
app.listen(port, '0.0.0.0', () => {
|
| 22 |
+
console.log(`[*] Heartbeat server active on port ${port}.`);
|
| 23 |
+
console.log(`[*] All Redirect/OAuth logic has been disabled per user request.`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
});
|
| 25 |
}
|
| 26 |
|
| 27 |
+
module.exports = { startServer };
|
|
|