-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
65 lines (54 loc) · 1.51 KB
/
bot.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
package miyanbor
import (
"time"
cache "github.com/patrickmn/go-cache"
"github.com/sirupsen/logrus"
telegramAPI "gopkg.in/telegram-bot-api.v4"
)
// Bot contains API functions and params to contact Telegram servers.
type Bot struct {
*telegramAPI.BotAPI
updateConfig telegramAPI.UpdateConfig
updateChannel telegramAPI.UpdatesChannel
Timeout int
}
// NewBot creates new instance of Bot struct, also creates BotAPI using token.
func NewBot(token string, verboseLogging bool, sessionTimeout int) (*Bot, error) {
if verboseLogging {
logrus.SetLevel(logrus.DebugLevel)
} else {
logrus.SetLevel(logrus.ErrorLevel)
}
var err error
telegramBot := &Bot{}
telegramBot.BotAPI, err = telegramAPI.NewBotAPI(token)
if err != nil {
return nil, err
}
usersSessionCache = cache.New(time.Duration(sessionTimeout)*time.Minute,
time.Duration(sessionTimeout)*time.Minute)
return telegramBot, nil
}
// StartUpdater initializes updater channel.
func (b *Bot) StartUpdater(offset, timeout int) error {
// Create update config
b.updateConfig = telegramAPI.NewUpdate(offset)
b.updateConfig.Timeout = timeout
// Init update channel
var err error
b.updateChannel, err = b.GetUpdatesChan(b.updateConfig)
if err != nil {
return err
}
// Get updates
for update := range b.updateChannel {
logrus.Infof("new update")
go func(update telegramAPI.Update) {
startTime := time.Now()
b.handleNewUpdate(&update)
logrus.WithField("took", time.Since(startTime)).
Infof("update handled!")
}(update)
}
return nil
}