-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
194 lines (166 loc) · 5.15 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package main
import (
"context"
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/joho/godotenv"
"github.com/sashabaranov/go-openai"
"log"
"net/http"
"os"
"strconv"
"strings"
)
type CircularBuffer struct {
data [400]string
index int
}
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
botToken := os.Getenv("TELEGRAM_BOT_TOKEN")
botAPI, err := tgbotapi.NewBotAPI(botToken)
if err != nil {
log.Panic(err)
}
botUsername := os.Getenv("TELEGRAM_BOT_USERNAME")
if botUsername == "" {
log.Fatal("TELEGRAM_BOT_USERNAME not set in .env file")
}
botAdminUsername := os.Getenv("TELEGRAM_BOT_ADMIN_USERNAME")
if botAdminUsername == "" {
log.Fatal("TELEGRAM_BOT_ADMIN_USERNAME not set in .env file")
}
botAdminChatIDStr := os.Getenv("TELEGRAM_BOT_ADMIN_CHAT_ID")
if botAdminChatIDStr == "" {
log.Fatal("TELEGRAM_BOT_ADMIN_CHAT_ID not set in .env file")
}
botAdminChatID, err := strconv.ParseInt(botAdminChatIDStr, 10, 64)
if err != nil {
log.Fatal("TELEGRAM_BOT_ADMIN_CHAT_ID is not a valid integer")
}
botGroupChatIDStr := os.Getenv("TELEGRAM_BOT_GROUP_CHAT_ID")
if botGroupChatIDStr == "" {
log.Fatal("TELEGRAM_BOT_GROUP_CHAT_ID not set in .env file")
}
botGroupChatID, err := strconv.ParseInt(botGroupChatIDStr, 10, 64)
if err != nil {
log.Fatal("TELEGRAM_BOT_GROUP_CHAT_ID is not a valid integer")
}
httpPort := os.Getenv("HTTP_PORT")
if httpPort == "" {
log.Fatal("HTTP_PORT not set in .env file")
}
openAiToken := os.Getenv("OPENAI_TOKEN")
if openAiToken == "" {
log.Fatal("OPENAI_TOKEN not set in .env file")
}
botAPI.Debug = true
log.Printf("Authorized on account %s", botAPI.Self.UserName)
updates := botAPI.ListenForWebhook("/")
go http.ListenAndServe(":"+httpPort, nil)
cb := &CircularBuffer{}
for update := range updates {
if update.Message == nil {
continue
}
chatID := update.Message.Chat.ID
//Uncomment this to know your PV or group chat ID
//msg := tgbotapi.NewMessage(chatID, strconv.FormatInt(chatID, 10))
//botAPI.Send(msg)
//continue
if chatID != botAdminChatID && chatID != botGroupChatID {
msg := tgbotapi.NewMessage(chatID, "Sorry, only admin can communicate with this bot.")
botAPI.Send(msg)
continue
}
if update.Message.Text == "/start" || update.Message.Text == "/start@"+botUsername {
msg := tgbotapi.NewMessage(chatID, "Hi! I can summarize your group chat in Persian.")
botAPI.Send(msg)
} else if update.Message.Text == "/chishod" || update.Message.Text == "/chishod@"+botUsername {
if update.Message.From.UserName != botAdminUsername {
msg := tgbotapi.NewMessage(chatID, "Sorry, this command is only available to the bot admin.")
botAPI.Send(msg)
continue
}
allMessages := cb.ConcatMessages()
if allMessages == "" {
msg := tgbotapi.NewMessage(chatID, "No messages yet.")
botAPI.Send(msg)
}
openaiResp := OpenAIRequest(openAiToken, allMessages)
msg := tgbotapi.NewMessage(chatID, openaiResp)
botAPI.Send(msg)
cb.Empty()
} else if chatID == botGroupChatID {
cb.AddMessage(update.Message)
}
}
}
// AddMessage Adds a new message to the buffer
func (cb *CircularBuffer) AddMessage(message *tgbotapi.Message) {
if len(message.Text) <= 1 {
return
}
text := message.From.FirstName
if message.ReplyToMessage != nil {
text = text + "(در پاسخ به " + message.ReplyToMessage.From.FirstName + ")"
}
text += ": " + StringReplace(message.Text)
cb.data[cb.index] = text
cb.index = (cb.index + 1) % 400
}
// ConcatMessages Concatenates all messages into a single string with break lines between them
func (cb *CircularBuffer) ConcatMessages() string {
var messages []string
messages = append(messages, "این یک مکالمه در گروه است. خلاصه ای از این مکالمه به فارسی و در حداکثر دو خط ارائه بده: ")
for i := 0; i < 400; i++ {
idx := (cb.index + i) % 400
if cb.data[idx] != "" {
messages = append(messages, cb.data[idx])
}
}
return strings.Join(messages, "\n")
}
func (cb *CircularBuffer) Empty() {
for i := range cb.data {
cb.data[i] = ""
}
cb.index = 0
}
// StringReplace Replaces all emojis with an empty string
func StringReplace(s string) string {
//var emojiRx = regexp.MustCompile(`[\x{1F600}-\x{1F6FF}|[\x{2600}-\x{26FF}]`)
//s = emojiRx.ReplaceAllString(s, ``)
return strings.Replace(s, "\n", " ", -1)
}
// TrimToMax Trims a string to a maximum length
func TrimToMax(s string, maxLen int) string {
if len(s) > maxLen {
return s[:maxLen]
}
return s
}
// OpenAIRequest Sends a request to OpenAI API and returns the response
func OpenAIRequest(token string, text string) string {
client := openai.NewClient(token)
text = TrimToMax(text, 8000) // Max length of a chatgpt prompt is 4,096 tokens ~ 8,000 characters
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: text,
},
},
},
)
if err != nil {
return fmt.Sprintf("ChatCompletion error: %v\n", err)
}
return resp.Choices[0].Message.Content
}