-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
71 lines (58 loc) · 1.5 KB
/
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
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
package robotic
import (
"errors"
"fmt"
"regexp"
"strconv"
)
const (
CommandPrefix = "#"
CommandMaxLength = 10
commandRegexPTemp = "^%s([a-zA-Z]{1,%d})$|^%s([a-zA-Z]{1,%d}) ([\\W\\w]+)$"
)
var commandNameRegexp = regexp.MustCompile(fmt.Sprintf("^[a-zA-Z]{1,%d}$", CommandMaxLength))
type CommandHandler func(message *ResolvedChatMessage, value string) error
type Command struct {
Role Role
Name string
Desc string
Handle CommandHandler
regex *regexp.Regexp
}
func NewCommand(role Role, name string, handle CommandHandler) (*Command, error) {
return NewCommand2(role, name, "no description", handle)
}
func NewCommand2(role Role, name string, desc string, handle CommandHandler) (*Command, error) {
c := &Command{
Role: role,
Name: name,
Desc: desc,
Handle: handle,
regex: nil,
}
err := c.compileRe()
if err != nil {
return nil, err
}
return c, nil
}
func (c *Command) compileRe() error {
if !commandNameRegexp.MatchString(c.Name) {
return errors.New("command name must be: A-Z, a-z, 1<len<" + strconv.Itoa(CommandMaxLength))
}
re, err := regexp.Compile(fmt.Sprintf(commandRegexPTemp, CommandPrefix, CommandMaxLength, CommandPrefix, CommandMaxLength))
if c.regex == nil {
c.regex = re
}
return err
}
func (c *Command) handle(message *ResolvedChatMessage) bool {
match := c.regex.FindStringSubmatch(message.ChatMessage.Content)
if len(match) != 0 {
if c.Name == match[2] || c.Name == match[1] {
_ = c.Handle(message, match[3])
return true
}
}
return false
}