all repos — honk @ 44171e9dfbec511dff779d0367eae635725f48ee

my fork of honk

toys/autobonker.go (view raw)

  1package main
  2
  3import (
  4	"encoding/json"
  5	"flag"
  6	"fmt"
  7	"io/ioutil"
  8	"log"
  9	"net/http"
 10	"net/url"
 11	"os"
 12	"strings"
 13	"time"
 14)
 15
 16type Honk struct {
 17	ID     int
 18	XID    string
 19	Honker string
 20}
 21
 22type HonkSet struct {
 23	Honks []Honk
 24}
 25
 26func gethonks(server, token string, wanted int) HonkSet {
 27	form := make(url.Values)
 28	form.Add("action", "gethonks")
 29	form.Add("page", "atme")
 30	form.Add("after", fmt.Sprintf("%d", wanted))
 31	form.Add("wait", "30")
 32	apiurl := fmt.Sprintf("https://%s/api?%s", server, form.Encode())
 33	req, err := http.NewRequest("GET", apiurl, nil)
 34	if err != nil {
 35		log.Fatal(err)
 36	}
 37	req.Header.Add("Authorization", "Bearer "+token)
 38	resp, err := http.DefaultClient.Do(req)
 39	if err != nil {
 40		log.Fatal(err)
 41	}
 42	defer resp.Body.Close()
 43	if resp.StatusCode != 200 {
 44		if resp.StatusCode == 502 {
 45			log.Printf("server error 502...")
 46			time.Sleep(5 * time.Minute)
 47			return HonkSet{}
 48		}
 49		answer, _ := ioutil.ReadAll(resp.Body)
 50		log.Fatalf("status: %d: %s", resp.StatusCode, answer)
 51	}
 52	var honks HonkSet
 53	d := json.NewDecoder(resp.Body)
 54	err = d.Decode(&honks)
 55	if err != nil {
 56		log.Fatal(err)
 57	}
 58	return honks
 59}
 60
 61func bonk(server, token string, honk Honk) {
 62	log.Printf("bonking %s from %s", honk.XID, honk.Honker)
 63	form := make(url.Values)
 64	form.Add("action", "zonkit")
 65	form.Add("wherefore", "bonk")
 66	form.Add("what", honk.XID)
 67	apiurl := fmt.Sprintf("https://%s/api", server)
 68	req, err := http.NewRequest("POST", apiurl, strings.NewReader(form.Encode()))
 69	if err != nil {
 70		log.Fatal(err)
 71	}
 72	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
 73	req.Header.Add("Authorization", "Bearer "+token)
 74	resp, err := http.DefaultClient.Do(req)
 75	if err != nil {
 76		log.Fatal(err)
 77	}
 78	defer resp.Body.Close()
 79	if resp.StatusCode != 200 {
 80		answer, _ := ioutil.ReadAll(resp.Body)
 81		log.Fatalf("status: %d: %s", resp.StatusCode, answer)
 82	}
 83}
 84
 85func main() {
 86	server := ""
 87	token := ""
 88	flag.StringVar(&server, "server", server, "server to connnect")
 89	flag.StringVar(&token, "token", token, "auth token to use")
 90	flag.Parse()
 91
 92	if server == "" || token == "" {
 93		flag.Usage()
 94		os.Exit(1)
 95	}
 96
 97	wanted := 0
 98
 99	for {
100		honks := gethonks(server, token, wanted)
101		for i, h := range honks.Honks {
102			bonk(server, token, h)
103			if i > 0 {
104				time.Sleep(3 * time.Second)
105			}
106			if wanted < h.ID {
107				wanted = h.ID
108			}
109
110		}
111		time.Sleep(3 * time.Second)
112	}
113}