-
Notifications
You must be signed in to change notification settings - Fork 16
/
chat.js
85 lines (63 loc) · 1.91 KB
/
chat.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
import { ChatGPTAPI } from "chatgpt";
import dotenv from "dotenv";
import { marked } from "marked";
import { Telegraf } from "telegraf";
dotenv.config();
let conversation = null;
let start = Date.now();
console.log("starting:", start);
const api = new ChatGPTAPI({
apiKey: process.env.APIKEY,
});
const bot = new Telegraf(process.env.TOKEN);
bot.start((ctx) => {
ctx.reply(
"Hello, this is a bot that uses OpenAI.\nAsk anything using /ask followed by your question, if your directly texting the bot you don't need to use /ask, just ask your question."
);
});
async function askAI(question, userId) {
conversation = conversation
? await api.sendMessage(question, {
conversationId: conversation.conversationId,
parentMessageId: conversation.messageId,
})
: await api.sendMessage(question);
console.log(conversation.text);
return conversation.text;
}
bot.command("ask", async (ctx) => {
const userId = ctx.update.message.from.id;
if (ctx.update.message.from.is_bot) {
return false;
}
const args = ctx.update.message.text.split(" ");
args.shift();
let question = args.join(" ");
if (question.length == 0) {
return ctx.reply("Type something after /ask to ask me stuff.", {
reply_to_message_id: ctx.message.message_id,
});
}
ctx.sendChatAction("typing");
try {
const completion = await askAI(question, userId);
ctx.reply(marked.parseInline(completion), {
reply_to_message_id: ctx.message.message_id,
parse_mode: "HTML",
});
} catch (error) {
console.log(error);
}
});
bot.command("reload", async (ctx) => {
chat_log.clear();
ctx.sendChatAction("typing");
if (chat_log.size === 0) {
return ctx.reply("Conversation history reloaded!", {
reply_to_message_id: ctx.message.message_id,
});
}
});
bot.launch();
process.once("SIGINT", () => bot.stop("SIGINT"));
process.once("SIGTERM", () => bot.stop("SIGTERM"));