-
Notifications
You must be signed in to change notification settings - Fork 72
/
index.js
406 lines (333 loc) · 11 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
const https = require('https');
const express = require('express');
const path = require('path');
const fs = require('fs');
const querystring = require('querystring');
const { Configuration, OpenAIApi } = require('openai');
const OPENAI_KEY = process.env.OPENAI_KEY;
const SECRET_KEY = process.env.SECRET_KEY;
const WHATSAPP_ACCESS_TOKEN = process.env.WHATSAPP_ACCESS_TOKEN
const PHONE_NUMBER = process.env.PHONE_NUMBER;
const PHONE_NUMBER_ID = process.env.PHONE_NUMBER_ID;
const systemPrompt = "You are InstaIntern and your job is to help the user craft engaging, creative Instagram posts. You will output at least 3 options and they should be in this format - Content: The content of the post, Image: suggested image for the post, Hashtags: suggested hashtags for the post."
const configuration = new Configuration({
apiKey: OPENAI_KEY,
});
const openai = new OpenAIApi(configuration);
const app = express();
app.use(express.json());
function getMsg(body) {
try {
let phone_number_id =
body.entry[0].changes[0].value.metadata.phone_number_id || "";
let from = ""
let msg_body = "";
if (body.entry[0].changes[0].value && body.entry[0].changes[0].value.messages[0]) {
from = body.entry[0].changes[0].value.messages[0].from || ""; // extract the phone number from the webhook payload
msg_body = body.entry[0].changes[0].value?.messages[0]?.text?.body || "";
}
return { phone_number_id, from, msg_body }
} catch (error) {
return error
}
}
async function getCompletion(prompt) {
let model = "text-davinci-003"
try {
const prediction = await openai.createCompletion({
model: model,
prompt: prompt,
max_tokens: 512,
temperature: 0.5,
});
return prediction.data.choices[0].text
} catch (error) {
console.log("Failed to get completion - ", error.message)
return error
}
}
async function getChatCompletion(prompt) {
// let model = "text-davinci-003"
try {
const prediction = await openai.createChatCompletion({
// model: "gpt-3.5-turbo",
model: "gpt-4",
messages: [{
role: "user",
content: prompt
}],
max_tokens: 300
});
return prediction.data.choices[0].message.content
} catch (error) {
console.log("Failed to get completion - ", error.message)
return error
}
}
async function sendMessage(msg, from, id) {
return new Promise((resolve, reject) => {
// Set up the options for the POST request
const options = {
hostname: 'graph.facebook.com',
// port: 443,
path: `/v15.0/${id}/messages`,
method: 'POST',
headers: {
'Authorization': `Bearer ${WHATSAPP_ACCESS_TOKEN}`,
'Content-Type': `application/json`
}
};
// Make the POST request
const req = https.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
// Build up the data string as the response comes in
data += chunk;
});
res.on('end', () => {
// Resolve the promise with the data when the response is complete
resolve(data);
});
});
req.on('error', (error) => {
// Reject the promise if there's an error
reject(error);
});
// Write the data you want to send as the request body
req.write(JSON.stringify({
messaging_product: "whatsapp",
to: from,
// type: "image",
text: {
body: msg
},
// "image": {
// "link": generatedImg,
// }
}));
req.end();
});
}
app.post('/webhook', async (req, res) => {
try {
const body = req.body;
const { phone_number_id, from, msg_body } = getMsg(body)
console.log("phone", phone_number_id, from)
if (from && msg_body) {
let msg = await getChatCompletion(msg_body)
console.log("message:", from, msg_body + ": " + msg)
let result = await sendMessage(msg, from, phone_number_id);
}
} catch (error) {
console.log(error)
}
// res.send('Yo!')
res.sendStatus(200);
});
// app.post('/chat', async (req, res) => {
// try {
// const body = req.body;
// console.log("body", body)
// const { messages, secret } = body
// if (secret == SECRET_KEY && messages.length) {
// try {
// const prediction = await openai.createChatCompletion({
// model: "gpt-3.5-turbo",
// messages: messages,
// max_tokens: 256
// });
// return prediction.data.choices[0].message.content
// } catch (error) {
// console.log("Failed to get completion - ", error.message)
// return error
// }
// } else {
// return {
// error: "Secret doesn't match",
// }
// }
// } catch (error) {
// console.log(error)
// return error
// }
// // res.send('Yo!')
// res.sendStatus(200);
// });
app.post('/chat', async (req, res) => {
try {
const body = req.body;
console.log("req", req)
const messages = body.messages
const secret = body.secret
// console.log("secret", secret, SECRET_KEY)
if (secret == SECRET_KEY && messages.length) {
try {
const prediction = await openai.createChatCompletion({
// model: "gpt-3.5-turbo",
model: "gpt-4",
messages: messages,
max_tokens: 256
});
const response = prediction.data.choices[0].message.content;
res.setHeader('Access-Control-Allow-Origin', '*');
res.send(response);
} catch (error) {
console.log("Failed to get completion - ", error.message);
res.status(500).send(error);
}
} else {
res.status(400).send({ error: "Secret doesn't match" });
}
} catch (error) {
console.log(error);
res.status(500).send(error);
}
});
app.get('/chat', async (req, res) => {
try {
const body = req.body;
// console.log("req", req)
const prompt = req.query.prompt
const secret = req.query.secret
// console.log("secret", secret, SECRET_KEY)
if (secret == SECRET_KEY && prompt.length) {
try {
const messages = [
{
"role": "system",
"content": systemPrompt,
},
{
"role": "user",
"content": prompt,
}
]
const prediction = await openai.createChatCompletion({
// model: "gpt-3.5-turbo",
model: "gpt-4",
messages: messages,
max_tokens: 256
});
const response = prediction.data.choices[0].message.content;
res.setHeader('Access-Control-Allow-Origin', '*');
res.send(response);
} catch (error) {
console.log("Failed to get completion - ", error.message);
res.status(500).send(error);
}
} else {
res.status(400).send({ error: "Secret doesn't match" });
}
} catch (error) {
console.log(error);
res.status(500).send(error);
}
});
app.get('/message', async (req, res) => {
try {
const msg = req.query.msg
await sendMessage(msg, PHONE_NUMBER, PHONE_NUMBER_ID);
res.sendStatus(200);
// setTimeout(() => {
// console.log(`Reminder: ${msg}`);
// sendMessage(msg, PHONE_NUMBER, PHONE_NUMBER_ID);
// // Send out a message here
// }, 10000);
// res.status(200).send('Reminder set');
} catch (error) {
console.log(error);
res.status(500).send(error);
}
});
// app.get('/', async (req, res) => {
// res.send('Yo!')
// res.sendStatus(200);
// });
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// app.post('/', (req, res) => {
// let data = '';
// req.on('data', chunk => {
// data += chunk.toString();
// });
// req.on('end', () => {
// const text = data.split('=')[1];
// const filePath = '/tmp/myFile.txt';
// fs.writeFile(filePath, text, err => {
// if (err) {
// console.error(err);
// res.sendStatus(500);
// } else {
// console.log('File written successfully');
// res.sendStatus(200);
// }
// });
// });
// });
app.post('/save', (req, res) => {
let data = '';
req.on('data', chunk => {
data += chunk.toString();
});
req.on('end', () => {
const formData = querystring.parse(data);
const textInput = formData['text-input'].replace(/\+/g, ' ');
const filePath = '/tmp/myFile.txt';
fs.appendFile(filePath, textInput, err => {
if (err) {
console.error(err);
res.sendStatus(500);
} else {
res.redirect('/');
}
});
});
});
app.get('/get', (req, res) => {
const filePath = '/tmp/myFile.txt';
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error(err);
res.sendStatus(500);
} else {
res.send(data);
}
});
});
app.get('/webhook', (req, res) => {
let mode = req.query["hub.mode"];
let token = req.query["hub.verify_token"];
let challenge = req.query["hub.challenge"];
res.send(challenge)
});
app.get('/privacy', (req, res) => {
let text = `Thank you for visiting our website/app. We take the privacy of our users very seriously and are committed to protecting your personal information. This privacy policy explains how we collect, use, and share your personal information when you use our website/app.
Collection of Personal Information
We may collect personal information from you when you use our website/app, such as your name, email address, and any other information you choose to provide. We may also collect certain information automatically, such as your IP address, device type, and browser type.
Use of Personal Information
We may use your personal information for the following purposes:
To provide and improve our website/app and services
To communicate with you about your account or our services
To personalize your experience on our website/app
To protect against, identify, and prevent fraud and other illegal activities
Sharing of Personal Information
We may share your personal information with third parties for the following purposes:
To service providers who assist us in providing our services
To comply with legal requirements, such as a subpoena or court order
To protect the rights, property, or safety of us or our users
Cookies and Tracking Technologies
We may use cookies and other tracking technologies to collect and store information about your use of our website/app. These technologies may be used to personalize your experience, remember your preferences, and track your movements on our website/app. You can disable cookies in your browser settings, but doing so may limit your ability to use certain features of our website/app.
Third-Party Links
Our website/app may contain links to third-party websites. We are not responsible for the privacy practices of these websites, and we encourage you to review the privacy policies of each website you visit.
Data Security
We take appropriate measures to protect your personal information from unauthorized access, disclosure, alteration, or destruction. However, no security measures are perfect, and we cannot guarantee the security of your personal information.
Changes to This Privacy Policy
We may update this privacy policy from time to time. We will post any changes on this page and encourage you to review the policy periodically. Your continued use of our website/app after any changes have been made signifies your acceptance of the updated policy.
Contact Us
If you have any questions or concerns about this privacy policy or the collection, use, and sharing of your personal information, please contact us at [email protected].`
res.send(text)
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});