package commands import ( "encoding/json" "io/ioutil" "math/rand" "net/http" "time" helpers "ion606_bot/Bot/Helpers" "github.com/bwmarrin/discordgo" ) var CatfactCommand = &discordgo.ApplicationCommand{ Name: "catfact", Description: "Fetches a random cat fact", } type CatFactAPIResponse struct { Facts []struct { FactNumber int `json:"fact_number"` Fact string `json:"fact"` } `json:"facts"` } func HandleCatfact(s *discordgo.Session, i *discordgo.InteractionCreate) { client := http.Client{ Timeout: 10 * time.Second, } resp, err := client.Get("https://www.catfacts.net/api/") if err != nil { helpers.HandleError(s, i, err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { helpers.HandleError(s, i, err) return } var result CatFactAPIResponse err = json.Unmarshal(body, &result) if err != nil || len(result.Facts) == 0 { helpers.HandleError(s, i, err) return } // Pick a random fact from the array. rand.Seed(time.Now().UnixNano()) randomFact := result.Facts[rand.Intn(len(result.Facts))].Fact s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseChannelMessageWithSource, Data: &discordgo.InteractionResponseData{ Content: randomFact, }, }) }