Database: Init
Signed-off-by: Sayan Biswas <sayan@pokurt.me>
This commit is contained in:
parent
f1851f51a2
commit
a60c28ce11
|
@ -1 +1,2 @@
|
|||
spb.conf
|
||||
spb.conf
|
||||
*.db
|
|
@ -0,0 +1,33 @@
|
|||
package database
|
||||
|
||||
import "errors"
|
||||
|
||||
type Chat struct {
|
||||
ChatID int64 `gorm:"primaryKey" gorm:"column:chat_id"`
|
||||
AutoBan bool `gorm:"column:auto_ban"`
|
||||
SpamDetect bool `gorm:"column:spam_detect"`
|
||||
SpamAction string `gorm:"column:spam_action"`
|
||||
}
|
||||
|
||||
func (c *Chat) DoesAutoBan() bool {
|
||||
return c.AutoBan
|
||||
}
|
||||
|
||||
func InsertChat(ChatID int64, AutoBan bool, SpamDetect bool, SpamAction string) {
|
||||
tx := SESSION.Begin()
|
||||
chat := &Chat{ChatID: ChatID, AutoBan: AutoBan, SpamDetect: SpamDetect, SpamAction: SpamAction}
|
||||
tx.Save(chat)
|
||||
tx.Commit()
|
||||
}
|
||||
|
||||
func GetChat(ChatID int64) (*Chat, error) {
|
||||
if SESSION == nil {
|
||||
return nil, errors.New("cannot access to SESSION " +
|
||||
"of db, because it's nil")
|
||||
}
|
||||
|
||||
p := Chat{}
|
||||
SESSION.Where("chat_id = ?", ChatID).Take(&p)
|
||||
return &p, nil
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gitlab.com/Dank-del/SpamProtection-Mirror-Bot/core"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var SESSION *gorm.DB
|
||||
|
||||
func StartDatabase(name string) {
|
||||
db, err := gorm.Open(sqlite.Open(fmt.Sprintf("%s.db", name)), &gorm.Config{})
|
||||
if err != nil {
|
||||
core.SUGARED.Error("failed to connect database")
|
||||
}
|
||||
|
||||
SESSION = db
|
||||
core.SUGARED.Info("Database connected")
|
||||
|
||||
// Create tables if they don't exist
|
||||
err = SESSION.AutoMigrate(&Chat{})
|
||||
if err != nil {
|
||||
core.SUGARED.Error(err)
|
||||
}
|
||||
|
||||
core.SUGARED.Info("Auto-migrated database schema")
|
||||
|
||||
}
|
4
main.go
4
main.go
|
@ -1,6 +1,7 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"gitlab.com/Dank-del/SpamProtection-Mirror-Bot/database"
|
||||
"gitlab.com/Dank-del/SpamProtection-Mirror-Bot/handlers"
|
||||
"go.uber.org/zap"
|
||||
"log"
|
||||
|
@ -26,9 +27,10 @@ func main() {
|
|||
core.SUGARED = loggerMgr.Sugar()
|
||||
b, up, err := core.BotInit(e)
|
||||
if err != nil {
|
||||
return
|
||||
log.Fatal(err)
|
||||
}
|
||||
handlers.LoadHandlers(up.Dispatcher)
|
||||
database.StartDatabase(e.DatabaseName)
|
||||
logger.Info(b.FirstName, " has started, ID: ", b.Id)
|
||||
up.Idle()
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue