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

90 lines
2.1 KiB
Go
Raw Normal View History

2016-09-01 12:06:30 +00:00
package main
import (
"flag"
"io/ioutil"
"log"
"math/rand"
"net/http"
2016-09-09 15:25:19 +00:00
"regexp"
2016-09-01 12:06:30 +00:00
"strconv"
"strings"
2018-04-03 10:07:06 +00:00
"github.com/hamcha/tg"
2016-09-01 12:06:30 +00:00
)
2016-09-09 15:25:19 +00:00
const KYMURL = "http://knowyourmeme.com/memes/it-s-finally-a-friday/photos/page/2"
const Search = "data-src=\"([^\"]*)masonry([^\"]*)\""
2016-09-01 12:06:30 +00:00
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()
2016-09-09 15:25:19 +00:00
resp, err := http.Get(KYMURL)
2016-09-01 12:06:30 +00:00
assert(err)
2016-09-09 15:25:19 +00:00
log.Println("Got KYM page")
2016-09-01 12:06:30 +00:00
2016-09-09 15:25:19 +00:00
data, err := ioutil.ReadAll(resp.Body)
2016-09-01 12:06:30 +00:00
assert(err)
2016-09-09 15:25:19 +00:00
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)
}
2016-09-01 12:06:30 +00:00
2016-09-09 15:25:19 +00:00
urlcount := len(urls)
2016-09-01 12:06:30 +00:00
for attempt := 0; attempt < 10; attempt += 1 {
2016-09-09 15:25:19 +00:00
imgindex := rand.Int() % urlcount
chosen := urls[imgindex]
2016-09-01 12:06:30 +00:00
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")
}