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

89 lines
2.1 KiB
Go

package main
import (
"flag"
"io/ioutil"
"log"
"math/rand"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/hamcha/clessy/tg"
)
const KYMURL = "http://knowyourmeme.com/memes/it-s-finally-a-friday/photos/page/2"
const Search = "data-src=\"([^\"]*)masonry([^\"]*)\""
func assert(err error) {
if err != nil {
panic(err)
}
}
func main() {
brokerAddr := flag.String("broker", "localhost:7314", "Broker address:port")
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()
resp, err := http.Get(KYMURL)
assert(err)
log.Println("Got KYM page")
data, err := ioutil.ReadAll(resp.Body)
assert(err)
resp.Body.Close()
r := regexp.MustCompile(Search)
urls := r.FindAllString(string(data), -1)
// 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 {
imgindex := rand.Int() % urlcount
chosen := urls[imgindex]
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")
}