-
Notifications
You must be signed in to change notification settings - Fork 0
/
today.go
82 lines (69 loc) · 1.72 KB
/
today.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"time"
"github.com/go-joe/joe"
)
const todayStoreKey string = "today.cache"
type TodayCache struct {
Key string `json:"key"`
Cache OnThisDay `json:"cache"`
}
type OnThisDay struct {
Wikipedia string `json:"wikipedia"`
Date string `json:"date"`
Events []OnThisDayEvent `json:"events"`
}
type OnThisDayEvent struct {
Year string `json:"year"`
Description string `json:"description"`
Wikipedia []OnThisDayLink `json:"wikipedia"`
}
type OnThisDayLink struct {
Title string `json:"title"`
Wikipedia string `json:"wikipedia"`
}
func Today(msg joe.Message) error {
t := time.Now()
urlDate := fmt.Sprintf("%d/%d", int(t.Month()), t.Day())
var cache TodayCache
ok, err := Edi.Store.Get(todayStoreKey, &cache)
if err != nil {
return err
}
var events OnThisDay
if !ok || cache.Key != urlDate {
Edi.Logger.Info("Refreshing today cache data")
url := fmt.Sprintf("https://byabbe.se/on-this-day/%s/events.json", urlDate)
res, err := http.Get(url)
if err != nil {
return err
}
defer res.Body.Close()
content, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
err = json.Unmarshal(content, &events)
if err != nil {
return err
}
cache = TodayCache{
Key: urlDate,
Cache: events,
}
Edi.Store.Set(todayStoreKey, cache)
} else {
Edi.Logger.Info("Pulled data from cache")
events = cache.Cache
}
gen := rand.New(rand.NewSource(time.Now().UnixNano()))
randEvent := events.Events[gen.Intn(len(events.Events)-1)]
output := fmt.Sprintf("On this day in %s: %s", randEvent.Year, randEvent.Description)
msg.Respond(output)
return nil
}