clash

package module
v2.8.3+incompatible Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2019 License: MIT Imports: 10 Imported by: 0

README

go-clash

API bindings for the public Clash Royale API, for Go.

https://developer.clashroyale.com/#/documentation

These bindings provide time.Time castings for the (non-standard) datestamps. Such properties are still accessible as strings, though you are more likely to appreciate the helper methods that parse these timestamps into date values.

Usage

client := clash.NewClient("Your bearer token"),

player := client.Player("9PLJLPQ8G") // "#9PLJLPQ8G" is also fine

chests, _ := player.UpcomingChests()

for _, chest := range chests.Items {
    fmt.Printf("Chest %s is %d drops away!\n", chest.Name, chest.Index)
}

Error handling

Any issues with HTTP transport or response codes >=400 will be reflected in the returned error.

Cast the error to an API error structure. If casting wasn't successful, the error must be from net/http.

if err, ok := err.(clash.APIError); ok {
    // handle a clash API error response
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var TimeLayout = "20060102T150405.000Z"

This is the time format used by time fields -- we'll be using it to provide cleaner APIs.

Functions

func NormaliseTag

func NormaliseTag(tag string) string

make sure the tag is prefixed with a # if it doesn't have one

Types

type APIError

type APIError struct {
	Response *http.Response
	Body     *ErrorBody
}

APIError implements the error interface.

func (*APIError) Error

func (e *APIError) Error() string

type Achievement

type Achievement struct {
	Name   string `json:"name"`
	Stars  int    `json:"stars"`
	Value  int    `json:"value"`
	Target int    `json:"target"`
	Info   string `json:"info"`
}

type Arena

type Arena struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

type Badge

type Badge struct {
	Name     string `json:"name"`
	Level    int    `json:"level,omitempty"`
	MaxLevel int    `json:"maxLevel,omitempty"`
	Progress int    `json:"progress,omitempty"`
	Target   int    `json:"target,omitempty"`
}

type Battle

type Battle struct {
	Type                    string         `json:"type"`
	RawBattleTime           string         `json:"battleTime"`
	Arena                   Arena          `json:"arena"`
	GameMode                GameMode       `json:"gameMode"`
	DeckSelection           string         `json:"deckSelection"`
	Team                    []BattlePlayer `json:"team"`
	Opponent                []BattlePlayer `json:"opponent"`
	TournamentTag           string         `json:"tournamentTag"`
	ChallengeId             int            `json:"challengeId"`
	ChallengeWinCountBefore int            `json:"challengeWinCountBefore"`
	ReplayTag               string         `json:"replayTag,omitempty"`
}

func (*Battle) BattleTime

func (b *Battle) BattleTime() time.Time

Get the time of the battle.

func (*Battle) Outcome

func (b *Battle) Outcome() BattleOutcome

Get a struct describing the outcome of the battle.

func (*Battle) PlayerByTag

func (b *Battle) PlayerByTag(tag string) (BattlePlayer, error)

Find a player in the battle by tag. Return an error if the tag could not be found.

type BattleOutcome

type BattleOutcome struct {
	IsDraw  bool
	Winners []BattlePlayer
	Losers  []BattlePlayer
}

type BattlePlayer

type BattlePlayer struct {
	Tag              string `json:"tag"`
	Name             string `json:"name"`
	StartingTrophies int    `json:"startingTrophies"`
	TrophyChange     int    `json:"trophyChange"`
	Crowns           int    `json:"crowns"`
	// king tower hit points is missing from the response if it is zero.
	KingTowerHitPoints int `json:"kingTowerHitPoints,omitempty"`
	// ditto. princess tower hit points are an array of values.
	PrincessTowersHitPoints []int `json:"princessTowersHitPoints,omitempty"`
	Clan                    struct {
		Tag     string `json:"tag"`
		Name    string `json:"name"`
		BadgeId int    `json:"badgeId"`
	} `json:"clan"`
	Cards []Card `json:"cards"`
}

type Battles

type Battles []Battle

type Card

type Card struct {
	Name      string   `json:"name"`
	Level     int      `json:"level"`
	MaxLevel  int      `json:"maxLevel"`
	Count     int      `json:"count"`
	IconUrls  IconUrls `json:"iconUrls"`
	StarLevel int      `json:"starLevel"`
}

func (*Card) ClientLevel

func (c *Card) ClientLevel() int

Return the internal client level for the card, as these are zero-indexed

type Clan

type Clan struct {
	Tag               string       `json:"tag"`
	Name              string       `json:"name"`
	Type              string       `json:"type"`
	Description       string       `json:"description"`
	BadgeId           int          `json:"badgeId"`
	ClanScore         int          `json:"clanScore"`
	ClanWarTrophies   int          `json:"clanWarTrophies"`
	Location          Location     `json:"location"`
	RequiredTrophies  int          `json:"requiredTrophies"`
	DonationsPerWeek  int          `json:"donationsPerWeek"`
	ClanChestStatus   string       `json:"clanChestStatus"`
	ClanChestPoints   int          `json:"clanChestPoints"`
	ClanChestLevel    int          `json:"clanChestLevel"`
	ClanChestMaxLevel int          `json:"clanChestMaxLevel"`
	Members           int          `json:"members"`
	MemberList        []ClanMember `json:"memberList"`
}

type ClanMember

type ClanMember struct {
	Tag               string `json:"tag"`
	Name              string `json:"name"`
	Role              string `json:"role"`
	ExpLevel          int    `json:"expLevel"`
	Trophies          int    `json:"trophies"`
	Arena             Arena  `json:"arena"`
	ClanRank          int    `json:"clanRank"`
	PreviousClanRank  int    `json:"previousClanRank"`
	Donations         int    `json:"donations"`
	DonationsReceived int    `json:"donationsReceived"`
	ClanChestPoints   int    `json:"clanChestPoints"`
	RawLastSeen       string `json:"lastSeen"`
}

func (*ClanMember) LastSeen

func (c *ClanMember) LastSeen() time.Time

type ClanPager

type ClanPager struct {
	Items  []Clan `json:"items"`
	Paging Paging `json:"paging"`
}

type ClanQuery

type ClanQuery struct {
	PagedQuery
	LocationId int
	MinScore   int
	MinMembers int
	MaxMembers int
	Name       string
}

type ClanRanking

type ClanRanking struct {
	Tag          string   `json:"tag"`
	Name         string   `json:"name"`
	Rank         int      `json:"rank"`
	PreviousRank int      `json:"previousRank"`
	Location     Location `json:"location"`
	BadgeId      int      `json:"badgeId"`
	ClanScore    int      `json:"clanScore"`
	Members      int      `json:"members"`
}

type ClanService

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

func (*ClanService) CurrentWar

func (i *ClanService) CurrentWar() (CurrentWar, error)

Retrieve information about clan's current clan war

func (*ClanService) Get

func (i *ClanService) Get() (Clan, error)

Get information about a single clan by clan tag. Clan tags can be found using clan search operation.

func (*ClanService) Members

func (i *ClanService) Members() (MemberPager, error)

List clan members

func (*ClanService) WarLog

func (i *ClanService) WarLog() (WarLogPager, error)

Retrieve clan's clan war log

type ClansService

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

func (*ClansService) Search

func (i *ClansService) Search(query *ClanQuery) (ClanPager, error)

Search all clans by name and/or filtering the results using various criteria. At least one filtering criteria must be defined and if name is used as part of search, it is required to be at least three characters long.

type Client

type Client struct {
	BaseURL   *url.URL
	UserAgent string
	Bearer    string
	// contains filtered or unexported fields
}

func NewClient added in v1.1.0

func NewClient(token string) *Client

func (*Client) Clan

func (c *Client) Clan(tag string) *ClanService

func (*Client) Clans

func (c *Client) Clans() *ClansService

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) (*http.Response, error)

execute the request.

func (*Client) Location

func (c *Client) Location(id string) *LocationService

NB: Location ID is a string. This is because 'global' is a valid location ID.

func (*Client) Locations

func (c *Client) Locations() *LocationsService

func (*Client) NewRequest

func (c *Client) NewRequest(method, path string, body interface{}) (*http.Request, error)

make a new request object.

func (*Client) Player

func (c *Client) Player(tag string) *PlayerService

func (*Client) Replay

func (c *Client) Replay(tag string) *ReplayService

func (*Client) SetTimeout

func (c *Client) SetTimeout(duration time.Duration)

func (*Client) Tournament

func (c *Client) Tournament(tag string) *TournamentService

func (*Client) Tournaments

func (c *Client) Tournaments() *TournamentsService

type CurrentWar

type CurrentWar struct {
	State                string           `json:"state"`
	RawCollectionEndTime string           `json:"collectionEndTime"`
	Clan                 WarClanDetails   `json:"clan"`
	Clans                []WarClanDetails `json:"clans"`
	Participants         []WarParticipant `json:"participants"`
	RawWarEndTime        string           `json:"warEndTime"`
}

func (*CurrentWar) CollectionEndTime

func (w *CurrentWar) CollectionEndTime() time.Time

func (*CurrentWar) WarEndTime

func (w *CurrentWar) WarEndTime() time.Time

type ErrorBody

type ErrorBody struct {
	Reason  string `json:"reason"`
	Message string `json:"message"`
}

The error response sent by the API if 4xx/5xx status code.

type FavouriteCard

type FavouriteCard struct {
	Name     string   `json:"name"`
	ID       int      `json:"id"`
	MaxLevel int      `json:"maxLevel"`
	IconUrls IconUrls `json:"iconUrls"`
}

type GameMode

type GameMode struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

type IconUrls

type IconUrls struct {
	Medium string `json:"medium"`
}

type LeagueStats

type LeagueStats struct {
	BestSeason     Season `json:"bestSeason"`
	PreviousSeason Season `json:"previousSeason"`
	CurrentSeason  Season `json:"currentSeason"`
}

type Location

type Location struct {
	ID          int    `json:"id"`
	Name        string `json:"name"`
	IsCountry   bool   `json:"isCountry"`
	CountryCode string `json:"countryCode,omitempty"`
}

type LocationClanRankingPager

type LocationClanRankingPager struct {
	Items  []ClanRanking `json:"items"`
	Paging Paging        `json:"paging"`
}

type LocationPager

type LocationPager struct {
	Items  []Location `json:"items"`
	Paging Paging     `json:"paging"`
}

type LocationPlayerRankingPager

type LocationPlayerRankingPager struct {
	Items  []PlayerRanking `json:"items"`
	Paging Paging          `json:"paging"`
}

type LocationService

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

func (*LocationService) ClanRankings

func (i *LocationService) ClanRankings(query *PagedQuery) (LocationClanRankingPager, error)

Get clan rankings for a specific location

func (*LocationService) ClanWarRankings

func (i *LocationService) ClanWarRankings(query *PagedQuery) (LocationClanRankingPager, error)

Get clan war rankings for a specific location

func (*LocationService) Get

func (i *LocationService) Get() (Location, error)

Get information about specific location

func (*LocationService) PlayerRankings

func (i *LocationService) PlayerRankings(query *PagedQuery) (LocationPlayerRankingPager, error)

Get player rankings for a specific location

type LocationsService

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

func (*LocationsService) All

func (i *LocationsService) All() (LocationPager, error)

List all available locations

type MemberPager

type MemberPager struct {
	Items  []ClanMember `json:"items"`
	Paging Paging       `json:"paging"`
}

type PagedQuery added in v1.1.0

type PagedQuery struct {
	Limit  int
	After  int
	Before int
}

Base struct for paged queries.

type Paging added in v1.1.0

type Paging struct {
	Cursors struct {
		Before string `json:"before"`
		After  string `json:"after"`
	} `json:"cursors"`
}

Paging for pager responses. 'before' and 'after' may be empty if there are no more results to return.

type Player

type Player struct {
	Tag                   string        `json:"tag"`
	Name                  string        `json:"name"`
	ExpLevel              int           `json:"expLevel"`
	Trophies              int           `json:"trophies"`
	BestTrophies          int           `json:"bestTrophies"`
	Wins                  int           `json:"wins"`
	Losses                int           `json:"losses"`
	BattleCount           int           `json:"battleCount"`
	ThreeCrownWins        int           `json:"threeCrownWins"`
	ChallengeCardsWon     int           `json:"challengeCardsWon"`
	ChallengeMaxWins      int           `json:"challengeMaxWins"`
	TournamentCardsWon    int           `json:"tournamentCardsWon"`
	TournamentBattleCount int           `json:"tournamentBattleCount"`
	Role                  string        `json:"role"`
	Donations             int           `json:"donations"`
	DonationsReceived     int           `json:"donationsReceived"`
	TotalDonations        int           `json:"totalDonations"`
	WarDayWins            int           `json:"warDayWins"`
	ClanCardsCollected    int           `json:"clanCardsCollected"`
	Clan                  PlayerClan    `json:"clan"`
	Arena                 Arena         `json:"arena"`
	Achievements          []Achievement `json:"achievements"`
	Badges                []Badge       `json:"badges"`
	Cards                 []Card        `json:"cards"`
	CurrentDeck           []Card        `json:"currentDeck"`
	CurrentFavouriteCard  FavouriteCard `json:"currentFavouriteCard"`
	LeagueStatistics      LeagueStats   `json:"leagueStatistics"`
	StarPoints            int           `json:"starPoints"`
}

type PlayerClan

type PlayerClan struct {
	Tag     string `json:"tag"`
	Name    string `json:"name"`
	BadgeID int    `json:"badgeId"`
}

type PlayerRanking

type PlayerRanking struct {
	Tag          string     `json:"tag"`
	Name         string     `json:"name"`
	ExpLevel     int        `json:"expLevel"`
	Trophies     int        `json:"trophies"`
	Clan         PlayerClan `json:"clan"`
	Rank         int        `json:"Rank"`
	PreviousRank int        `json:"previousRank"`
	Arena        Arena      `json:"arena"`
}

type PlayerService

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

func (*PlayerService) BattleLog

func (i *PlayerService) BattleLog() (Battles, error)

Get list of recent battle results for a player.

func (*PlayerService) Get

func (i *PlayerService) Get() (Player, error)

Get information about a single player by player tag. Player tags can be found either in game or by from clan member lists.

func (*PlayerService) UpcomingChests

func (i *PlayerService) UpcomingChests() (UpcomingChests, error)

Get list of reward chests that the player will receive next in the game.

func (*PlayerService) VerifyToken

func (i *PlayerService) VerifyToken(token string) (VerificationResult, error)

Verifies a player token and returns whether or not the token was associated with the given player.

This API call can be used by a player to prove that they own a particular game account as the token can only be retrieved inside the game from settings view.

type Replay

type Replay struct {
	BattleTime string `json:"battleTime"`
	// Replay data is hideously unstructured, so let's save some time.
	ReplayData map[string]interface{} `json:"replayData"`
	ShareCount int                    `json:"shareCount"`
	Tag        string                 `json:"tag"`
	ViewCount  int                    `json:"viewCount"`
}

type ReplayService

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

func (*ReplayService) Get

func (i *ReplayService) Get() (Replay, error)

Get information about a single replay by a replay tag.

type Season

type Season struct {
	Rank         int    `json:"rank"`
	Trophies     int    `json:"trophies"`
	BestTrophies int    `json:"bestTrophies"`
	ID           string `json:"id"`
}

type Tournament

type Tournament struct {
	Tag                 string             `json:"tag"`
	Type                string             `json:"type"`
	Status              string             `json:"status"`
	CreatorTag          string             `json:"creatorTag"`
	Name                string             `json:"name"`
	Description         string             `json:"description"`
	Capacity            int                `json:"capacity"`
	MaxCapacity         int                `json:"maxCapacity"`
	PreparationDuration int                `json:"preparationDuration"`
	Duration            int                `json:"duration"`
	RawCreatedTime      string             `json:"createdTime"`
	RawStartedTime      string             `json:"startedTime"`
	MembersList         []TournamentMember `json:"membersList"`
	FirstPlaceCardPrize int                `json:"firstPlaceCardPrize"`
	GameMode            GameMode           `json:"gameMode"`
	LevelCap            int                `json:"levelCap"`
}

func (*Tournament) CreatedTime

func (t *Tournament) CreatedTime() time.Time

func (*Tournament) StartedTime

func (t *Tournament) StartedTime() time.Time

type TournamentMember

type TournamentMember struct {
	Tag   string     `json:"tag"`
	Name  string     `json:"name"`
	Score int        `json:"score"`
	Rank  int        `json:"rank"`
	Clan  PlayerClan `json:"clan"`
}

type TournamentPager

type TournamentPager struct {
	Items  []Tournament `json:"items"`
	Paging Paging       `json:"paging"`
}

type TournamentQuery

type TournamentQuery struct {
	PagedQuery
	Name string
}

type TournamentService

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

func (*TournamentService) Get

func (i *TournamentService) Get() (Tournament, error)

Get information about a single tournament by a tournament tag.

type TournamentsService

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

func (*TournamentsService) Search

Search all tournaments by name.

It is not possible to specify ordering for results so clients should not rely on any specific ordering as that may change in the future releases of the API.

type UpcomingChest

type UpcomingChest struct {
	Index int    `json:"index"`
	Name  string `json:"name"`
}

type UpcomingChests

type UpcomingChests struct {
	Items []UpcomingChest `json:"items"`
}

type VerificationResult

type VerificationResult struct {
	Tag    string `json:"tag"`
	Token  string `json:"token"`
	Status string `json:"status"`
}

func (*VerificationResult) IsValid

func (v *VerificationResult) IsValid() bool

type War

type War struct {
	SeasonId       int              `json:"seasonId"`
	RawCreatedDate string           `json:"createdDate"`
	Participants   []WarParticipant `json:"participants"`
	Standings      []WarStanding    `json:"standings"`
}

func (*War) CreatedDate

func (w *War) CreatedDate() time.Time

type WarClanDetails

type WarClanDetails struct {
	Tag           string `json:"tag"`
	Name          string `json:"name"`
	BadgeId       int    `json:"badgeId"`
	ClanScore     int    `json:"clanScore"`
	Participants  int    `json:"participants"`
	BattlesPlayed int    `json:"battlesPlayed"`
	Wins          int    `json:"wins"`
	Crowns        int    `json:"crowns"`
}

type WarLogPager

type WarLogPager struct {
	Items  []War  `json:"items"`
	Paging Paging `json:"paging"`
}

type WarParticipant

type WarParticipant struct {
	Tag                        string `json:"tag"`
	Name                       string `json:"name"`
	CollectionDayBattlesPlayed int    `json:"collectionDayBattlesPlayed"`
	CardsEarned                int    `json:"cardsEarned"`
	BattlesPlayed              int    `json:"battlesPlayed"`
	Wins                       int    `json:"wins"`
}

type WarStanding

type WarStanding struct {
	Clan         WarClanDetails `json:"clan"`
	TrophyChange int            `json:"trophyChange"`
}

Jump to

Keyboard shortcuts

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