-
Notifications
You must be signed in to change notification settings - Fork 921
/
advice.go
78 lines (64 loc) · 1.54 KB
/
advice.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
package advice
import (
"encoding/json"
"net/http"
"net/url"
"github.com/jonas747/dcmd"
"github.com/jonas747/yagpdb/commands"
)
var Command = &commands.YAGCommand{
Cooldown: 5,
CmdCategory: commands.CategoryFun,
Name: "Advice",
Description: "Don't be afraid to ask for advice!",
Arguments: []*dcmd.ArgDef{
&dcmd.ArgDef{Name: "What", Type: dcmd.String},
},
RunFunc: func(data *dcmd.Data) (interface{}, error) {
//return "The API this command used has been shut down :(", nil
random := true
addr := "http://api.adviceslip.com/advice"
if data.Args[0].Str() != "" {
random = false
addr = "http://api.adviceslip.com/advice/search/" + url.QueryEscape(data.Args[0].Str())
}
resp, err := http.Get(addr)
if err != nil {
return nil, err
}
var decoded interface{}
if random {
decoded = &RandomAdviceResp{}
} else {
decoded = &SearchAdviceResp{}
}
err = json.NewDecoder(resp.Body).Decode(&decoded)
if err != nil {
return err, err
}
advice := "No advice found :'("
if random {
slip := decoded.(*RandomAdviceResp).Slip
if slip != nil {
advice = slip.Advice
}
} else {
cast := decoded.(*SearchAdviceResp)
if len(cast.Slips) > 0 {
advice = cast.Slips[0].Advice
}
}
return advice, nil
},
}
type AdviceSlip struct {
Advice string `json:"advice"`
ID string `json:"slip_id"`
}
type RandomAdviceResp struct {
Slip *AdviceSlip `json:"slip"`
}
type SearchAdviceResp struct {
TotalResults json.Number `json:"total_results"`
Slips []*AdviceSlip `json:"slips"`
}