-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
192 lines (150 loc) · 4.27 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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package main
import (
"encoding/json"
"log"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gempir/go-twitch-irc/v2"
"github.com/joho/godotenv"
)
type TokenResponse struct {
AccessToken string `json:"access_token"`
}
type StreamsResponse struct {
Data []Stream `json:"data"`
}
type Stream struct {
UserID string `json:"user_id"`
UserName string `json:"user_name"`
StartedAt string `json:"started_at"`
}
const MINUTE = 60 * time.Second
const HOUR = 60 * MINUTE
var client *twitch.Client
var liveChannels = make(map[string]bool)
var messageQueue = make(map[string]bool)
func main() {
var envs map[string]string
envs, err := godotenv.Read(".env")
godotenv.Load(".env")
// ensure needed envs are set
if envs["TW_OAUTH"] == "" {
log.Fatal("TW_OAUTH not set")
}
if envs["CLIENT_ID"] == "" {
log.Fatal("CLIENT_ID not set")
}
if envs["CLIENT_SECRET"] == "" {
log.Fatal("CLIENT_SECRET not set")
}
if err != nil {
log.Fatal("Error loading .env file")
}
usernames := strings.Split(envs["CHANNELS"], ",")
userQuery := "user_login=" + strings.Join(usernames, "&user_login=")
// Create a new client instance
client = twitch.NewClient(envs["USERNAME"], envs["TW_OAUTH"])
ticker := time.NewTicker(5 * MINUTE)
quit := make(chan struct{})
go func() {
for {
select {
// looping logic
case <-ticker.C:
// fetch and set streams
token := getAccessToken(envs["CLIENT_ID"], envs["CLIENT_SECRET"])
channels := fetchStreams(userQuery, envs["CLIENT_ID"], token)
liveChannels = make(map[string]bool)
for _, channel := range channels {
liveChannels[channel.UserName] = true
if messageQueue[channel.UserName] {
continue // skip if already in queue
}
t, err := time.Parse(time.RFC3339, channel.StartedAt)
if err != nil {
log.Panic("Error parsing time", err)
}
streamTime := time.Since(t)
timeTilReminder := HOUR - (streamTime % HOUR)
hoursLive := math.Ceil(streamTime.Hours())
messageQueue[channel.UserName] = true
time.AfterFunc(timeTilReminder, func() {
sendReminder(channel.UserName, int(hoursLive))
})
}
case <-quit:
ticker.Stop()
return
}
}
}()
client.OnConnect(func() {
log.Println("Successfully connected to Twitch!")
})
// Connect to the Twitch IRC
err = client.Connect()
if err != nil {
panic(err)
}
}
func fetchStreams(users string, clientId string, token string) []Stream {
req, err := http.NewRequest("GET", "https://api.twitch.tv/helix/streams?"+users, nil)
req.Header.Set("Client-ID", clientId)
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Panic("Error fetching streams token", err)
}
defer resp.Body.Close()
data := StreamsResponse{}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
log.Panic("Error unmarshalling json", err)
}
liveChannels = make(map[string]bool)
for _, channel := range data.Data {
liveChannels[channel.UserName] = true
}
return data.Data
}
func sendReminder(channel string, hoursLive int) {
delete(messageQueue, channel) // remove channel from liveChannels
if _, ok := liveChannels[channel]; !ok {
return
}
water := hoursLive * 120
var waterText string
if water >= 1000 {
waterText = strconv.FormatFloat(float64(water)/1000, 'f', 1, 64) + " L"
} else {
waterText = strconv.Itoa(water) + " mL"
}
var hourString string
if hoursLive == 1 {
hourString = "hour"
} else {
hourString = "hours"
}
message := "You have been live for " + strconv.Itoa(hoursLive) + " " + hourString + " and should have consumed at least " + waterText + " of water to maintain optimal hydration! 💦"
log.Println("Send reminder to " + channel + ", " + strconv.Itoa(hoursLive) + " hour(s) live")
client.Say(channel, message)
}
func getAccessToken(clientId string, clientSecret string) string {
data := url.Values{
"client_id": {clientId},
"client_secret": {clientSecret},
"grant_type": {"client_credentials"},
}
resp, err := http.PostForm("https://id.twitch.tv/oauth2/token", data)
if err != nil {
log.Panic("Error fetching getting access token", err)
}
// TODO: use expires in instead of always getting a new token
res := TokenResponse{}
json.NewDecoder(resp.Body).Decode(&res)
return res.AccessToken
}