-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
136 lines (110 loc) · 2.88 KB
/
index.ts
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
import OpenAI from 'openai'
import { PrismaClient } from '@prisma/client'
import TelegramBot from 'node-telegram-bot-api'
import telegramifyMarkdown from 'telegramify-markdown'
require('dotenv').config()
const prisma = new PrismaClient()
const openAI = new OpenAI({
apiKey: process.env.OPENAI_KEY,
})
const makeCompletion = async () => {
const bot = new TelegramBot(process.env.TELEGRAM_TOKEN, { polling: true })
bot.onText(/\/password/, async (msg) => {
const providedPassword = msg.text.replace('/password ', '')
if (process.env.TELEGRAM_PASSWORD !== providedPassword) {
return
}
const user = await prisma.user.findUnique({
where: {
telegramId: String(msg.from.id),
},
})
if (user) {
bot.sendMessage(msg.chat.id, 'You are already registered')
return
}
await prisma.user.create({
data: {
telegramId: String(msg.from.id),
},
})
bot.sendMessage(msg.chat.id, 'You are now registered')
})
bot.onText(/\/clear/, async (msg) => {
await prisma.message.updateMany({
where: {
isActive: true,
userId: msg.from.id,
},
data: {
isActive: false,
},
})
bot.sendMessage(msg.chat.id, 'Cleared all messages')
})
bot.on('message', async (msg) => {
if (['/clear', '/password'].includes(msg.text)) return
const user = await prisma.user.findUnique({
where: {
telegramId: String(msg.from.id),
},
})
if (!user) {
return
}
var dt = new Date()
const dateString =
dt.getFullYear() + '/' + (dt.getMonth() + 1) + '/' + dt.getDate()
const previousMessages = await prisma.message.findMany({
where: {
isActive: true,
userId: user.id,
},
})
const previousMessagesCapped = previousMessages.slice(
Math.max(previousMessages.length - 10, 0)
)
const completion = await openAI.chat.completions.create({
model: 'gpt-4',
messages: [
...previousMessagesCapped.map((message) => ({
content: message.text,
role: message.role as any,
})),
{
content: msg.text,
role: 'user',
},
],
})
bot.sendMessage(
msg.chat.id,
telegramifyMarkdown(completion.choices[0].message.content),
{ parse_mode: 'MarkdownV2' }
)
const userMessagePromise = prisma.message.create({
data: {
text: msg.text,
role: 'user',
user: {
connect: {
id: user.id,
},
},
},
})
const botMessagePromise = prisma.message.create({
data: {
text: completion.choices[0].message.content,
role: 'assistant',
user: {
connect: {
id: user.id,
},
},
},
})
await Promise.all([userMessagePromise, botMessagePromise])
})
}
makeCompletion()