/
messenger.go
90 lines (73 loc) · 1.96 KB
/
messenger.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package telegram
import (
"log"
"time"
"github.com/baor/ah-helper-bot/domain"
tlg "github.com/go-telegram-bot-api/telegram-bot-api"
)
// Messenger is an inteface which describes basic messenger functionality
type Messenger interface {
Send(m domain.Message)
}
// MessageProcessor is a function to process updates in telegram chat
type MessageProcessor func(msg domain.Message)
// tlgMessenger is an adapter for telegram bot functionality
type tlgMessenger struct {
botAPI *tlg.BotAPI
updatesCh tlg.UpdatesChannel
messageProcessor MessageProcessor
}
// NewMessenger is a constructor
func NewMessenger(token string, messageProcessor MessageProcessor, delay time.Duration) Messenger {
var err error
if token == "" {
log.Println("Warning! Token is empty! Return nil adapter")
return nil
}
a := tlgMessenger{}
a.botAPI, err = tlg.NewBotAPI(token)
if err != nil {
log.Panic(err)
}
a.botAPI.Debug = false
log.Printf("Telegram bot authorized on account %s", a.botAPI.Self.UserName)
u := tlg.NewUpdate(0)
u.Timeout = 60
a.updatesCh, err = a.botAPI.GetUpdatesChan(u)
if err != nil {
log.Panic(err)
}
a.messageProcessor = messageProcessor
go a.updatesListener(delay)
return &a
}
// Send will send a Chattable item to Telegram.
//
// It requires the Chattable to send.
func (a *tlgMessenger) Send(m domain.Message) {
botMsg := tlg.NewMessage(int64(m.ChatID), m.Text)
botMsg.ParseMode = "Markdown"
log.Printf("Send message: %+v", botMsg)
_, err := a.botAPI.Send(botMsg)
if err != nil {
log.Panic(err)
}
}
func (a *tlgMessenger) updatesListener(delay time.Duration) {
for {
select {
case u := <-a.updatesCh:
if u.Message == nil || u.Message.Chat == nil || len(u.Message.Text) == 0 {
continue
}
message := domain.Message{
ChatID: domain.ChatID(u.Message.Chat.ID),
Text: u.Message.Text,
}
log.Printf("Messenger received message: %+v", message)
a.messageProcessor(message)
default:
time.Sleep(delay)
}
}
}