-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.go
More file actions
60 lines (49 loc) · 1.23 KB
/
bot.go
File metadata and controls
60 lines (49 loc) · 1.23 KB
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
package botty
import (
"strings"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
type Bot struct {
botApi *tgbotapi.BotAPI
defaultHandler Handler
messageHandlers map[string]Handler
}
func (b *Bot) Start(timeout int) (err error) {
u := tgbotapi.NewUpdate(0)
u.Timeout = timeout
updates, err := b.botApi.GetUpdatesChan(u)
messageChan := make(chan Message)
for update := range updates {
if update.Message == nil {
continue
}
for msg, handler := range b.messageHandlers {
if strings.ToLower(update.Message.Text) == msg {
go handler(MessageIn(*update.Message), messageChan)
} else {
go b.defaultHandler(MessageIn(*update.Message), messageChan)
}
message := <-messageChan
if _, err := b.botApi.Send(message.Config); err != nil {
return err
}
}
}
return nil
}
func (b *Bot) AddMessageHandler(msgReq string, handler Handler) {
b.messageHandlers[strings.ToLower(msgReq)] = handler
}
func (b *Bot) DefaultHandler(handler Handler) {
b.defaultHandler = handler
}
func NewBot(apiKey string) (Bot, error) {
botApi, err := tgbotapi.NewBotAPI(apiKey)
if err != nil {
return Bot{}, err
}
return Bot{
messageHandlers: make(map[string]Handler),
botApi: botApi,
}, nil
}