-
Notifications
You must be signed in to change notification settings - Fork 0
/
matcher.go
107 lines (84 loc) · 1.96 KB
/
matcher.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
package matcher
import (
"fmt"
"regexp"
"strings"
logger "github.com/br0-space/bot-logger"
telegramclient "github.com/br0-space/bot-telegramclient"
"github.com/spf13/viper"
)
type Matcher struct {
log logger.Interface
identifier string
regexp *regexp.Regexp
help []HelpStruct
cfg *Config
}
type Config struct {
enabled *bool
}
func MakeMatcher(
identifier string,
pattern *regexp.Regexp,
help []HelpStruct,
) Matcher {
return Matcher{
log: logger.New(),
identifier: identifier,
regexp: pattern,
help: help,
cfg: nil,
}
}
func (m Matcher) WithConfig(cfg *Config) Matcher {
m.cfg = cfg
return m
}
func (m Matcher) IsEnabled() bool {
if m.cfg == nil || m.cfg.enabled == nil {
return true
}
return *m.cfg.enabled
}
func (m Matcher) Identifier() string {
return m.identifier
}
func (m Matcher) Help() []HelpStruct {
return m.help
}
func (m Matcher) DoesMatch(messageIn telegramclient.WebhookMessageStruct) bool {
return m.regexp.MatchString(messageIn.TextOrCaption())
}
func (m Matcher) CommandMatch(messageIn telegramclient.WebhookMessageStruct) []string {
match := m.regexp.FindStringSubmatch(messageIn.TextOrCaption())
if match == nil {
return nil
}
if len(match) > 0 {
return match[1:]
}
return match
}
func (m Matcher) InlineMatches(messageIn telegramclient.WebhookMessageStruct) []string {
matches := m.regexp.FindAllString(messageIn.TextOrCaption(), -1)
if matches == nil {
return []string{}
}
for i, match := range matches {
matches[i] = strings.TrimSpace(match)
}
return matches
}
func (m Matcher) HandleError(_ telegramclient.WebhookMessageStruct, identifier string, err error) {
m.log.Error(identifier, err.Error())
}
func LoadMatcherConfig(identifier string, cfg interface{}) {
v := viper.New()
v.SetConfigFile(fmt.Sprintf("config/%s.yaml", identifier))
if err := v.ReadInConfig(); err != nil {
panic(err)
}
if err := v.Unmarshal(cfg); err != nil {
panic(err)
}
}