Store tips fetched from api and only fetch a new batch when we've ran out of tips.
parent
efa9bc2e8b
commit
980a8bf16f
56
bot/frog.go
56
bot/frog.go
|
@ -7,8 +7,8 @@ package bot
|
|||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/arachnist/gorepost/irc"
|
||||
)
|
||||
|
@ -20,30 +20,50 @@ type tip struct {
|
|||
|
||||
type tips struct {
|
||||
Tips []tip `json:"tips"`
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
func frog(output func(irc.Message), msg irc.Message) {
|
||||
var values tips
|
||||
func (tips *tips) fetchTips() error {
|
||||
tips.lock.Lock()
|
||||
defer tips.lock.Unlock()
|
||||
|
||||
data, err := httpGet("http://frog.tips/api/1/tips/")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = json.Unmarshal(data, tips)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tips *tips) popTip() string {
|
||||
if len(tips.Tips) == 0 {
|
||||
if err := tips.fetchTips(); err != nil {
|
||||
return fmt.Sprint(err)
|
||||
}
|
||||
}
|
||||
|
||||
tips.lock.RLock()
|
||||
defer tips.lock.RUnlock()
|
||||
|
||||
rmsg := tips.Tips[len(tips.Tips)-1].Tip
|
||||
tips.Tips = tips.Tips[:len(tips.Tips)-1]
|
||||
|
||||
return rmsg
|
||||
}
|
||||
|
||||
var t tips
|
||||
|
||||
func frog(output func(irc.Message), msg irc.Message) {
|
||||
if strings.Split(msg.Trailing, " ")[0] != ":frog" {
|
||||
return
|
||||
}
|
||||
|
||||
data, err := httpGet("http://frog.tips/api/1/tips/")
|
||||
if err != nil {
|
||||
output(reply(msg, fmt.Sprint("error:", err)))
|
||||
return
|
||||
}
|
||||
|
||||
err = json.Unmarshal(data, &values)
|
||||
if err != nil {
|
||||
output(reply(msg, fmt.Sprint("error:", err)))
|
||||
return
|
||||
}
|
||||
|
||||
tip := values.Tips[rand.Intn(len(values.Tips))]
|
||||
|
||||
output(reply(msg, fmt.Sprintf("frog tip #%d: %s", tip.Number, tip.Tip)))
|
||||
output(reply(msg, t.popTip()))
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
|
Loading…
Reference in New Issue