-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (82 loc) · 2.73 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
const Discord = require("discord.js");
const { Client, GatewayIntentBits } = require("discord.js");
const { Configuration, OpenAIApi } = require("openai");
const MiniSearch = require("minisearch");
const faq = require("./snapshot-faq.json");
const fs = require("fs");
const dotenv = require("dotenv");
dotenv.config({ path: `.env.local`, override: true });
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
let miniSearch = new MiniSearch({
fields: ["question"],
storeFields: ["question", "answer"],
searchOptions: {
fuzzy: 0.1,
},
});
miniSearch.addAll(faq.data);
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("messageCreate", async (message) => {
if (message.author.bot) return;
const userInput = message.content;
console.log("userInput:", userInput);
let bestMatchingFaq = miniSearch
.search(userInput)
.slice(0, 6)
.map((x) => {
return `Q: ${x.question} \n A: ${x.answer}`;
});
try {
const chatResponseUserAnswer = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: `You are a helpful FAQ bot for the Snapshot (decentralized governance) support channel. You should only reply to questions (not statements) and can only respond in two ways, 1. answer questions you find in the FAQ or 2. answer 'I don't know that'. Under no circumstances should you response with your own made up answers. Here are Snapshot FAQ: ${bestMatchingFaq}`,
},
{
role: "user",
content: `${userInput}`,
},
],
});
const responseMessage =
chatResponseUserAnswer.data.choices[0].message.content;
if (responseMessage.includes("I don't know that")) {
const fileArray = JSON.parse(
fs.readFileSync("snapshot-faq-unknown.json")
);
if (!fileArray.map((el) => el.content).includes(userInput)) {
fileArray.push({ count: 0, content: userInput });
} else {
const index = fileArray.map((el) => el.content).indexOf(userInput);
fileArray[index].count += 1;
}
const uniqueFileArray = [...new Set(fileArray)];
fs.writeFileSync(
"snapshot-faq-unknown.json",
JSON.stringify(uniqueFileArray, null, 2),
function (err) {
if (err) throw err;
console.log("Saved!");
}
);
}
message.reply(responseMessage);
} catch (error) {
console.log(error);
}
});
client.login(process.env.DISCORD_BOT_KEY);