From 4e81567338e281d757d29979efd9b699b301e0c4 Mon Sep 17 00:00:00 2001 From: Daniel Tam Date: Sat, 6 Jun 2020 21:13:55 -0500 Subject: [PATCH] working on imgur function --- bunnybot.go | 2 +- func-images.go | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/bunnybot.go b/bunnybot.go index 715bcc4..40c86c1 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_redditbooru_image("awwnime") + url := <-get_imgur_image("awwnime") // print message with url s.ChannelMessageSend(m.ChannelID, url) diff --git a/func-images.go b/func-images.go index bf779b6..27fdcc5 100644 --- a/func-images.go +++ b/func-images.go @@ -54,7 +54,7 @@ func get_redditbooru_image(sub string) <-chan string{ panic(err) } - // randomize the seed + // randomize the seed for the random int rand.Seed(time.Now().UnixNano()) // get a random number for the image @@ -69,5 +69,52 @@ func get_redditbooru_image(sub string) <-chan string{ }() return ret +} + +// imgur request +func get_imgur_image(sub string) <-chan string { + // make channel + ret := make(chan string) + + go func() { + defer close(ret) + + // create the proper url with the subreddit + url := "https://api.imgur.com/3/gallery/r/" + sub + "/time/1" + + // set 5 second timeout on request + client := http.Client { + Timeout: 5 * time.Second, + } + + // create the request + req, err := http.NewRequest("GET", url, nil) + req.Header.Add("Authorization", "Client-ID " + auth.imgur) + + // 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 { + panic(err) + } + + // randomize the seed for the random int + rand.Seed(time.Now().UnixNano()) + + // get a random number for the image + //outlen, _ := getArrayLen(out) + //random_img := rand.Intn(outlen) + + // parse the data (fix this) + img_url, _ := jsonparser.GetString(out, "[0]", "[0]", "link") + fmt.Println(string(img_url)) + + ret <- "" + }() + + return ret }