Add actual support for live scores.
This commit is contained in:
parent
b5f343e19c
commit
801396923b
@ -1,41 +1,41 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"discord-cfb-bot/config"
|
||||
"discord-cfb-bot/internal/clients"
|
||||
"github.com/bwmarrin/discordgo"
|
||||
"fmt"
|
||||
"strings"
|
||||
"discord-cfb-bot/config"
|
||||
"discord-cfb-bot/internal/clients"
|
||||
"github.com/bwmarrin/discordgo"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var Bot *discordgo.Session
|
||||
|
||||
func Start() error {
|
||||
var err error
|
||||
Bot, err = discordgo.New("Bot " + config.BotToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating a Discord session: %w", err)
|
||||
}
|
||||
var err error
|
||||
Bot, err = discordgo.New("Bot " + config.BotToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating a Discord session: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("Discord session created successfully")
|
||||
fmt.Println("Discord session created successfully")
|
||||
|
||||
Bot.AddHandler(commandHandler)
|
||||
err = Bot.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error opening connection: %w", err)
|
||||
}
|
||||
fmt.Println("Bot is now running.")
|
||||
return nil
|
||||
Bot.AddHandler(commandHandler)
|
||||
err = Bot.Open()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error opening connection: %w", err)
|
||||
}
|
||||
fmt.Println("Bot is now running.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func commandHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
|
||||
if m.Author.Bot {
|
||||
return
|
||||
}
|
||||
if m.Author.Bot {
|
||||
return
|
||||
}
|
||||
|
||||
if strings.HasPrefix(m.Content, "!s ") {
|
||||
teamName := strings.TrimSpace(strings.TrimPrefix(m.Content, "!s "))
|
||||
response := clients.GetGameInfo(teamName)
|
||||
s.ChannelMessageSend(m.ChannelID, response)
|
||||
}
|
||||
if strings.HasPrefix(m.Content, "!s ") {
|
||||
teamName := strings.TrimSpace(strings.TrimPrefix(m.Content, "!s "))
|
||||
response := clients.GetGameInfo(teamName)
|
||||
s.ChannelMessageSend(m.ChannelID, response)
|
||||
}
|
||||
}
|
||||
|
@ -1,115 +1,93 @@
|
||||
package cfbd_client
|
||||
package clients
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"discord-cfb-bot/config"
|
||||
)
|
||||
|
||||
type Game struct {
|
||||
HomeTeam string `json:"home_team"`
|
||||
AwayTeam string `json:"away_team"`
|
||||
HomePoints *int `json:"home_points"`
|
||||
AwayPoints *int `json:"away_points"`
|
||||
StartDateTime string `json:"start_date"`
|
||||
ID int `json:"id"`
|
||||
StartDate string `json:"startDate"`
|
||||
Status string `json:"status"`
|
||||
Period *int `json:"period"`
|
||||
Clock *string `json:"clock"`
|
||||
HomeTeam Team `json:"homeTeam"`
|
||||
AwayTeam Team `json:"awayTeam"`
|
||||
}
|
||||
|
||||
type ScoreboardGame struct {
|
||||
HomeTeam string `json:"home_team"`
|
||||
AwayTeam string `json:"away_team"`
|
||||
HomePoints *int `json:"home_points"`
|
||||
AwayPoints *int `json:"away_points"`
|
||||
StartDateTime string `json:"start_date"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func getCurrentWeek() int {
|
||||
seasonStartDate := "2024-08-28" // Replace with actual season start date
|
||||
startDate, _ := time.Parse("2006-01-02", seasonStartDate)
|
||||
weeks := int(time.Since(startDate).Hours() / (24 * 7))
|
||||
return weeks + 1
|
||||
}
|
||||
|
||||
func getLiveGame(teamName string) string {
|
||||
url := "https://api.collegefootballdata.com/scoreboard"
|
||||
currentWeek := getCurrentWeek()
|
||||
params := fmt.Sprintf("?year=%d&week=%d", time.Now().Year(), currentWeek)
|
||||
|
||||
req, _ := http.NewRequest("GET", url+params, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+config.CFBDAPIKey)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
fmt.Println("Error fetching data from scoreboard API:", err)
|
||||
return "Error fetching live game data."
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var games []ScoreboardGame
|
||||
if err := json.NewDecoder(resp.Body).Decode(&games); err != nil {
|
||||
fmt.Println("Error decoding scoreboard response:", err)
|
||||
return "Error parsing live game data."
|
||||
}
|
||||
|
||||
for _, game := range games {
|
||||
if game.Status == "in_progress" && (game.HomeTeam == teamName || game.AwayTeam == teamName) {
|
||||
return fmt.Sprintf("Live: %s: %d %s: %d", game.AwayTeam, *game.AwayPoints, game.HomeTeam, *game.HomePoints)
|
||||
}
|
||||
}
|
||||
|
||||
return "No live games found for the team."
|
||||
type Team struct {
|
||||
Name string `json:"name"`
|
||||
Points *int `json:"points"`
|
||||
}
|
||||
|
||||
func GetGameInfo(teamName string) string {
|
||||
apiUrl := "https://api.collegefootballdata.com/games"
|
||||
currentWeek := getCurrentWeek()
|
||||
queryParams := fmt.Sprintf("?year=%d&week=%d&team=%s", time.Now().Year(), currentWeek, url.QueryEscape(teamName))
|
||||
|
||||
req, _ := http.NewRequest("GET", apiUrl+queryParams, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+config.CFBDAPIKey)
|
||||
apiURL := "https://apinext.collegefootballdata.com/scoreboard"
|
||||
req, _ := http.NewRequest("GET", apiURL, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+config.CFBDAPIKey) // Use the API key from config
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
fmt.Println("Error fetching data:", err)
|
||||
return "Error fetching game info."
|
||||
return fmt.Sprintf("Failed to reach the scoreboard API: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Sprintf("Failed to reach the scoreboard API. Status code: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
|
||||
var games []Game
|
||||
if err := json.NewDecoder(resp.Body).Decode(&games); err != nil {
|
||||
fmt.Println("Error decoding response:", err)
|
||||
return "Error parsing game data."
|
||||
if err := json.Unmarshal(body, &games); err != nil {
|
||||
return "Error parsing the API response."
|
||||
}
|
||||
|
||||
for _, game := range games {
|
||||
startTime, _ := time.Parse(time.RFC3339, game.StartDateTime)
|
||||
if strings.Contains(strings.ToLower(game.HomeTeam.Name), strings.ToLower(teamName)) ||
|
||||
strings.Contains(strings.ToLower(game.AwayTeam.Name), strings.ToLower(teamName)) {
|
||||
|
||||
// Load Eastern Time location
|
||||
eastern, err := time.LoadLocation("America/New_York")
|
||||
if err != nil {
|
||||
fmt.Println("Error loading Eastern timezone:", err)
|
||||
return "Error fetching game time."
|
||||
}
|
||||
startTimeEastern := startTime.In(eastern)
|
||||
startTime, _ := time.Parse(time.RFC3339, game.StartDate)
|
||||
adjustedTime := startTime.Add(-5 * time.Hour) // Subtract 5 hours for upcoming games
|
||||
formattedTime := adjustedTime.Format("03:04 PM")
|
||||
|
||||
if time.Now().After(startTime) && game.HomePoints != nil && game.AwayPoints != nil {
|
||||
return fmt.Sprintf("%s: %d %s: %d", game.AwayTeam, *game.AwayPoints, game.HomeTeam, *game.HomePoints)
|
||||
} else if time.Now().Before(startTime) {
|
||||
return fmt.Sprintf("%s @ %s %s Eastern", game.AwayTeam, game.HomeTeam, startTimeEastern.Format("03:04 PM"))
|
||||
if game.Status == "in_progress" {
|
||||
return fmt.Sprintf("%s: **%d** %s: **%d** | Quarter: %d | Time Remaining: %s",
|
||||
game.AwayTeam.Name, valueOrZero(game.AwayTeam.Points),
|
||||
game.HomeTeam.Name, valueOrZero(game.HomeTeam.Points),
|
||||
*game.Period, derefOrDefault(game.Clock, "00:00"))
|
||||
} else if game.Status == "scheduled" {
|
||||
return fmt.Sprintf("Upcoming: %s @ %s at %s Eastern",
|
||||
game.AwayTeam.Name, game.HomeTeam.Name, formattedTime)
|
||||
} else if game.Status == "completed" {
|
||||
return fmt.Sprintf("Final: %s: %d %s: %d",
|
||||
game.AwayTeam.Name, valueOrZero(game.AwayTeam.Points),
|
||||
game.HomeTeam.Name, valueOrZero(game.HomeTeam.Points))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Call the getLiveGame function if no specific game is found
|
||||
liveGameResult := getLiveGame(teamName)
|
||||
if liveGameResult != "No live games found for the team." {
|
||||
return liveGameResult
|
||||
}
|
||||
|
||||
return "No recent, upcoming, or live games found for the team."
|
||||
return "No game found for the specified team."
|
||||
}
|
||||
|
||||
// Helper function to safely dereference pointers
|
||||
func derefOrDefault(str *string, defaultVal string) string {
|
||||
if str != nil {
|
||||
return *str
|
||||
}
|
||||
return defaultVal
|
||||
}
|
||||
|
||||
// Helper function to return a value or zero if nil
|
||||
func valueOrZero(val *int) int {
|
||||
if val != nil {
|
||||
return *val
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user