-
Notifications
You must be signed in to change notification settings - Fork 30
/
updates.go
106 lines (89 loc) · 2.2 KB
/
updates.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package botgolang
import (
"context"
"fmt"
"time"
dura "github.com/hako/durafmt"
"github.com/sirupsen/logrus"
)
const (
sleepTime = time.Second * 3
)
var (
sleepTimeStr = dura.Parse(sleepTime)
)
type Updater struct {
logger *logrus.Logger
client *Client
lastEventID int
PollTime int
}
// NewMessageFromPart returns new message based on part message
func (u *Updater) NewMessageFromPayload(message EventPayload) *Message {
return &Message{
client: u.client,
ID: message.MsgID,
Chat: Chat{ID: message.From.User.ID, Title: message.From.FirstName},
Text: message.Text,
Timestamp: message.Timestamp,
}
}
func (u *Updater) RunUpdatesCheck(ctx context.Context, ch chan<- Event) {
_, err := u.GetLastEventsWithContext(ctx, 0)
if err != nil {
u.logger.WithFields(logrus.Fields{
"err": err,
}).Debug("cannot make initial request to events")
}
for {
select {
case <-ctx.Done():
close(ch)
return
default:
events, err := u.GetLastEventsWithContext(ctx, u.PollTime)
if err != nil {
u.logger.WithFields(logrus.Fields{
"err": err,
"retry interval": sleepTimeStr,
}).Errorf("Failed to get updates, retrying in %s ...", sleepTimeStr)
time.Sleep(sleepTime)
continue
}
for _, event := range events {
event.client = u.client
event.Payload.client = u.client
ch <- *event
}
}
}
}
func (u *Updater) GetLastEvents(pollTime int) ([]*Event, error) {
return u.GetLastEventsWithContext(context.Background(), pollTime)
}
func (u *Updater) GetLastEventsWithContext(ctx context.Context, pollTime int) ([]*Event, error) {
events, err := u.client.GetEventsWithContext(ctx, u.lastEventID, pollTime)
if err != nil {
u.logger.WithFields(logrus.Fields{
"err": err,
"events": events,
}).Debug("events getting error")
return events, fmt.Errorf("cannot get events: %s", err)
}
count := len(events)
if count > 0 {
u.lastEventID = events[count-1].EventID
}
return events, nil
}
func NewUpdater(client *Client, pollTime int, logger *logrus.Logger) *Updater {
if pollTime == 0 {
pollTime = 60
}
return &Updater{
client: client,
lastEventID: 0,
PollTime: pollTime,
logger: logger,
}
}