Nexchan commited on
Commit
6e0286a
·
verified ·
1 Parent(s): ce50a9e

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +84 -227
index.js CHANGED
@@ -1,250 +1,83 @@
1
  const express = require('express');
2
  const bodyParser = require('body-parser');
3
- const app = express();
4
  const axios = require('axios');
5
  const { DateTime, Duration } = require('luxon');
6
- const { format } = require("util")
7
- const port = 7860;
8
- app.use(bodyParser.json());
9
-
10
- function textToBase64(text) {
11
- return Buffer.from(text).toString('base64');
12
- }
13
-
14
- // Fungsi untuk mengembalikan teks dari Base64
15
- function base64ToText(base64) {
16
- return Buffer.from(base64, 'base64').toString('utf-8');
17
- }
18
-
19
  const { GoogleGenerativeAI } = require("@google/generative-ai");
20
- const genAI = new GoogleGenerativeAI(base64ToText("QUl6YVN5QXdTbndWaVdkUmZhS1ozQVVsaUtnQnFZczlLbUZqOWEw"));
21
-
22
- const chatHistory = {};
23
-
24
- const generateRandomString = (length) => {
25
- const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
26
- let result = '';
27
- for (let i = 0; i < length; i++) {
28
- result += characters.charAt(Math.floor(Math.random() * characters.length));
29
- }
30
- return result;
31
- };
32
-
33
- const generateRandomIP = () => {
34
- const octet = () => Math.floor(Math.random() * 256);
35
- return `${octet()}.${octet()}.${octet()}.${octet()}`;
36
- };
37
-
38
- async function createNewChat() {
39
- try {
40
- const randomUserId = generateRandomString(17);
41
- const randomIP = generateRandomIP();
42
-
43
- const response = await axios.post('https://chat.chatgptdemo.net/new_chat', {
44
- user_id: randomUserId
45
- }, {
46
- headers: {
47
- 'Content-Type': 'application/json',
48
- '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',
49
- 'X-Forwarded-For': randomIP
50
- }
51
- });
52
 
53
- return response.data.id_;
54
- } catch (error) {
55
- console.error(error);
56
- return false;
57
- }
58
- }
59
 
60
- async function updateChatName(id, chatName) {
61
- try {
62
- const response = await axios.post('https://chat.chatgptdemo.net/update_chat_name', {
63
- chat_id: id,
64
- chat_name: chatName
65
- }, {
66
- headers: {
67
- 'Content-Type': 'application/json',
68
- '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',
69
- 'X-Forwarded-For': generateRandomIP()
70
- }
71
- });
72
- } catch (error) {
73
- console.error(error);
74
- }
75
- }
76
 
77
- async function sendMessage(question, id, retry) {
78
- try {
79
- const response = await axios.post('https://chat.chatgptdemo.net/chat_api_stream', {
80
- question: question,
81
- chat_id: id,
82
- timestamp: Date.now(),
83
- retry: retry
84
- }, {
85
- headers: {
86
- 'Content-Type': 'application/json',
87
- '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',
88
- 'X-Forwarded-For': generateRandomIP()
89
- }
90
- });
91
- return response.data;
92
- } catch (error) {
93
- console.error(error);
94
- }
95
- }
96
 
97
- async function updateMessages(id, message) {
98
- const url = 'https://chat.chatgptdemo.net/update_messages';
99
- const data = {
100
- chat_id: id,
101
- bot_response: message,
102
- timestamp: Date.now(),
103
- };
104
 
105
- try {
106
- const response = await axios.post(url, data, {
107
- headers: {
108
- 'Content-Type': 'application/json',
109
- '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',
110
- 'X-Forwarded-For': generateRandomIP()
111
- }
112
- });
113
 
114
- return response.data;
115
- } catch (error) {
116
- console.error(error);
117
- }
118
  }
119
 
120
-
121
- async function cleanInactiveUsers() {
122
- const currentTime = DateTime.local();
123
-
124
- Object.keys(chatHistory).forEach((userId) => {
125
- const user = chatHistory[userId];
126
-
127
- if (user && user.lastChat && user.lastChat.plus(Duration.fromObject({ minutes: 20 })) < currentTime) {
128
- // User's last message was more than 10 minutes ago, remove the user from chatHistory
129
- delete chatHistory[userId];
130
- }
131
- });
132
-
133
- // Schedule the next execution after 1 minute
134
- setTimeout(cleanInactiveUsers, 180000);
135
  }
136
 
137
- // Start the continuous execution of cleanInactiveUsers
138
- cleanInactiveUsers();
139
-
140
-
141
-
142
-
143
- app.get('/send', async (req, res) => {
144
- try {
145
- const { id, message } = req.query;
146
- if(!id)return res.status(400).json({ success: false, response: "input param id & input id user"});
147
- if(!message)return res.status(400).json({ success: false, response: "input param message & input a message from user"});
148
- if (!chatHistory[id]) {
149
- const newid = await createNewChat();
150
- await updateChatName(newid, 'you are AI chat gpt-3.5-turbo who will help me and will always answer with cute kaomoji like this (⁠≧⁠▽⁠≦⁠), always answer me cutely like loli in anime');
151
- chatHistory[id] = {
152
- lastChat: DateTime.local(),
153
- chat_id: newid,
154
- message: [],
155
- };
156
- }
157
- const role = 'user';
158
- chatHistory[id].message.push({ role, message });
159
- chatHistory[id].lastChat = DateTime.local();
160
- id_room = chatHistory[id].chat_id
161
- const botResponse = await sendMessage(message, id_room, false);
162
- const regex = /"content":"(.*?)"/g;
163
- let matches;
164
- let contents = '';
165
- while ((matches = regex.exec(botResponse)) !== null) {
166
- if (typeof matches[1] !== 'undefined') {
167
- contents += matches[1];
168
- }
169
- }
170
- chatHistory[id].message.push({ role: 'Assistant', message: contents });
171
- chatHistory[id].lastChat = DateTime.local();
172
- await updateMessages(id_room, contents);
173
- res.status(200).json({ success: true, response: contents });
174
- } catch (e) {
175
- res.status(400).json({ success: false, response: format(e) });
176
- }
177
- });
178
-
179
- app.get('/listuser', (req, res) => {
180
- const userList = Object.keys(chatHistory);
181
- res.status(200).json({ userList });
182
- });
183
-
184
- app.get('/get/message', (req, res) => {
185
- const id = req.query.id;
186
- if(!id)return res.status(400).json({ success: false, response: "input id"});
187
- if (!chatHistory[id]) {
188
- return res.status(404).json({ error: 'User not found' });
189
- }
190
- const userMessages = chatHistory[id].message;
191
- const userRoom = chatHistory[id].chat_id;
192
- res.status(200).json({ id, messages: userMessages });
193
- });
194
-
195
-
196
 
 
 
197
 
198
-
199
-
200
-
201
-
202
- const db_chatHistory = {};
203
-
204
  function generateUID(length) {
205
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
206
- const charactersLength = characters.length;
207
  let uid = '';
208
  for (let i = 0; i < length; i++) {
209
- uid += characters.charAt(Math.floor(Math.random() * charactersLength));
210
  }
211
  return uid;
212
  }
213
 
214
- async function sendMessageV2(data_chat, msg) {
 
215
  try {
216
- const model = genAI.getGenerativeModel({ model: "gemini-pro"});
217
-
218
- const chat = model.startChat(data_chat)
219
  const result = await chat.sendMessage(msg);
220
  const response = await result.response;
221
- const text = response.text();
222
-
223
  return text;
224
  } catch (error) {
225
  console.error(error);
226
  }
227
  }
228
 
229
- async function cleanInactiveUsersV2() {
 
230
  const currentTime = DateTime.local();
231
 
232
- Object.keys(db_chatHistory).forEach((userId) => {
233
- const user = db_chatHistory[userId];
234
 
235
  if (user && user.lastChat && user.lastChat.plus(Duration.fromObject({ minutes: 20 })) < currentTime) {
236
- // User's last message was more than 10 minutes ago, remove the user from db_chatHistory
237
- delete db_chatHistory[userId];
238
  }
239
  });
240
 
241
- // Schedule the next execution after 1 minute
242
- setTimeout(cleanInactiveUsersV2, 180000);
243
  }
244
 
245
- // Start the continuous execution of cleanInactiveUsers
246
- cleanInactiveUsersV2();
247
 
 
248
  app.get('/v2/send', async (req, res) => {
249
  try {
250
  const { id, message } = req.query;
@@ -255,31 +88,31 @@ app.get('/v2/send', async (req, res) => {
255
  });
256
  }
257
 
258
- let chatData = db_chatHistory[id];
259
 
260
  if (!chatData) {
261
  // Jika data riwayat obrolan tidak ada, buat data baru
262
  chatData = {
263
  lastChat: DateTime.local(),
264
  data: {
265
- history: [
266
- {
267
- role: "user",
268
- parts: "hello, can you answer my question with a cute kaomoji like this 。⁠◕⁠‿⁠◕⁠。"
269
- },
270
- {
271
- role: "model",
272
- parts: "sure (⁠◠⁠‿⁠◕⁠) , so.... (⁠ ⁠/⁠^⁠ω⁠^⁠)⁠/⁠♪⁠♪ how can I help dear user (⁠ ⁠╹⁠▽⁠╹⁠ ⁠)?",
273
- },
274
- ],
275
- generationConfig: {
276
  maxOutputTokens: 500,
277
  },
278
  }
279
- }
280
  }
281
-
282
- const botResponse = await sendMessageV2(chatData.data, message);
283
 
284
  // Simpan pesan user ke riwayat obrolan
285
  chatData.data.history.push({
@@ -288,12 +121,12 @@ app.get('/v2/send', async (req, res) => {
288
  });
289
  // Simpan bot response ke riwayat obrolan
290
  chatData.data.history.push({
291
- role: 'model',
292
- parts: botResponse
293
  });
294
  // Update waktu terakhir obrolan
295
  chatData.lastChat = DateTime.local();
296
- db_chatHistory[id] = chatData;
297
  res.status(200).json({
298
  success: true,
299
  response: botResponse
@@ -306,23 +139,47 @@ app.get('/v2/send', async (req, res) => {
306
  }
307
  });
308
 
309
-
310
  app.get('/v2/listuser', (req, res) => {
311
- const userList = Object.keys(db_chatHistory);
312
  res.status(200).json({ userList });
313
  });
314
 
 
315
  app.get('/v2/get/message', (req, res) => {
316
  const id = req.query.id;
317
  if (!id) return res.status(400).json({ success: false, response: "input id" });
318
- if (!db_chatHistory[id]) {
319
  return res.status(404).json({ error: 'User not found' });
320
  }
321
- const userMessages = db_chatHistory[id].data.history;
322
  res.status(200).json({ messages: userMessages });
323
  });
324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325
 
326
  app.listen(port, () => {
327
- console.log(`Server is running on port ${port}`);
328
- });
 
1
  const express = require('express');
2
  const bodyParser = require('body-parser');
 
3
  const axios = require('axios');
4
  const { DateTime, Duration } = require('luxon');
5
+ const { format } = require("util");
6
+ const puppeteer = require("puppeteer");
 
 
 
 
 
 
 
 
 
 
 
7
  const { GoogleGenerativeAI } = require("@google/generative-ai");
8
+ const GPT4js = require('gpt4js');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ const app = express();
11
+ const port = 7860;
 
 
 
 
12
 
13
+ app.use(bodyParser.json());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
 
 
 
 
 
 
 
16
 
 
 
 
 
 
 
 
 
17
 
18
+ // Fungsi untuk mengonversi teks menjadi Base64
19
+ function convertTextToBase64(text) {
20
+ return Buffer.from(text).toString('base64');
 
21
  }
22
 
23
+ // Fungsi untuk mengembalikan teks dari Base64
24
+ function convertBase64ToText(base64) {
25
+ return Buffer.from(base64, 'base64').toString('utf-8');
 
 
 
 
 
 
 
 
 
 
 
 
26
  }
27
 
28
+ // Inisialisasi GoogleGenerativeAI
29
+ const genAI = new GoogleGenerativeAI(convertBase64ToText("QUl6YVN5RGFVX1dTWlduWXF4ZG9fclJhbktCM0Z0elMtQTg2dzUw"));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ // Data sesi chat untuk versi 2
32
+ const db_chatSessions = {};
33
 
34
+ // Fungsi untuk menghasilkan UID
 
 
 
 
 
35
  function generateUID(length) {
36
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
 
37
  let uid = '';
38
  for (let i = 0; i < length; i++) {
39
+ uid += characters.charAt(Math.floor(Math.random() * characters.length));
40
  }
41
  return uid;
42
  }
43
 
44
+ // Fungsi untuk mengirim pesan versi 2
45
+ async function sendChatMessageV2(data_chat, msg) {
46
  try {
47
+ const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
48
+
49
+ const chat = model.startChat(data_chat);
50
  const result = await chat.sendMessage(msg);
51
  const response = await result.response;
52
+ const text = response.text();
53
+
54
  return text;
55
  } catch (error) {
56
  console.error(error);
57
  }
58
  }
59
 
60
+ // Fungsi untuk membersihkan pengguna tidak aktif versi 2
61
+ async function clearInactiveUsersV2() {
62
  const currentTime = DateTime.local();
63
 
64
+ Object.keys(db_chatSessions).forEach((userId) => {
65
+ const user = db_chatSessions[userId];
66
 
67
  if (user && user.lastChat && user.lastChat.plus(Duration.fromObject({ minutes: 20 })) < currentTime) {
68
+ // Hapus pengguna yang tidak aktif lebih dari 20 menit dari db_chatSessions
69
+ delete db_chatSessions[userId];
70
  }
71
  });
72
 
73
+ // Jadwalkan eksekusi berikutnya setelah 3 menit
74
+ setTimeout(clearInactiveUsersV2, 180000);
75
  }
76
 
77
+ // Mulai eksekusi terus-menerus untuk membersihkan pengguna tidak aktif
78
+ clearInactiveUsersV2();
79
 
80
+ // Endpoint untuk mengirim pesan versi 2
81
  app.get('/v2/send', async (req, res) => {
82
  try {
83
  const { id, message } = req.query;
 
88
  });
89
  }
90
 
91
+ let chatData = db_chatSessions[id];
92
 
93
  if (!chatData) {
94
  // Jika data riwayat obrolan tidak ada, buat data baru
95
  chatData = {
96
  lastChat: DateTime.local(),
97
  data: {
98
+ history: [
99
+ {
100
+ role: "user",
101
+ parts: "hello, can you answer my question with a cute kaomoji like this 。⁠◕⁠‿⁠◕⁠。"
102
+ },
103
+ {
104
+ role: "model",
105
+ parts: "sure (⁠◠⁠‿⁠◕⁠) , so.... (⁠ ⁠/⁠^⁠ω⁠^⁠)⁠/⁠♪⁠♪ how can I help dear user (⁠ ⁠╹⁠▽⁠╹⁠ ⁠)?",
106
+ },
107
+ ],
108
+ generationConfig: {
109
  maxOutputTokens: 500,
110
  },
111
  }
112
+ };
113
  }
114
+
115
+ const botResponse = await sendChatMessageV2(chatData.data, message);
116
 
117
  // Simpan pesan user ke riwayat obrolan
118
  chatData.data.history.push({
 
121
  });
122
  // Simpan bot response ke riwayat obrolan
123
  chatData.data.history.push({
124
+ role: 'model',
125
+ parts: botResponse
126
  });
127
  // Update waktu terakhir obrolan
128
  chatData.lastChat = DateTime.local();
129
+ db_chatSessions[id] = chatData;
130
  res.status(200).json({
131
  success: true,
132
  response: botResponse
 
139
  }
140
  });
141
 
142
+ // Endpoint untuk daftar pengguna versi 2
143
  app.get('/v2/listuser', (req, res) => {
144
+ const userList = Object.keys(db_chatSessions);
145
  res.status(200).json({ userList });
146
  });
147
 
148
+ // Endpoint untuk mendapatkan pesan versi 2
149
  app.get('/v2/get/message', (req, res) => {
150
  const id = req.query.id;
151
  if (!id) return res.status(400).json({ success: false, response: "input id" });
152
+ if (!db_chatSessions[id]) {
153
  return res.status(404).json({ error: 'User not found' });
154
  }
155
+ const userMessages = db_chatSessions[id].data.history;
156
  res.status(200).json({ messages: userMessages });
157
  });
158
 
159
+ // Fungsi untuk ping website
160
+ async function pingWebsite() {
161
+ const browser = await puppeteer.launch({
162
+ headless: true,
163
+ args: ['--no-sandbox', '--disable-setuid-sandbox']
164
+ });
165
+ const page = await browser.newPage();
166
+ 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;]");
167
+ await page.goto('https://huggingface.co/spaces/Nexchan/gptdemo');
168
+ console.log("Ping");
169
+ await browser.close();
170
+ }
171
+
172
+ // Ping website setiap 5 jam
173
+ async function pingEvery5Hours() {
174
+ await pingWebsite();
175
+ setInterval(async () => {
176
+ await pingWebsite();
177
+ }, 5 * 60 * 60 * 1000); // 5 jam dalam milidetik
178
+ }
179
+
180
+ // Mulai ping
181
+ pingEvery5Hours();
182
 
183
  app.listen(port, () => {
184
+ console.log(`Server is running on port ${port}`);
185
+ });