-
Notifications
You must be signed in to change notification settings - Fork 3
/
filters.go
63 lines (56 loc) · 1.51 KB
/
filters.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
package fsm
import (
tele "gopkg.in/telebot.v3"
)
// Filter object. Needs for graceful works with state filters.
type Filter struct {
Endpoint any
States []State
}
// F returns new Filter object.
func F(endpoint any, states ...State) Filter {
if len(states) == 0 {
states = []State{DefaultState}
}
return Filter{Endpoint: endpoint, States: states}
}
// TelebotHandlerForState creates tele.Handler with local filter for given state.
func (m *Manager) TelebotHandlerForState(want State, handler Handler) tele.HandlerFunc {
return m.HandlerAdapter(func(c tele.Context, state Context) error {
s, err := state.State()
if err != nil {
return &ErrHandlerState{Handler: "Manager.ForState", Err: err}
}
if Is(s, want) {
return handler(c, state)
}
return nil
})
}
// TelebotHandlerForStates creates a handler with local filter
// for current state to check for presence in given states.
func (m *Manager) TelebotHandlerForStates(h Handler, states ...State) tele.HandlerFunc {
return m.HandlerAdapter(func(c tele.Context, state Context) error {
s, err := state.State()
if err != nil {
return &ErrHandlerState{Handler: "Manager.ForStates", Err: err}
}
if ContainsState(s, states...) {
return h(c, state)
}
return nil
})
}
func (f Filter) CallbackUnique() string {
return getEndpoint(f.Endpoint)
}
func getEndpoint(e any) string {
switch end := e.(type) {
case string:
return end
case tele.CallbackEndpoint:
return end.CallbackUnique()
default:
panic("fsm: telebot: unsupported endpoint")
}
}