switched to third party json parser, jsonpaser

This commit is contained in:
2020-06-06 04:29:32 -05:00
parent dc0ca7b469
commit ede07b71ce
2 changed files with 36 additions and 17 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" {
s.ChannelMessageSend(m.ChannelID, get_redditbooru("awwnime")) s.ChannelMessageSend(m.ChannelID, get_redditbooru_image("awwnime"))
} }
//get_redditbooru("awwnime") //get_redditbooru("awwnime")

View File

@@ -1,17 +1,38 @@
/*
This contains our functions used for image searches"
*/
package main package main
import ( import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"encoding/json"
"time" "time"
"math/rand" "math/rand"
"fmt"
"strconv"
"github.com/buger/jsonparser"
) )
func get_redditbooru(sub string) string{ // get the length of array for our parser
func getArrayLen(value []byte) (int, error) {
ret := 0
arrayCallback := func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
ret++
}
if _, err := jsonparser.ArrayEach(value, arrayCallback); err != nil {
return 0, fmt.Errorf("getArrayLen ArrayEach error: %v", err)
}
return ret, nil
}
// redditbooru request
func get_redditbooru_image(sub string) string{
// create the proper url with the subreddit // create the proper url with the subreddit
url := "https://" + sub + ".redditbooru.com/images/?limit=1000" url := "https://" + sub + ".redditbooru.com/images/?limit=1000"
// set 5 second timeout on request // set 5 second timeout on request
client := http.Client { client := http.Client {
Timeout: 5 * time.Second, Timeout: 5 * time.Second,
@@ -19,26 +40,24 @@ func get_redditbooru(sub string) string{
// get the content of the page // get the content of the page
resp, err := client.Get(url) resp, err := client.Get(url)
defer resp.Body.Close() defer resp.Body.Close()
// read html as slice of bytes // read response
out, err := ioutil.ReadAll(resp.Body) out, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
panic(err) 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 // randomize the seed
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UnixNano())
// select a random image to return
return results[rand.Intn(len(results))]["cdnUrl"].(string)
}
// 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")
return img_url
}