ALFRED/commands/quote.go

54 lines
950 B
Go

/*
* @Author: Bartuccio Antoine
* @Date: 2018-11-14 00:15:43
* @Last Modified by: klmp200
* @Last Modified time: 2018-11-14 00:31:48
*/
package commands
import (
"encoding/json"
"io/ioutil"
"math/rand"
"sync"
"../shared"
tb "gopkg.in/tucnak/telebot.v2"
)
type quoteStorage struct {
mutex sync.Mutex
data []string
}
var sharedQuotes *quoteStorage
// Quote display a quote on the chat
func Quote(m *tb.Message) {
if sharedQuotes == nil {
loadQuotes("quotes.json")
}
sharedQuotes.mutex.Lock()
defer sharedQuotes.mutex.Unlock()
shared.Bot.Send(m.Chat, sharedQuotes.data[rand.Intn(len(sharedQuotes.data))])
}
func loadQuotes(path string) {
sharedQuotes = &quoteStorage{}
sharedQuotes.mutex.Lock()
defer sharedQuotes.mutex.Unlock()
sharedQuotes.data = []string{}
data, err := ioutil.ReadFile(path)
if err != nil {
return
}
if json.Unmarshal(data, &sharedQuotes.data) != nil {
sharedQuotes.data = []string{}
}
}