This repository has been archived on 2023-07-05. You can view files and clone it, but cannot push or open issues or pull requests.
clessy/friday/main.go

102 lines
2.4 KiB
Go
Raw Normal View History

2016-09-01 12:06:30 +00:00
package main
import (
"encoding/json"
"flag"
"io/ioutil"
"log"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
"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"
type BingAPISearchResult struct {
MediaUrl string
}
type BingAPIResponseData struct {
Results []BingAPISearchResult `json:"results"`
}
type BingAPIResponse struct {
Data BingAPIResponseData `json:"d"`
}
func assert(err error) {
if err != nil {
panic(err)
}
}
func main() {
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")
flag.Parse()
broker, err := tg.ConnectToBroker(*brokerAddr)
assert(err)
log.Println("Connected to broker")
defer broker.Close()
req, err := http.NewRequest("GET", APIUrl, nil)
assert(err)
req.SetBasicAuth(*apiKey, *apiKey)
resp, err := http.DefaultClient.Do(req)
assert(err)
log.Println("Connecting to Bing API")
var body BingAPIResponse
err = json.NewDecoder(resp.Body).Decode(&body)
resp.Body.Close()
assert(err)
log.Println("Successfully obtained JSON of miracles")
images := body.Data.Results
imgcount := len(body.Data.Results)
rand.Seed(time.Now().Unix())
for attempt := 0; attempt < 10; attempt += 1 {
imgindex := rand.Int() % imgcount
chosen := images[imgindex].MediaUrl
log.Println("Trying " + chosen)
resp, err := http.Get(chosen)
if err != nil {
log.Println("Cannot GET url, trying new image")
continue
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Println("Cannot read data, trying new image")
continue
}
log.Println("Read " + strconv.Itoa(len(data)) + " bytes from " + chosen)
ctype := strings.SplitN(resp.Header.Get("Content-Type"), "/", 2)
if len(ctype) < 2 {
log.Println("Cannot read type (" + resp.Header.Get("Content-Type") + "), trying new image")
continue
} else {
// DOES THIS FIX THINGS??
ctype[1] = strings.Replace(ctype[1], "jpeg", "jpg", 1)
}
log.Println("Type is " + ctype[1])
broker.SendPhoto(&tg.APIChat{ChatID: *chatId}, data, "jojo."+ctype[1], "IT IS FRIDAY MY DUDES", nil)
log.Println("Sent SendPhoto request to " + strconv.FormatInt(*chatId, 10))
return
}
log.Fatalln("FRIDAY has failed, too many attemps")
}