goclash

package module
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2024 License: MIT Imports: 13 Imported by: 5

README

GoClash

A blazingly fast, feature rich Clash of Clans API wrapper for Go

Installation

To use GoClash, simply run go get github.com/aaantiii/goclash.

Key Features

  • Automatic Key Management - GoClash automatically manages your API keys, so you don't have to worry about them.
  • Multi Account Support - GoClash allows you to use multiple API Accounts at once, so that you are not limited to 10 API-Keys.
  • Easy to use - GoClash is easy to use, and has a very simple API.
  • Caching - GoClash caches all requests, so that you don't have to worry about rate limits (can be disabled).
  • Concurrency - GoClash is fully concurrent, so that you can make multiple requests at once.

Usage

package main

import "github.com/aaantiii/goclash"

func main() {
	credentials := goclash.Credentials{"email1": "password1", "email2": "password2"}
	client, err := goclash.New(credentials)
	if err != nil {
		panic(err)
	}

	// get a player by tag
	player, err := client.GetPlayer("#8QYG8CJ0")
	if err != nil {
		panic(err)
	}
	println(player.Name)
}
More Examples

You can see more examples here.

Documentation

Index

Constants

View Source
const (
	WarFrequencyUnknown       = "unknown"
	WarFrequencyAlways        = "always"
	WarFrequencyMTOncePerWeek = "moreThanOncePerWeek"
	WarFrequencyOncePerWeek   = "oncePerWeek"
	WarFrequencyLTOncePerWeek = "lessThanOncePerWeek"
	WarFrequencyNever         = "never"
	WarFrequencyAny           = "any"
)
View Source
const (
	ReasonBadRequest           = "badRequest"
	ReasonInvalidAuthorization = "accessDenied"
	ReasonInvalidIP            = "accessDenied.invalidIp"
	ReasonNotFound             = "notFound"
)
View Source
const (
	WarLeagueUnranked = 48000000 + iota
	WarLeagueBronzeIII
	WarLeagueBronzeII
	WarLeagueBronzeI
	WarLeagueSilverIII
	WarLeagueSilverII
	WarLeagueSilverI
	WarLeagueGoldIII
	WarLeagueGoldII
	WarLeagueGoldI
	WarLeagueCrystalIII
	WarLeagueCrystalII
	WarLeagueCrystalI
	WarLeagueMasterIII
	WarLeagueMasterII
	WarLeagueMasterI
	WarLeagueChampionIII
	WarLeagueChampionII
	WarLeagueChampionI
)

CWL leagues

View Source
const (
	LeagueUnranked = 29000000 + iota
	LeagueBronzeIII
	LeagueBronzeII
	LeagueBronzeI
	LeagueSilverIII
	LeagueSilverII
	LeagueSilverI
	LeagueGoldIII
	LeagueGoldII
	LeagueGoldI
	LeagueCrystalIII
	LeagueCrystalII
	LeagueCrystalI
	LeagueMasterIII
	LeagueMasterII
	LeagueMasterI
	LeagueChampionIII
	LeagueChampionII
	LeagueChampionI
	LeagueTitanIII
	LeagueTitanII
	LeagueTitanI
	LeagueLegend
)

Home village leagues

View Source
const (
	VillageHome    = "home"
	VillageBuilder = "builderBase"

	PlayerVerificationStatusOk      = "ok"
	PlayerVerificationStatusInvalid = "invalid"

	PlayerHouseElementTypeGround = "ground"
	PlayerHouseElementTypeRoof   = "roof"
	PlayerHouseElementTypeFoot   = "foot"
	PlayerHouseElementTypeDeco   = "deco"
)

Variables

View Source
var (
	AchievementBiggerCoffers           = &Achievement{Name: "Bigger Coffers"}
	AchievementGetThoseGoblins         = &Achievement{Name: "Get those Goblins!"}
	AchievementBiggerAndBetter         = &Achievement{Name: "Bigger & Better"}
	AchievementNiceAndTidy             = &Achievement{Name: "Nice and Tidy"}
	AchievementDiscoverNewTroops       = &Achievement{Name: "Discover New Troops"}
	AchievementGoldGrab                = &Achievement{Name: "Gold Grab"}
	AchievementElixirEscapade          = &Achievement{Name: "Elixir Escapade"}
	AchievementSweetVictory            = &Achievement{Name: "Sweet Victory!"}
	AchievementEmpireBuilder           = &Achievement{Name: "Empire Builder"}
	AchievementWallBuster              = &Achievement{Name: "Wall Buster"}
	AchievementHumiliator              = &Achievement{Name: "Humiliator"}
	AchievementUnionBuster             = &Achievement{Name: "Union Buster"}
	AchievementConqueror               = &Achievement{Name: "Conqueror"}
	AchievementUnbreakable             = &Achievement{Name: "Unbreakable"}
	AchievementFriendInNeed            = &Achievement{Name: "Friend in Need"}
	AchievementMortarMauler            = &Achievement{Name: "Mortar Mauler"}
	AchievementHeroicHeist             = &Achievement{Name: "Heroic Heist"}
	AchievementLeagueAllStar           = &Achievement{Name: "League All-Star"}
	AchievementXBowExterminator        = &Achievement{Name: "X-Bow Exterminator"}
	AchievementFirefighter             = &Achievement{Name: "Firefighter"}
	AchievementWarHero                 = &Achievement{Name: "War Hero"}
	AchievementClanWarWealth           = &Achievement{Name: "Clan War Wealth"}
	AchievementAntiArtillery           = &Achievement{Name: "Anti-Artillery"}
	AchievementSharingIsCaring         = &Achievement{Name: "Sharing is caring"}
	AchievementKeepYourAccountSafeOld  = &Achievement{Name: "Keep Your Account Safe!", Info: "Protect your village by connecting to a social network"}
	AchievementMasterEngineering       = &Achievement{Name: "Master Engineering"}
	AchievementNextGenerationModel     = &Achievement{Name: "Next Generation Model"}
	AchievementUnBuildIt               = &Achievement{Name: "Un-Build It"}
	AchievementChampionBuilder         = &Achievement{Name: "Champion Builder"}
	AchievementHighGear                = &Achievement{Name: "High Gear"}
	AchievementHiddenTreasures         = &Achievement{Name: "Hidden Treasures"}
	AchievementGamesChampion           = &Achievement{Name: "Games Champion"}
	AchievementDragonSlayer            = &Achievement{Name: "Dragon Slayer"}
	AchievementWarLeagueLegend         = &Achievement{Name: "War League Legend"}
	AchievementKeepYourAccountSafeSCID = &Achievement{Name: "Keep Your Account Safe!", Info: "Connect your account to Supercell ID for safe keeping."}
	AchievementWellSeasoned            = &Achievement{Name: "Well Seasoned"}
	AchievementShatteredAndScattered   = &Achievement{Name: "Shattered and Scattered"}
	AchievementNotSoEasyThisTime       = &Achievement{Name: "Not So Easy This Time"}
	AchievementBustThis                = &Achievement{Name: "Bust This"}
	AchievementSuperbWork              = &Achievement{Name: "Superb Work"}
	AchievementSiegeSharer             = &Achievement{Name: "Siege Sharer"}
	AchievementCounterspell            = &Achievement{Name: "Counterspell"}
	AchievementMonolithMasher          = &Achievement{Name: "Monolith Masher"}
	AchievementGetThoseOtherGoblins    = &Achievement{Name: "Get those other Goblins!"}
	AchievementGetEvenMoreGoblins      = &Achievement{Name: "Get even more Goblins!"}
	AchievementUngratefulChild         = &Achievement{Name: "Ungrateful Child"}
	AchievementAggressiveCapitalism    = &Achievement{Name: "Aggressive Capitalism"}
	AchievementMostValuableClanmate    = &Achievement{Name: "Most Valuable Clanmate"}
)

Functions

func CorrectTag

func CorrectTag(tag string) string

CorrectTag returns a valid Clash of Clans tag. It will be uppercase, have no special characters, and have a # at the beginning.

Credit to: https://github.com/mathsman5133/coc.py/blob/master/coc/utils.py

func TagURLSafe

func TagURLSafe(tag string) string

TagURLSafe encodes a tag to be used in a URL.

Types

type APIAccount

type APIAccount struct {
	Credentials *APIAccountCredentials
	Keys        [keysPerAccount]*APIKey
}

type APIAccountCredentials

type APIAccountCredentials struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

type APIError

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

APIError is the error directly returned by the Clash of Clans API. Every error returned by Client is ClientError, which embeds *APIError.

type APIKey

type APIKey struct {
	ID          string   `json:"id"`
	Origins     any      `json:"origins"`
	ValidUntil  any      `json:"validUntil"`
	DeveloperID string   `json:"developerId"`
	Tier        string   `json:"tier"`
	Name        string   `json:"name"`
	Description any      `json:"description"`
	Key         string   `json:"key"`
	Scopes      []string `json:"scopes"`
	CidrRanges  []string `json:"cidrRanges"`
}

type APIKeyIndex

type APIKeyIndex struct {
	AccountIndex int
	KeyIndex     int
}

APIKeyIndex is used to determine which account and key to use for a given request.

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"`
	CompletionInfo string `json:"completionInfo"`
	Village        string `json:"village"`
}

Achievement represents a Clash of Clans achievement. Use AchievementIndex* constants to index into the Achievements slice.

type BuilderBaseLeague

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

type Cache

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

Cache is a simple but performant in-memory cache.

func (*Cache) CacheResponse

func (c *Cache) CacheResponse(url string, res *resty.Response)

CacheResponse caches the response body of a resty.Response, using the Cache-Control header to determine the cache time.

func (*Cache) Get

func (c *Cache) Get(key string) ([]byte, bool)

Get gets a value from the cache, and a boolean indicating whether the value was found.

func (*Cache) Set

func (c *Cache) Set(key string, data []byte, duration time.Duration)

Set sets a value in the cache, with a duration after it gets removed.

type CapitalLeague

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

type Clan

type Clan struct {
	WarLeague                   WarLeague     `json:"warLeague"`
	CapitalLeague               CapitalLeague `json:"capitalLeague"`
	MemberList                  []ClanMember  `json:"memberList"`
	Tag                         string        `json:"tag"`
	ChatLanguage                Language      `json:"chatLanguage"`
	BuilderBasePoints           int           `json:"clanBuilderBasePoints"`
	RequiredBuilderBaseTrophies int           `json:"requiredBuilderBaseTrophies"`
	RequiredTownHallLevel       int           `json:"requiredTownhallLevel"`
	IsFamilyFriendly            bool          `json:"IsFamilyFriendly"`
	IsWarLogPublic              bool          `json:"isWarLogPublic"`
	WarFrequency                string        `json:"warFrequency"`
	Level                       int           `json:"clanLevel"`
	WarWinStreak                int           `json:"warWinStreak"`
	WarWins                     int           `json:"warWins"`
	WarTies                     int           `json:"warTies"`
	WarLosses                   int           `json:"warLosses"`
	Points                      int           `json:"clanPoints"`
	CapitalPoints               int           `json:"clanCapitalPoints"`
	RequiredTrophies            int           `json:"requiredTrophies"`
	Labels                      []Label       `json:"labels"`
	Name                        string        `json:"name"`
	Location                    Location      `json:"location"`
	Type                        string        `json:"type"`
	MemberCount                 int           `json:"members"`
	Description                 string        `json:"description"`
	ClanCapital                 ClanCapital   `json:"clanCapital"`
	BadgeURLs                   ImageURLs     `json:"badgeUrls"`
}

type ClanBuilderBaseRanking

type ClanBuilderBaseRanking struct {
	ClanPoints            int `json:"clanPoints"`
	ClanBuilderBasePoints int `json:"clanBuilderBasePoints"`
}

type ClanCapital

type ClanCapital struct {
	CapitalHallLevel int            `json:"capitalHallLevel"`
	Districts        []ClanDistrict `json:"districts"`
}

type ClanCapitalRaidSeason

type ClanCapitalRaidSeason struct {
	AttackLog               []ClanCapitalRaidSeasonAttackLogEntry  `json:"attackLog"`
	DefenseLog              []ClanCapitalRaidSeasonDefenseLogEntry `json:"defenseLog"`
	State                   string                                 `json:"state"`
	StartTime               string                                 `json:"startTime"`
	EndTime                 string                                 `json:"endTime"`
	CapitalTotalLoot        int                                    `json:"capitalTotalLoot"`
	RaidsCompleted          int                                    `json:"raidsCompleted"`
	TotalAttacks            int                                    `json:"totalAttacks"`
	EnemyDistrictsDestroyed int                                    `json:"enemyDistrictsDestroyed"`
	OffensiveReward         int                                    `json:"offensiveReward"`
	DefensiveReward         int                                    `json:"defensiveReward"`
	Members                 []ClanCapitalRaidSeasonMember          `json:"members"`
}

type ClanCapitalRaidSeasonAttack

type ClanCapitalRaidSeasonAttack struct {
	Attacker           ClanCapitalRaidSeasonAttacker `json:"attacker"`
	DestructionPercent int                           `json:"destructionPercent"`
	Stars              int                           `json:"stars"`
}

type ClanCapitalRaidSeasonAttackLogEntry

type ClanCapitalRaidSeasonAttackLogEntry struct {
	Defender           ClanCapitalRaidSeasonClanInfo   `json:"defender"`
	AttackCount        int                             `json:"attackCount"`
	DistrictCount      int                             `json:"districtCount"`
	DistrictsDestroyed int                             `json:"districtsDestroyed"`
	Districts          []ClanCapitalRaidSeasonDistrict `json:"districts"`
}

type ClanCapitalRaidSeasonAttacker

type ClanCapitalRaidSeasonAttacker struct {
	Tag  string `json:"tag"`
	Name string `json:"name"`
}

type ClanCapitalRaidSeasonClanInfo

type ClanCapitalRaidSeasonClanInfo struct {
	Tag       string    `json:"tag"`
	Name      string    `json:"name"`
	Level     int       `json:"level"`
	BadgeURLs ImageURLs `json:"badgeUrls"`
}

type ClanCapitalRaidSeasonDefenseLogEntry

type ClanCapitalRaidSeasonDefenseLogEntry struct {
	Attacker           ClanCapitalRaidSeasonClanInfo   `json:"attacker"`
	AttackCount        int                             `json:"attackCount"`
	DistrictCount      int                             `json:"districtCount"`
	DistrictsDestroyed int                             `json:"districtsDestroyed"`
	Districts          []ClanCapitalRaidSeasonDistrict `json:"districts"`
}

type ClanCapitalRaidSeasonDistrict

type ClanCapitalRaidSeasonDistrict struct {
	Stars              int                           `json:"stars"`
	Name               string                        `json:"name"`
	ID                 int                           `json:"id"`
	DestructionPercent int                           `json:"destructionPercent"`
	AttackCount        int                           `json:"attackCount"`
	TotalLooted        int                           `json:"totalLooted"`
	Attacks            []ClanCapitalRaidSeasonAttack `json:"attacks"`
	DistrictHallLevel  int                           `json:"districtHallLevel"`
}

type ClanCapitalRaidSeasonMember

type ClanCapitalRaidSeasonMember struct {
	Tag                    string `json:"tag"`
	Name                   string `json:"name"`
	Attacks                int    `json:"attacks"`
	AttackLimit            int    `json:"attackLimit"`
	BonusAttackLimit       int    `json:"bonusAttackLimit"`
	CapitalResourcesLooted int    `json:"capitalResourcesLooted"`
}

type ClanCapitalRanking

type ClanCapitalRanking struct {
	ClanPoints        int `json:"clanPoints"`
	ClanCapitalPoints int `json:"clanCapitalPoints"`
}

type ClanDistrict

type ClanDistrict struct {
	Name              string `json:"name"`
	ID                int    `json:"id"`
	DistrictHallLevel int    `json:"districtHallLevel"`
}

type ClanMember

type ClanMember struct {
	Tag  string `json:"tag"`
	Name string `json:"name"`
}

type ClanRanking

type ClanRanking struct {
	ClanLevel    int       `json:"clanLevel"`
	ClanPoints   int       `json:"clanPoints"`
	Location     Location  `json:"location"`
	Members      int       `json:"members"`
	Tag          string    `json:"tag"`
	Name         string    `json:"name"`
	Rank         int       `json:"rank"`
	PreviousRank int       `json:"previousRank"`
	BadgeURLs    ImageURLs `json:"badgeUrls"`
}

type ClanRole

type ClanRole string
const (
	ClanRoleNotMember ClanRole = "notMember"
	ClanRoleMember    ClanRole = "member"
	ClanRoleAdmin     ClanRole = "admin"
	ClanRoleCoLeader  ClanRole = "coLeader"
	ClanRoleLeader    ClanRole = "leader"
)

func (ClanRole) Format

func (r ClanRole) Format() string

func (ClanRole) String

func (r ClanRole) String() string

type ClanWar

type ClanWar struct {
	Clan                 WarClan      `json:"clan"`
	Opponent             WarClan      `json:"opponent"`
	TeamSize             int          `json:"teamSize"`
	StartTime            string       `json:"startTime"`
	State                ClanWarState `json:"state"`
	EndTime              string       `json:"endTime"`
	PreparationStartTime string       `json:"preparationStartTime"`
}

type ClanWarAttack

type ClanWarAttack struct {
	Order                 int    `json:"order"`
	AttackerTag           string `json:"attackerTag"`
	DefenderTag           string `json:"defenderTag"`
	Stars                 int    `json:"stars"`
	DestructionPercentage int    `json:"destructionPercentage"`
	Duration              int    `json:"duration"`
}

type ClanWarLeagueClan

type ClanWarLeagueClan struct {
	Tag       string                    `json:"tag"`
	ClanLevel int                       `json:"clanLevel"`
	Name      string                    `json:"name"`
	Members   []ClanWarLeagueClanMember `json:"members"`
	BadgeURLs ImageURLs                 `json:"badgeUrls"`
}

type ClanWarLeagueClanMember

type ClanWarLeagueClanMember struct {
	Tag           string `json:"tag"`
	TownHallLevel int    `json:"townHallLevel"`
	Name          string `json:"name"`
}

type ClanWarLeagueGroup

type ClanWarLeagueGroup struct {
	Tag    string                  `json:"tag"`
	State  ClanWarLeagueGroupState `json:"state"`
	Season string                  `json:"season"`
	Clans  []ClanWarLeagueClan
	Rounds []ClanWarLeagueRound
}

type ClanWarLeagueGroupState

type ClanWarLeagueGroupState = string
const (
	ClanWarLeagueGroupStateNotFound ClanWarLeagueGroupState = "groupNotFound"
	ClanWarLeagueGroupStateNotInWar ClanWarLeagueGroupState = "notInWar"
	ClanWarLeagueGroupStatePrep     ClanWarLeagueGroupState = "preparation"
	ClanWarLeagueGroupStateWar      ClanWarLeagueGroupState = "war"
	ClanWarLeagueGroupStateEnded    ClanWarLeagueGroupState = "ended"
)

type ClanWarLeagueRound

type ClanWarLeagueRound struct {
	WarTags []string `json:"warTags"`
}

type ClanWarLogEntry

type ClanWarLogEntry struct {
	Clan             WarClan       `json:"clan"`
	Opponent         WarClan       `json:"opponent"`
	TeamSize         int           `json:"teamSize"`
	AttacksPerMember int           `json:"attacksPerMember"`
	EndTime          string        `json:"endTime"`
	Result           ClanWarResult `json:"result"`
}

type ClanWarMember

type ClanWarMember struct {
	Tag                string          `json:"tag"`
	Name               string          `json:"name"`
	MapPosition        int             `json:"mapPosition"`
	TownHallLevel      int             `json:"townHallLevel"`
	OpponentAttacks    int             `json:"opponentAttacks"`
	BestOpponentAttack *ClanWarAttack  `json:"bestOpponentAttack,omitempty"`
	Attacks            []ClanWarAttack `json:"attacks,omitempty"`
}

type ClanWarResult

type ClanWarResult = string
const (
	ClanWarResultWin  ClanWarResult = "win"
	ClanWarResultLose ClanWarResult = "lose"
	ClanWarResultTie  ClanWarResult = "tie"
)

type ClanWarState

type ClanWarState = string
const (
	ClanWarStateClanNotFound  ClanWarState = "clanNotFound"
	ClanWarStateAccessDenied  ClanWarState = "accessDenied"
	ClanWarStateNotInWar      ClanWarState = "notInWar"
	ClanWarStateInMatchmaking ClanWarState = "inMatchmaking"
	ClanWarStateEnterWar      ClanWarState = "enterWar"
	ClanWarStateMatched       ClanWarState = "matched"
	ClanWarStatePreparation   ClanWarState = "preparation"
	ClanWarStateWar           ClanWarState = "war"
	ClanWarStateInWar         ClanWarState = "inWar"
	ClanWarStateEnded         ClanWarState = "ended"
)

type Clans

type Clans []*Clan

func (Clans) Tags

func (c Clans) Tags() []string

type Client

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

func New

func New(creds Credentials) (*Client, error)

New creates a new clash client, using the provided credentials.

func (*Client) GetBuilderBaseLeague

func (h *Client) GetBuilderBaseLeague(id string) (*BuilderBaseLeague, error)

GetBuilderBaseLeague returns information about a single builder base league.

GET /builderbaseleagues/{leagueId}

func (*Client) GetBuilderBaseLeagues

func (h *Client) GetBuilderBaseLeagues(params *PagingParams) (*PaginatedResponse[BuilderBaseLeague], error)

GetBuilderBaseLeagues returns a list of builder base leagues. Pass params=nil to get all leagues.

GET /builderbaseleagues

func (*Client) GetCapitalLeague

func (h *Client) GetCapitalLeague(id string) (*CapitalLeague, error)

GetCapitalLeague returns information about a single capital league.

GET /capitalleagues/{leagueId}

func (*Client) GetCapitalLeagues

func (h *Client) GetCapitalLeagues(params *PagingParams) (*PaginatedResponse[CapitalLeague], error)

GetCapitalLeagues returns a paginated list of capital leagues. Pass params=nil to get all leagues.

GET /capitalleagues

func (*Client) GetClan

func (h *Client) GetClan(tag string) (*Clan, error)

GetClan returns a clan by its tag.

GET /clans/{clanTag}

func (*Client) GetClanBuilderBaseRankings

func (h *Client) GetClanBuilderBaseRankings(locationID int, params *PagingParams) (*PaginatedResponse[ClanBuilderBaseRanking], error)

GetClanBuilderBaseRankings returns a paginated list of clan builder base rankings for a specific location.

GET /locations/{locationId}/rankings/clans-builder-base

func (*Client) GetClanCapitalRaidSeasons

func (h *Client) GetClanCapitalRaidSeasons(tag string, params *PagingParams) (*PaginatedResponse[ClanCapitalRaidSeason], error)

func (*Client) GetClanCapitalRankings

func (h *Client) GetClanCapitalRankings(locationID int, params *PagingParams) (*PaginatedResponse[ClanCapitalRanking], error)

GetClanCapitalRankings returns a paginated list of clan capital rankings for a specific location.

GET /locations/{locationId}/rankings/capitals

func (*Client) GetClanLabels

func (h *Client) GetClanLabels(params *PagingParams) (*PaginatedResponse[Label], error)

GetClanLabels returns a paginated list of clan labels. Pass params=nil to get all labels.

func (*Client) GetClanMembers

func (h *Client) GetClanMembers(tag string, params *PagingParams) (*PaginatedResponse[ClanMember], error)

func (*Client) GetClanRankings

func (h *Client) GetClanRankings(locationID int, params *PagingParams) (*PaginatedResponse[ClanRanking], error)

GetClanRankings returns a paginated list of clan rankings for a specific location.

GET /locations/{locationId}/rankings/clans

func (*Client) GetClanWarLeagueWar

func (h *Client) GetClanWarLeagueWar(warTag string) (*ClanWarLeagueGroup, error)

GetClanWarLeagueWar returns information about a single war within a clan war league.

GET /clanwarleagues/wars/{warTag}

func (*Client) GetClanWarLog

func (h *Client) GetClanWarLog(tag string, params *PagingParams) (*PaginatedResponse[ClanWarLogEntry], error)

GetClanWarLog returns a clan's war log.

GET /clans/{clanTag}/warlog

func (*Client) GetClans

func (h *Client) GetClans(tags ...string) (Clans, error)

GetClans makes use of concurrency to get multiple clans simultaneously. The original order of the tags is preserved.

func (*Client) GetCurrentClanWar

func (h *Client) GetCurrentClanWar(tag string) (*ClanWar, error)

GetCurrentClanWar returns information about a clan's current clan war.

GET /clans/{clanTag}/currentwar

func (*Client) GetCurrentClanWarLeagueGroup

func (h *Client) GetCurrentClanWarLeagueGroup(tag string) (*ClanWarLeagueGroup, error)

GetCurrentClanWarLeagueGroup returns the current war league group for a clan.

GET /clans/{clanTag}/currentwar/leaguegroup

func (*Client) GetCurrentGoldPassSeason

func (h *Client) GetCurrentGoldPassSeason() (*GoldPassSeason, error)

GetCurrentGoldPassSeason returns the current gold pass season.

GET /goldpass/seasons/current

func (*Client) GetLeague

func (h *Client) GetLeague(id string) (*League, error)

GetLeague returns information about a single league.

GET /leagues/{leagueId}

func (*Client) GetLeagueSeasons

func (h *Client) GetLeagueSeasons(id int, params *PagingParams) (*PaginatedResponse[LeagueSeason], error)

GetLeagueSeasons returns a list of league seasons. Pass params=nil to get all seasons.

GET /leagues/{leagueId}/seasons

func (*Client) GetLeagues

func (h *Client) GetLeagues(params *PagingParams) (*PaginatedResponse[League], error)

GetLeagues returns a paginated list of leagues. Pass params=nil to get all leagues.

GET /leagues

func (*Client) GetLegendLeagueRanking

func (h *Client) GetLegendLeagueRanking(leagueID, seasonID string, params *PagingParams) (*PaginatedResponse[PlayerRankingList], error)

GetLegendLeagueRanking returns a paginated list of players in the provided legend league season.

GET /leagues/{leagueId}/seasons/{seasonId}

func (*Client) GetLocation

func (h *Client) GetLocation(locationID int) (*Location, error)

GetLocation returns information about a specific location.

GET /locations/{locationId}

func (*Client) GetLocations

func (h *Client) GetLocations(params *PagingParams) (*PaginatedResponse[Location], error)

GetLocations returns a paginated list of all available locations.

GET /locations

func (*Client) GetPlayer

func (h *Client) GetPlayer(tag string) (*Player, error)

GetPlayer returns information about a single player by tag.

GET /players/{playerTag}

func (*Client) GetPlayerBuilderBaseRankings

func (h *Client) GetPlayerBuilderBaseRankings(locationID int, params *PagingParams) (*PaginatedResponse[PlayerBuilderBaseRanking], error)

GetPlayerBuilderBaseRankings returns a paginated list of player builder base rankings for a specific location.

GET /locations/{locationId}/rankings/players-builder-base

func (*Client) GetPlayerLabels

func (h *Client) GetPlayerLabels(params *PagingParams) (*PaginatedResponse[Label], error)

GetPlayerLabels returns a paginated list of player labels. Pass params=nil to get all labels.

func (*Client) GetPlayerRankings

func (h *Client) GetPlayerRankings(locationID int, params *PagingParams) (*PaginatedResponse[PlayerRanking], error)

GetPlayerRankings returns a paginated list of player rankings for a specific location.

GET /locations/{locationId}/rankings/players

func (*Client) GetPlayers

func (h *Client) GetPlayers(tags ...string) Players

GetPlayers makes use of concurrency to get multiple players simultaneously. Players that failed to be fetched will be nil in the returned slice.

func (*Client) GetPlayersWithError added in v1.0.8

func (h *Client) GetPlayersWithError(tags ...string) (Players, error)

GetPlayersWithError makes use of concurrency to get multiple players simultaneously. Unlike GetPlayers, this function returns nil and error if any of the players failed to be fetched.

func (*Client) GetWarLeague

func (h *Client) GetWarLeague(id string) (*WarLeague, error)

GetWarLeague returns information about a single war league.

GET /warleagues/{leagueId}

func (*Client) GetWarLeagues

func (h *Client) GetWarLeagues(params *PagingParams) ([]*WarLeague, error)

GetWarLeagues returns a list of war leagues. Pass params=nil to get all leagues.

GET /warleagues

func (*Client) SearchClans

func (h *Client) SearchClans(params SearchClanParams) (*PaginatedResponse[Clan], error)

SearchClans returns a list of clans that match the given params.

GET /clans

func (*Client) SetCacheTime

func (h *Client) SetCacheTime(d time.Duration)

SetCacheTime sets a fixed cache time, ignoring CacheControl headers. Disable by passing 0 as argument.

func (*Client) UseCache

func (h *Client) UseCache(v bool)

UseCache sets whether to use cache.

Cache is capable of storing large amounts of data in memory, across different shards. Using it together with SetCacheTime may replace the need for a store like Redis, depending on your needs.

func (*Client) VerifyPlayer

func (h *Client) VerifyPlayer(tag, token string) (*PlayerVerification, error)

VerifyPlayer verifies a player token.

POST /players/{playerTag}/verifytoken

type ClientError

type ClientError struct {
	*APIError
	Status int `json:"status"`
}

ClientError is the error type returned by the client.

func (*ClientError) Error

func (e *ClientError) Error() string

type CreateKeyResponse

type CreateKeyResponse struct {
	Key                     *APIKey `json:"key,omitempty"`
	Status                  Status  `json:"status"`
	SessionExpiresInSeconds int     `json:"sessionExpiresInSeconds"`
}

type Credentials

type Credentials map[string]string

Credentials is a map of email to password.

type CurrentSeason

type CurrentSeason struct {
	Rank     int `json:"rank,omitempty"`
	Trophies int `json:"trophies,omitempty"`
}

type DevEndpoint

type DevEndpoint string
const (
	DevBaseURL                       = "https://developer.clashofclans.com"
	DevLoginEndpoint     DevEndpoint = "/api/login"
	DevKeyListEndpoint   DevEndpoint = "/api/apikey/list"
	DevKeyCreateEndpoint DevEndpoint = "/api/apikey/create"
	DevKeyRevokeEndpoint DevEndpoint = "/api/apikey/revoke"
	IPifyEndpoint                    = "https://api.ipify.org"
)

func (DevEndpoint) URL

func (e DevEndpoint) URL() string

type Developer

type Developer struct {
	ID            string   `json:"id"`
	Name          string   `json:"name"`
	Game          string   `json:"game"`
	Tier          string   `json:"tier"`
	AllowedScopes []string `json:"allowedScopes"`
	MaxCidrs      int      `json:"maxCidrs"`
	PrevLoginTS   string   `json:"prevLoginTs"`
	PrevLoginIP   string   `json:"prevLoginIp"`
	PrevLoginUA   string   `json:"prevLoginUa"`
}

type Endpoint

type Endpoint string
const (
	BaseURL                             = "https://api.clashofclans.com/v1"
	ClansEndpoint              Endpoint = "/clans"
	ClanWarLeaguesEndpoint     Endpoint = "/clanwarleagues"
	PlayersEndpoint            Endpoint = "/players"
	LeaguesEndpoint            Endpoint = "/leagues"
	WarLeaguesEndpoint         Endpoint = "/warleagues"
	BuilderBaseLeaguesEndpoint Endpoint = "/builderbaseleagues"
	CapitalLeaguesEndpoint     Endpoint = "/capitalleagues"
	LocationsEndpoint          Endpoint = "/locations"
	GoldPassEndpoint           Endpoint = "/goldpass/seasons/current"
	LabelsEndpoint             Endpoint = "/labels"
)

func (Endpoint) Build

func (e Endpoint) Build(routes ...string) string

Build returns the full URL for the endpoint.

Example: PlayersEndpoint.Build("ABC123") returns "https://api.clashofclans.com/v1/players/ABC123"

type GoldPassSeason

type GoldPassSeason struct {
	StartTime string
	EndTime   string
}

type ImageURLs

type ImageURLs struct {
	Tiny   string `json:"tiny,omitempty"`
	Small  string `json:"small,omitempty"`
	Medium string `json:"medium,omitempty"`
	Large  string `json:"large,omitempty"`
}

type IndexedAchievement added in v1.0.1

type IndexedAchievement struct {
	*Achievement
	Index int
}

IndexedAchievement embeds Achievement and adds the index of the achievement in the Player.Achievements slice to it.

type KeyListResponse

type KeyListResponse struct {
	Keys                    []*APIKey `json:"keys,omitempty"`
	Status                  Status    `json:"status"`
	SessionExpiresInSeconds int       `json:"sessionExpiresInSeconds"`
}

type Label

type Label struct {
	IconUrls ImageURLs `json:"iconUrls,omitempty"`
	Name     string    `json:"name,omitempty"`
	ID       int       `json:"id,omitempty"`
}

type LabelsData

type LabelsData struct {
	Paging *Paging `json:"paging,omitempty"`
	Labels []Label `json:"items,omitempty"`
}

type Language

type Language struct {
	Name         string `json:"name"`
	ID           int    `json:"id"`
	LanguageCode string `json:"languageCode"`
}

type League

type League struct {
	IconUrls ImageURLs `json:"iconUrls,omitempty"`
	Name     string    `json:"name,omitempty"`
	ID       int       `json:"id,omitempty"`
}

type LeagueData

type LeagueData struct {
	Paging  Paging   `json:"paging,omitempty"`
	Leagues []League `json:"items,omitempty"`
}

type LeagueSeason

type LeagueSeason struct {
	ID string `json:"id"`
}

type LegendStatistics

type LegendStatistics struct {
	PreviousSeason   Season        `json:"previousSeason,omitempty"`
	BestSeason       Season        `json:"bestSeason,omitempty"`
	BestVersusSeason Season        `json:"bestVersusSeason,omitempty"`
	CurrentSeason    CurrentSeason `json:"currentSeason,omitempty"`
	LegendTrophies   int           `json:"legendTrophies,omitempty"`
}

type Location

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

type PaginatedResponse

type PaginatedResponse[T any] struct {
	Paging Paging `json:"paging,omitempty"`
	Items  []T    `json:"items,omitempty"`
}

PaginatedResponse represents a paginated response from the API.

type Paging

type Paging struct {
	Cursors PagingCursors `json:"cursors,omitempty"`
}

Paging represents the paging information returned by the API.

type PagingCursors

type PagingCursors struct {
	Before string `json:"before,omitempty"`
	After  string `json:"after,omitempty"`
}

PagingCursors represents the paging cursors returned by the API.

type PagingParams

type PagingParams struct {
	PagingCursors
	Limit int `json:"limit,omitempty"`
}

PagingParams represents the parameters for a paginated request.

type Player

type Player struct {
	*PlayerBase
	WarPreference       string            `json:"warPreference"`
	TownHallWeaponLevel int               `json:"townHallWeaponLevel"`
	LegendStatistics    LegendStatistics  `json:"legendStatistics"`
	Troops              []PlayerItemLevel `json:"troops"`
	Heroes              []PlayerItemLevel `json:"heroes,omitempty"`
	HeroEquipment       []PlayerItemLevel `json:"heroEquipment,omitempty"`
	Spells              []PlayerItemLevel `json:"spells"`
	Labels              []Label           `json:"labels"`
	Achievements        []Achievement     `json:"achievements"`
	PlayerHouse         PlayerHouse       `json:"playerHouse"`
}

Player is a player returned by the API.

func (*Player) GetAchievement added in v1.0.1

func (p *Player) GetAchievement(achievement *Achievement) (*IndexedAchievement, error)

GetAchievement returns an IndexedAchievement by Achievement.Name and Achievement.Info. The index can be used to get the same achievement from other players, to make it more efficient.

func (*Player) InGameURL

func (p *Player) InGameURL() string

InGameURL returns a link.clashofclans.com URL that can be used to open the player profile in game.

type PlayerBase

type PlayerBase struct {
	League                   League            `json:"league"`
	BuilderBaseLeague        BuilderBaseLeague `json:"builderBaseLeague"`
	Clan                     PlayerClan        `json:"clan"`
	Role                     ClanRole          `json:"role"`
	AttackWins               int               `json:"attackWins"`
	DefenseWins              int               `json:"defenseWins"`
	TownHallLevel            int               `json:"townHallLevel"`
	Tag                      string            `json:"tag"`
	Name                     string            `json:"name"`
	ExpLevel                 int               `json:"expLevel"`
	Trophies                 int               `json:"trophies"`
	BestTrophies             int               `json:"bestTrophies"`
	Donations                int               `json:"donations"`
	DonationsReceived        int               `json:"donationsReceived"`
	BuilderHallLevel         int               `json:"builderHallLevel"`
	BuilderBaseTrophies      int               `json:"builderBaseTrophies"`
	BestBuilderBaseTrophies  int               `json:"bestBuilderBaseTrophies"`
	WarStars                 int               `json:"warStars"`
	ClanCapitalContributions int               `json:"clanCapitalContributions"`
}

PlayerBase is embedded in Player and contains the most basic information about a player. May be used as DTO.

type PlayerBuilderBaseRanking

type PlayerBuilderBaseRanking struct {
	BuilderBaseLeague   BuilderBaseLeague `json:"builderBaseLeague"`
	Clan                PlayerRankingClan `json:"clan"`
	Tag                 string            `json:"tag"`
	Name                string            `json:"name"`
	ExpLevel            int               `json:"expLevel"`
	Rank                int               `json:"rank"`
	PreviousRank        int               `json:"previousRank"`
	BuilderBaseTrophies int               `json:"builderBaseTrophies"`
}

type PlayerClan

type PlayerClan struct {
	Tag       string    `json:"tag"`
	Level     int       `json:"clanLevel"`
	Name      string    `json:"name"`
	BadgeURLs ImageURLs `json:"badgeUrls"`
}

type PlayerHouse

type PlayerHouse struct {
	Elements []PlayerHouseElement `json:"elements"`
}

type PlayerHouseElement

type PlayerHouseElement struct {
	ID   int    `json:"id"`
	Type string `json:"type"`
}

type PlayerItemLevel

type PlayerItemLevel struct {
	Name               string            `json:"name"`
	Village            string            `json:"village"`
	Level              int               `json:"level"`
	MaxLevel           int               `json:"maxLevel"`
	SuperTroopIsActive bool              `json:"superTroopIsActive,omitempty"`
	Equipment          []PlayerItemLevel `json:"equipment,omitempty"`
}

type PlayerRanking

type PlayerRanking struct {
	League       League            `json:"league"`
	Clan         PlayerRankingClan `json:"clan"`
	AttackWins   int               `json:"attackWins"`
	DefenseWins  int               `json:"defenseWins"`
	Tag          string            `json:"tag"`
	Name         string            `json:"name"`
	ExpLevel     int               `json:"expLevel"`
	Rank         int               `json:"rank"`
	PreviousRank int               `json:"previousRank"`
	Trophies     int               `json:"trophies"`
}

type PlayerRankingClan

type PlayerRankingClan struct {
	Tag       string    `json:"tag"`
	Name      string    `json:"name"`
	BadgeURLs ImageURLs `json:"badgeUrls"`
}

type PlayerRankingList

type PlayerRankingList struct {
	League       League            `json:"league"`
	Clan         PlayerRankingClan `json:"clan"`
	AttackWins   int               `json:"attackWins"`
	DefenseWins  int               `json:"defenseWins"`
	Tag          string            `json:"tag"`
	Name         string            `json:"name"`
	ExpLevel     int               `json:"expLevel"`
	Rank         int               `json:"rank"`
	PreviousRank int               `json:"previousRank"`
	Trophies     int               `json:"trophies"`
}

PlayerRankingList contains information about a player's ranking.

type PlayerVerification

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

func (*PlayerVerification) IsOk

func (v *PlayerVerification) IsOk() bool

type Players

type Players []*Player

func (Players) GetAchievement added in v1.0.1

func (p Players) GetAchievement(achievement *Achievement) ([]*Achievement, error)

func (Players) String added in v1.0.6

func (p Players) String() string

String implements fmt.Stringer, returning a comma-separated list of player names.

func (Players) Tags

func (p Players) Tags() []string

type SearchClanParams

type SearchClanParams struct {
	*PagingParams
	Name          string   `json:"name,omitempty"`
	WarFrequency  string   `json:"warFrequency,omitempty"`
	LocationID    string   `json:"locationId,omitempty"`
	MinMembers    string   `json:"minMembers,omitempty"`
	MaxMembers    string   `json:"maxMembers,omitempty"`
	MinClanPoints string   `json:"minClanPoints,omitempty"`
	MinClanLevel  string   `json:"minClanLevel,omitempty"`
	LabelIDs      []string `json:"labelIds,omitempty"`
}

type Season

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

type Status

type Status struct {
	Detail  any    `json:"detail"`
	Message string `json:"message,omitempty"`
	Code    int    `json:"code,omitempty"`
}

type WarClan

type WarClan struct {
	DestructionPercentage float64         `json:"destructionPercentage"`
	Tag                   string          `json:"tag"`
	Name                  string          `json:"name"`
	BadgeURLs             ImageURLs       `json:"badgeUrls"`
	ClanLevel             int             `json:"clanLevel"`
	Attacks               int             `json:"attacks"`
	Stars                 int             `json:"stars"`
	ExpEarned             int             `json:"expEarned"`
	Members               []ClanWarMember `json:"members"`
}

type WarLeague

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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