This repository has been archived by the owner on Jun 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
438 lines (372 loc) · 10.4 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
_ "github.com/mattn/go-sqlite3"
openai "github.com/sashabaranov/go-openai"
)
// Structs
type env_var struct {
BotToken string `json:"botToken"`
GptApiKey string `json:"gptApiKey"`
Log bool `json:"log"`
}
type stats struct {
MsgScanned int
Questions int
Answers int
Tokens int
Profiles int
}
type profile struct {
Name string `json:"name"`
Regex string `json:"regex"`
Context string `json:"context"`
}
type last struct {
Guild string
Channel string
}
// Global variables
var (
Env env_var
Obs stats
Profiles []profile
CurrentProfile profile
LastGuildChan last
db *sql.DB
startTime time.Time
client *openai.Client
)
func main() {
// Load environment variables
execPath, err := os.Executable()
if err != nil {
panic(err)
}
// Check if the bot is running from the main folder or the binaries folder
var baseDir string
if filepath.Base(filepath.Dir(execPath)) == "bin" {
baseDir = filepath.Dir(filepath.Dir(execPath)) + "/"
} else {
baseDir = filepath.Dir(execPath) + "/"
}
// Load config
file, err := os.Open(baseDir + ".env")
if err != nil {
fmt.Println("error opening config file")
panic(err)
}
defer file.Close()
bytes, err := io.ReadAll(file)
if err != nil {
fmt.Println("error reading config file")
panic(err)
}
err = json.Unmarshal(bytes, &Env)
if err != nil {
fmt.Println("error unmarshalling config file")
panic(err)
}
// Create/reset database
db, err = sql.Open("sqlite3", "file:"+baseDir+"data/database.db?mode=rwc")
if err != nil {
fmt.Println("error opening/creating database")
panic(err)
}
defer db.Close()
// Load profiles
file, err = os.Open(baseDir + "data/profiles.json")
if err != nil {
fmt.Println("error opening profiles file")
panic(err)
}
defer file.Close()
bytes, err = io.ReadAll(file)
if err != nil {
fmt.Println("error reading profiles file")
panic(err)
}
err = json.Unmarshal([]byte(bytes), &Profiles)
if err != nil {
fmt.Println("error unmarshalling profiles file")
panic(err)
}
// Set the current profile
CurrentProfile = Profiles[0]
// Initialize the database
// Ask user if they want to reset the database
var reset string
fmt.Print("Do you want to reset the database? (y/n) ")
fmt.Scanln(&reset)
if reset == "y" {
resetDb(db)
}
err = initDb(db)
if err != nil {
fmt.Println("error initializing database")
panic(err)
}
// Initiate openai client
client = openai.NewClient(Env.GptApiKey)
// Create a new Discord session using the provided bot token.
dg, err := discordgo.New("Bot " + Env.BotToken)
if err != nil {
fmt.Println("error creating Discord session")
panic(err)
}
// Register the messageCreate func as a callback for MessageCreate events.
dg.AddHandler(messageCreate)
dg.Identify.Intents = discordgo.IntentsGuildMessages
// Open a websocket connection to Discord and begin listening.
err = dg.Open()
if err != nil {
fmt.Println("error opening connection")
panic(err)
}
// Get current time
startTime = time.Now()
// Wait here until CTRL-C or other term signal is received.
fmt.Println("Bot is now running. Press CTRL-C to exit.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-sc
// Reset username and send a goodbye message in the last channel the bot was active in
err = (*dg).GuildMemberNickname(LastGuildChan.Guild, "@me", "")
if err != nil {
dg.ChannelMessageSend(LastGuildChan.Channel, "Error resetting nickname! Please reset it manually. :(")
fmt.Println("error changing nickname", err)
}
_, err = dg.ChannelMessageSend(LastGuildChan.Channel, "Bot shutting down for maintenance!")
if err != nil {
fmt.Println("error sending goodbye message:", err)
}
_, err = dg.ChannelMessageSend(LastGuildChan.Channel, "Stats :\n```\n"+getStats(startTime)+"\n```")
if err != nil {
fmt.Println("error sending stats:", err)
}
// Cleanly close down the Discord session.
dg.Close()
// Print stats
fmt.Print(getStats(startTime))
}
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
msgScanned()
var err error
// Ignore all messages created by the bot itself
if m.Author.ID == s.State.User.ID {
// Update the current channel
LastGuildChan.Guild = m.GuildID
LastGuildChan.Channel = m.ChannelID
return
} else if isMentioned(m.Mentions, s.State.User) {
// If bot is tagged in the message, do command
// profile command
if regexp.MustCompile(`(?mi)profile`).MatchString(m.Content) {
// Extract profile name
needle := regexp.MustCompile(`(?i)profile\s+(?P<name>\w+)`).FindStringSubmatch(m.Content)
changed := false
// Change string to lowercase
needle[1] = strings.ToLower(needle[1])
// Find the corresponding profile
for _, profile := range Profiles {
if profile.Name == needle[1] {
CurrentProfile = profile
changed = true
profileChanged()
err = (*s).GuildMemberNickname(m.GuildID, "@me", profile.Name)
if err != nil {
fmt.Println("error changing nickname", err)
}
fmt.Println("profile changed to", profile.Name)
break
}
}
// Send a message to confirm the profile change if no errors occured
if changed {
_, err = s.ChannelMessageSend(m.ChannelID, "Profile changed to "+CurrentProfile.Name)
if err != nil {
fmt.Println("error sending profile change message:", err)
}
answerSent()
} else {
_, err = s.ChannelMessageSend(m.ChannelID, "Profile not found")
if err != nil {
fmt.Println("error sending profile not found message:", err)
}
}
return
} else if regexp.MustCompile(`(?i)clear$`).MatchString(m.Content) {
// Delete all messages from user in database
clearUserMessages(db, m.Author.ID)
_, err = s.ChannelMessageSend(m.ChannelID, "Your messages have been deleted from the database.")
if err != nil {
fmt.Println("error sending clear message:", err)
}
} else if regexp.MustCompile(`(?i)stats$`).MatchString(m.Content) {
// Create a stat message
msg := "```\n" + getStats(startTime) + "\n```"
// Send a message with the stats
_, err = s.ChannelMessageSend(m.ChannelID, msg)
if err != nil {
fmt.Println("error sending stats message:", err)
}
return
} else if regexp.MustCompile(`(?i)help$`).MatchString(m.Content) {
// Create a help message
msg := "```" +
"Commands:" +
"\n@bipolarplushie profile <name>: change the profile" +
"\n@bipolarplushie stats: show statistics" +
"\n@bipolarplushie help: show this message" +
"\n@bipolarplushie clear: delete *your* messages from the database" +
"\n\nProfiles:"
for _, profile := range Profiles {
msg += "\n- " + profile.Name + ": " + profile.Regex
}
msg += "```"
_, err = s.ChannelMessageSend(m.ChannelID, msg)
if err != nil {
fmt.Println("error sending help message:", err)
}
return
}
}
// If the message is a reply to the bot, send a completion
if m.ReferencedMessage != nil && m.ReferencedMessage.Author.ID == s.State.User.ID {
// Update DB
if messagesTimeDiff(m.ID, numberMessagesUser(db, m.Author.ID)) > 5*time.Minute {
clearUserMessages(db, m.Author.ID)
}
insertUser(db, m.Author.ID, m.Author.Username)
insertMessage(db, m)
originalMessage, err := s.ChannelMessage(m.ChannelID, m.ReferencedMessage.ID)
if err != nil {
fmt.Println("error getting original message:", err)
}
err = sendChatCompletion(s, m, originalMessage.Content)
if err != nil {
fmt.Println("error sending completion:", err)
}
} else if regexp.MustCompile(CurrentProfile.Regex).MatchString(m.Content) {
// Clear user messages if the last message was sent more than 5 minutes ago
if messagesTimeDiff(m.ID, numberMessagesUser(db, m.Author.ID)) > 5*time.Minute {
clearUserMessages(db, m.Author.ID)
}
insertUser(db, m.Author.ID, m.Author.Username)
insertMessage(db, m)
err = sendChatCompletion(s, m, "")
if err != nil {
fmt.Println("error sending completion:", err)
}
}
}
func isMentioned(s []*discordgo.User, u *discordgo.User) bool {
for _, m := range s {
if m.ID == u.ID {
return true
}
}
return false
}
func snowflakeToUnix(s string) time.Time {
si, err := strconv.Atoi(s)
if err != nil {
fmt.Println("error converting snowflake to int:", err)
panic(err)
}
return time.UnixMilli(int64(si>>22 + 1420070400000))
}
func messagesTimeDiff(m1 string, m2 string) time.Duration {
if m1 == "" || m2 == "" {
return 0
}
return snowflakeToUnix(m1).Sub(snowflakeToUnix(m2))
}
func sendChatCompletion(s *discordgo.Session, m *discordgo.MessageCreate, reply string) error {
questionAsked()
(*s).ChannelTyping(m.ChannelID)
var err error
// Get previous messages
messages := getConversations(db, m.Author.ID)
// Create completion request
request := openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: messages,
}
// Get completion
completion, err := client.CreateChatCompletion(
context.Background(),
request)
// Update tokens
tokenUsed(completion.Usage.TotalTokens)
// Extract completion
answer := completion.Choices[0].Message.Content
// Update conversation
insertAnswer(db, m.ID, answer)
if err != nil {
fmt.Println("error getting completion:", err)
return err
}
_, err = s.ChannelMessageSendReply(m.ChannelID, answer, (*m).Reference())
if err != nil {
fmt.Println("error sending message", err)
return err
}
// Update stats
answerSent()
return nil
}
// Observer stats
func msgScanned() {
Obs.MsgScanned++
if Env.Log {
fmt.Println("Message scanned")
}
}
func questionAsked() {
Obs.Questions++
if Env.Log {
fmt.Println("Question asked")
}
}
func answerSent() {
Obs.Answers++
if Env.Log {
fmt.Println("Answer sent")
}
}
func tokenUsed(amount int) {
Obs.Tokens += amount
if Env.Log {
fmt.Println(amount, " token used")
}
}
func profileChanged() {
Obs.Profiles++
if Env.Log {
fmt.Println("Profile changed")
}
}
func getStats(t time.Time) string {
msg := "Uptime : " + time.Since(t).Round(time.Second).String()
msg += "\nMessages scanned: " + strconv.Itoa(Obs.MsgScanned)
msg += "\nQuestions asked: " + strconv.Itoa(Obs.Questions)
msg += "\nAnswers sent: " + strconv.Itoa(Obs.Answers)
msg += "\nTokens used: " + strconv.Itoa(Obs.Tokens)
msg += "\nProfiles change: " + strconv.Itoa(Obs.Profiles)
msg += "\n"
return msg
}