-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommand_example_test.go
52 lines (42 loc) · 1.11 KB
/
command_example_test.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
package gobot_test
import (
"fmt"
"github.com/jlindsey/gobot"
"regexp"
"strconv"
)
// Implement a more complex command that adds two numbers together.
type AddCommand struct {
matcher *regexp.Regexp
}
func (a AddCommand) String() string {
return `AddCommand{ trigger: "add a b" }`
}
func (a AddCommand) Matches(text string) bool {
return a.matcher.MatchString(text)
}
func (a AddCommand) Help() string {
return `*add*: Add two numbers together.
Add takes two numbers and adds them together.
ex: @gobot: add 1 2`
}
func (a AddCommand) Run(channel string, text string, out chan *gobot.SlackMessage) error {
names := a.matcher.SubexpNames()
matches := a.matcher.FindAllStringSubmatch(text, -1)[0]
md := map[string]int{}
for i, n := range matches {
conv, err := strconv.Atoi(n)
if err != nil {
return err
}
md[names[i]] = conv
}
res := md["a"] + md["b"]
out <- gobot.NewSlackMessage(channel, fmt.Sprintf("%d + %d = %d", md["a"], md["b"], res))
return nil
}
func ExampleCommand() {
b := gobot.NewBot()
matcher := regexp.MustCompile(`add (?{<a>\d+) (?P<b>\d+)`)
b.RegisterCommand(AddCommand{matcher})
}