twitchapon

[Twi]tch [Cha]nnel [Po]ints Rewards Redemption Listener
git clone git://bsandro.tech/twitchapon
Log | Files | Refs | README | LICENSE

client.go (1418B)


      1 package main
      2 
      3 import (
      4 	"fmt"
      5 	"golang.org/x/net/websocket"
      6 	"log"
      7 	"net/http"
      8 )
      9 
     10 type TMessage struct {
     11 	Type string `json:"type"`
     12 	Data struct {
     13 		Topic   string `json:"topic"`
     14 		Message string `json:"message"`
     15 	} `json:"data"`
     16 }
     17 
     18 var App TApp
     19 
     20 func ListenJob() {
     21 	for App.Connection != nil {
     22 		var msg TMessage
     23 		if err := websocket.JSON.Receive(App.Connection, &msg); err != nil {
     24 			log.Fatal(err)
     25 		}
     26 		// ignore PING and RESPONSE for now
     27 		if msg.Type != "MESSAGE" {
     28 			continue
     29 		}
     30 		if resp, err := http.Get(App.Config.AnimServer); err == nil {
     31 			resp.Body.Close()
     32 		} else {
     33 			fmt.Println("Error while making the query to the animation service")
     34 		}
     35 	}
     36 
     37 	App.WaitGroup.Done()
     38 }
     39 
     40 func CloseConn() {
     41 	if App.Connection != nil {
     42 		App.Connection.Close()
     43 		App.Connection = nil
     44 	}
     45 }
     46 
     47 func main() {
     48 	const code_request_url string = "https://id.twitch.tv/oauth2/authorize?client_id=%s&redirect_uri=http%%3A%%2F%%2F%s&response_type=code&scope=channel:read:redemptions\n"
     49 
     50 	err := App.InitConfig()
     51 	if err != nil {
     52 		log.Fatal(err)
     53 	}
     54 
     55 	fmt.Printf(code_request_url, App.Config.ClientId, App.Config.LocalServer)
     56 
     57 	url := fmt.Sprintf("wss://%s:%s/", App.Config.WssServer, App.Config.WssPort)
     58 	App.Connection, err = websocket.Dial(url, "", App.Config.WssOrigin)
     59 	if err != nil {
     60 		log.Fatal(err)
     61 	}
     62 	defer CloseConn()
     63 
     64 	App.WaitGroup.Add(3)
     65 	go ListenJob()
     66 	go PingJob()
     67 	go LocalServerJob()
     68 
     69 	App.WaitGroup.Wait()
     70 }