Phase 1 MVP — echo bot factory
All checks were successful
Docker Build / build-and-push-image (push) Successful in 1m8s
All checks were successful
Docker Build / build-and-push-image (push) Successful in 1m8s
This commit is contained in:
75
handlers.go
Normal file
75
handlers.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Handler interface {
|
||||
Handle(ctx context.Context, update Update, bot Bot) error
|
||||
}
|
||||
|
||||
type Bot struct {
|
||||
Slug string
|
||||
Token string
|
||||
Secret string
|
||||
Handler Handler
|
||||
}
|
||||
|
||||
type Registry struct {
|
||||
bots map[string]Bot
|
||||
}
|
||||
|
||||
func NewRegistry(cfg *Config) (*Registry, error) {
|
||||
if len(cfg.Bots) == 0 {
|
||||
return nil, fmt.Errorf("no bots configured")
|
||||
}
|
||||
|
||||
tg := NewTelegramClient()
|
||||
bots := make(map[string]Bot, len(cfg.Bots))
|
||||
|
||||
for slug, b := range cfg.Bots {
|
||||
token := b.Token
|
||||
secret := b.Secret
|
||||
if token == "" {
|
||||
return nil, fmt.Errorf("bot %s: token missing", slug)
|
||||
}
|
||||
if secret == "" {
|
||||
return nil, fmt.Errorf("bot %s: secret missing", slug)
|
||||
}
|
||||
|
||||
var h Handler
|
||||
switch b.Handler {
|
||||
case "echo":
|
||||
h = &EchoHandler{tg: tg}
|
||||
case "":
|
||||
return nil, fmt.Errorf("bot %s: handler missing", slug)
|
||||
default:
|
||||
return nil, fmt.Errorf("bot %s: unknown handler %q", slug, b.Handler)
|
||||
}
|
||||
|
||||
bots[slug] = Bot{
|
||||
Slug: slug,
|
||||
Token: token,
|
||||
Secret: secret,
|
||||
Handler: h,
|
||||
}
|
||||
}
|
||||
|
||||
return &Registry{bots: bots}, nil
|
||||
}
|
||||
|
||||
func (r *Registry) Get(slug string) (Bot, bool) {
|
||||
b, ok := r.bots[slug]
|
||||
return b, ok
|
||||
}
|
||||
|
||||
func (r *Registry) Count() int { return len(r.bots) }
|
||||
|
||||
func (r *Registry) Slugs() []string {
|
||||
out := make([]string, 0, len(r.bots))
|
||||
for s := range r.bots {
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user