require('dotenv').config(); const express = require('express'); const cors = require('cors'); const path = require('path'); const dns = require('node:dns'); // Force IPv4 for DNS resolution to avoid ENOTFOUND issues in some environments dns.setDefaultResultOrder('ipv4first'); // Modular imports const { setupBot } = require('./app/bot/bot'); const app = express(); const PORT = process.env.PORT || 7860; // Normalize WEBAPP_URL: remove trailing slash and common suffixes to avoid double-pathing in bot.js let WEBAPP_URL = (process.env.WEBAPP_URL || '').replace(/\/$/, ''); if (WEBAPP_URL.endsWith('/app/index.html')) { WEBAPP_URL = WEBAPP_URL.replace('/app/index.html', ''); } else if (WEBAPP_URL.endsWith('/app')) { WEBAPP_URL = WEBAPP_URL.replace('/app', ''); } if (!WEBAPP_URL) WEBAPP_URL = `http://localhost:${PORT}`; // --- Express Server Setup --- app.use(cors()); app.use(express.json()); // Request logging middleware app.use((req, res, next) => { console.log(`[Server] ${req.method} ${req.url}`); next(); }); // Serve static files for Mini App // We map '/app' URL path to the local 'app/miniApp' directory app.use('/app', express.static(path.join(__dirname, 'app/miniApp'))); // Serve prompts so the Mini App can load stylePresets.js // We map '/prompts' URL path to the local 'prompts' directory app.use('/prompts', express.static(path.join(__dirname, 'prompts'))); // Basic health check app.get('/', (req, res) => { res.send('Bot and Mini App Server are running.'); }); // --- API Endpoints --- const { updateUserSession } = require('./app/bot/userSession'); app.post('/api/settings', (req, res) => { console.log('[API] Received /api/settings request:', req.body); const { userId, presetName, creativity, tags } = req.body; if (!userId) { return res.status(400).json({ error: 'Missing userId' }); } // We pass all fields to the update function const success = updateUserSession(userId, { presetName, creativity, tags }); if (success) { console.log(`[API] Settings updated for user ${userId}`); res.json({ success: true }); } else { res.status(500).json({ error: 'Failed to update settings' }); } }); // --- Bot Setup --- let bot; try { bot = setupBot(process.env.BOT_TOKEN, WEBAPP_URL); } catch (error) { console.error("Failed to initialize bot:", error.message); process.exit(1); } // --- Start Server & Bot --- async function start() { try { // Start Express Server app.listen(PORT, () => { console.log(`🚀 Server running on port ${PORT}`); console.log(`🌍 Web App URL: ${WEBAPP_URL}/app/index.html`); }); // Start Telegram Bot console.log('🤖 Bot is launching...'); await bot.launch(); console.log('✅ Bot is running.'); } catch (e) { console.error('❌ Error starting app:', e); } } // Graceful stop process.once('SIGINT', () => { if (bot) bot.stop('SIGINT'); process.exit(0); }); process.once('SIGTERM', () => { if (bot) bot.stop('SIGTERM'); process.exit(0); }); start();