From 1f62882cec954825574fa6f9c75ca9a62e5d8197 Mon Sep 17 00:00:00 2001 From: Giovanni Harting <539@idlegandalf.com> Date: Wed, 1 May 2024 14:13:36 +0200 Subject: [PATCH] add global tf2 player stats --- main.go | 41 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 8609f6b..3f3c804 100644 --- a/main.go +++ b/main.go @@ -4,15 +4,25 @@ import ( "encoding/json" "flag" "fmt" - "github.com/influxdata/line-protocol/v2/lineprotocol" - log "github.com/sirupsen/logrus" "hash/fnv" + "io" + "net/http" "os/exec" "strings" "time" "unicode" + + "github.com/influxdata/line-protocol/v2/lineprotocol" + log "github.com/sirupsen/logrus" ) +type SteamAPIResponse struct { + Response struct { + PlayerCount int `json:"player_count"` + Result int `json:"result"` + } `json:"response"` +} + type TF2Stat struct { Name string `json:"name"` Map string `json:"map"` @@ -53,6 +63,29 @@ func main() { tServer = append(tServer, TF2Server(strings.TrimSpace(srv))) } + totalStat := new(SteamAPIResponse) + resp, err := http.Get("https://api.steampowered.com/ISteamUserStats/GetNumberOfCurrentPlayers/v1?appid=440") + if err != nil { + log.Debugf("error retrieving tf2 player count: %v", err) + } + defer resp.Body.Close() + bResp, err := io.ReadAll(resp.Body) + if err != nil { + log.Debugf("error reading tf2 player count response: %v", err) + } + err = json.Unmarshal(bResp, &totalStat) + if err != nil { + log.Debugf("error parsing tf2 player count response: %v", err) + } + + if totalStat != nil { + var globalEnc lineprotocol.Encoder + globalEnc.StartLine("tf2stats") + globalEnc.AddField("players", lineprotocol.IntValue(int64(totalStat.Response.PlayerCount))) + globalEnc.EndLine(time.Now()) + fmt.Print(string(globalEnc.Bytes())) + } + for _, ip := range tServer { tStat, err := ip.Stats() if err != nil { @@ -77,7 +110,7 @@ func main() { // hash map to convert it to int h := fnv.New32a() - h.Write([]byte(tStat.Map)) + _, _ = h.Write([]byte(tStat.Map)) enc.AddField("map", lineprotocol.UintValue(uint64(h.Sum32()))) enc.EndLine(time.Now()) @@ -86,7 +119,7 @@ func main() { } func (ip TF2Server) Stats() (*TF2Stat, error) { - cmd := exec.Command("gamedig", "--type", "teamfortress2", string(ip)) + cmd := exec.Command("gamedig", "--type", "teamfortress2", string(ip)) //nolint:gosec bOut, err := cmd.CombinedOutput() if err != nil { return nil, err