-
Notifications
You must be signed in to change notification settings - Fork 911
/
xkcd.go
121 lines (102 loc) · 2.56 KB
/
xkcd.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
package xkcd
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"github.com/jonas747/dcmd/v3"
"github.com/jonas747/discordgo"
"github.com/jonas747/yagpdb/commands"
)
type Xkcd struct {
Month string
Num int64
Link string
Year string
News string
SafeTitle string
Transcript string
Alt string
Img string
Title string
Day string
}
var XkcdHost = "https://xkcd.com/"
var XkcdJson = "info.0.json"
var Command = &commands.YAGCommand{
CmdCategory: commands.CategoryFun,
Name: "Xkcd",
Description: "An xkcd comic, by default returns random comic strip",
Arguments: []*dcmd.ArgDef{
{Name: "Comic-number", Type: dcmd.Int},
},
ArgSwitches: []*dcmd.ArgDef{
{Name: "l", Help: "Latest comic"},
},
SlashCommandEnabled: true,
DefaultEnabled: true,
RunFunc: func(data *dcmd.Data) (interface{}, error) {
//first query to get latest number
latest := false
xkcd, err := getComic()
if err != nil {
return "Something happened whilst getting the comic!", err
}
xkcdNum := rand.Int63n(xkcd.Num) + 1
//latest comic strip flag, already got that data
if data.Switches["l"].Value != nil && data.Switches["l"].Value.(bool) {
latest = true
}
//specific comic strip number
if data.Args[0].Value != nil {
n := data.Args[0].Int64()
if n >= 1 && n <= xkcd.Num {
xkcdNum = n
} else {
return fmt.Sprintf("There's no comic numbered %d, current range is 1-%d", n, xkcd.Num), nil
}
}
//if no latest flag is set, fetches a comic by number
if !latest {
xkcd, err = getComic(xkcdNum)
if err != nil {
return "Something happened whilst getting the comic!", err
}
}
embed := &discordgo.MessageEmbed{
Title: fmt.Sprintf("#%d: %s", xkcd.Num, xkcd.Title),
Description: fmt.Sprintf("[%s](%s%d/)", xkcd.Alt, XkcdHost, xkcd.Num),
Color: int(rand.Int63n(16777215)),
Image: &discordgo.MessageEmbedImage{
URL: xkcd.Img,
},
}
return embed, nil
},
}
func getComic(number ...int64) (*Xkcd, error) {
xkcd := Xkcd{}
queryUrl := XkcdHost + XkcdJson
if len(number) >= 1 {
queryUrl = fmt.Sprintf(XkcdHost+"%d/"+XkcdJson, number[0])
}
req, err := http.NewRequest("GET", queryUrl, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "curl/7.65.1")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
queryErr := json.Unmarshal(body, &xkcd)
if queryErr != nil {
return nil, queryErr
}
return &xkcd, nil
}