gptdemo / index.js
Nexchan's picture
Update index.js
43791af verified
raw
history blame
8.37 kB
import express from 'express';
import { DateTime, Duration } from 'luxon';
import puppeteer from 'puppeteer';
import { format } from 'util';
import { GoogleGenerativeAI } from '@google/generative-ai';
import GPT4js from 'gpt4js';
const app = express();
const port = 7860;
app.use(express.json());
const db_chatHitamAi = {};
const db_chatGPTAi = {};
const G4 = {};
G4.sendMessage = async function(msg, providerName) {
try {
const options = {
provider: providerName || "BlackBox",
model: "gpt-4o-free",
};
const provider = GPT4js.createProvider(options.provider);
const text = await provider.chatCompletion(msg, options);
return text;
} catch (error) {
console.error("Error in G4.sendMessage: ", error);
throw error;
}
};
app.get('/blackbox/send', async (req, res) => {
try {
const { id, message } = req.query;
if (!id || !message) {
return res.status(400).json({
success: false,
response: "Input parameter id and message are required."
});
}
let chatData = db_chatHitamAi[id] || {
lastChat: DateTime.local(),
data: {
message: [
{ role: "system", content: "You're an expert bot in programming." }
]
}
};
chatData.data.message.push({ role: 'user', content: message });
const botResponse = await G4.sendMessage(chatData.data.message, "BlackBox");
chatData.data.message.push({ role: 'assistant', content: botResponse });
chatData.lastChat = DateTime.local();
db_chatHitamAi[id] = chatData;
res.status(200).json({ success: true, response: botResponse });
} catch (e) {
res.status(400).json({ success: false, response: format(e) });
}
});
app.get('/blackbox/listuser', (req, res) => {
const userList = Object.keys(db_chatHitamAi);
res.status(200).json({ userList });
});
app.get('/blackbox/get/message', (req, res) => {
const id = req.query.id;
if (!id || !db_chatHitamAi[id]) {
return res.status(404).json({ success: false, response: "User not found" });
}
const userMessages = db_chatHitamAi[id].data.history;
res.status(200).json({ messages: userMessages });
});
async function cleanInactiveUsersV4B() {
const currentTime = DateTime.local();
Object.keys(db_chatHitamAi).forEach((userId) => {
const user = db_chatHitamAi[userId];
if (user && user.lastChat && user.lastChat.plus(Duration.fromObject({ minutes: 20 })) < currentTime) {
delete db_chatHitamAi[userId];
}
});
setTimeout(cleanInactiveUsersV4B, 180000);
}
cleanInactiveUsersV4B();
app.get('/gpt4/send', async (req, res) => {
try {
const { id, message } = req.query;
if (!id || !message) {
return res.status(400).json({
success: false,
response: "Input parameter id and message are required."
});
}
let chatData = db_chatGPTAi[id] || {
lastChat: DateTime.local(),
data: {
message: [
{ role: "system", content: "You're an expert bot in programming." }
]
}
};
chatData.data.message.push({ role: 'user', content: message });
const botResponse = await G4.sendMessage(chatData.data.message, "Nextway");
chatData.data.message.push({ role: 'assistant', content: botResponse });
chatData.lastChat = DateTime.local();
db_chatGPTAi[id] = chatData;
res.status(200).json({ success: true, response: botResponse });
} catch (e) {
res.status(400).json({ success: false, response: format(e) });
}
});
app.get('/gpt4/listuser', (req, res) => {
const userList = Object.keys(db_chatGPTAi);
res.status(200).json({ userList });
});
app.get('/gpt4/get/message', (req, res) => {
const id = req.query.id;
if (!id || !db_chatGPTAi[id]) {
return res.status(404).json({ success: false, response: "User not found" });
}
const userMessages = db_chatGPTAi[id].data.history;
res.status(200).json({ messages: userMessages });
});
async function cleanInactiveUsersV5G() {
const currentTime = DateTime.local();
Object.keys(db_chatGPTAi).forEach((userId) => {
const user = db_chatGPTAi[userId];
if (user && user.lastChat && user.lastChat.plus(Duration.fromObject({ minutes: 20 })) < currentTime) {
delete db_chatGPTAi[userId];
}
});
setTimeout(cleanInactiveUsersV5G, 180000);
}
cleanInactiveUsersV5G();
const db_chatHistory = {};
const genAI = new GoogleGenerativeAI(base64ToText("QUl6YVN5QXYyeHlBblQ5dXZqVTcwdlN1YVBXNGRFa25vWHpnMDVN"));
function textToBase64(text) {
return Buffer.from(text).toString('base64');
}
function base64ToText(base64) {
return Buffer.from(base64, 'base64').toString();
}
function generateUID(length) {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let uid = '';
for (let i = 0; i < length; i++) {
uid += characters.charAt(Math.floor(Math.random() * characters.length));
}
return uid;
}
async function sendMessageV2(data_chat, msg) {
try {
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const chat = model.startChat(data_chat);
const result = await chat.sendMessage(msg);
const response = await result.response;
const text = response.text();
return text;
} catch (error) {
console.error("Error in sendMessageV2: ", error);
throw error;
}
}
async function cleanInactiveUsersV2() {
const currentTime = DateTime.local();
Object.keys(db_chatHistory).forEach((userId) => {
const user = db_chatHistory[userId];
if (user && user.lastChat && user.lastChat.plus(Duration.fromObject({ minutes: 20 })) < currentTime) {
delete db_chatHistory[userId];
}
});
setTimeout(cleanInactiveUsersV2, 180000);
}
cleanInactiveUsersV2();
app.get('/v2/send', async (req, res) => {
try {
const { id, message } = req.query;
if (!id || !message) {
return res.status(400).json({
success: false,
response: "Input parameter id and message are required."
});
}
let chatData = db_chatHistory[id] || {
lastChat: DateTime.local(),
data: {
history: [
{ role: "user", parts: [{ text: "hello, can you answer my question with a cute kaomoji like this 。⁠◕⁠‿⁠◕⁠。" }] },
{ role: "model", parts: [{ text: "sure (⁠◠⁠‿⁠◕⁠) , so.... (⁠ ⁠/⁠^⁠ω⁠^⁠)⁠/⁠♪⁠♪ how can I help dear user (⁠ ⁠╹⁠▽⁠╹⁠ ⁠)?" }] }
],
generationConfig: { maxOutputTokens: 500 }
}
};
const botResponse = await sendMessageV2(chatData.data, message);
if (!chatData.data.history.some(item => item.role === 'user' && item.parts[0].text === message)) {
chatData.data.history.push({ role: 'user', parts: [{ text: message }] });
}
if (!chatData.data.history.some(item => item.role === 'model' && item.parts[0].text === botResponse)) {
chatData.data.history.push({ role: 'model', parts: [{ text: botResponse }] });
}
chatData.lastChat = DateTime.local();
db_chatHistory[id] = chatData;
res.status(200).json({ success: true, response: botResponse });
} catch (e) {
res.status(400).json({ success: false, response: format(e) });
}
});
app.get('/v2/listuser', (req, res) => {
const userList = Object.keys(db_chatHistory);
res.status(200).json({ userList });
});
app.get('/v2/get/message', (req, res) => {
const id = req.query.id;
if (!id || !db_chatHistory[id]) {
return res.status(404).json({ success: false, response: "User not found" });
}
const userMessages = db_chatHistory[id].data.history;
res.status(200).json({ messages: userMessages });
});
async function pingWebsite() {
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] });
const page = await browser.newPage();
await page.setUserAgent("Mozilla/5.0 (Linux; Android 10; SM-G965U Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/114.0.5735.141 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/420.0.0.32.61;]");
await page.goto('https://huggingface.co/spaces/Nexchan/gptdemo');
console.log("Ping");
await browser.close();
}
async function pingEvery5Hours() {
await pingWebsite();
setInterval(pingWebsite, 5 * 60 * 60 * 1000);
}
pingEvery5Hours();
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});