Restructure

This commit is contained in:
2024-10-29 09:06:41 -04:00
parent da832d5923
commit 20668d2754
4 changed files with 2 additions and 2 deletions

41
internal/bot/bot.go Normal file
View File

@ -0,0 +1,41 @@
package bot
import (
"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)
}
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
}
func commandHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
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)
}
}

3
internal/bot/handlers.go Normal file
View File

@ -0,0 +1,3 @@
package bot
// I'll use this eventually

View File

@ -0,0 +1,61 @@
package clients
import (
"discord-cfb-bot/config"
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
const seasonStartDate = "2024-08-28"
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"`
}
func getCurrentWeek() int {
startDate, _ := time.Parse("2006-01-02", seasonStartDate)
weeks := int(time.Since(startDate).Hours() / (24 * 7))
return weeks + 1
}
func GetGameInfo(teamName string) string {
currentWeek := getCurrentWeek()
encodedTeamName := url.QueryEscape(teamName)
url := fmt.Sprintf("https://api.collegefootballdata.com/games?year=%d&week=%d&team=%s", time.Now().Year(), currentWeek, encodedTeamName)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer "+config.CFBDAPIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error fetching data:", err)
return "Error fetching game info."
}
defer resp.Body.Close()
var games []Game
if err := json.NewDecoder(resp.Body).Decode(&games); err != nil {
fmt.Println("Error decoding response:", err)
return "Error parsing game data."
}
for _, game := range games {
startTime, _ := time.Parse(time.RFC3339, game.StartDateTime)
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, startTime.Format("03:04 PM"))
}
}
return "No recent or upcoming game data found."
}