-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (47 loc) · 1.5 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
require('dotenv').config();
const lang = require('./lang.js');
const ResponseError = require('./responseError.js');
const { Configuration, OpenAIApi } = require('openai');
const openaiConfiguration = new Configuration({
apiKey: process.env.OPENAI_TOKEN,
});
const TelegramBot = require('node-telegram-bot-api');
const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, { polling: true });
//on any text which is not command
bot.onText(/^[\w\d]+/, async (msg) => {
let chatId = msg.chat.id;
let chatGPTanswer = await askChatGPT(msg.text);
bot.sendMessage(chatId, chatGPTanswer);
});
async function askChatGPT(text) {
try {
return await getChatGPTAnswer(text);
} catch (error) {
console.log(error);
return new ResponseError(error.response.status, error).message;
}
}
async function getChatGPTAnswer(text) {
const openai = new OpenAIApi(openaiConfiguration);
const response = await openai.createCompletion({
model: 'text-davinci-003',
prompt: text,
max_tokens: 2048,
});
``;
return response.data.choices[0].text;
}
//on any text which is command
bot.onText(/^\/.+/, (msg) => {
let chatId = msg.chat.id;
switch (msg.text) {
case '/start':
bot.sendMessage(chatId, lang[process.env.LANGUAGE].welcomeMessage, {
parse_mode: 'Markdown',
});
break;
default:
bot.sendMessage(chatId, lang[process.env.LANGUAGE].commandNotFound);
break;
}
});