add global tf2 player stats

This commit is contained in:
2024-05-01 14:13:36 +02:00
parent f54f59437e
commit 1f62882cec

41
main.go
View File

@@ -4,15 +4,25 @@ import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"github.com/influxdata/line-protocol/v2/lineprotocol"
log "github.com/sirupsen/logrus"
"hash/fnv" "hash/fnv"
"io"
"net/http"
"os/exec" "os/exec"
"strings" "strings"
"time" "time"
"unicode" "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 { type TF2Stat struct {
Name string `json:"name"` Name string `json:"name"`
Map string `json:"map"` Map string `json:"map"`
@@ -53,6 +63,29 @@ func main() {
tServer = append(tServer, TF2Server(strings.TrimSpace(srv))) 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 { for _, ip := range tServer {
tStat, err := ip.Stats() tStat, err := ip.Stats()
if err != nil { if err != nil {
@@ -77,7 +110,7 @@ func main() {
// hash map to convert it to int // hash map to convert it to int
h := fnv.New32a() h := fnv.New32a()
h.Write([]byte(tStat.Map)) _, _ = h.Write([]byte(tStat.Map))
enc.AddField("map", lineprotocol.UintValue(uint64(h.Sum32()))) enc.AddField("map", lineprotocol.UintValue(uint64(h.Sum32())))
enc.EndLine(time.Now()) enc.EndLine(time.Now())
@@ -86,7 +119,7 @@ func main() {
} }
func (ip TF2Server) Stats() (*TF2Stat, error) { 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() bOut, err := cmd.CombinedOutput()
if err != nil { if err != nil {
return nil, err return nil, err