-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot_listener.go
67 lines (59 loc) · 1.83 KB
/
bot_listener.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
package tgbot
import (
"context"
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type BotListener struct {
BotRunner
handlers map[string]*ListenerFilteredHandler
commands map[string]*ListenerCommandHandler
callbackHandlers map[string]*ListenerCallbackHandler
}
func createBotListener(bot *tgbotapi.BotAPI) *BotListener {
listener := &BotListener{
handlers: make(map[string]*ListenerFilteredHandler),
commands: make(map[string]*ListenerCommandHandler),
callbackHandlers: make(map[string]*ListenerCallbackHandler),
}
listener.Init("BotListener")
return listener
}
func (lst *BotListener) AddHandler(title string, filter func(update tgbotapi.Update) bool, handler func(ctx context.Context, update tgbotapi.Update) error) {
lst.handlers[title] = &ListenerFilteredHandler{
Filter: filter,
Func: handler,
Title: title,
}
}
func (lst *BotListener) AddCommandHandler(title string, command string, handler ListenerHandlerFunc) {
lst.commands[command] = &ListenerCommandHandler{
Command: command,
Func: handler,
Title: title,
}
}
func (lst *BotListener) AddCallbackHandler(title string, filter func(update tgbotapi.Update) bool, handler ListenerHandlerFunc) {
lst.callbackHandlers[title] = &ListenerCallbackHandler{
Filter: filter,
Func: handler,
Title: title,
}
}
func (lst *BotListener) SetupCommandsMessage() (msg tgbotapi.SetMyCommandsConfig, err error) {
if len(lst.commands) == 0 {
err = fmt.Errorf("no commands")
return
}
commands := make([]tgbotapi.BotCommand, len(lst.commands))
index := 0
for name, cmd := range lst.commands {
commands[index] = tgbotapi.BotCommand{
Command: name,
Description: cmd.Title,
}
index++
}
scope := tgbotapi.NewBotCommandScopeDefault()
return tgbotapi.NewSetMyCommandsWithScope(scope, commands...), nil
}