File size: 3,133 Bytes
66e3a81
 
 
 
44a5753
 
 
 
66e3a81
 
 
 
 
95ce595
f3b3e6f
 
 
 
 
 
 
 
 
66e3a81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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();