Skip to content

Commit

Permalink
refactor: auto-save every 5minutes
Browse files Browse the repository at this point in the history
  • Loading branch information
TheTipo01 committed Mar 16, 2022
1 parent edb7350 commit c8a58ab
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
5 changes: 4 additions & 1 deletion database.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ func addMessage(m *discordgo.Message) {

if !m.Author.Bot {
server[m.GuildID].model.Add(strings.Split(m.Content, " "))
saveModel(m.GuildID)
}
} else {
_, err = db.Exec("INSERT INTO messages (guildID, channelID, messageID, message) VALUES (?, ?, ?, ?)", m.GuildID, m.ChannelID, m.ID, inJSON)
Expand Down Expand Up @@ -250,6 +249,10 @@ func loadScheduler(s *discordgo.Session) {
lit.Debug("Added cronjob for server %s", guildID)
}

_, _ = cron.Every(5).Minute().Do(func() {
saveAllModels()
})

// And start the scheduler
cron.StartAsync()
}
3 changes: 3 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ func main() {

// Cleanly close down the Discord session.
_ = dg.Close()

saveAllModels()

// And the database connection
_ = db.Close()
}
Expand Down
19 changes: 15 additions & 4 deletions markov.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,23 @@ func buildModel(guildID string) *gomarkov.Chain {

// saveModel updates the model on the database
func saveModel(guildID string) {
data, _ := json.Marshal(server[guildID].model)
if server[guildID] != nil {
data, _ := json.Marshal(server[guildID].model)

_, err := db.Exec("UPDATE servers SET model=? WHERE id=?", data, guildID)
_, err := db.Exec("UPDATE servers SET model=? WHERE id=?", data, guildID)

if err != nil {
lit.Error("Error updating model: %s", err.Error())
if err != nil {
lit.Error("Error updating model: %s", err.Error())
}
} else {
lit.Warn("Server map for guild %s is nil", guildID)
}
}

// saveAllModels saves all the models in the map server
func saveAllModels() {
for guildID, _ := range server {
saveModel(guildID)
}
}

Expand Down

0 comments on commit c8a58ab

Please sign in to comment.