From e161be6a38a6e5c2df0c0d694882f0714fce88f2 Mon Sep 17 00:00:00 2001 From: Daniel Tam Date: Wed, 3 Jun 2020 20:18:01 -0500 Subject: [PATCH] created redditbooru request --- bunnybot.go | 15 +++++++++++++++ func-images.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 bunnybot.go create mode 100644 func-images.go diff --git a/bunnybot.go b/bunnybot.go new file mode 100644 index 0000000..6c2bda1 --- /dev/null +++ b/bunnybot.go @@ -0,0 +1,15 @@ +package main + +import ( + //"flag" + "fmt" + //"os" + //"os/signal" + //"syscall" + + //"github.com/bwmarrin/discordgo" +) + +func main() { + fmt.Println(get_redditbooru("awwnime")) +} diff --git a/func-images.go b/func-images.go new file mode 100644 index 0000000..5b97915 --- /dev/null +++ b/func-images.go @@ -0,0 +1,44 @@ +package main + +import ( + "io/ioutil" + "net/http" + "encoding/json" + "time" + "math/rand" +) + +func get_redditbooru(sub string) string{ + // create the proper url with the subreddit + url := "https://" + sub + ".redditbooru.com/images/?limit=1000" + + // set 5 second timeout on request + client := http.Client { + Timeout: 5 * time.Second, + } + + // get the content of the page + resp, err := client.Get(url) + + defer resp.Body.Close() + + // read html as slice of bytes + out, err := ioutil.ReadAll(resp.Body) + if err != nil { + panic(err) + } + + // convert output to string + jsonout := string(out) + + // convert to proper json + var results []map[string] interface {} + json.Unmarshal([]byte(jsonout), &results) + + // randomize the seed + rand.Seed(time.Now().UnixNano()) + + // select a random image to return + return results[rand.Intn(len(results))]["cdnUrl"].(string) +} +