-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate_loop.go
More file actions
90 lines (81 loc) · 2.41 KB
/
Copy pathupdate_loop.go
File metadata and controls
90 lines (81 loc) · 2.41 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
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 main
import (
"fmt"
"log"
"time"
"github.com/minya/erc/erclib"
"github.com/minya/ercInfoBot/model"
"github.com/minya/telegram"
)
type notifier struct {
sleepDuration time.Duration
storage model.UserStorage
botToken string
}
func (n notifier) Start(api *telegram.Api) {
go n.updateLoop(api)
}
func (n notifier) updateLoop(api *telegram.Api) {
for true {
log.Printf("Update...\n")
subsMap, err := n.storage.GetUsers()
if err != nil {
log.Printf("Error: %v\n", err)
} else {
for id, userInfo := range subsMap {
log.Printf("[Update] Check user %v\n", id)
for accountNum, sub := range userInfo.Subscriptions {
ercClient := erclib.NewErcClientWithCredentials(userInfo.Login, userInfo.Password)
accounts, err := ercClient.GetAccounts()
if err != nil {
log.Printf("WARN No accounts")
continue
}
account, err := findAccount(accounts, accountNum)
if err != nil {
log.Printf("WARN No account %v among accounts", accountNum)
continue
}
n.compareAndNotify(api, id, account, sub, userInfo, ercClient)
}
}
}
time.Sleep(n.sleepDuration)
}
}
func (n notifier) compareAndNotify(
api *telegram.Api, userID int, account erclib.Account, sub model.SubscriptionInfo, userInfo model.UserInfo, ercClient erclib.ErcClient) {
if sub.ChatID == 0 {
log.Printf("[Update] User %v is not subscribed. Skip.\n", userID)
return
}
balanceInfo, err := ercClient.GetBalanceInfo(account.Number, time.Now())
if err != nil {
log.Printf("[Update] Error: can't get balance for user %v\n", userID)
return
}
newState := fmt.Sprintf("%v", balanceInfo)
if sub.LastSeenState == "" {
sub.LastSeenState = newState
userInfo.Subscriptions[account.Number] = sub
n.storage.SaveUser(userID, userInfo)
log.Printf("[Update] Initial balance correction for user %v\n", userID)
} else if sub.LastSeenState != newState {
log.Printf("[Update] Balance changed for user %v\n", userID)
sub.LastSeenState = newState
userInfo.Subscriptions[account.Number] = sub
n.storage.SaveUser(userID, userInfo)
messageText := "Баланс обновился:\n" + formatBalance(account, balanceInfo)
msg := telegram.ReplyMessage{
ChatId: sub.ChatID,
Text: messageText,
ReplyMarkup: replyButtons(),
}
err = api.SendMessage(msg)
if err != nil {
fmt.Printf("%v\n", err)
}
} else {
log.Printf("[Update] Balance hasn't been changed\n")
}
}