2020-06-12 17:01:17 +00:00
|
|
|
package discord
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2021-05-14 03:27:39 +00:00
|
|
|
"errors"
|
2020-06-12 17:01:17 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2021-05-14 03:27:39 +00:00
|
|
|
|
|
|
|
"go.jolheiser.com/beaver"
|
2020-06-12 17:01:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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() {
|
2021-02-23 05:53:55 +00:00
|
|
|
commands = append(commands, &command{
|
|
|
|
name: "dad",
|
2020-06-12 17:01:17 +00:00
|
|
|
validate: func(cmd commandInit) bool {
|
|
|
|
return true
|
|
|
|
},
|
|
|
|
run: func(cmd commandInit) (string, error) {
|
2020-07-02 20:00:22 +00:00
|
|
|
if !memeRateLimit.Try() {
|
2020-07-02 21:33:47 +00:00
|
|
|
return "", nil
|
2020-07-02 20:00:22 +00:00
|
|
|
}
|
|
|
|
|
2021-05-14 03:27:39 +00:00
|
|
|
dj, err := newDadJoke()
|
2020-06-12 17:01:17 +00:00
|
|
|
if err != nil {
|
2021-05-14 03:27:39 +00:00
|
|
|
beaver.Warnf("error getting new dad joke: %v", err)
|
2020-06-12 17:01:17 +00:00
|
|
|
return dadJokeErr, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return dj.Joke, nil
|
|
|
|
},
|
|
|
|
help: "Get a random Dad joke",
|
2021-02-23 05:53:55 +00:00
|
|
|
})
|
2020-06-12 17:01:17 +00:00
|
|
|
}
|
2021-05-14 03:27:39 +00:00
|
|
|
|
|
|
|
func newDadJoke() (*dadJoke, error) {
|
|
|
|
req, err := http.NewRequest(http.MethodGet, dadJokeAPI, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
req.Header.Add("Accept", "application/json")
|
|
|
|
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return nil, errors.New("non-ok status")
|
|
|
|
}
|
|
|
|
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var dj *dadJoke
|
|
|
|
if err := json.Unmarshal(body, &dj); err != nil {
|
|
|
|
return nil, errors.New("could not unmarshal")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check status again, in case API returned an error
|
|
|
|
if dj.Status != http.StatusOK {
|
|
|
|
return nil, errors.New("API error")
|
|
|
|
}
|
|
|
|
|
|
|
|
return dj, nil
|
|
|
|
}
|