-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathcommand.go
42 lines (35 loc) · 905 Bytes
/
command.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
package fbbot
import (
"regexp"
)
type Commander struct {
mapCommandFunc map[string]func(*Bot, *Message, string)
}
func NewCommander() *Commander {
commandHandler := Commander{}
commandHandler.mapCommandFunc = make(map[string]func(*Bot, *Message, string))
return &commandHandler
}
func (h *Commander) Add(name string, f func(*Bot, *Message, string)) {
h.mapCommandFunc[name] = f
}
func (h *Commander) HandleEcho(bot *Bot, echoMsg *Message) {
// Do not handle echo from bot itself
if echoMsg.AppID > 0 {
return
}
name, param := h.extractCommand(echoMsg.Text)
f, ok := h.mapCommandFunc[name]
if ok {
f(bot, echoMsg, param)
}
}
func (h *Commander) extractCommand(msg string) (name string, param string) {
re := regexp.MustCompile("^/([a-z]*)(?: (.*))?")
matches := re.FindStringSubmatch(msg)
if len(matches) == 3 {
name = matches[1]
param = matches[2]
}
return name, param
}