-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
58 lines (45 loc) · 1.58 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
const { Client } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const { Configuration, OpenAIApi } = require("openai");
require('dotenv').config()
const client = new Client();
client.on('qr', (qr) => {
qrcode.generate(qr, { small: true });
});
client.on('ready', () => {
console.log('Client is ready!');
});
client.initialize();
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const messageHistories = {};
client.on('message', async (message) => {
console.log(message.body);
if (message.body.startsWith("#")) {
const senderId = message.from;
const userMessage = message.body.substring(1);
if (!messageHistories[senderId]) {
messageHistories[senderId] = [
{ role: "system", content: process.env.OPENAI_API_ROLE },
];
}
if (userMessage === "reset") {
delete messageHistories[senderId];
message.reply("The history has been deleted.");
} else {
messageHistories[senderId].push({ role: "user", content: userMessage });
const reply = await runCompletion(messageHistories[senderId]);
message.reply(reply);
messageHistories[senderId].push({ role: "assistant", content: reply });
}
}
});
async function runCompletion (messages) {
const completion = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: messages,
});
return completion.data.choices[0].message.content;
}