twitchapon

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

user.go (1583B)


      1 package main
      2 
      3 import (
      4 	"encoding/json"
      5 	"errors"
      6 	"fmt"
      7 	"io"
      8 	"net/http"
      9 )
     10 
     11 const users_request_url string = "https://api.twitch.tv/helix/users?login=%s"
     12 
     13 type TUser struct {
     14 	Id              string `json:"id"`
     15 	BroadcasterType string `json:"broadcaster_type"`
     16 	Name            string `json:"display_name"`
     17 	Login           string `json:"login"`
     18 	Description     string `json:"description"`
     19 	OfflineImageUrl string `json:"offline_image_url"`
     20 	ProfileIMageUrl string `json:"profile_image_url"`
     21 	UserType        string `json:"type"`
     22 	ViewCount       int    `json:"view_count"`
     23 	CreatedAt       string `json:"created_at"`
     24 }
     25 
     26 type TUsersResponse struct {
     27 	Data []TUser `json:"data"`
     28 }
     29 
     30 func getUser(user_name string, user *TUser) error {
     31 	client := &http.Client{}
     32 	request, err := http.NewRequest("GET", fmt.Sprintf(users_request_url, user_name), nil)
     33 	if err != nil {
     34 		return err
     35 	}
     36 	request.Header.Add("Client-Id", App.Config.ClientId)
     37 	request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", App.Auth.AccessToken))
     38 	response, err := client.Do(request)
     39 	if err != nil {
     40 		return err
     41 	}
     42 	defer response.Body.Close()
     43 	body, err := io.ReadAll(response.Body)
     44 	if err != nil {
     45 		return err
     46 	}
     47 
     48 	var users TUsersResponse
     49 	if err := json.Unmarshal(body, &users); err != nil {
     50 		return err
     51 	}
     52 	if len(users.Data) == 0 {
     53 		return errors.New("getUser(): no users returned")
     54 	}
     55 	*user = users.Data[0]
     56 
     57 	return nil
     58 }
     59 
     60 func (user *TUser) Init() error {
     61 	err := getUser(App.Config.UserName, user)
     62 	return err
     63 }
     64 
     65 func (user *TUser) IsInited() bool {
     66 	return user != nil && len(user.Id) > 0
     67 }