This repository has been archived by the owner on Mar 1, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
dispatch.go
97 lines (81 loc) · 2.2 KB
/
dispatch.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package victor
import (
"regexp"
"strings"
"github.com/brettbuddin/victor/pkg/chat"
)
// HandlerPair provides an interface for a handler as well as the regular
// expression which a message should match in order to pass control onto the
// handler
type HandlerPair interface {
Exp() *regexp.Regexp
Handler() Handler
}
type handlerPair struct {
exp *regexp.Regexp
handle Handler
}
func (pair *handlerPair) Exp() *regexp.Regexp {
return pair.exp
}
func (pair *handlerPair) Handler() Handler {
return pair.handle
}
type dispatch struct {
robot Robot
handlers []HandlerPair
}
func newDispatch(bot Robot) *dispatch {
return &dispatch{
robot: bot,
handlers: make([]HandlerPair, 0, 10),
}
}
// HandleCommand registers a Handler for matching statements directed at the bot
func (d *dispatch) HandleCommand(exp string, h Handler) {
d.handle(d.Direct(exp), h)
}
// HandleCommandFunc registers a Handler for matching statements directed at the bot
func (d *dispatch) HandleCommandFunc(exp string, f HandlerFunc) {
d.handle(d.Direct(exp), f)
}
// Handle registers a Handler for matching
func (d *dispatch) Handle(exp string, h Handler) {
d.handle(exp, h)
}
// HandleFunc registers a HandlerFunc for matching
func (d *dispatch) HandleFunc(exp string, f HandlerFunc) {
d.handle(exp, f)
}
func (d *dispatch) handle(exp string, h Handler) {
d.handlers = append(d.handlers, &handlerPair{
exp: regexp.MustCompile(exp),
handle: h,
})
}
// Direct wraps a regexp pattern in the necessary pattern
// for a direct command to the bot.
func (d *dispatch) Direct(exp string) string {
return strings.Join([]string{
"(?i)", // flags
"\\A", // begin
"(?:(?:@)?" + d.robot.Name() + "[:,]?\\s*|/)", // bot name
"(?:" + exp + ")", // expression
"\\z", // end
}, "")
}
// ProcessMessage finds a match for a message and runs its Handler
func (d *dispatch) ProcessMessage(m chat.Message) {
for _, pair := range d.handlers {
matches := pair.Exp().FindAllStringSubmatch(m.Text(), -1)
if len(matches) > 0 {
params := matches[0][1:]
pair.Handler().Handle(&state{
robot: d.robot,
message: m,
params: params,
})
return
}
}
}