clashy

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 4, 2026 License: MIT Imports: 18 Imported by: 0

README

clashy.go

Easy-to-use Go SDK for the Clash of Clans API.

Key Features

  • Go-native client built around context.Context
  • Broad coverage of the official Clash of Clans API
  • Developer-site email/password login, or direct token login
  • Built-in rate limiting, caching, and static game-data helpers

Getting Started

Installing

Go 1.25 or higher is required

go get github.com/clashkinginc/clashy.go

To use the latest development version:

go get github.com/clashkinginc/clashy.go@main

Quick Example

This is the basic usage of the library. This example logs in, fetches a player, searches for clans, and loads the current war for a clan.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	clashy "github.com/clashkinginc/clashy.go"
)

func main() {
	ctx := context.Background()

	client, err := clashy.NewClient(clashy.DefaultClientConfig())
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = client.Close() }()

	if err := client.Login(ctx, "email", "password"); err != nil {
		var invalid *clashy.InvalidCredentials
		if errors.As(err, &invalid) {
			log.Fatal("invalid developer credentials")
		}
		log.Fatal(err)
	}

	player, err := client.GetPlayer(ctx, "#TAG")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s has %d trophies\n", player.Name, player.Trophies)

	clans, err := client.SearchClans(ctx, clashy.SearchClansRequest{
		Name:  "best clan ever",
		Limit: 5,
	})
	if err != nil {
		log.Fatal(err)
	}

	for _, clan := range clans {
		fmt.Printf("%s (%s) has %d members\n", clan.Name, clan.Tag, clan.MemberCount)
	}

	war, err := client.GetCurrentWar(ctx, "#CLANTAG")
	if err != nil {
		var privateWarLog *clashy.PrivateWarLog
		if errors.As(err, &privateWarLog) {
			fmt.Println("uh oh, they have a private war log")
			return
		}
		log.Fatal(err)
	}

	fmt.Printf("%s is currently in %s state\n", war.ClanTag, war.State)
}

If you already have API tokens, you can skip developer-site login:

package main

import (
	"context"
	"log"

	clashy "github.com/clashkinginc/clashy.go"
)

func main() {
	ctx := context.Background()

	client, err := clashy.NewClient(clashy.DefaultClientConfig())
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = client.Close() }()

	if err := client.LoginWithTokens(ctx, "your-api-token"); err != nil {
		log.Fatal(err)
	}
}

Other Features

The client also includes helpers for:

  • locations, rankings, leagues, labels, and gold pass endpoints
  • battle logs, raid logs, war logs, and CWL data
  • player token verification
  • static game-data lookups such as troops, spells, heroes, pets, equipment, and translations

Contributing

Contributions are welcome. If you find a bug or want to add functionality, open an issue or submit a pull request.

To run the test suite:

go test ./...

Disclaimer

This content is not affiliated with, endorsed, sponsored, or specifically approved by Supercell, and Supercell is not responsible for it. For more information, see Supercell's Fan Content Policy.

Documentation

Overview

Package clashy provides a Go SDK for the Clash of Clans API.

It ports the major functionality of cocpy while using Go conventions for contexts, interfaces, generics, and package structure.

Index

Constants

This section is empty.

Variables

View Source
var (
	TroopBaseID      = 4000000
	SpellBaseID      = 26000000
	HeroBaseID       = 2000000
	PetBaseID        = 60000000
	EquipmentBaseID  = 30000000
	ElixirTroopOrder = []string{
		"Barbarian",
		"Archer",
		"Goblin",
		"Giant",
		"Wall Breaker",
		"Balloon",
		"Wizard",
		"Healer",
		"Dragon",
		"P.E.K.K.A",
		"Baby Dragon",
		"Miner",
		"Yeti",
		"Electro Dragon",
		"Dragon Rider",
		"Electro Titan",
		"Root Rider",
		"Thrower",
		"Meteor Golem",
	}
	DarkElixirTroopOrder = []string{
		"Minion",
		"Hog Rider",
		"Valkyrie",
		"Golem",
		"Witch",
		"Lava Hound",
		"Bowler",
		"Ice Golem",
		"Headhunter",
		"Apprentice Warden",
		"Druid",
		"Furnace",
	}
	HomeTroopOrder    = append(append([]string{}, ElixirTroopOrder...), DarkElixirTroopOrder...)
	SiegeMachineOrder = []string{
		"Wall Wrecker",
		"Battle Blimp",
		"Stone Slammer",
		"Siege Barracks",
		"Log Launcher",
		"Flame Flinger",
		"Battle Drill",
		"Troop Launcher",
		"Sky Wagon",
	}
	SuperTroopOrder = []string{
		"Super Barbarian",
		"Super Archer",
		"Super Wall Breaker",
		"Super Giant",
		"Sneaky Goblin",
		"Super Miner",
		"Rocket Balloon",
		"Inferno Dragon",
		"Super Valkyrie",
		"Super Witch",
		"Ice Hound",
		"Super Bowler",
		"Super Dragon",
		"Super Wizard",
		"Super Minion",
		"Super Hog Rider",
		"Super Yeti",
	}
	HomeTroopOrderWithSieges = append(append([]string{}, HomeTroopOrder...), SiegeMachineOrder...)
	SeasonalTroopOrder       = []string{
		"Ice Wizard",
		"Battle Ram",
		"Royal Ghost",
		"Pumpkin Barbarian",
		"Giant Skeleton",
		"Skeleton Barrel",
		"M.E.C.H.A",
		"Party Wizard",
		"Ram Rider",
		"Barcher",
		"Witch Golem",
		"Hog Wizard",
		"Lavaloon",
		"C.O.O.K.I.E",
		"Firecracker",
		"Azure Dragon",
		"Barbarian Kicker",
		"Giant Thrower",
		"Broom Witch",
		"Ice Minion",
		"Debt Collector",
		"Snake Barrel",
		"Giant Giant",
		"K.A.N.E",
		"The Disarmer",
		"YEETer",
		"YEETer",
		"The Disarmer",
		"Meteor Golem",
	}
	BuilderTroopOrder = []string{
		"Raged Barbarian",
		"Sneaky Archer",
		"Beta Minion",
		"Boxer Giant",
		"Bomber",
		"Power P.E.K.K.A",
		"Cannon Cart",
		"Drop Ship",
		"Baby Dragon",
		"Night Witch",
		"Hog Glider",
		"Electrofire Wizard",
	}
	ElixirSpellOrder = []string{
		"Lightning Spell",
		"Healing Spell",
		"Rage Spell",
		"Jump Spell",
		"Freeze Spell",
		"Clone Spell",
		"Invisibility Spell",
		"Recall Spell",
		"Revive Spell",
		"Totem Spell",
	}
	DarkElixirSpellOrder = []string{
		"Poison Spell",
		"Earthquake Spell",
		"Haste Spell",
		"Skeleton Spell",
		"Bat Spell",
		"Overgrowth Spell",
		"Ice Block Spell",
	}
	SeasonalSpellOrder = []string{
		"Santa's Surprise",
		"Bag of Frostmites",
	}
	SpellOrder        = append(append([]string{}, ElixirSpellOrder...), DarkElixirSpellOrder...)
	HomeBaseHeroOrder = []string{
		"Barbarian King",
		"Archer Queen",
		"Minion Prince",
		"Grand Warden",
		"Royal Champion",
		"Dragon Duke",
	}
	BuilderBaseHeroOrder = []string{
		"Battle Machine",
		"Battle Copter",
	}
	HeroOrder = append(append([]string{}, HomeBaseHeroOrder...), BuilderBaseHeroOrder...)
	PetOrder  = []string{
		"L.A.S.S.I",
		"Mighty Yak",
		"Electro Owl",
		"Unicorn",
		"Phoenix",
		"Poison Lizard",
		"Diggy",
		"Frosty",
		"Spirit Fox",
		"Angry Jelly",
		"Sneezy",
		"Greedy Raven",
	}
	EquipmentOrder = []string{
		"Barbarian Puppet",
		"Rage Vial",
		"Archer Puppet",
		"Invisibility Vial",
		"Eternal Tome",
		"Life Gem",
		"Seeking Shield",
		"Royal Gem",
		"Earthquake Boots",
		"Hog Rider Puppet",
		"Giant Gauntlet",
		"Vampstache",
		"Haste Vial",
		"Rocket Spear",
		"Spiky Ball",
		"Frozen Arrow",
		"Giant Arrow",
		"Heroic Torch",
		"Healer Puppet",
		"Fireball",
		"Rage Gem",
		"Snake Bracelet",
		"Healing Tome",
		"Dark Crown",
		"Magic Mirror",
		"Electro Boots",
		"Lavaloon Puppet",
		"Henchmen Puppet",
		"Dark Orb",
		"Metal Pants",
		"Noble Iron",
		"Action Figure",
		"Meteor Staff",
		"Frost Flake",
		"Stick Horse",
		"Fire Heart",
		"Rocket Backpack",
		"Stun Blaster",
		"Flame Blower",
		"Electro Fangs",
	}
	HVBuildingOrder = []string{
		"Army Camp",
		"Town Hall",
		"Elixir Collector",
		"Elixir Storage",
		"Gold Mine",
		"Gold Storage",
		"Barracks",
		"Laboratory",
		"Cannon",
		"Archer Tower",
		"Wall",
		"Wizard Tower",
		"Air Defense",
		"Mortar",
		"Clan Castle",
		"Builder's Hut",
		"Hidden Tesla",
		"Spell Factory",
		"X-Bow",
		"Dark Elixir Drill",
		"Dark Elixir Storage",
		"Dark Barracks",
		"Inferno Tower",
		"Air Sweeper",
		"Dark Spell Factory",
		"Eagle Artillery",
		"Bomb Tower",
		"Workshop",
		"B.O.B's Hut",
		"Scattershot",
		"Pet House",
		"Blacksmith",
		"Hero Hall",
		"Spell Tower",
		"Monolith",
		"Multi-Gear Tower",
		"Sour Elixir Cauldron",
		"Multi-Archer Tower",
		"Ricochet Cannon",
		"Revenge Tower",
		"Firespitter",
		"Helper Hut",
		"Crafting Station",
		"Super Wizard Tower",
	}
	AchievementOrder = []string{
		"Keep Your Account Safe!",
		"Bigger & Better",
		"Discover New Troops",
		"Bigger Coffers",
		"Gold Grab",
		"Elixir Escapade",
		"Heroic Heist",
		"Well Seasoned",
		"Nice and Tidy",
		"Empire Builder",
		"Clan War Wealth",
		"Friend in Need",
		"Sharing is caring",
		"Siege Sharer",
		"War Hero",
		"War League Legend",
		"Games Champion",
		"Unbreakable",
		"Sweet Victory!",
		"Conqueror",
		"League All-Star",
		"League Follower",
		"League Enthusiast",
		"League Superfan",
		"League Fanatic",
		"League Master",
		"Humiliator",
		"Not So Easy This Time",
		"Union Buster",
		"Bust This!",
		"Wall Buster",
		"Mortar Mauler",
		"X-Bow Exterminator",
		"Firefighter",
		"Anti-Artillery",
		"Shattered and Scattered",
		"Counterspell",
		"Monolith Masher",
		"Multi-Archer Tower Terminator",
		"Ricochet Cannon Crusher",
		"Firespitter Finisher",
		"Multi-Gear Tower Trampler",
		"Crafter’s Nightmare",
		"Get those Goblins!",
		"Supercharger",
		"Crafting Connoisseur",
		"Get those other Goblins!",
		"Get even more Goblins!",
		"Dragon Slayer",
		"Ungrateful Child",
		"Superb Work",
		"Master Engineering",
		"Hidden Treasures",
		"High Gear",
		"Next Generation Model",
		"Un-Build It",
		"Champion Builder",
		"Aggressive Capitalism",
		"Most Valuable Clanmate",
	}
)

Functions

func CorrectTag

func CorrectTag(tag string) string

func FromTimestamp

func FromTimestamp(raw string) (time.Time, error)

func GetClanGamesEnd

func GetClanGamesEnd(timestamp time.Time) time.Time

func GetClanGamesStart

func GetClanGamesStart(timestamp time.Time) time.Time

func GetRaidWeekendEnd

func GetRaidWeekendEnd(timestamp time.Time) time.Time

func GetRaidWeekendStart

func GetRaidWeekendStart(timestamp time.Time) time.Time

func GetSeasonID

func GetSeasonID() string

func WithoutRateLimit

func WithoutRateLimit(ctx context.Context) context.Context

Types

type AccountData

type AccountData struct {
	Raw map[string]any
}

func ParseAccountData

func ParseAccountData(data map[string]any) AccountData

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"`
}

type ArmyRecipe

type ArmyRecipe struct {
	Link             string
	HeroesLoadout    []HeroLoadout
	Troops           []TroopCount
	Spells           []SpellCount
	ClanCastleTroops []TroopCount
	ClanCastleSpells []SpellCount
}

func ParseArmyRecipe

func ParseArmyRecipe(static *StaticData, link string) ArmyRecipe

type Badge

type Badge struct {
	Small  string `json:"small"`
	Medium string `json:"medium"`
	Large  string `json:"large"`
}

func (Badge) URL

func (b Badge) URL() string

type BattleLogEntry

type BattleLogEntry struct {
	BattleType            string     `json:"battleType,omitempty"`
	Attack                bool       `json:"attack,omitempty"`
	ArmyShareCode         string     `json:"armyShareCode,omitempty"`
	OpponentPlayerTag     string     `json:"opponentPlayerTag,omitempty"`
	Stars                 int        `json:"stars,omitempty"`
	DestructionPercentage int        `json:"destructionPercentage,omitempty"`
	LootedResources       []Resource `json:"lootedResources,omitempty"`
	ExtraLootedResources  []Resource `json:"extraLootedResources,omitempty"`
	AvailableLoot         []Resource `json:"availableLoot,omitempty"`
	// contains filtered or unexported fields
}

func (BattleLogEntry) RetryAfter

func (m BattleLogEntry) RetryAfter() int

type CapitalDistrict

type CapitalDistrict struct {
	ID                 int     `json:"id"`
	Name               string  `json:"name"`
	DistrictHallLevel  int     `json:"districtHallLevel"`
	DestructionPercent float64 `json:"destructionPercent"`
	AttackCount        int     `json:"attackCount"`
	Looted             int     `json:"totalLooted"`
}

type ChatLanguage

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

type Clan

type Clan struct {
	Tag                         string        `json:"tag,omitempty"`
	Name                        string        `json:"name,omitempty"`
	Type                        ClanType      `json:"type,omitempty"`
	Description                 string        `json:"description,omitempty"`
	FamilyFriendly              bool          `json:"isFamilyFriendly,omitempty"`
	Level                       int           `json:"clanLevel,omitempty"`
	Points                      int           `json:"clanPoints,omitempty"`
	BuilderBasePoints           int           `json:"clanBuilderBasePoints,omitempty"`
	CapitalPoints               int           `json:"clanCapitalPoints,omitempty"`
	RequiredTrophies            int           `json:"requiredTrophies,omitempty"`
	WarFrequency                string        `json:"warFrequency,omitempty"`
	WarWinStreak                int           `json:"warWinStreak,omitempty"`
	WarWins                     int           `json:"warWins,omitempty"`
	WarTies                     int           `json:"warTies,omitempty"`
	WarLosses                   int           `json:"warLosses,omitempty"`
	PublicWarLog                bool          `json:"isWarLogPublic,omitempty"`
	MemberCount                 int           `json:"members,omitempty"`
	RequiredBuilderBaseTrophies int           `json:"requiredBuilderBaseTrophies,omitempty"`
	RequiredTownhall            int           `json:"requiredTownhallLevel,omitempty"`
	Location                    *Location     `json:"location,omitempty"`
	Badge                       Badge         `json:"badgeUrls,omitempty"`
	Labels                      []Label       `json:"labels,omitempty"`
	Members                     []ClanMember  `json:"memberList,omitempty"`
	WarLeague                   *League       `json:"warLeague,omitempty"`
	CapitalLeague               *League       `json:"capitalLeague,omitempty"`
	ChatLanguage                *ChatLanguage `json:"chatLanguage,omitempty"`
	ClanCapital                 *ClanCapital  `json:"clanCapital,omitempty"`
	// contains filtered or unexported fields
}

func (*Clan) GetMember

func (c *Clan) GetMember(tag string) *ClanMember

func (*Clan) GetMemberBy

func (c *Clan) GetMemberBy(name string, trophies int) *ClanMember

func (Clan) RetryAfter

func (m Clan) RetryAfter() int

type ClanCapital

type ClanCapital struct {
	Districts []CapitalDistrict `json:"districts,omitempty"`
}

type ClanMember

type ClanMember struct {
	Tag                 string  `json:"tag,omitempty"`
	Name                string  `json:"name,omitempty"`
	Role                Role    `json:"role,omitempty"`
	ExpLevel            int     `json:"expLevel,omitempty"`
	Trophies            int     `json:"trophies,omitempty"`
	ClanRank            int     `json:"clanRank,omitempty"`
	ClanPreviousRank    int     `json:"previousClanRank,omitempty"`
	Donations           int     `json:"donations,omitempty"`
	Received            int     `json:"donationsReceived,omitempty"`
	VersusTrophies      int     `json:"versusTrophies,omitempty"`
	BuilderBaseTrophies int     `json:"builderBaseTrophies,omitempty"`
	VersusRank          int     `json:"versusRank,omitempty"`
	BuilderBaseRank     int     `json:"builderBaseRank,omitempty"`
	League              *League `json:"league,omitempty"`
	// contains filtered or unexported fields
}

func (ClanMember) RetryAfter

func (m ClanMember) RetryAfter() int

type ClanType

type ClanType string
const (
	ClanTypeOpen       ClanType = "open"
	ClanTypeClosed     ClanType = "closed"
	ClanTypeInviteOnly ClanType = "inviteOnly"
)

type ClanWar

type ClanWar struct {
	State                WarState   `json:"state,omitempty"`
	TeamSize             int        `json:"teamSize,omitempty"`
	PreparationStartTime *Timestamp `json:"preparationStartTime,omitempty"`
	StartTime            *Timestamp `json:"startTime,omitempty"`
	EndTime              *Timestamp `json:"endTime,omitempty"`
	Clan                 *WarClan   `json:"clan,omitempty"`
	Opponent             *WarClan   `json:"opponent,omitempty"`
	BattleModifier       string     `json:"battleModifier,omitempty"`
	WarTag               string     `json:"tag,omitempty"`
	ClanTag              string     `json:"-"`
	// contains filtered or unexported fields
}

func (*ClanWar) Attacks

func (w *ClanWar) Attacks() []WarAttack

func (ClanWar) RetryAfter

func (m ClanWar) RetryAfter() int

func (*ClanWar) Type

func (w *ClanWar) Type() string

type ClanWarLeagueClan

type ClanWarLeagueClan struct {
	Tag   string `json:"tag,omitempty"`
	Name  string `json:"name,omitempty"`
	Badge Badge  `json:"badgeUrls,omitempty"`
	Level int    `json:"clanLevel,omitempty"`
}

type ClanWarLeagueGroup

type ClanWarLeagueGroup struct {
	State  string              `json:"state,omitempty"`
	Season string              `json:"season,omitempty"`
	Clans  []ClanWarLeagueClan `json:"clans,omitempty"`
	Rounds []struct {
		WarTags []string `json:"warTags,omitempty"`
	} `json:"rounds,omitempty"`
	// contains filtered or unexported fields
}

func (ClanWarLeagueGroup) RetryAfter

func (m ClanWarLeagueGroup) RetryAfter() int

type ClanWarLogEntry

type ClanWarLogEntry struct {
	Result   WarResult  `json:"result,omitempty"`
	EndTime  *Timestamp `json:"endTime,omitempty"`
	TeamSize int        `json:"teamSize,omitempty"`
	Clan     *WarClan   `json:"clan,omitempty"`
	Opponent *WarClan   `json:"opponent,omitempty"`
	// contains filtered or unexported fields
}

func (ClanWarLogEntry) RetryAfter

func (m ClanWarLogEntry) RetryAfter() int

type ClanWarMember

type ClanWarMember struct {
	Tag                string      `json:"tag,omitempty"`
	Name               string      `json:"name,omitempty"`
	MapPosition        int         `json:"mapPosition,omitempty"`
	Townhall           int         `json:"townhallLevel,omitempty"`
	OpponentAttacks    int         `json:"opponentAttacks,omitempty"`
	Attacks            []WarAttack `json:"attacks,omitempty"`
	BestOpponentAttack *WarAttack  `json:"bestOpponentAttack,omitempty"`
	Clan               *WarClan
}

type ClashOfClansException

type ClashOfClansException struct {
	Message string
}

func (*ClashOfClansException) Error

func (e *ClashOfClansException) Error() string

type Client

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

func NewClient

func NewClient(cfg ClientConfig) (*Client, error)

func (*Client) Close

func (c *Client) Close() error

func (*Client) GetBattleLog

func (c *Client) GetBattleLog(ctx context.Context, playerTag string) ([]BattleLogEntry, error)

func (*Client) GetBuilderBaseLeague

func (c *Client) GetBuilderBaseLeague(ctx context.Context, id int) (*League, error)

func (*Client) GetCapitalLeague

func (c *Client) GetCapitalLeague(ctx context.Context, id int) (*League, error)

func (*Client) GetClan

func (c *Client) GetClan(ctx context.Context, tag string) (*Clan, error)

func (*Client) GetClanLabels

func (c *Client) GetClanLabels(ctx context.Context, limit int, before, after string) ([]Label, error)

func (*Client) GetClanWar

func (c *Client) GetClanWar(ctx context.Context, clanTag string) (*ClanWar, error)

func (*Client) GetClanWars

func (c *Client) GetClanWars(ctx context.Context, tags []string) ([]ClanWar, error)

func (*Client) GetCurrentGoldPassSeason

func (c *Client) GetCurrentGoldPassSeason(ctx context.Context) (*GoldPassSeason, error)

func (*Client) GetCurrentWar

func (c *Client) GetCurrentWar(ctx context.Context, clanTag string, round ...WarRound) (*ClanWar, error)

func (*Client) GetCurrentWars

func (c *Client) GetCurrentWars(ctx context.Context, tags []string) ([]ClanWar, error)

func (*Client) GetEquipment

func (c *Client) GetEquipment(name string, level int) *Equipment

func (*Client) GetExtendedCWLGroupData

func (c *Client) GetExtendedCWLGroupData(name string) *ExtendedCWLGroup

func (*Client) GetHero

func (c *Client) GetHero(name string, level int) *Hero

func (*Client) GetLeague

func (c *Client) GetLeague(ctx context.Context, id int) (*League, error)

func (*Client) GetLeagueGroup

func (c *Client) GetLeagueGroup(ctx context.Context, clanTag string) (*ClanWarLeagueGroup, error)

func (*Client) GetLeagueWar

func (c *Client) GetLeagueWar(ctx context.Context, clanTag string, round WarRound) (*ClanWar, error)

func (*Client) GetLeagueWars

func (c *Client) GetLeagueWars(ctx context.Context, warTags []string) ([]ClanWar, error)

func (*Client) GetLocation

func (c *Client) GetLocation(ctx context.Context, locationID int) (*Location, error)

func (*Client) GetLocationClans

func (c *Client) GetLocationClans(ctx context.Context, locationID, limit int, before, after string) ([]RankedClan, error)

func (*Client) GetLocationClansBuilderBase

func (c *Client) GetLocationClansBuilderBase(ctx context.Context, locationID, limit int, before, after string) ([]RankedClan, error)

func (*Client) GetLocationClansCapital

func (c *Client) GetLocationClansCapital(ctx context.Context, locationID, limit int, before, after string) ([]RankedClan, error)

func (*Client) GetLocationNamed

func (c *Client) GetLocationNamed(ctx context.Context, locationName string) (*Location, error)

func (*Client) GetLocationPlayers

func (c *Client) GetLocationPlayers(ctx context.Context, locationID, limit int, before, after string) ([]RankedPlayer, error)

func (*Client) GetLocationPlayersBuilderBase

func (c *Client) GetLocationPlayersBuilderBase(ctx context.Context, locationID, limit int, before, after string) ([]RankedPlayer, error)

func (*Client) GetMembers

func (c *Client) GetMembers(ctx context.Context, clanTag string, limit int, after, before string) ([]ClanMember, error)

func (*Client) GetPet

func (c *Client) GetPet(name string, level int) *Pet

func (*Client) GetPlayer

func (c *Client) GetPlayer(ctx context.Context, tag string) (*Player, error)

func (*Client) GetPlayerLabels

func (c *Client) GetPlayerLabels(ctx context.Context, limit int, before, after string) ([]Label, error)

func (*Client) GetPlayerLeagueGroup

func (c *Client) GetPlayerLeagueGroup(ctx context.Context, playerTag, leagueGroupTag string, leagueSeasonID int) (*LeagueTierGroup, error)

func (*Client) GetPlayerLeagueHistory

func (c *Client) GetPlayerLeagueHistory(ctx context.Context, playerTag string) ([]LeagueHistoryEntry, error)

func (*Client) GetRaidLog

func (c *Client) GetRaidLog(ctx context.Context, clanTag string, limit int, after, before string) ([]RaidLogEntry, error)

func (*Client) GetSeasonRankings

func (c *Client) GetSeasonRankings(ctx context.Context, leagueID int, seasonID string) ([]RankedPlayer, error)

func (*Client) GetSeasons

func (c *Client) GetSeasons(ctx context.Context, leagueID int) ([]string, error)

func (*Client) GetSpell

func (c *Client) GetSpell(name string, level int) *Spell

func (*Client) GetTranslation

func (c *Client) GetTranslation(id string) *Translation

func (*Client) GetTroop

func (c *Client) GetTroop(name string, isHomeVillage bool, level int) *Troop

func (*Client) GetWarLeague

func (c *Client) GetWarLeague(ctx context.Context, id int) (*League, error)

func (*Client) GetWarLog

func (c *Client) GetWarLog(ctx context.Context, clanTag string, limit int, after, before string) ([]ClanWarLogEntry, error)

func (*Client) Login

func (c *Client) Login(ctx context.Context, email, password string) error

func (*Client) LoginWithTokens

func (c *Client) LoginWithTokens(_ context.Context, tokens ...string) error

func (*Client) ParseAccountData

func (c *Client) ParseAccountData(data map[string]any) AccountData
func (c *Client) ParseArmyLink(link string) ArmyRecipe

func (*Client) SearchBuilderBaseLeagues

func (c *Client) SearchBuilderBaseLeagues(ctx context.Context, limit int, before, after string) ([]League, error)

func (*Client) SearchCapitalLeagues

func (c *Client) SearchCapitalLeagues(ctx context.Context, limit int, before, after string) ([]League, error)

func (*Client) SearchClans

func (c *Client) SearchClans(ctx context.Context, req SearchClansRequest) ([]Clan, error)

func (*Client) SearchLeagues

func (c *Client) SearchLeagues(ctx context.Context, limit int, before, after string) ([]League, error)

func (*Client) SearchLocations

func (c *Client) SearchLocations(ctx context.Context, limit int, before, after string) ([]Location, error)

func (*Client) SearchWarLeagues

func (c *Client) SearchWarLeagues(ctx context.Context, limit int, before, after string) ([]League, error)

func (*Client) StaticData

func (c *Client) StaticData() *StaticData

func (*Client) UpdateStatic

func (c *Client) UpdateStatic(ctx context.Context) error

func (*Client) VerifyPlayerToken

func (c *Client) VerifyPlayerToken(ctx context.Context, playerTag, token string) (bool, error)

type ClientConfig

type ClientConfig struct {
	KeyCount           int
	KeyNames           string
	ThrottleLimit      int
	Timeout            time.Duration
	BaseURL            string
	DeveloperBaseURL   string
	IP                 string
	Realtime           bool
	CorrectTags        bool
	CacheMaxSize       int
	LookupCache        bool
	UpdateCache        bool
	IgnoreCachedErrors []int
	RawJSON            bool
	LoadGameData       LoadGameData
	UserAgent          string
	DeveloperUserAgent string
}

func DefaultClientConfig

func DefaultClientConfig() ClientConfig

type Equipment

type Equipment struct {
	Name     string `json:"name"`
	Level    int    `json:"level"`
	MaxLevel int    `json:"maxLevel"`
	Village  string `json:"village"`
	Rarity   string `json:"rarity"`
	StaticUnit
}

func (Equipment) Static

func (e Equipment) Static(c *Client) *Equipment

type ExtendedCWLGroup

type ExtendedCWLGroup struct {
	Name              string `json:"name,omitempty"`
	FirstPlaceMedals  int    `json:"first_place_medals,omitempty"`
	SecondPlaceMedals int    `json:"second_place_medals,omitempty"`
}

type Forbidden

type Forbidden struct{ *HTTPException }

type GatewayError

type GatewayError struct{ *HTTPException }

type GoldPassSeason

type GoldPassSeason struct {
	StartTime *Timestamp `json:"startTime"`
	EndTime   *Timestamp `json:"endTime"`
	// contains filtered or unexported fields
}

func (GoldPassSeason) RetryAfter

func (m GoldPassSeason) RetryAfter() int

type HTTPClient

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

func NewHTTPClient

func NewHTTPClient(cfg ClientConfig) *HTTPClient

func (*HTTPClient) Do

func (h *HTTPClient) Do(ctx context.Context, method, fullURL string, body any, options RequestOptions) ([]byte, int, int, error)

func (*HTTPClient) LoginDeveloper

func (h *HTTPClient) LoginDeveloper(ctx context.Context, email, password string) error

func (*HTTPClient) SetTokens

func (h *HTTPClient) SetTokens(tokens ...string)

type HTTPException

type HTTPException struct {
	Status  int
	Reason  string
	Message string
	Body    []byte
}

func (*HTTPException) Error

func (e *HTTPException) Error() string

type Hero

type Hero struct {
	Name      string      `json:"name"`
	Level     int         `json:"level"`
	MaxLevel  int         `json:"maxLevel"`
	Village   string      `json:"village"`
	Equipment []Equipment `json:"equipment"`
	StaticUnit
}

func (Hero) Static

func (h Hero) Static(c *Client) *Hero

type HeroLoadout

type HeroLoadout struct {
	Hero      Hero
	Pet       *Pet
	Equipment []Equipment
}

type Icon

type Icon struct {
	Small  string `json:"small"`
	Medium string `json:"medium"`
	Tiny   string `json:"tiny"`
}

type InvalidArgument

type InvalidArgument struct{ *HTTPException }

type InvalidCredentials

type InvalidCredentials struct{ *HTTPException }

type Label

type Label struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
	Icon *Icon  `json:"iconUrls"`
	// contains filtered or unexported fields
}

func (Label) RetryAfter

func (m Label) RetryAfter() int

type League

type League struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
	Icon *Icon  `json:"iconUrls"`
	// contains filtered or unexported fields
}

func (League) RetryAfter

func (m League) RetryAfter() int

type LeagueHistoryEntry

type LeagueHistoryEntry struct {
	LeagueSeasonID int `json:"leagueSeasonId,omitempty"`
	LeagueTrophies int `json:"leagueTrophies,omitempty"`
	LeagueTierID   int `json:"leagueTierId,omitempty"`
	Placement      int `json:"placement,omitempty"`
	AttackWins     int `json:"attackWins,omitempty"`
	AttackLosses   int `json:"attackLosses,omitempty"`
	AttackStars    int `json:"attackStars,omitempty"`
	DefenseWins    int `json:"defenseWins,omitempty"`
	DefenseLosses  int `json:"defenseLosses,omitempty"`
	DefenseStars   int `json:"defenseStars,omitempty"`
	MaxBattles     int `json:"maxBattles,omitempty"`
	// contains filtered or unexported fields
}

func (LeagueHistoryEntry) RetryAfter

func (m LeagueHistoryEntry) RetryAfter() int

type LeagueTierGroup

type LeagueTierGroup struct {
	Members     []LeagueTierGroupMember         `json:"members,omitempty"`
	AttackLogs  []LeagueTierGroupBattleLogEntry `json:"attackLogs,omitempty"`
	DefenseLogs []LeagueTierGroupBattleLogEntry `json:"defenseLogs,omitempty"`
	// contains filtered or unexported fields
}

func (LeagueTierGroup) RetryAfter

func (m LeagueTierGroup) RetryAfter() int

type LeagueTierGroupBattleLogEntry

type LeagueTierGroupBattleLogEntry struct {
	OpponentPlayerTag     string `json:"opponentPlayerTag,omitempty"`
	OpponentName          string `json:"opponentName,omitempty"`
	Stars                 int    `json:"stars,omitempty"`
	DestructionPercentage int    `json:"destructionPercentage,omitempty"`
	Trophies              int    `json:"trophies,omitempty"`
	CreationTime          string `json:"creationTime,omitempty"`
}

type LeagueTierGroupMember

type LeagueTierGroupMember struct {
	PlayerTag        string `json:"playerTag,omitempty"`
	PlayerName       string `json:"playerName,omitempty"`
	ClanTag          string `json:"clanTag,omitempty"`
	ClanName         string `json:"clanName,omitempty"`
	LeagueTrophies   int    `json:"leagueTrophies,omitempty"`
	AttackWinCount   int    `json:"attackWinCount,omitempty"`
	AttackLoseCount  int    `json:"attackLoseCount,omitempty"`
	DefenseWinCount  int    `json:"defenseWinCount,omitempty"`
	DefenseLoseCount int    `json:"defenseLoseCount,omitempty"`
}

type LegendStatistics

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

type LoadGameData

type LoadGameData struct {
	Default     bool
	StartupOnly bool
	Always      bool
	Never       bool
}

func DefaultLoadGameData

func DefaultLoadGameData() LoadGameData

type Location

type Location struct {
	ID          int    `json:"id"`
	Name        string `json:"name"`
	IsCountry   bool   `json:"isCountry"`
	CountryCode string `json:"countryCode"`
	Localised   string `json:"localizedName"`
	// contains filtered or unexported fields
}

func (Location) RetryAfter

func (m Location) RetryAfter() int

type Maintenance

type Maintenance struct{ *HTTPException }

type NotFound

type NotFound struct{ *HTTPException }

type Pet

type Pet struct {
	Name     string `json:"name"`
	Level    int    `json:"level"`
	MaxLevel int    `json:"maxLevel"`
	Village  string `json:"village"`
	StaticUnit
}

func (Pet) Static

func (p Pet) Static(c *Client) *Pet

type Player

type Player struct {
	Tag                     string            `json:"tag,omitempty"`
	Name                    string            `json:"name,omitempty"`
	ExpLevel                int               `json:"expLevel,omitempty"`
	Trophies                int               `json:"trophies,omitempty"`
	BestTrophies            int               `json:"bestTrophies,omitempty"`
	WarStars                int               `json:"warStars,omitempty"`
	TownHall                int               `json:"townHallLevel,omitempty"`
	TownHallWeapon          int               `json:"townHallWeaponLevel,omitempty"`
	BuilderHall             int               `json:"builderHallLevel,omitempty"`
	BestBuilderBaseTrophies int               `json:"bestBuilderBaseTrophies,omitempty"`
	VersusAttackWins        int               `json:"versusBattleWins,omitempty"`
	Donations               int               `json:"donations,omitempty"`
	Received                int               `json:"donationsReceived,omitempty"`
	ClanRank                int               `json:"clanRank,omitempty"`
	ClanPreviousRank        int               `json:"previousClanRank,omitempty"`
	VersusTrophies          int               `json:"versusTrophies,omitempty"`
	BuilderBaseTrophies     int               `json:"builderBaseTrophies,omitempty"`
	LeagueTier              *League           `json:"leagueTier,omitempty"`
	BuilderBaseLeague       *League           `json:"builderBaseLeague,omitempty"`
	Role                    Role              `json:"role,omitempty"`
	Clan                    *PlayerClan       `json:"clan,omitempty"`
	CurrentLeagueGroupTag   string            `json:"currentLeagueGroupTag,omitempty"`
	CurrentLeagueSeasonID   int               `json:"currentLeagueSeasonId,omitempty"`
	PreviousLeagueGroupTag  string            `json:"previousLeagueGroupTag,omitempty"`
	PreviousLeagueSeasonID  int               `json:"previousLeagueSeasonId,omitempty"`
	LegendStatistics        *LegendStatistics `json:"legendStatistics,omitempty"`
	Labels                  []Label           `json:"labels,omitempty"`
	Achievements            []Achievement     `json:"achievements,omitempty"`
	Troops                  []Troop           `json:"troops,omitempty"`
	Heroes                  []Hero            `json:"heroes,omitempty"`
	Spells                  []Spell           `json:"spells,omitempty"`
	HeroEquipment           []Equipment       `json:"heroEquipment,omitempty"`
	// contains filtered or unexported fields
}

func (*Player) BuilderTroops

func (p *Player) BuilderTroops() []Troop

func (*Player) GetAchievement

func (p *Player) GetAchievement(name string) *Achievement

func (*Player) GetHero

func (p *Player) GetHero(name string) *Hero

func (*Player) GetSpell

func (p *Player) GetSpell(name string) *Spell

func (*Player) GetTroop

func (p *Player) GetTroop(name string) *Troop

func (*Player) HomeTroops

func (p *Player) HomeTroops() []Troop

func (Player) RetryAfter

func (m Player) RetryAfter() int

type PlayerClan

type PlayerClan struct {
	Tag   string `json:"tag,omitempty"`
	Name  string `json:"name,omitempty"`
	Level int    `json:"clanLevel,omitempty"`
	Badge Badge  `json:"badgeUrls,omitempty"`
}

type PlayerHouseElement

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

type PrivateWarLog

type PrivateWarLog struct{ *HTTPException }

type RaidAttack

type RaidAttack struct {
	AttackerTag  string  `json:"-"`
	AttackerName string  `json:"-"`
	Stars        int     `json:"stars,omitempty"`
	Destruction  float64 `json:"destructionPercent,omitempty"`
}

type RaidClan

type RaidClan struct {
	AttackCount            int            `json:"attackCount,omitempty"`
	DistrictCount          int            `json:"districtCount,omitempty"`
	DestroyedDistrictCount int            `json:"districtsDestroyed,omitempty"`
	Districts              []RaidDistrict `json:"districts,omitempty"`
	Attacker               *struct {
		Tag   string `json:"tag,omitempty"`
		Name  string `json:"name,omitempty"`
		Level int    `json:"level,omitempty"`
	} `json:"attacker,omitempty"`
	Defender *struct {
		Tag   string `json:"tag,omitempty"`
		Name  string `json:"name,omitempty"`
		Level int    `json:"level,omitempty"`
	} `json:"defender,omitempty"`
}

func (RaidClan) Level

func (r RaidClan) Level() int

func (RaidClan) Name

func (r RaidClan) Name() string

func (RaidClan) Tag

func (r RaidClan) Tag() string

type RaidDistrict

type RaidDistrict struct {
	ID          int          `json:"id,omitempty"`
	Name        string       `json:"name,omitempty"`
	HallLevel   int          `json:"districtHallLevel,omitempty"`
	Destruction float64      `json:"destructionPercent,omitempty"`
	AttackCount int          `json:"attackCount,omitempty"`
	Looted      int          `json:"totalLooted,omitempty"`
	Attacks     []RaidAttack `json:"attacks,omitempty"`
}

type RaidLogEntry

type RaidLogEntry struct {
	State                  string       `json:"state,omitempty"`
	TotalLoot              int          `json:"capitalTotalLoot,omitempty"`
	CompletedRaidCount     int          `json:"raidsCompleted,omitempty"`
	AttackCount            int          `json:"totalAttacks,omitempty"`
	DestroyedDistrictCount int          `json:"enemyDistrictsDestroyed,omitempty"`
	OffensiveReward        int          `json:"offensiveReward,omitempty"`
	DefensiveReward        int          `json:"defensiveReward,omitempty"`
	StartTime              *Timestamp   `json:"startTime,omitempty"`
	EndTime                *Timestamp   `json:"endTime,omitempty"`
	AttackLog              []RaidClan   `json:"attackLog,omitempty"`
	DefenseLog             []RaidClan   `json:"defenseLog,omitempty"`
	Members                []RaidMember `json:"members,omitempty"`
	// contains filtered or unexported fields
}

func (*RaidLogEntry) GetMember

func (r *RaidLogEntry) GetMember(tag string) *RaidMember

func (RaidLogEntry) RetryAfter

func (m RaidLogEntry) RetryAfter() int

type RaidMember

type RaidMember struct {
	Tag                    string `json:"tag,omitempty"`
	Name                   string `json:"name,omitempty"`
	AttackCount            int    `json:"attacks,omitempty"`
	AttackLimit            int    `json:"attackLimit,omitempty"`
	BonusAttackLimit       int    `json:"bonusAttackLimit,omitempty"`
	CapitalResourcesLooted int    `json:"capitalResourcesLooted,omitempty"`
}

type RankedClan

type RankedClan struct {
	Clan
	Rank         int `json:"rank,omitempty"`
	PreviousRank int `json:"previousRank,omitempty"`
}

func (RankedClan) RetryAfter

func (m RankedClan) RetryAfter() int

type RankedPlayer

type RankedPlayer struct {
	Player
	Rank         int `json:"rank,omitempty"`
	PreviousRank int `json:"previousRank,omitempty"`
}

func (RankedPlayer) RetryAfter

func (m RankedPlayer) RetryAfter() int

type RequestOptions

type RequestOptions struct {
	LookupCache bool
	UpdateCache bool
	SkipAuth    bool
}

type Resource

type Resource struct {
	Name   string `json:"name,omitempty"`
	Amount int    `json:"amount,omitempty"`
}

type Role

type Role string
const (
	RoleMember   Role = "member"
	RoleElder    Role = "admin"
	RoleCoLeader Role = "coLeader"
	RoleLeader   Role = "leader"
)

type SearchClansRequest

type SearchClansRequest struct {
	Name          string
	WarFrequency  string
	LocationID    int
	MinMembers    int
	MaxMembers    int
	MinClanPoints int
	MinClanLevel  int
	LabelIDs      []int
	Limit         int
	Before        string
	After         string
}

type Season

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

type SeasonWindow

type SeasonWindow struct {
	SeasonID  string
	StartTime time.Time
	EndTime   time.Time
}

func GetSeason

func GetSeason(timestamp time.Time, forward bool) SeasonWindow

func GetSeasonByID

func GetSeasonByID(seasonID string) (SeasonWindow, error)

type Spell

type Spell struct {
	Name     string `json:"name"`
	Level    int    `json:"level"`
	MaxLevel int    `json:"maxLevel"`
	Village  string `json:"village"`
	StaticUnit
}

func (Spell) Static

func (s Spell) Static(c *Client) *Spell

type SpellCount

type SpellCount struct {
	Spell    Spell
	Quantity int
}

type StaticData

type StaticData struct {
	Raw          map[string][]map[string]any
	ByID         map[int]map[string]any
	ByName       map[string]map[string]any
	Translations map[string]map[string]string
}

func LoadStaticData

func LoadStaticData() (*StaticData, error)

func (*StaticData) LookupByID

func (s *StaticData) LookupByID(id int) map[string]any

func (*StaticData) LookupByName

func (s *StaticData) LookupByName(name, section, village string) map[string]any

type StaticUnit

type StaticUnit struct {
	Name        string
	Level       int
	MaxLevel    int
	Village     string
	UpgradeCost int
	UpgradeTime time.Duration
}

type TimeDelta

type TimeDelta struct {
	time.Duration
}

type Timestamp

type Timestamp struct {
	RawTime string
	Time    time.Time
}

func (Timestamp) After

func (t Timestamp) After(other Timestamp) bool

func (Timestamp) Before

func (t Timestamp) Before(other Timestamp) bool

func (Timestamp) SecondsUntil

func (t Timestamp) SecondsUntil() int

func (*Timestamp) UnmarshalJSON

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

type TournamentWindow

type TournamentWindow struct {
	ID        string
	StartTime time.Time
	EndTime   time.Time
}

func GetTournamentWindow

func GetTournamentWindow(timestamp time.Time) TournamentWindow

func GetTournamentWindowByID

func GetTournamentWindowByID(id string) (TournamentWindow, error)

type Translation

type Translation struct {
	ID        string            `json:"id"`
	English   string            `json:"EN"`
	Languages map[string]string `json:"-"`
}

func (*Translation) UnmarshalJSON

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

type Troop

type Troop struct {
	Name               string `json:"name"`
	Level              int    `json:"level"`
	MaxLevel           int    `json:"maxLevel"`
	Village            string `json:"village"`
	SuperTroopIsActive bool   `json:"superTroopIsActive"`
	StaticUnit
}

func (Troop) IsBuilderBase

func (t Troop) IsBuilderBase() bool

func (Troop) IsHomeBase

func (t Troop) IsHomeBase() bool

func (Troop) IsSuperTroop

func (t Troop) IsSuperTroop() bool

func (Troop) Static

func (t Troop) Static(c *Client) *Troop

type TroopCount

type TroopCount struct {
	Troop    Troop
	Quantity int
}

type VillageType

type VillageType string
const (
	VillageHome        VillageType = "home"
	VillageBuilderBase VillageType = "builderBase"
	VillageClanCapital VillageType = "clanCapital"
)

type WarAttack

type WarAttack struct {
	Order       int     `json:"order,omitempty"`
	AttackerTag string  `json:"attackerTag,omitempty"`
	DefenderTag string  `json:"defenderTag,omitempty"`
	Stars       int     `json:"stars,omitempty"`
	Destruction float64 `json:"destructionPercentage,omitempty"`
	Duration    int     `json:"duration,omitempty"`
	Attacker    *ClanWarMember
	Defender    *ClanWarMember
}

type WarClan

type WarClan struct {
	Tag         string          `json:"tag,omitempty"`
	Name        string          `json:"name,omitempty"`
	Badge       Badge           `json:"badgeUrls,omitempty"`
	Level       int             `json:"clanLevel,omitempty"`
	Attacks     int             `json:"attacks,omitempty"`
	Stars       int             `json:"stars,omitempty"`
	Destruction float64         `json:"destructionPercentage,omitempty"`
	ExpEarned   int             `json:"expEarned,omitempty"`
	Members     []ClanWarMember `json:"members,omitempty"`
}

type WarResult

type WarResult string
const (
	WarResultWin  WarResult = "win"
	WarResultLose WarResult = "lose"
	WarResultTie  WarResult = "tie"
)

type WarRound

type WarRound int
const (
	PreviousWar WarRound = iota
	CurrentWar
	CurrentPreparation
)

type WarState

type WarState string
const (
	WarStateNotInWar    WarState = "notInWar"
	WarStatePreparation WarState = "preparation"
	WarStateInWar       WarState = "inWar"
	WarStateEnded       WarState = "warEnded"
)

Jump to

Keyboard shortcuts

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