-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
87 lines (70 loc) · 1.82 KB
/
handler.go
File metadata and controls
87 lines (70 loc) · 1.82 KB
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
package mmbot
import (
"fmt"
"regexp"
"github.com/yukithm/mmbot/message"
)
// Handler is a message handler.
type Handler interface {
CanHandle(*message.InMessage) bool
Handle(*message.InMessage) error
}
// HandlerAction is a function that process a message.
type HandlerAction func(*message.InMessage) error
// PatternHandler is a pattern matching handler.
type PatternHandler struct {
MessageType message.Type
Pattern *regexp.Regexp
Action HandlerAction
}
// CanHandle returns true if the handler can process the message.
func (h PatternHandler) CanHandle(msg *message.InMessage) bool {
_, ok := h.matchPattern(msg)
return ok
}
// Handle processes a message.
func (h PatternHandler) Handle(msg *message.InMessage) error {
matches, ok := h.matchPattern(msg)
if !ok {
return fmt.Errorf("Cannot handle message: %#v", msg)
}
msg.Matches = matches
if err := h.Action(msg); err != nil {
return err
}
return nil
}
func (h PatternHandler) matchPattern(msg *message.InMessage) ([]string, bool) {
if !h.matchMessageType(msg.Type) {
return nil, false
}
if msg.Type == message.MentionMessage {
mentionName := msg.MentionName()
if mentionName != msg.Sender.SenderName() {
return nil, false
}
}
text := msg.Text
if msg.Type == message.MentionMessage {
text = msg.MentionlessText()
}
matches := h.Pattern.FindStringSubmatch(text)
if matches == nil {
return nil, false
}
return matches, true
}
func (h PatternHandler) matchMessageType(t message.Type) bool {
if h.MessageType == 0 {
return true
}
return t&h.MessageType != 0
}
func (h PatternHandler) trimBotName(text string, name string) string {
pattern := fmt.Sprintf(`\A@?(?:%s)\s*[:,]?\s+`, regexp.QuoteMeta(name))
re := regexp.MustCompile(pattern)
if loc := re.FindStringIndex(text); loc != nil {
return text[loc[1]:]
}
return text
}