66 lines
1.2 KiB
Go
66 lines
1.2 KiB
Go
package discord
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io/ioutil"
|
|
"net/http"
|
|
)
|
|
|
|
const (
|
|
dadJokeAPI = "https://icanhazdadjoke.com/"
|
|
dadJokeErr = "Could not get a Dad joke. :slight_frown:"
|
|
)
|
|
|
|
type dadJoke struct {
|
|
ID string `json:"id"`
|
|
Joke string `json:"joke"`
|
|
Status int `json:"status"`
|
|
}
|
|
|
|
func init() {
|
|
commands = append(commands, &command{
|
|
name: "dad",
|
|
validate: func(cmd commandInit) bool {
|
|
return true
|
|
},
|
|
run: func(cmd commandInit) (string, error) {
|
|
if !memeRateLimit.Try() {
|
|
return "", nil
|
|
}
|
|
|
|
req, err := http.NewRequest(http.MethodGet, dadJokeAPI, nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Header.Add("Accept", "application/json")
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return dadJokeErr, nil
|
|
}
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
var dj dadJoke
|
|
if err := json.Unmarshal(body, &dj); err != nil {
|
|
return "", nil
|
|
}
|
|
|
|
// Check status again, in case API returned an error
|
|
if dj.Status != http.StatusOK {
|
|
return dadJokeErr, nil
|
|
}
|
|
|
|
return dj.Joke, nil
|
|
},
|
|
help: "Get a random Dad joke",
|
|
})
|
|
}
|