forked from go-telegram/bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
128 lines (99 loc) · 2.21 KB
/
handlers.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package bot
import (
"regexp"
"strings"
"github.com/go-telegram/bot/models"
)
type HandlerType int
const (
HandlerTypeMessageText HandlerType = iota
HandlerTypeCallbackQueryData
)
type MatchType int
const (
MatchTypeExact MatchType = iota
MatchTypePrefix
MatchTypeContains
matchTypeRegexp
matchTypeFunc
)
type handler struct {
handlerType HandlerType
matchType MatchType
handler HandlerFunc
pattern string
re *regexp.Regexp
matchFunc MatchFunc
}
func (h handler) match(update *models.Update) bool {
if h.matchType == matchTypeFunc {
return h.matchFunc(update)
}
var data string
switch h.handlerType {
case HandlerTypeMessageText:
if update.Message != nil {
data = update.Message.Text
}
case HandlerTypeCallbackQueryData:
if update.CallbackQuery != nil {
data = update.CallbackQuery.Data
}
}
if h.matchType == MatchTypeExact {
return data == h.pattern
}
if h.matchType == MatchTypePrefix {
return strings.HasPrefix(data, h.pattern)
}
if h.matchType == MatchTypeContains {
return strings.Contains(data, h.pattern)
}
if h.matchType == matchTypeRegexp {
return h.re.Match([]byte(data))
}
return false
}
func (b *Bot) RegisterHandlerMatchFunc(matchFunc MatchFunc, f HandlerFunc) string {
b.handlersMx.Lock()
defer b.handlersMx.Unlock()
id := RandomString(16)
h := handler{
matchType: matchTypeFunc,
matchFunc: matchFunc,
handler: f,
}
b.handlers[id] = h
return id
}
func (b *Bot) RegisterHandlerRegexp(handlerType HandlerType, re *regexp.Regexp, f HandlerFunc) string {
b.handlersMx.Lock()
defer b.handlersMx.Unlock()
id := RandomString(16)
h := handler{
handlerType: handlerType,
matchType: matchTypeRegexp,
re: re,
handler: f,
}
b.handlers[id] = h
return id
}
func (b *Bot) RegisterHandler(handlerType HandlerType, pattern string, matchType MatchType, f HandlerFunc) string {
b.handlersMx.Lock()
defer b.handlersMx.Unlock()
id := RandomString(16)
h := handler{
handlerType: handlerType,
matchType: matchType,
pattern: pattern,
handler: f,
}
b.handlers[id] = h
return id
}
func (b *Bot) UnregisterHandler(id string) {
b.handlersMx.Lock()
defer b.handlersMx.Unlock()
delete(b.handlers, id)
}