chesscompubapi

package module
v0.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 23, 2024 License: MIT Imports: 7 Imported by: 2

README

Go Reference codecov Go Report Card License

♟️ chesscompubapi

Go client for the chess.com Published-Data API (PubAPI). This package depends on the standard library only. It uses

Installation

$ go get -u github.com/agoblet/chesscompubapi

Quick Start

c := chesscompubapi.NewClient()
profile, err := c.GetPlayerProfile("hikaru")

Endpoint Implementation Status

  • ✅ /club/{url-ID}
  • ✅ /club/{url-ID}/matches
  • ✅ /club/{url-ID}/members
  • ✅ /country/{iso}
  • ✅ /country/{iso}/clubs
  • ✅ /country/{iso}/players
  • ✅ /leaderboards
  • ✅ /player/{username}
  • ✅ /player/{username}/clubs
  • ✅ /player/{username}/games/archives
  • ✅ /player/{username}/games/to-move
  • ✅ /player/{username}/games/{YYYY}/{MM}
  • ✅ /player/{username}/games/{YYYY}/{MM}/pgn
  • ✅ /player/{username}/stats
  • ✅ /puzzle
  • ✅ /puzzle/random
  • ✅ /streamers
  • ✅ /titled/{title-abbrev}
  • ❌ /match/{ID}
  • ❌ /match/{ID}/{board}
  • ❌ /match/live/{ID}
  • ❌ /match/live/{ID}/{board}
  • ❌ /player/{username}/games
  • ❌ /player/{username}/matches
  • ❌ /player/{username}/tournaments
  • ❌ /tournament/{url-ID}
  • ❌ /tournament/{url-ID}/{round}
  • ❌ /tournament/{url-ID}/{round}/{group}

Contributing

Dev dependencies
Testing your changes locally
$ make

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Accuracies

type Accuracies struct {
	Black float64 `json:"black"`
	White float64 `json:"white"`
}

Accuracies represents the accuracies of the 2 players of a chess game.

type Archive

type Archive struct {
	Username string
	Year     int
	Month    time.Month
}

Archive represents a monthly archive of games of a player.

func (*Archive) UnmarshalJSON added in v0.2.0

func (a *Archive) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals an archive URL from a JSON document into an Archive.

type BestPlayerGameTypeStats added in v0.2.0

type BestPlayerGameTypeStats struct {
	Date   UnixSecondsTimestamp `json:"date"`
	Rating int                  `json:"rating"`
	Game   string               `json:"game"`
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client handles HTTP requests to the chess.com PubAPI.

The Get* and List* functions of the Client, e.g. GetPlayerProfile, all behave in the same way:

  • Get* functions return a single item.
  • List* functions return a slice of items.
  • They return an *HTTPError if the API returns a status code other than 200.
  • They an *url.Error if the API call failed for other reasons.
  • They return an error if the response cannot be decoded into the return type, e.g. PlayerProfile for function GetPlayerProfile.

func NewClient

func NewClient(options ...Option) *Client

NewClient creates a new *Client to send requests to the chess.com PubAPI. Accepts any number of Options to customize the *Client.

func (*Client) GetClub added in v0.8.0

func (c *Client) GetClub(id string) (Club, error)

GetClub gets additional details about a club. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-club-profile.

func (*Client) GetClubMatches added in v0.14.0

func (c *Client) GetClubMatches(id string) (ClubMatches, error)

GetClubMatches gets a list of daily and club matches, grouped by status (registered, in progress, finished). Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-club-matches.

func (*Client) GetClubMemberActivity added in v0.9.0

func (c *Client) GetClubMemberActivity(id string) (ClubMemberActivity, error)

GetClubMemberActivity gets a list of club members (usernames and joined date timestamp), grouped by club-activity frequency. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-club-members.

func (*Client) GetCountryProfile

func (c *Client) GetCountryProfile(code string) (CountryProfile, error)

GetCountryProfile gets the profile of the country. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-country-profile.

func (*Client) GetDailyPuzzle added in v0.12.0

func (c *Client) GetDailyPuzzle() (Puzzle, error)

GetDailyPuzzle gets information about the daily puzzle found in www.chess.com. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-daily-puzzle.

func (*Client) GetLeaderboards added in v0.13.0

func (c *Client) GetLeaderboards() (Leaderboards, error)

GetLeaderboards gets information about top 50 player for daily and live games, tactics and lessons. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-leaderboards.

func (*Client) GetPGN added in v0.4.0

func (c *Client) GetPGN(archive Archive) (string, error)

GetPGN lists all Games available in an archive. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-games-pgn.

func (*Client) GetPlayerProfile

func (c *Client) GetPlayerProfile(username string) (PlayerProfile, error)

GetPlayerProfile gets the profile of a player. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-player.

func (*Client) GetPlayerStats added in v0.2.0

func (c *Client) GetPlayerStats(username string) (PlayerStats, error)

GetPlayerStats gets the profile of a player. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-player-stats.

func (*Client) GetRandomPuzzle added in v0.12.0

func (c *Client) GetRandomPuzzle() (Puzzle, error)

GetRandomPuzzle gets information about a randomly picked daily puzzle. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-random-daily-puzzle.

func (*Client) ListArchives

func (c *Client) ListArchives(username string) ([]Archive, error)

ListArchives lists all Archives available for a player. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-games-archive-list.

func (*Client) ListCountryClubs added in v0.7.0

func (c *Client) ListCountryClubs(code string) ([]StringFromPathSuffix, error)

ListCountryClubs lists usernames for players who identify themselves as being in this country. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-country-clubs.

func (*Client) ListCountryPlayers added in v0.3.0

func (c *Client) ListCountryPlayers(code string) ([]string, error)

ListCountryPlayers lists usernames for players who identify themselves as being in this country. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-country-players.

func (*Client) ListGames

func (c *Client) ListGames(archive Archive) ([]Game, error)

ListGames lists all Games available in an archive. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-games-archive.

func (*Client) ListGamesToMove added in v0.11.0

func (c *Client) ListGamesToMove(username string) ([]GameToMove, error)

ListGamesToMove lists all Daily Chess games where it is the player's turn to act. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-games-tomove.

func (*Client) ListPlayerClubs added in v0.1.0

func (c *Client) ListPlayerClubs(username string) ([]PlayerClub, error)

ListPlayerClubs lists the clubs that a player is member of. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-player-clubs.

func (*Client) ListStreamers added in v0.5.0

func (c *Client) ListStreamers() ([]Streamer, error)

ListStreamers lists information about Chess.com streamers. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-streamers.

func (*Client) ListTitledPlayers added in v0.9.0

func (c *Client) ListTitledPlayers(title string) ([]string, error)

ListTitledPlayers lists usernames for titled players. Details about the endpoint can be found at https://www.chess.com/news/view/published-data-api#pubapi-endpoint-titled.

type Club added in v0.8.0

type Club struct {
	ID                 StringFromPathSuffix   `json:"@id"`
	Name               string                 `json:"name"`
	URL                string                 `json:"url"`
	ClubID             int                    `json:"club_id"`
	Icon               string                 `json:"icon"`
	Visibility         string                 `json:"visibility"`
	JoinRequest        string                 `json:"join_request"`
	Description        string                 `json:"description"`
	Country            StringFromPathSuffix   `json:"country"`
	AverageDailyRating int                    `json:"average_daily_rating"`
	MembersCount       int                    `json:"members_count"`
	Created            UnixSecondsTimestamp   `json:"created"`
	LastActivity       UnixSecondsTimestamp   `json:"last_activity"`
	Admins             []StringFromPathSuffix `json:"admin"`
}

type ClubMatches added in v0.14.0

type ClubMatches struct {
	Finished   []FinishedClubMatch   `json:"finished"`
	InProgress []InProgressClubMatch `json:"in_progress"`
	Registered []RegisteredClubMatch `json:"registered"`
}

type ClubMember added in v0.9.0

type ClubMember struct {
	Username string               `json:"username"`
	Joined   UnixSecondsTimestamp `json:"joined"`
}

type ClubMemberActivity added in v0.9.0

type ClubMemberActivity struct {
	Weekly  []ClubMember `json:"weekly"`
	Monthly []ClubMember `json:"monthly"`
	AllTime []ClubMember `json:"all_time"`
}

type CountryProfile

type CountryProfile struct {
	Code string `json:"code"`
	Name string `json:"name"`
}

type DateRating added in v0.2.0

type DateRating struct {
	Date   UnixSecondsTimestamp `json:"date"`
	Rating int                  `json:"rating"`
}

type DurationInSeconds added in v0.2.0

type DurationInSeconds time.Duration

DurationInSeconds decodes durations in seconds in JSON documents.

func (*DurationInSeconds) UnmarshalJSON added in v0.2.0

func (d *DurationInSeconds) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals an integer representing a duration in seconds into a time.Duration.

type FinishedClubMatch added in v0.14.0

type FinishedClubMatch struct {
	Name      string               `json:"name"`
	ID        StringFromPathSuffix `json:"@id"`
	Opponent  StringFromPathSuffix `json:"opponent"`
	Result    string               `json:"result"`
	StartTime UnixSecondsTimestamp `json:"start_time"`
	TimeClass string               `json:"time_class"`
}

type Game

type Game struct {
	Black        GamePlayer           `json:"black"`
	FEN          string               `json:"fen"`
	Accuracies   *Accuracies          `json:"accuracies"`
	White        GamePlayer           `json:"white"`
	UUID         string               `json:"uuid"`
	PGN          string               `json:"pgn"`
	TCN          string               `json:"tcn"`
	URL          string               `json:"url"`
	TimeControl  string               `json:"time_control"`
	Rules        string               `json:"rules"`
	InitialSetup string               `json:"initial_setup"`
	TimeClass    string               `json:"time_class"`
	ECO          *string              `json:"eco"`
	Match        *string              `json:"match"`
	Tournament   *string              `json:"tournament"`
	Rated        bool                 `json:"rated"`
	StartTime    UnixSecondsTimestamp `json:"start_time"`
	EndTime      UnixSecondsTimestamp `json:"end_time"`
}

Game represents a finished game played by 2 players.

type GamePlayer

type GamePlayer struct {
	Username string `json:"username"`
	Rating   int    `json:"rating"`
	UUID     string `json:"uuid"`
	Result   string `json:"result"`
}

GamePlayer represents one of the 2 players of a chess game.

type GameToMove added in v0.11.0

type GameToMove struct {
	URL          string               `json:"url"`
	DrawOffer    *bool                `json:"draw_offer"`
	LastActivity UnixSecondsTimestamp `json:"last_activity"`
	MoveBy       UnixSecondsTimestamp `json:"move_by"`
}

GameToMove represents a Daily Chess gameswhere it is the player's turn to act.

type HTTPError

type HTTPError struct {
	StatusCode   int
	ResponseBody string
}

HTTPError is used when a status code other than 200 is returned by the chess.com PubAPI.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error returns a formatted string representing the HTTPError.

type InProgressClubMatch added in v0.14.0

type InProgressClubMatch struct {
	Name      string               `json:"name"`
	ID        StringFromPathSuffix `json:"@id"`
	Opponent  StringFromPathSuffix `json:"opponent"`
	StartTime UnixSecondsTimestamp `json:"start_time"`
	TimeClass string               `json:"time_class"`
}

type LastPlayerGameTypeStats added in v0.2.0

type LastPlayerGameTypeStats struct {
	Date   UnixSecondsTimestamp `json:"date"`
	Rating int                  `json:"rating"`
	RD     int                  `json:"rd"`
}

type LeaderboardEntry added in v0.13.0

type LeaderboardEntry struct {
	PlayerID   int                  `json:"player_id"`
	WinCount   int                  `json:"win_count"`
	LossCount  int                  `json:"loss_count"`
	DrawCount  int                  `json:"draw_count"`
	URL        string               `json:"url"`
	Title      *string              `json:"title"`
	Name       *string              `json:"name"`
	FlairCode  string               `json:"flair_code"`
	Avatar     string               `json:"avatar"`
	TrendScore Trend                `json:"trend_score"`
	TrendRank  Trend                `json:"trend_rank"`
	Status     string               `json:"status"`
	Country    StringFromPathSuffix `json:"country"`
	Username   string               `json:"username"`
	Score      int                  `json:"score"`
	Rank       int                  `json:"rank"`
}

type Leaderboards added in v0.13.0

type Leaderboards struct {
	Daily             []LeaderboardEntry `json:"daily"`
	Daily960          []LeaderboardEntry `json:"daily960"`
	LiveRapid         []LeaderboardEntry `json:"live_rapid"`
	LiveBullet        []LeaderboardEntry `json:"live_bullet"`
	LiveBlitz         []LeaderboardEntry `json:"live_blitz"`
	LiveBlitz960      []LeaderboardEntry `json:"live_blitz960"`
	LiveBughouse      []LeaderboardEntry `json:"live_bughouse"`
	LiveCrazyhouse    []LeaderboardEntry `json:"live_crazyhouse"`
	LiveKingOfTheHill []LeaderboardEntry `json:"live_kingofthehill"`
	LiveThreeCheck    []LeaderboardEntry `json:"live_threecheck"`
	Tactics           []LeaderboardEntry `json:"tactics"`
	Rush              []LeaderboardEntry `json:"rush"`
	Battle            []LeaderboardEntry `json:"battle"`
}

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is the inferface used for functional options to configure the *Client. To apply an Option, pass it to the NewClient function.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL configures a custom base URL to send requests to. It must have the format protocol://host[:port]. If this option is omitted, the default URL https://api.chess.com will be used. To apply this Option, pass it to the NewClient function.

func WithTimeout added in v0.10.0

func WithTimeout(timeout time.Duration) Option

WithTimeout configures a timeout for requests to the chess.com PubAPI. If this Option is omitted or a timeout of 0 is passed, there will be no timeout. To apply this Option, pass it to the NewClient function.

type PlayerClub added in v0.1.0

type PlayerClub struct {
	URL          string               `json:"url"`
	Name         string               `json:"name"`
	Joined       UnixSecondsTimestamp `json:"joined"`
	LastActivity UnixSecondsTimestamp `json:"last_activity"`
	Icon         string               `json:"icon"`
	ID           StringFromPathSuffix `json:"@id"`
}

type PlayerGameTypeStats added in v0.2.0

type PlayerGameTypeStats struct {
	Last       LastPlayerGameTypeStats       `json:"last"`
	Best       *BestPlayerGameTypeStats      `json:"best"`
	Record     RecordPlayerGameTypeStats     `json:"record"`
	Tournament TournamentPlayerGameTypeStats `json:"tournament"`
}

type PlayerHighestLowestStats added in v0.2.0

type PlayerHighestLowestStats struct {
	Highest DateRating `json:"highest"`
	Lowest  DateRating `json:"lowest"`
}

type PlayerProfile

type PlayerProfile struct {
	URL         string               `json:"url"`
	Username    string               `json:"username"`
	PlayerId    int                  `json:"player_id"`
	Title       *string              `json:"title"`
	Status      string               `json:"status"`
	Name        string               `json:"name"`
	Avatar      string               `json:"avatar"`
	Location    string               `json:"location"`
	CountryCode StringFromPathSuffix `json:"country"`
	Joined      UnixSecondsTimestamp `json:"joined"`
	LastOnline  UnixSecondsTimestamp `json:"last_online"`
	Followers   int                  `json:"followers"`
	IsStreamer  bool                 `json:"is_streamer"`
	Verified    bool                 `json:"verified"`
	League      string               `json:"league"`
	TwitchURL   string               `json:"twitch_url"`
	FIDE        int                  `json:"fide"`
}

type PlayerPuzzleRushStats added in v0.2.0

type PlayerPuzzleRushStats struct {
	Daily *TotalAttemptsScore `json:"daily"`
	Best  TotalAttemptsScore  `json:"best"`
}

type PlayerStats added in v0.2.0

type PlayerStats struct {
	ChessDaily    *PlayerGameTypeStats      `json:"chess_daily"`
	Chess960Daily *PlayerGameTypeStats      `json:"chess960_daily"`
	ChessBlitz    *PlayerGameTypeStats      `json:"chess_blitz"`
	ChessBullet   *PlayerGameTypeStats      `json:"chess_bullet"`
	ChessRapid    *PlayerGameTypeStats      `json:"chess_rapid"`
	Tactics       *PlayerHighestLowestStats `json:"tactics"`
	Lessons       *PlayerHighestLowestStats `json:"lessons"`
	PuzzleRush    *PlayerPuzzleRushStats    `json:"puzzle_rush"`
	FIDE          int                       `json:"fide"`
}

type Puzzle added in v0.12.0

type Puzzle struct {
	URL         string               `json:"url"`
	FEN         string               `json:"fen"`
	PGN         string               `json:"pgn"`
	Image       string               `json:"image"`
	Title       string               `json:"title"`
	Comments    string               `json:"comments"`
	PublishTime UnixSecondsTimestamp `json:"publish_time"`
}

type RecordPlayerGameTypeStats added in v0.2.0

type RecordPlayerGameTypeStats struct {
	Win            int                `json:"win"`
	Loss           int                `json:"loss"`
	Draw           int                `json:"draw"`
	TimePerMove    *DurationInSeconds `json:"time_per_move"`
	TimeoutPercent *float64           `json:"timeout_percent"`
}

type RegisteredClubMatch added in v0.14.0

type RegisteredClubMatch struct {
	Name      string               `json:"name"`
	ID        StringFromPathSuffix `json:"@id"`
	Opponent  StringFromPathSuffix `json:"opponent"`
	TimeClass string               `json:"time_class"`
}

type Streamer added in v0.5.0

type Streamer struct {
	Username            string `json:"username"`
	Avatar              string `json:"avatar"`
	TwitchURL           string `json:"twitch_url"`
	URL                 string `json:"url"`
	IsLive              bool   `json:"is_live"`
	IsCommunityStreamer bool   `json:"is_community_streamer"`
}

type StringFromPathSuffix added in v0.3.0

type StringFromPathSuffix string

StringFromPathSuffix decodes url paths in JSON documents where only the part after the last string is needed.

func (*StringFromPathSuffix) UnmarshalJSON added in v0.3.0

func (d *StringFromPathSuffix) UnmarshalJSON(data []byte) error

UnmarshalJSON extracts the part after the last slash from a path. For example, "path/to/some/id" would be unmarshaled as "id".

type TotalAttemptsScore added in v0.2.0

type TotalAttemptsScore struct {
	TotalAttempts int `json:"total_attempts"`
	Score         int `json:"score"`
}

type TournamentPlayerGameTypeStats added in v0.2.0

type TournamentPlayerGameTypeStats struct {
	Count         int `json:"count"`
	Withdraw      int `json:"withdraw"`
	Points        int `json:"points"`
	HighestFinish int `json:"highest_finish"`
}

type Trend added in v0.13.0

type Trend struct {
	Direction int `json:"direction"`
	Delta     int `json:"delta"`
}

type UnixSecondsTimestamp added in v0.2.0

type UnixSecondsTimestamp time.Time

UnixSecondsTimestamp decodes Unix seconds timestamps in JSON documents.

func (*UnixSecondsTimestamp) UnmarshalJSON added in v0.2.0

func (t *UnixSecondsTimestamp) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals an integer representing Unix seconds into a time.Time.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL