Rewrite for new API

This commit is contained in:
Kevin Thompson
2024-11-10 17:23:41 -06:00
parent 801396923b
commit 856e1b1cbd
5 changed files with 113 additions and 126 deletions

81
internal/clients/cfb.go Normal file
View File

@ -0,0 +1,81 @@
package cfb
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
)
// Game represents the structure of a single game
type Game struct {
AwayTeam string `json:"away_team"`
AwayScore string `json:"away_score"`
HomeTeam string `json:"home_team"`
HomeScore string `json:"home_score"`
GameState string `json:"game_state"`
CurrentPeriod string `json:"current_period"`
StartTime string `json:"start_time"`
ContestClock string `json:"contest_clock"`
StartTimeEpoch int64 `json:"start_time_epoch"`
}
// FetchScoreboard retrieves and parses the scoreboard data from the specified API URL
func FetchScoreboard(weekNumber int) ([]Game, error) {
apiKey := os.Getenv("CFBD_API_KEY")
if apiKey == "" {
return nil, errors.New("missing API key")
}
url := fmt.Sprintf("https://ncaa.ewnix.net/scoreboard/football/fbs/2024/%d/all-conf", weekNumber)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch scoreboard, status code: %d", resp.StatusCode)
}
body, _ := ioutil.ReadAll(resp.Body)
var data struct {
Games []struct {
Game Game `json:"game"`
} `json:"games"`
}
if err := json.Unmarshal(body, &data); err != nil {
return nil, fmt.Errorf("error parsing scoreboard: %w", err)
}
games := make([]Game, len(data.Games))
for i, g := range data.Games {
// Adjust start time by subtracting 5 hours for upcoming games
if g.Game.GameState == "upcoming" {
epochTime := time.Unix(g.Game.StartTimeEpoch, 0).Add(-5 * time.Hour)
g.Game.StartTime = epochTime.Format("03:04PM ET")
}
games[i] = g.Game
}
return games, nil
}
// FormatGameOutput formats the game data into a string
func FormatGameOutput(game Game) string {
if game.GameState == "live" {
return fmt.Sprintf("%s: *%s* %s: *%s* Quarter: %s Time Remaining: %s",
game.AwayTeam, game.AwayScore, game.HomeTeam, game.HomeScore, game.CurrentPeriod, game.ContestClock)
}
return fmt.Sprintf("%s: %s %s: %s Final",
game.AwayTeam, game.AwayScore, game.HomeTeam, game.HomeScore)
}