changed redditbooru function to async function

This commit is contained in:
2020-06-06 20:20:16 -05:00
parent 545591700a
commit 110c1c472f
2 changed files with 39 additions and 25 deletions

View File

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

View File

@@ -1,5 +1,5 @@
/* /*
This contains our functions used for image searches" This contains our functions used for image searches
*/ */
package main package main
@@ -29,35 +29,45 @@ func getArrayLen(value []byte) (int, error) {
} }
// redditbooru request // redditbooru request
func get_redditbooru_image(sub string) string{ func get_redditbooru_image(sub string) <-chan string{
// create the proper url with the subreddit // make the channel
url := "https://" + sub + ".redditbooru.com/images/?limit=1000" ret := make(chan string)
// set 5 second timeout on request go func() {
client := http.Client { defer close(ret)
Timeout: 5 * time.Second,
}
// get the content of the page // create the proper url with the subreddit
resp, err := client.Get(url) url := "https://" + sub + ".redditbooru.com/images/?limit=1000"
defer resp.Body.Close()
// read response // set 5 second timeout on request
out, err := ioutil.ReadAll(resp.Body) client := http.Client {
if err != nil { Timeout: 5 * time.Second,
panic(err) }
}
// randomize the seed // get the content of the page
rand.Seed(time.Now().UnixNano()) resp, err := client.Get(url)
defer resp.Body.Close()
// get a random number for the image // read response
outlen,err := getArrayLen(out) out, err := ioutil.ReadAll(resp.Body)
random_img := rand.Intn(outlen) if err != nil {
panic(err)
}
// select a random url from our list // randomize the seed
img_url,err := jsonparser.GetString(out, "[" + strconv.Itoa(random_img) + "]", "cdnUrl") rand.Seed(time.Now().UnixNano())
return img_url // get a random number for the image
outlen,err := getArrayLen(out)
random_img := rand.Intn(outlen)
// select a random url from our list
img_url,err := jsonparser.GetString(out, "[" + strconv.Itoa(random_img) + "]", "cdnUrl")
// set the return value
ret <- img_url
}()
return ret
} }