diff --git a/bunnybot.go b/bunnybot.go index 40c86c1..f80cbef 100644 --- a/bunnybot.go +++ b/bunnybot.go @@ -64,7 +64,7 @@ func message_create (s *discordgo.Session, m *discordgo.MessageCreate) { // awwnime (test) if message == "awwnime" { // get url - url := <-get_imgur_image("awwnime") + url := <-get_subreddit_image("awwnime") // print message with url s.ChannelMessageSend(m.ChannelID, url) diff --git a/func-images.go b/func-images.go index 27fdcc5..304deda 100644 --- a/func-images.go +++ b/func-images.go @@ -51,7 +51,7 @@ func get_redditbooru_image(sub string) <-chan string{ // read response out, err := ioutil.ReadAll(resp.Body) if err != nil { - panic(err) + fmt.Println("Error reading response from redditbooru, ", err) } // randomize the seed for the random int @@ -116,5 +116,59 @@ func get_imgur_image(sub string) <-chan string { }() return ret - +} + +// subreddit request +func get_subreddit_image(sub string) <-chan string { + ret := make(chan string) + + go func() { + defer close(ret) + + // create the proper url with the subreddit + url := "https://www.reddit.com/r/" + sub + "/.json?show=all&limit=100" + + // set 5 second timeout on request + client := http.Client { + Timeout: 5 * time.Second, + } + + req, err := http.NewRequest("GET", url, nil) + req.Header.Add("User-Agent", "BunnyBot") + + // get the content of the page + resp, err := client.Do(req) + defer resp.Body.Close() + + // read response + out, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Println("Error reading response from reddit, ", err) + } + + // randomize the seed for the random int + rand.Seed(time.Now().UnixNano()) + + // make sure we aren't grabbing a text post by cylcing through looking for an image + limit64, _ := jsonparser.GetInt(out, "data", "dist") + limit := int(limit64) // convert from int64 to int + + // loop through and try to find a post that isn't a text post + for i := 0; i < limit; i++ { + // get a random number + random_img := rand.Intn(limit) + + // check the post hint to see what type of post it is + hint, _ := jsonparser.GetString(out, "data", "children", "[" + strconv.Itoa(random_img) + "]", "data", "post_hint") + + // make sure that it is an image, or at least a gif + if hint == "image" || hint == "link" || hint == "rich:video" { + image, _ := jsonparser.GetString(out, "data", "children", "[" + strconv.Itoa(random_img) + "]", "data", "url") + ret <- image + break + } + } + }() + + return ret }