-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
179 lines (145 loc) · 4.61 KB
/
main.go
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package main
import (
"bytes"
"context"
"encoding/json"
"github.com/go-redis/redis/v8"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
)
const (
openAIAPI = "https://api.openai.com/v1/chat/completions"
)
var ctx = context.Background()
var openAiToken, telegramBotToken string
type Update struct {
UpdateID int `json:"update_id"`
Message struct {
MessageID int `json:"message_id"`
From struct {
ID int `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
UserName string `json:"username"`
} `json:"from"`
Chat struct {
ID int `json:"id"`
Type string `json:"type"`
Title string `json:"title"`
} `json:"chat"`
Text string `json:"text"`
} `json:"message"`
}
type OpenAiResponse struct {
ID string `json:"id"`
Choices []struct {
Message Message `json:"message"`
} `json:"choices"`
}
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
var redisClient *redis.Client
func main() {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Some error occured on reading . env file. Err: %s", err)
}
openAiToken = os.Getenv("openAiToken")
telegramBotToken = os.Getenv("telegramBotToken")
redisClient = redis.NewClient(&redis.Options{
Addr: "redis:6379",
Password: os.Getenv("redisPassword"),
DB: 0,
})
setTelegramWebhook()
router := mux.NewRouter()
router.HandleFunc("/webhook", handleWebhook).Methods("POST")
http.ListenAndServe(":"+os.Getenv("golangPort"), router)
}
func setTelegramWebhook() {
setWebhookReqBody := map[string]interface{}{
"url": os.Getenv("botDomain"),
}
sendTelegramRequest(setWebhookReqBody, "setWebhook")
}
func sendTelegramRequest(reqBody map[string]interface{}, endPoint string) {
client := &http.Client{}
reqBodyJSON, _ := json.Marshal(reqBody)
log.Println(string(reqBodyJSON))
request, _ := http.NewRequest("POST", "https://api.telegram.org/bot"+telegramBotToken+"/"+endPoint, bytes.NewBuffer(reqBodyJSON))
request.Header.Set("Content-Type", "application/json")
sendMessageResp, _ := client.Do(request)
defer sendMessageResp.Body.Close()
}
func handleWebhook(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
var update Update
json.Unmarshal(body, &update)
if update.Message.Text == "" {
return
}
text := ""
if strings.ToUpper(update.Message.Text) == "/START" {
text = "Welcome, You can start chatting with Haj Jipit."
} else if strings.ToUpper(update.Message.Text) == "/CLEAR" {
redisClient.Del(ctx, "userHistory:"+strconv.Itoa(update.Message.Chat.ID))
text = "Conversation cleared."
} else {
messages := getMessagesFromRedis(update.Message.Chat.ID)
var newMessage = Message{Content: update.Message.Text, Role: "user"}
messages = append(messages, newMessage)
openAIResponse := callOpenAiApi(messages)
if len(openAIResponse.Choices) > 0 {
text = openAIResponse.Choices[0].Message.Content
messageJson, _ := json.Marshal(newMessage)
replyJson, _ := json.Marshal(openAIResponse.Choices[0].Message)
redisClient.RPush(ctx, "userHistory:"+strconv.Itoa(update.Message.Chat.ID), messageJson, replyJson)
} else {
text = "There was a problem processing your message. Maybe it's because of number of tokens. Try to /CLEAR your conversation history."
}
}
sendTelegramMessage(update.Message.Chat.ID, text)
}
func callOpenAiApi(messages []Message) OpenAiResponse {
client := &http.Client{}
openAIReqBody := map[string]interface{}{
"model": "gpt-3.5-turbo",
"messages": messages,
}
openAIReqBodyJSON, _ := json.Marshal(openAIReqBody)
openAIReq, _ := http.NewRequest("POST", openAIAPI, bytes.NewBuffer(openAIReqBodyJSON))
openAIReq.Header.Set("Content-Type", "application/json")
openAIReq.Header.Set("Authorization", "Bearer "+openAiToken)
openAIResp, _ := client.Do(openAIReq)
openAIRespBody, _ := ioutil.ReadAll(openAIResp.Body)
defer openAIResp.Body.Close()
log.Printf("openAi response %+v", string(openAIRespBody))
var openAIResponse OpenAiResponse
json.Unmarshal(openAIRespBody, &openAIResponse)
return openAIResponse
}
func getMessagesFromRedis(chatID int) []Message {
list := redisClient.LRange(ctx, "userHistory:"+strconv.Itoa(chatID), 0, -1)
var messages []Message
for _, value := range list.Val() {
var message Message
json.Unmarshal([]byte(value), &message)
messages = append(messages, message)
}
return messages
}
func sendTelegramMessage(chatID int, text string) {
sendMessageReqBody := map[string]interface{}{
"chat_id": chatID,
"text": text,
}
sendTelegramRequest(sendMessageReqBody, "sendMessage")
}