nechotron/dispatcher.go

59 lines
1.2 KiB
Go

package nechotron
import (
"strings"
)
type dispatchHandler func(u *Update) (bool, error)
type updateHandler func(u *Update) error
type commandHandler func(u *UpdateCommand) error
type Dispatcher struct {
handlers []dispatchHandler
}
func NewDispatcher() *Dispatcher {
return &Dispatcher{}
}
func (d *Dispatcher) Run(u *Update) error {
for _, h := range d.handlers {
executed, err := h(u)
if executed {
return err
}
}
return nil
}
func (d *Dispatcher) HandleCommand(command *Command, handler commandHandler) *Dispatcher {
newHandler := func(u *Update) (bool, error) {
if !strings.HasPrefix(u.Text(), command.String()) {
return false, nil
}
if command.IsAdminOnly && !u.IsUserAdmin() && u.ChatID() < 0 {
return false, nil
}
upd := &UpdateCommand{
Update: *u,
Param: command.Param(u.Text()),
}
err := handler(upd)
return true, err
}
d.handlers = append(d.handlers, newHandler)
return d
}
func (d *Dispatcher) HandleFilter(filter FilterFn, handler updateHandler) *Dispatcher {
newHandler := func(u *Update) (bool, error) {
if !filter(u) {
return false, nil
}
err := handler(u)
return true, err
}
d.handlers = append(d.handlers, newHandler)
return d
}