diff --git a/plugins/beer.go b/plugins/beer.go new file mode 100644 index 0000000..f1793a0 --- /dev/null +++ b/plugins/beer.go @@ -0,0 +1,65 @@ +package plugins + +import ( + "fmt" + "io/ioutil" + "log" + "net/http" + "net/url" + "regexp" + + "github.com/matrix-org/gomatrix" +) + +// Beer responds to hi messages +type Beer struct { +} + +func (h *Beer) match(msg string) string { + re := regexp.MustCompile(`(?i)^beer: `) + return re.ReplaceAllString(msg, "$1") +} + +func (h *Beer) get(beer string) (string, error) { + u := "https://data.opendatasoft.com/api/records/1.0/search?dataset=open-beer-database%40public-us&q=" + u = fmt.Sprintf("%s%s", u, url.PathEscape(beer)) + log.Println(u) + resp, err := http.Get(u) + if err != nil { + return "", err + } + + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return "", err + } + + return string(body), nil +} + +// Respond to hi events +func (h *Beer) Respond(c *gomatrix.Client, ev *gomatrix.Event, user string) { + if mtype, ok := ev.MessageType(); ok { + switch mtype { + case "m.text": + if post, ok := ev.Body(); ok { + beer := h.match(post) + if beer != "" { + log.Printf("%s: responding to '%s'", h.Name(), ev.Sender) + json, err := h.get(beer) + if err != nil { + SendMessage(c, ev.RoomID, fmt.Sprintf("sorry %s, I can't look for beer. (%s)", ev.Sender, err)) + } + SendMessage(c, ev.RoomID, fmt.Sprintf("%s!", json)) + } + } + } + } +} + +// Name hi +func (h *Beer) Name() string { + return "Beer" +} diff --git a/plugins/plugins.go b/plugins/plugins.go index cb4753a..1e463de 100644 --- a/plugins/plugins.go +++ b/plugins/plugins.go @@ -42,6 +42,7 @@ type Plugins []Plugin // Plugs are all of our plugins var Plugs = Plugins{ + &Beer{}, &BotSnack{}, &HighFive{}, &Hi{},