2023-05-06 21:37:21 +02:00
|
|
|
package commands
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"github.com/lyx0/nourybot-matrix/internal/common"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
type xkcdResponse struct {
|
|
|
|
Num int `json:"num"`
|
|
|
|
SafeTitle string `json:"safe_title"`
|
|
|
|
Img string `json:"img"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func Xkcd() (string, error) {
|
|
|
|
response, err := http.Get("https://xkcd.com/info.0.json")
|
|
|
|
if err != nil {
|
2023-05-06 22:30:53 +02:00
|
|
|
return "", ErrInternalServerError
|
2023-05-06 21:37:21 +02:00
|
|
|
}
|
|
|
|
responseData, err := io.ReadAll(response.Body)
|
|
|
|
if err != nil {
|
2023-05-06 22:30:53 +02:00
|
|
|
return "", ErrInternalServerError
|
2023-05-06 21:37:21 +02:00
|
|
|
}
|
|
|
|
var responseObject xkcdResponse
|
|
|
|
if err = json.Unmarshal(responseData, &responseObject); err != nil {
|
2023-05-06 22:30:53 +02:00
|
|
|
return "", ErrInternalServerError
|
2023-05-06 21:37:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
reply := fmt.Sprint("Current Xkcd #", responseObject.Num, " Title: ", responseObject.SafeTitle, " ", responseObject.Img)
|
|
|
|
|
|
|
|
return reply, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func RandomXkcd() (string, error) {
|
|
|
|
comicNum := fmt.Sprint(common.GenerateRandomNumber(2772))
|
|
|
|
|
|
|
|
response, err := http.Get(fmt.Sprint("http://xkcd.com/" + comicNum + "/info.0.json"))
|
|
|
|
if err != nil {
|
2023-05-06 22:30:53 +02:00
|
|
|
return "", ErrInternalServerError
|
2023-05-06 21:37:21 +02:00
|
|
|
}
|
|
|
|
responseData, err := io.ReadAll(response.Body)
|
|
|
|
if err != nil {
|
2023-05-06 22:30:53 +02:00
|
|
|
return "", ErrInternalServerError
|
2023-05-06 21:37:21 +02:00
|
|
|
}
|
|
|
|
var responseObject xkcdResponse
|
|
|
|
if err = json.Unmarshal(responseData, &responseObject); err != nil {
|
2023-05-06 22:30:53 +02:00
|
|
|
return "", ErrInternalServerError
|
2023-05-06 21:37:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
reply := fmt.Sprint("Random Xkcd #", responseObject.Num, " Title: ", responseObject.SafeTitle, " ", responseObject.Img)
|
|
|
|
|
|
|
|
return reply, nil
|
|
|
|
}
|