forked from profawk/espurnaBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (70 loc) · 1.59 KB
/
main.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
package main
import (
"fmt"
"github.com/profawk/espurnaBot/bot"
"log"
"time"
"github.com/profawk/espurnaBot/api"
"github.com/profawk/espurnaBot/schedule"
tb "gopkg.in/tucnak/telebot.v2"
)
func validateChatIds(upd *tb.Update) bool {
if upd.Message == nil {
return true
}
chatID := upd.Message.Chat.ID
for _, allowedID := range config.ChatIds {
if allowedID == chatID {
return true
}
}
log.Printf("chat ID %d is not in allowed chat ids", chatID)
return false
}
func main() {
a := api.NewAPI(config.Espurna.ApiKey, config.Espurna.Hostname, config.Espurna.Relay)
s := schedule.NewSchedule()
poller := &tb.LongPoller{Timeout: 10 * time.Second}
privateBotPoller := tb.NewMiddlewarePoller(poller, validateChatIds)
b, err := tb.NewBot(tb.Settings{
Token: config.BotToken,
Poller: privateBotPoller,
})
if err != nil {
log.Fatal(err)
return
}
if config.Watchdog {
t := time.NewTicker(1 * time.Minute)
go func() {
for range t.C {
// set LastKnownState to known good value
_, err := a.Status()
// loop until no error
if err == nil {
break
}
log.Print("error while starting watchdog", err, "retrying")
}
for range t.C {
s := a.LastKnownState()
newS, err := a.Status()
if err != nil {
log.Print("error in watchdog", err)
}
if newS == s {
continue
}
for _, chatId := range config.ChatIds {
b.Send(
tb.ChatID(chatId),
fmt.Sprintf("relay state has changed. it is now %s", api.StateNames[newS]),
)
}
}
}()
}
bot.AddTriggers(config.Triggers)
bot.SetHandlers(b, a, s)
b.Start()
}