Persistant history across reboots
the build was successful Details

This commit is contained in:
Antoine Bartuccio 2018-07-24 12:57:31 +02:00
parent 7336770332
commit 85b52e23e5
Signed by: klmp200
GPG Key ID: E7245548C53F904B
4 changed files with 41 additions and 6 deletions

3
.gitignore vendored
View File

@ -14,4 +14,5 @@
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/
settings_custom.json
settings_custom.json
history.json

View File

@ -2,7 +2,7 @@
* @Author: Bartuccio Antoine
* @Date: 2018-07-23 15:24:22
* @Last Modified by: klmp200
* @Last Modified time: 2018-07-24 12:35:08
* @Last Modified time: 2018-07-24 12:44:38
*/
package main
@ -30,7 +30,8 @@ func main() {
}
log.Println("Initialize history")
shared.InitHistory(int(settings.Settings["history size"].(float64)))
shared.InitHistory(int(settings.Settings["history size"].(float64)),
settings.Settings["history file"].(string))
log.Println("Bot initialisation")
b, err := tb.NewBot(tb.Settings{

View File

@ -1,4 +1,5 @@
{
"token": "INSERT TOKEN HERE",
"history size": 10
"history size": 10,
"history file": "history.json"
}

View File

@ -2,12 +2,14 @@
* @Author: Bartuccio Antoine
* @Date: 2018-07-24 01:27:11
* @Last Modified by: klmp200
* @Last Modified time: 2018-07-24 11:51:52
* @Last Modified time: 2018-07-24 12:54:21
*/
package shared
import (
"encoding/json"
"io/ioutil"
"sync"
)
@ -17,15 +19,24 @@ type history struct {
data map[int64][]string
}
type historyFile struct {
mutex sync.Mutex
path string
}
var History history
var hf historyFile
// Init a chat history of a given size
func InitHistory(size int) {
func InitHistory(size int, history_file_path string) {
hf = historyFile{}
hf.path = history_file_path
History = history{}
History.mutex.Lock()
defer History.mutex.Unlock()
History.size = size
History.data = make(map[int64][]string)
hf.read()
}
// Get the number of messages saved in the history
@ -89,4 +100,25 @@ func (h history) append(chatID int64, m string) {
array[i] = val
}
array[h.size-1] = m
go hf.write()
}
func (h historyFile) read() {
h.mutex.Lock()
defer h.mutex.Unlock()
data, err := ioutil.ReadFile(h.path)
if err != nil {
// File doesn't exist, skip import
return
}
json.Unmarshal(data, &History.data)
}
func (h historyFile) write() {
h.mutex.Lock()
defer h.mutex.Unlock()
History.mutex.Lock()
defer History.mutex.Unlock()
data, _ := json.Marshal(History.data)
ioutil.WriteFile(h.path, data, 0770)
}