added subreddit image request

This commit is contained in:
2020-06-06 22:55:42 -05:00
parent a003083b8b
commit 9b7ca0a125
2 changed files with 57 additions and 3 deletions

View File

@@ -64,7 +64,7 @@ func message_create (s *discordgo.Session, m *discordgo.MessageCreate) {
// awwnime (test) // awwnime (test)
if message == "awwnime" { if message == "awwnime" {
// get url // get url
url := <-get_imgur_image("awwnime") url := <-get_subreddit_image("awwnime")
// print message with url // print message with url
s.ChannelMessageSend(m.ChannelID, url) s.ChannelMessageSend(m.ChannelID, url)

View File

@@ -51,7 +51,7 @@ func get_redditbooru_image(sub string) <-chan string{
// read response // read response
out, err := ioutil.ReadAll(resp.Body) out, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
panic(err) fmt.Println("Error reading response from redditbooru, ", err)
} }
// randomize the seed for the random int // randomize the seed for the random int
@@ -116,5 +116,59 @@ func get_imgur_image(sub string) <-chan string {
}() }()
return ret 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
} }