-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrot.go
64 lines (52 loc) · 1.11 KB
/
grot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package grot
import (
"log"
"net/http"
"os"
"regexp"
)
type Bot struct {
Logger *log.Logger
Router *http.ServeMux
Client ChatAdapter
listeners []Listener
}
func NewBot() *Bot {
logger := log.New(os.Stdout, "", 0)
router := http.NewServeMux()
// TODO: if chatAdapter is not set, simply allow http routing
return &Bot{
Client: chatAdapter,
Logger: logger,
Router: router,
}
}
func (b *Bot) Hear(pattern string, fn func(res *Response)) {
l := &listener{
fn: fn,
regex: regexp.MustCompile(pattern),
}
b.listeners = append(b.listeners, l)
}
func (b *Bot) Run() error {
go b.Client.Receive(b)
b.Router.HandleFunc("/grot/ping", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("PONG"))
})
// TODO: create routing structure to allow providing handlers
if err := http.ListenAndServe(":"+os.Getenv("PORT"), b.Router); err != nil {
return err
}
return nil
}
func (b *Bot) Receive(msg Message) error {
b.Logger.Printf("Robot received message %+v\n", msg)
for _, l := range b.listeners {
res := &Response{
bot: b,
Message: msg,
}
l.Handle(res)
}
return nil
}