const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const axios = require('axios'); const { DateTime } = require('luxon'); const { format } = require("util") const port = 7860; app.use(bodyParser.json()); const chatHistory = {}; const generateRandomString = (length) => { const characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; let result = ''; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * characters.length)); } return result; }; const generateRandomIP = () => { const octet = () => Math.floor(Math.random() * 256); return `${octet()}.${octet()}.${octet()}.${octet()}`; }; async function createNewChat() { try { const randomUserId = generateRandomString(17); const randomIP = generateRandomIP(); const response = await axios.post('https://chat.chatgptdemo.net/new_chat', { user_id: randomUserId }, { headers: { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 (iPhone14,3; U; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/19A346 Safari/602.1', 'X-Forwarded-For': randomIP } }); return response.data.id_; } catch (error) { console.error(error); return false; } } async function updateChatName(id, chatName) { try { const response = await axios.post('https://chat.chatgptdemo.net/update_chat_name', { chat_id: id, chat_name: chatName }, { headers: { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 (iPhone14,3; U; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/19A346 Safari/602.1', 'X-Forwarded-For': generateRandomIP() } }); } catch (error) { console.error(error); } } async function sendMessage(question, id, retry) { try { const response = await axios.post('https://chat.chatgptdemo.net/chat_api_stream', { question: question, chat_id: id, timestamp: Date.now(), retry: retry }, { headers: { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 (iPhone14,3; U; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/19A346 Safari/602.1', 'X-Forwarded-For': generateRandomIP() } }); return response.data; } catch (error) { console.error(error); } } async function updateMessages(id, message) { const url = 'https://chat.chatgptdemo.net/update_messages'; const data = { chat_id: id, bot_response: message, timestamp: Date.now(), }; try { const response = await axios.post(url, data, { headers: { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 (iPhone14,3; U; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/19A346 Safari/602.1', 'X-Forwarded-For': generateRandomIP() } }); return response.data; } catch (error) { console.error(error); } } async function cleanInactiveUsers() { const currentTime = DateTime.local(); Object.keys(chatHistory).forEach((userId) => { const user = chatHistory[userId]; if (user && user.lastChat && user.lastChat.plus(Duration.fromObject({ minutes: 10 })) < currentTime) { // User's last message was more than 10 minutes ago, remove the user from chatHistory delete chatHistory[userId]; } }); // Schedule the next execution after 1 minute setTimeout(cleanInactiveUsers, 30000); } // Start the continuous execution of cleanInactiveUsers cleanInactiveUsers(); app.get('/send', async (req, res) => { try { const { id, message } = req.query; if(!id)return res.status(400).json({ success: false, response: "input param id & input id user"}); if(!message)return res.status(400).json({ success: false, response: "input param message & input a message from user"}); if (!chatHistory[id]) { const newid = await createNewChat(); chatHistory[id] = { lastChat: DateTime.local(), chat_id: newid, message: [], }; } const role = 'user'; chatHistory[id].message.push({ role, message }); chatHistory[id].lastChat = DateTime.local(); id_room = chatHistory[id].chat_id const botResponse = await sendMessage(message, id_room, false); const regex = /"content":"(.*?)"/g; let matches; let contents = ''; while ((matches = regex.exec(botResponse)) !== null) { if (typeof matches[1] !== 'undefined') { contents += matches[1]; } } chatHistory[id].message.push({ role: 'Assistant', message: contents }); chatHistory[id].lastChat = DateTime.local(); await updateMessages(id_room, contents); res.status(200).json({ success: true, response: contents }); } catch (e) { res.status(400).json({ success: false, response: format(e) }); } }); app.get('/listuser', (req, res) => { const userList = Object.keys(chatHistory); res.status(200).json({ userList }); }); app.get('/get/message/:id', (req, res) => { const id = req.params.id; if(!id)return res.status(400).json({ success: false, response: "input id"}); if (!chatHistory[id]) { return res.status(404).json({ error: 'User not found' }); } const userMessages = chatHistory[id].message; const userRoom = chatHistory[id].chat_id; res.status(200).json({ id, messages: userMessages }); }); app.listen(port, () => { console.log(`Server is running on port ${port}`); });