-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdb.go
64 lines (52 loc) · 1.33 KB
/
db.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
package main
import (
"github.com/rs/zerolog/log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var (
dbFile = "chats.db"
DB *gorm.DB
)
type Message struct {
gorm.Model
ID uint `gorm:"primaryKey" json:"id"`
ChatID string `json:"chatId,omitempty"` // telegrams conversation id
Role string `json:"role,omitempty"` // chatgpt role
Content string `json:"content,omitempty"` // message content
PromptTokens int `json:"prompt_tokens,omitempty"`
CompletionTokens int `json:"completion_tokens,omitempty"`
TotalTokens int `json:"total_tokens,omitempty"`
}
// ConnectDB
func ConnectDB() error {
db, err := gorm.Open(sqlite.Open(dbFile), &gorm.Config{
Logger: logger.Default,
})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&Message{})
DB = db
log.Debug().Msg("database migrated")
return nil
}
// FindMessages finds the prevous users conversations from the telegrams conversation id
func FindMessages(chatId string) ([]Message, error) {
var messages []Message
err := DB.Where(&Message{
ChatID: chatId,
}).Find(&messages).Error
if err != nil {
return nil, err
}
return messages, nil
}
// CreateMessage creates a new chat
func CreateMessage(msg Message) (*Message, error) {
if err := DB.Create(&msg).Error; err != nil {
return nil, err
}
return &msg, nil
}