add psg commands

This commit is contained in:
unintended fraud
2022-10-19 23:35:36 +02:00
parent 80d2dc9b6f
commit 4716341cc8
3 changed files with 114 additions and 29 deletions
+1
View File
@@ -1 +1,2 @@
env.go env.go
data/
+111 -28
View File
@@ -1,89 +1,174 @@
package commands package commands
import ( import (
"bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log"
"net/http" "net/http"
"os" "os"
"sort"
"time"
tempest "github.com/Amatsagu/Tempest" tempest "github.com/Amatsagu/Tempest"
) )
type Matches []Match
func (m Matches) Len() int {
return len(m)
}
func (m Matches) Less(i int, j int) bool {
return m[i].Fixture.Timestamp < m[j].Fixture.Timestamp
}
func (m Matches) Swap(i int, j int) {
m[i], m[j] = m[j], m[i]
}
const PSG_FILE_PATH = "../data/football/psg_fixtures.json"
const endpoint = "https://v3.football.api-sports.io/fixtures" const endpoint = "https://v3.football.api-sports.io/fixtures"
const authorizedUser = "160073741076922369"
var PsgRefreshFixtures tempest.Command = tempest.Command{ var PsgRefreshFixtures tempest.Command = tempest.Command{
Name: "psg-refresh-fixtures", Name: "psg-refresh-fixtures",
Description: "met à jour les matchs du psg si ça change ou des matchs sont ajoutés (e.g. CL)", Description: "met à jour les matchs du psg si ça change ou des matchs sont ajoutés (e.g. CL)",
Options: []tempest.Option{}, Options: []tempest.Option{},
SlashCommandHandler: func(itx tempest.CommandInteraction) { SlashCommandHandler: func(itx tempest.CommandInteraction) {
if itx.User.Id != 160073741076922369 { if itx.User.Id.String() != authorizedUser {
itx.SendLinearReply("command cannot be used by you :(", true) itx.SendLinearReply("command cannot be used by you :(", true)
return return
} }
client := &http.Client{} client := &http.Client{}
payload := &Payload{ url := fmt.Sprintf("%s?season=2022&team=85&timezone=Europe/Paris", endpoint)
Season: "2022",
Team: "85",
}
payloadBytes, err := json.Marshal(payload) req, err := http.NewRequest("GET", url, nil)
if err != nil {
itx.SendLinearReply(fmt.Sprintf("failed to marshal the payload: %s", err.Error()), true)
return
}
req, err := http.NewRequest("GET", endpoint, bytes.NewReader(payloadBytes))
if err != nil { if err != nil {
itx.SendLinearReply(fmt.Sprintf("failed to create the request: %s", err.Error()), true) itx.SendLinearReply(fmt.Sprintf("failed to create the request: %s", err.Error()), true)
return return
} }
req.Header.Add("x-rapidapi-key", os.Getenv("FOOTBALL_API_KEY")) req.Header.Add("x-rapidapi-key", "a22d9050a0d04cfeb988bffe89854617")
req.Header.Add("x-rapidapi-host", "v3.football.api-sports.io") req.Header.Add("x-rapidapi-host", "v3.football.api-sports.io")
res, err := client.Do(req) res, err := client.Do(req)
if err != nil { if err != nil {
itx.SendLinearReply(fmt.Sprintf("failed to execute the request: %s", err.Error()), true) itx.SendLinearReply(fmt.Sprintf("request failed: %s", err.Error()), true)
return return
} }
defer res.Body.Close() defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body) body, err := ioutil.ReadAll(res.Body)
if err != nil { if err != nil {
itx.SendLinearReply(fmt.Sprintf("failed to read the response: %s", err.Error()), true) itx.SendLinearReply(fmt.Sprintf("failed to read the response body: %s", err.Error()), true)
return return
} }
var r *Response r := &Response{}
if err = json.Unmarshal(body, r); err != nil { if err = json.Unmarshal(body, r); err != nil {
itx.SendLinearReply(fmt.Sprintf("failed to unmarshal the response: %s", err.Error()), true) itx.SendLinearReply(fmt.Sprintf("failed to unmarshal the response: %s", err.Error()), true)
return return
} }
itx.SendLinearReply(fmt.Sprintf("it worked, matches count: %d", r.Results), true) matches := Matches(r.Response)
sort.Sort(matches)
sortedBytes, err := json.Marshal(matches)
if err != nil {
itx.SendLinearReply(fmt.Sprintf("failed to marshal the sorted list: %s", err.Error()), true)
return
}
f, err := os.Create(PSG_FILE_PATH)
if err != nil {
itx.SendLinearReply(fmt.Sprintf("failed to create the json file: %s", err.Error()), true)
return
}
if _, err = f.Write(sortedBytes); err != nil {
itx.SendLinearReply(fmt.Sprintf("failed to write the json: %s", err.Error()), true)
return
}
itx.SendLinearReply("matches refreshed", true)
}, },
} }
var PsgNextMatch tempest.Command = tempest.Command{
Name: "psg-next-match",
Description: "montre le prochain match du PSG",
Options: []tempest.Option{},
SlashCommandHandler: func(itx tempest.CommandInteraction) {
file, err := ioutil.ReadFile(PSG_FILE_PATH)
if err != nil {
itx.SendLinearReply(fmt.Sprintf("failed to open the json file: %s", err.Error()), true)
return
}
var list Matches
if err = json.Unmarshal(file, &list); err != nil {
itx.SendLinearReply(fmt.Sprintf("failed to unmarshal the list: %s", err.Error()), true)
return
}
now := time.Now()
var nextMatch *Match
for _, m := range list {
if m.Fixture.Date.Before(now) {
continue
}
nextMatch = &m
}
if err := itx.SendReply(tempest.ResponseData{
Content: formatNextPSGMatchContent(nextMatch),
}, false); err != nil {
log.Printf("failed to send reply with the pinned message: %s",err.Error())
itx.SendLinearReply(err.Error(), true)
}
},
}
func formatNextPSGMatchContent(m *Match) string {
if m == nil {
return "no next match available"
}
return fmt.Sprintf(
"%s - %s, %s (%s, %s)",
m.Teams.Home.Name,
m.Teams.Away.Name,
m.Fixture.Date.Format("02 Jan 2006, 15:04"),
m.Fixture.Venue.Name,
m.Fixture.Venue.City,
)
}
type Match struct { type Match struct {
Fixture Fixture Fixture `json:"fixture"`
League LeagueStruct `json:"league"`
Teams struct {
Home TeamStruct `json:"home"`
Away TeamStruct `json:"away"`
}`json:"teams"`
} }
type Fixture struct { type Fixture struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Referee string `json:"referee"` Referee string `json:"referee"`
Timezone string `json:"timezone"` Timezone string `json:"timezone"`
Date string `json:"date"` Date time.Time `json:"date"`
Timestamp string `json:"timestamp"` Timestamp int64 `json:"timestamp"`
Venue VenueStruct `json:"venue"` Venue VenueStruct `json:"venue"`
League LeagueStruct `json:"league"`
Teams struct {
Home TeamStruct `json:"home"`
Away TeamStruct `json:"away"`
}`json:"teams"`
} }
type TeamStruct struct { type TeamStruct struct {
@@ -106,8 +191,6 @@ type VenueStruct struct {
type Response struct { type Response struct {
Get string `json:"get"` Get string `json:"get"`
Parameters map[string]string `json:"parameters"`
Errors []interface{} `json:"errors"`
Results int64 `json:"results"` Results int64 `json:"results"`
Paging Paging `json:"paging"` Paging Paging `json:"paging"`
Response []Match `json:"response"` Response []Match `json:"response"`
+2 -1
View File
@@ -11,7 +11,7 @@ import (
tempest "github.com/Amatsagu/Tempest" tempest "github.com/Amatsagu/Tempest"
) )
func main() { func main_old() {
env := getEnvVariables() env := getEnvVariables()
client := tempest.CreateClient(tempest.ClientOptions{ client := tempest.CreateClient(tempest.ClientOptions{
@@ -39,6 +39,7 @@ func main() {
client.RegisterCommand(commands.Pinned) client.RegisterCommand(commands.Pinned)
client.RegisterCommand(commands.PsgRefreshFixtures) client.RegisterCommand(commands.PsgRefreshFixtures)
client.RegisterCommand(commands.PsgNextMatch)
client.SyncCommands(env.ServerIDs, nil, false) client.SyncCommands(env.ServerIDs, nil, false)