friday: Use KYM instead of Bing Images

This commit is contained in:
Hamcha 2016-09-09 17:25:19 +02:00
parent 3b3fbbac26
commit fd3e2b081c

View file

@ -1,32 +1,20 @@
package main package main
import ( import (
"encoding/json"
"flag" "flag"
"io/ioutil" "io/ioutil"
"log" "log"
"math/rand" "math/rand"
"net/http" "net/http"
"regexp"
"strconv" "strconv"
"strings" "strings"
"time"
"github.com/hamcha/clessy/tg" "github.com/hamcha/clessy/tg"
) )
const APIUrl = "https://api.datamarket.azure.com/Bing/Search/v1/Image?$format=json&Query=%27jojo%20bizarre%20adventure%20friday%20know%20your%20meme%27" const KYMURL = "http://knowyourmeme.com/memes/it-s-finally-a-friday/photos/page/2"
const Search = "data-src=\"([^\"]*)masonry([^\"]*)\""
type BingAPISearchResult struct {
MediaUrl string
}
type BingAPIResponseData struct {
Results []BingAPISearchResult `json:"results"`
}
type BingAPIResponse struct {
Data BingAPIResponseData `json:"d"`
}
func assert(err error) { func assert(err error) {
if err != nil { if err != nil {
@ -36,7 +24,6 @@ func assert(err error) {
func main() { func main() {
brokerAddr := flag.String("broker", "localhost:7314", "Broker address:port") brokerAddr := flag.String("broker", "localhost:7314", "Broker address:port")
apiKey := flag.String("apiKey", "", "Bing Search API key")
chatId := flag.Int64("chatId", -1001063099772, "Chat to write to") chatId := flag.Int64("chatId", -1001063099772, "Chat to write to")
flag.Parse() flag.Parse()
@ -45,26 +32,27 @@ func main() {
log.Println("Connected to broker") log.Println("Connected to broker")
defer broker.Close() defer broker.Close()
req, err := http.NewRequest("GET", APIUrl, nil) resp, err := http.Get(KYMURL)
assert(err) assert(err)
req.SetBasicAuth(*apiKey, *apiKey) log.Println("Got KYM page")
resp, err := http.DefaultClient.Do(req)
assert(err)
log.Println("Connecting to Bing API")
var body BingAPIResponse data, err := ioutil.ReadAll(resp.Body)
err = json.NewDecoder(resp.Body).Decode(&body) assert(err)
resp.Body.Close() resp.Body.Close()
assert(err)
log.Println("Successfully obtained JSON of miracles")
images := body.Data.Results r := regexp.MustCompile(Search)
imgcount := len(body.Data.Results) urls := r.FindAllString(string(data), -1)
rand.Seed(time.Now().Unix()) // Process urls
for i := range urls {
// Take out prefix/suffix and get original instead of thumb
urls[i] = strings.Replace(urls[i][10:len(urls[i])-1], "masonry", "original", 1)
}
urlcount := len(urls)
for attempt := 0; attempt < 10; attempt += 1 { for attempt := 0; attempt < 10; attempt += 1 {
imgindex := rand.Int() % imgcount imgindex := rand.Int() % urlcount
chosen := images[imgindex].MediaUrl chosen := urls[imgindex]
log.Println("Trying " + chosen) log.Println("Trying " + chosen)
resp, err := http.Get(chosen) resp, err := http.Get(chosen)