There are a couple of components:
- Contexts
-
Represents a container for chat messages. The exact meaning varies between providers, but it’s often a (public or private) chat room.
- Hooks
-
Hooks are essentially tasks that run when certain events happen. In actual-code they’re just structs that implement the
RunHook(bot.Bot, bot.Context)
interface. - Bot
-
A container for hooks and contexts.
- Wrapper
-
A struct that implements the
RunHook
function and "wraps" another hook. This allows you to easily combine pieces to finetune your hooks.
Let’s say we have a super innovative GIF producer hook:
type GifProducer struct {
URL string
}
func (g GifProducer) RunHook(b bot.Bot, ctx bot.Context) {
ctx.Send(g.URL)
}
Well I don’t want to repeat all this complicated code every time I need slightly different gif behaviors, and I also don’t want it to run for every message. Luckily, we can wrap it:
orig := GifProducer{URL: "http://giphy.com/posts/evil-laugh-of-the-day-12"}
wrapped := bot.RegexMatcher(regexp.MustCompile("/bot gif me/"), orig)
RegexMatcher
looks like this:
type RegexMatcher {
next bot.Hook
re *regexp.Regexp
}
func NewRegexMatcher(re *regexp.Regexp, next bot.Hook) *RegexMatcher {
return &RegexMatcher{next: next, re: re}
}
func (r *RegexMatcher) RunHook(b bot.Bot, ctx bot.Context) {
// if it matches, call the next (wrapped) hook
if r.re.MatchString(ctx.Message) {
r.next(b, ctx)
}
}
There’s a couple of other helpful hook wrappers. Check the godoc.
Copyright (c) 2014, Ciaran Downey <code@ciarand.me>
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.