-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
53 lines (46 loc) · 1.71 KB
/
index.js
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
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
puppeteer.use(StealthPlugin());
/**
* Sends a query to the YouChat API and returns the response.
* @param {string} query - The query to send to the API.
* @returns {string} - The response from the API.
*/
async function youChat(query) {
// Launch a new browser instance and create a new page.
const browser = await puppeteer.launch({
executablePath: require('puppeteer').executablePath(),
});
const page = await browser.newPage();
// Encode the query for use in the API URL.
let input = encodeURI(query.toLowerCase());
// Create a new Promise that will resolve with the API response.
const output = new Promise((resolve, reject) => {
// Listen for responses from the API.
page.on('response', async response => {
// If the response is from the correct API endpoint, process the response.
if (
response.url() ==
`https://you.com/api/youchatStreaming?question=${input}&chat=%5B%5D`
) {
var text = await response.text();
var array = text.split('event: token').slice(1).slice(0, -2);
var jsonArray = array.map(
a => JSON.parse(a.replace(`\ndata: `, '').replace(`\n\n`, '')).token
);
// Resolve the Promise with the processed response.
resolve(jsonArray.join('').trim());
}
});
});
// Send the query to the API.
await page.goto(
`https://you.com/api/youchatStreaming?question=${input}&chat=%5B%5D`,
{ waitUntil: 'networkidle0' }
);
// Close the browser instance.
await browser.close();
// Return the Promise with the API response.
return await output;
}
module.exports = { youChat };