From 184e0452437df58695f5b73fe465cf4aef3028d3 Mon Sep 17 00:00:00 2001 From: Daniel Tam Date: Tue, 9 Jun 2020 14:01:47 -0500 Subject: [PATCH] set up list for redditbooru subreddits --- bunnybot.go | 4 ++++ images.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/bunnybot.go b/bunnybot.go index f80cbef..6474581 100644 --- a/bunnybot.go +++ b/bunnybot.go @@ -12,11 +12,15 @@ import ( var ( auth Auth + redditbooru_sources []string ) func init() { // build the authentication struct buildAuth() + + // build the redditbooru sources slice + build_redditbooru_sources() } func main() { diff --git a/images.go b/images.go index 80e7908..1529a91 100644 --- a/images.go +++ b/images.go @@ -11,6 +11,7 @@ import ( "math/rand" "fmt" "strconv" + "strings" "github.com/buger/jsonparser" ) @@ -28,6 +29,62 @@ func getArrayLen(value []byte) (int, error) { return ret, nil } +// get the length of object for our parser +func getObjectLen(value []byte) (int, error) { + ret := 0 + objectCallback := func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error { + ret++ + return nil + } + + if err := jsonparser.ObjectEach(value, objectCallback); err != nil { + return 0, fmt.Errorf("getObjectLen ObjectEach error: %v", err) + } + + return ret, nil +} + +// build our sources list for redditbooru +func build_redditbooru_sources() { + // the url for the sources from redditbooru + url := "https://redditbooru.com/sources/" + + // set 5 second timeout on request + client := http.Client { + Timeout: 5 * time.Second, + } + + // get the content of the page + resp, err := client.Get(url) + if err != nil { + fmt.Print("Error getting redditbooru sources, ") + panic(err) + } + defer resp.Body.Close() + + // read response + out, err := ioutil.ReadAll(resp.Body) + if err != nil { + fmt.Print("Error reading response from redditbooru, ") + panic(err) + } + + // get the length of the sources + outlen, err := getArrayLen(out) + + // set our slice to the appropriate size + redditbooru_sources = make([]string, outlen) + + // set our sources into the slice + for i := 0; i < outlen; i++ { + // pull out the title + title,_ := jsonparser.GetString(out, "[" + strconv.Itoa(i) + "]", "title") + + // set to lowercase then into our slice + redditbooru_sources[i] = strings.ToLower(title) + } +} + // redditbooru request func get_redditbooru_image(sub string) <-chan string{ // make the channel