diff options
author | Robert Gerus <arachnist@i.am-a.cat> | 2016-06-13 19:22:21 +0200 |
---|---|---|
committer | Robert Gerus <arachnist@i.am-a.cat> | 2016-06-13 19:22:21 +0200 |
commit | 980a8bf16f8936f4ad6238b1e29e590d0513f76c (patch) | |
tree | 5a9080bf43e4f152ba207da4a3ba47298c7b65db | |
parent | efa9bc2e8b3c08d8a8e32fc5518a96904ff09ee4 (diff) | |
download | gorepost-master.tar.gz gorepost-master.tar.bz2 gorepost-master.tar.xz gorepost-master.zip |
-rw-r--r-- | bot/frog.go | 48 |
1 files changed, 34 insertions, 14 deletions
diff --git a/bot/frog.go b/bot/frog.go index ea5afbd..a43cec1 100644 --- a/bot/frog.go +++ b/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 - - if strings.Split(msg.Trailing, " ")[0] != ":frog" { - return - } +func (tips *tips) fetchTips() error { + tips.lock.Lock() + defer tips.lock.Unlock() data, err := httpGet("http://frog.tips/api/1/tips/") if err != nil { - output(reply(msg, fmt.Sprint("error:", err))) - return + return err } - err = json.Unmarshal(data, &values) + err = json.Unmarshal(data, tips) if err != nil { - output(reply(msg, fmt.Sprint("error:", err))) - return + return err + } + + return nil +} + +func (tips *tips) popTip() string { + if len(tips.Tips) == 0 { + if err := tips.fetchTips(); err != nil { + return fmt.Sprint(err) + } } - tip := values.Tips[rand.Intn(len(values.Tips))] + 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 + } - output(reply(msg, fmt.Sprintf("frog tip #%d: %s", tip.Number, tip.Tip))) + output(reply(msg, t.popTip())) } func init() { |