summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--bot/frog.go48
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() {