diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..2e6895d --- /dev/null +++ b/config/config.go @@ -0,0 +1,18 @@ +package config + +import ( + "log" + "os" + + "gopkg.in/yaml.v3" +) + +func Parse(path string, spec interface{}) error { + configData, err := os.ReadFile(path) + if err != nil { + log.Fatal(err) + return err + } + err = yaml.Unmarshal(configData, spec) + return nil +} diff --git a/main.go b/main.go index 21a4270..51d1a90 100644 --- a/main.go +++ b/main.go @@ -2,18 +2,25 @@ package main import ( "log" - "os" "time" - "mechanus.net/pgobot/matcher" - "mechanus.net/pgobot/responder" + "mechanus.net/pgbot/config" + "mechanus.net/pgbot/matcher" + "mechanus.net/pgbot/responder" "gopkg.in/telebot.v4" ) +type ConfigSpec struct { + Token string `yaml:"token"` +} + func main() { + var conf ConfigSpec + config.Parse("config.yml", &conf) + pref := telebot.Settings{ - Token: os.Getenv("TOKEN"), + Token: conf.Token, Poller: &telebot.LongPoller{Timeout: 10 * time.Second}, } diff --git a/matcher/matcher.go b/matcher/matcher.go index f022393..3bd6135 100644 --- a/matcher/matcher.go +++ b/matcher/matcher.go @@ -1,12 +1,16 @@ package matcher import ( - "os" "regexp" - "gopkg.in/yaml.v3" + "mechanus.net/pgbot/config" ) +type tokenSpec struct { + Token string `yaml:"token"` + Regex []string `yaml:"regex"` +} + type Matcher struct { tokens []TokenCompiled } @@ -16,11 +20,11 @@ type TokenCompiled struct { regex []*regexp.Regexp } -func createToken(token string, regexList []string) TokenCompiled { +func createToken(spec tokenSpec) TokenCompiled { result := new(TokenCompiled) - result.token = token - result.regex = make([]*regexp.Regexp, len(regexList)) - for i, regex := range regexList { + result.token = spec.Token + result.regex = make([]*regexp.Regexp, len(spec.Regex)) + for i, regex := range spec.Regex { result.regex[i] = regexp.MustCompile(regex) } return *result @@ -46,22 +50,14 @@ func (m *Matcher) Tokenize(input string) []string { return result } -func InitMatcher(config string) *Matcher { - configData, err := os.ReadFile(config) - if err != nil { - panic(err) - } - var configMap map[string][]string +func InitMatcher(tokenPath string) *Matcher { + var list []tokenSpec + _ = config.Parse(tokenPath, &list) - err = yaml.Unmarshal(configData, &configMap) - if err != nil { - panic(err) - } + tokens := make([]TokenCompiled, 0, len(list)) - tokens := make([]TokenCompiled, 0, len(configMap)) - - for k, v := range configMap { - tokensCompiled := createToken(k, v) + for _, spec := range list { + tokensCompiled := createToken(spec) tokens = append(tokens, tokensCompiled) } result := new(Matcher) diff --git a/responder/responder.go b/responder/responder.go index d3f0376..a91b792 100644 --- a/responder/responder.go +++ b/responder/responder.go @@ -3,7 +3,7 @@ package responder import ( "strings" - "mechanus.net/pgobot/matcher" + "mechanus.net/pgbot/matcher" "gopkg.in/telebot.v4" )