require('dotenv').config(); // Загружаем переменные окружения из .env файла const express = require('express'); const bodyParser = require('body-parser'); const { BotFrameworkAdapter } = require('botbuilder'); // Импортируем Bot Framework Adapter const briefingQuestions = require('./briefing'); const recommendPackage = require('./pricing'); const { translateText } = require('./translator'); const { getGptResponse } = require('./gpt'); // Создаём экземпляр Express const app = express(); const port = process.env.PORT || 3000; // Настройка middleware app.use(bodyParser.json()); // Создаём объект для хранения данных клиента let clientData = {}; let currentQuestionIndex = {}; // Создаём адаптер для Bot Framework const adapter = new BotFrameworkAdapter({ appId: process.env.MICROSOFT_APP_ID, // Используем App ID из переменной окружения appPassword: process.env.MICROSOFT_APP_PASSWORD // Используем App Password из переменной окружения }); // Роут для начала брифинга app.post('/api/start', async (req, res) => { const { sessionId, language } = req.body; clientData[sessionId] = { answers: {}, language: language || 'en' }; currentQuestionIndex[sessionId] = 0; const translatedQuestion = await translateText(briefingQuestions[0].question, clientData[sessionId].language); res.json({ question: translatedQuestion }); }); // Роут для получения ответа от клиента app.post('/api/answer', async (req, res) => { const { sessionId, answer } = req.body; if (!clientData[sessionId]) return res.status(400).json({ error: 'Session not found' }); const currentIndex = currentQuestionIndex[sessionId]; const currentKey = briefingQuestions[currentIndex].key; clientData[sessionId].answers[currentKey] = answer; currentQuestionIndex[sessionId]++; if (currentQuestionIndex[sessionId] >= briefingQuestions.length) { const result = await finishBriefing(sessionId); delete clientData[sessionId]; delete currentQuestionIndex[sessionId]; return res.json(result); } const nextQuestion = briefingQuestions[currentQuestionIndex[sessionId]].question; const translatedQuestion = await translateText(nextQuestion, clientData[sessionId].language); res.json({ question: translatedQuestion }); }); // Обработчик POST для маршрута /api/messages app.post('/api/messages', async (req, res) => { const { sessionId, message } = req.body; if (!clientData[sessionId]) { return res.status(400).json({ error: 'Session not found' }); } // Получение ответа от GPT-4 const gptResponse = await getGptResponse(message); // Отправка ответа обратно в Bot Framework res.json({ message: gptResponse }); }); // Функция для завершения брифинга и генерации плана async function finishBriefing(sessionId) { const answers = clientData[sessionId].answers; const budgetAnswer = answers['marketingBudget'] || ''; const budgetMatch = budgetAnswer.match(/\d+/g); const budget = budgetMatch ? parseInt(budgetMatch[0], 10) : 0; const packageRecommendation = recommendPackage(budget); const briefingSummary = Object.entries(answers) .map(([key, value]) => `${key}: ${value}`) .join('\n'); const gptPrompt = `Here is the client briefing:\n\n${briefingSummary}\n\nBased on this, generate a short content marketing plan and 3 main recommendations.`; const gptResponse = await getGptResponse(gptPrompt); return { message: 'Briefing complete', recommendedPackage: packageRecommendation, marketingPlan: gptResponse }; } // Стартовый маршрут app.get('/', (req, res) => { res.send('AImpress Bot is running! Use /api/start and /api/answer.'); }); // Запуск сервера app.listen(port, () => { console.log(`Server is running on port ${port}`); });