Basic Client Interface

The following details all operations on the basic client instance.

class coc.Client(*, key_count: int = 1, key_names: str = 'Created with coc.py Client', throttle_limit: int = 30, loop: ~typing.Optional[~asyncio.events.AbstractEventLoop] = None, correct_tags: bool = True, throttler: ~typing.Type[~typing.Union[~coc.http.BasicThrottler, ~coc.http.BatchThrottler]] = <class 'coc.http.BasicThrottler'>, connector=None, timeout: float = 30.0, cache_max_size: int = 10000, stats_max_size: int = 1000, load_game_data: ~coc.miscmodels.LoadGameData = <coc.miscmodels.LoadGameData object>, realtime=False, raw_attribute=False, base_url: str = 'https://api.clashofclans.com/v1', **kwargs)

This is the client connection used to interact with the Clash of Clans API.

Parameters:
  • key_count (int) – The amount of keys to use for this client. Maximum of 10. Defaults to 1.

  • key_names (str) – Default name for keys created to use for this client. All keys created or to be used with this client must have this name. Defaults to “Created with coc.py Client”.

  • throttle_limit (int) –

    The number of requests per token per second to send to the API. Once hitting this limit, the library will automatically throttle your requests.

    Note

    Setting this value too high may result in the API rate-limiting your requests. This means you cannot request for ~30-60 seconds.

    Warning

    Setting this value too high may result in your requests being deemed “API Abuse”, potentially resulting in an IP ban.

    Defaults to 10 requests per token, per second.

  • loop (asyncio.AbstractEventLoop, optional) – The asyncio.AbstractEventLoop to use for HTTP requests. An asyncio.get_event_loop() will be used if None is passed

  • correct_tags (bool) – Whether the client should correct tags before requesting them from the API. This process involves stripping tags of whitespace and adding a # prefix if not present. Defaults to True.

  • connector (aiohttp.BaseConnector) – The aiohttp connector to use. By default, this is None.

  • timeout (float) – The number of seconds before timing out with an API query. Defaults to 30.

  • cache_max_size (int) – The max size of the internal cache layer. Defaults to 10 000. Set this to None to remove any cache layer.

  • load_game_data (LoadGameData) – The option for how coc.py will load game data. See Initialising the Client for more info.

  • realtime (bool) – Some developers are given special access to an uncached API access by Super Cell. If you are one of those developers, your account will have special flags that will only be interpreted by coc.py if you set this bool to True.

  • raw_attribute (bool) – The option to enable the _raw_data attribute for most objects in the library. This attribute will contain the original json data as returned by the API. This can be useful if you want to store a response in a database for later use or are interested in new things that coc.py does not support otherwise yet. But because this increases the memory footprint and is not needed for most use cases, this defaults to False.

  • base_url (str) – The base URL to use for API requests. Defaults to “https://api.clashofclans.com/v1

loop

The loop that is used for HTTP requests

Type:

asyncio.AbstractEventLoop

async close() None

Closes the HTTP connection from within a loop function such as async def main()

Transform troops and spells into an in-game army share link.

Note

You must have Troop and Spell game metadata loaded in order to use this method. This means load_game_metadata of Client must be anything but LoadGameData.never.

Example

link = client.create_army_link(
            barbarian=10,
            archer=20,
            hog_rider=30,
            healing_spell=3,
            poison_spell=2,
            rage_spell=2
        )
print(link)  # prints https://link.clashofclans.com/en?action=CopyArmy&army=u0x10-1x20-11x30s1x3-9x2-2x2
Parameters:

**kwargs – Troop name to quantity mapping. See the example for more info. The troop name must match in-game exactly, and is case-insensitive. Replace spaces (” “) with an underscore. The quantity must be an integer.

Raises:

RuntimeError – Troop and Spell game metadata must be loaded to use this feature.

Returns:

The army share link.

Return type:

str

dispatch(event_name: str, *args, **kwargs) None

Dispatches an event listener matching the event_name parameter.

async get_builder_base_league(league_id: int) BaseLeague

Get builder base league information

Parameters:

league_id (str) – The League ID to search for.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

  • NotFound – No league was found with the supplied league ID.

Returns:

The league with the requested ID

Return type:

BaseLeague

async get_builder_base_league_named(league_name: str) Optional[BaseLeague]

Get a builder base league by name.

This is somewhat equivalent to

leagues = await client.search_builder_base_leagues(limit=None)
return utils.get(leagues, name=league_name)
Parameters:

league_name (str) – The builder base league name to search for

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The first league matching the league name. Could be None if not found.

Return type:

BaseLeague

async get_capital_league(league_id: int) BaseLeague

Get capital league information

Parameters:

league_id (str) – The League ID to search for.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

  • NotFound – No league was found with the supplied league ID.

Returns:

The league with the requested ID

Return type:

BaseLeague

async get_capital_league_named(league_name: str) Optional[BaseLeague]

Get a capital league by name.

This is somewhat equivalent to

leagues = await client.search_capital_leagues(limit=None)
return utils.get(leagues, name=league_name)
Parameters:

league_name (str) – The capital league name to search for

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The first league matching the league name. Could be None if not found.

Return type:

BaseLeague

async get_clan(tag: str, cls: ~typing.Type[~coc.clans.Clan] = <class 'coc.clans.Clan'>, **kwargs) Clan

Get information about a single clan by clan tag.

Clan tags can be found using clan search operation.

Parameters:
  • tag (str) – The clan tag to search for.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of Clan.

  • NotFound – No clan was found with the supplied tag.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The clan with provided tag.

Return type:

Clan

async get_clan_labels(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[Label]

Fetch all possible clan labels.

Parameters:
  • limit (int) – The number of results to fetch.

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

A list of all possible clan labels.

Return type:

List[Label]

async get_clan_war(clan_tag: str, cls: ~typing.Type[~coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) ClanWar

Retrieve information about clan’s current clan war

Parameters:

clan_tag (str) – The clan tag to search for.

Raises:
  • TypeError – The cls parameter must be a subclass of ClanWar.

  • NotFound – No clan was found with the supplied tag.

  • PrivateWarLog – The clan’s war log is private.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The clan’s current war.

Return type:

ClanWar

get_clan_wars(clan_tags: ~typing.Iterable[str], cls: ~typing.Type[~coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) AsyncIterator[ClanWar]

Retrieve information multiple clan’s current clan wars

This returns a coc.WarIterator which fetches the requested wars in parallel.

Note

This will skip any clans who have a private war-log.

Note

This will not fetch any CWL wars. Use Client.get_current_wars() for that.

Example

tags = [...]
async for clan_war in Client.get_clan_wars(tags):
    print(clan_war.opponent)
Parameters:
  • clan_tags (Iterable[str]) – An iterable of clan tags to search for.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of ClanWar.

  • NotFound – No clan was found with the supplied tag.

  • PrivateWarLog – The clan’s warlog is private.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Yields:

ClanWar – A war matching one of the tags requested.

get_clans(tags: ~typing.Iterable[str], cls: ~typing.Type[~coc.clans.Clan] = <class 'coc.clans.Clan'>, **kwargs) AsyncIterator[Clan]

Get information about multiple clans by clan tag. Refer to Client.get_clan for more information.

This returns a ClanIterator which fetches the requested clan tags in parallel.

Example

tags = [...]
async for clan in client.get_clans(tags):
    print(clan.name)
Parameters:
  • tags (Iterable[str]) – An iterable of clan tags to search for.

  • cls – Target class to use to model that data returned

Raises:

TypeError – The cls parameter must be a subclass of Clan.

Yields:

Clan – A clan matching one of the tags requested.

async get_current_goldpass_season() GoldPassSeason

Get the current gold pass season

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The gold pass season object of the current season

Return type:

GoldPassSeason

async get_current_war(clan_tag: str, cwl_round: ~coc.enums.WarRound = WarRound.current_war, cls: ~typing.Type[~coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) Optional[ClanWar]

Retrieve a clan’s current war.

Unlike Client.get_clan_war or Client.get_league_war, this method will search for a regular war, and if the clan is in notInWar state, search for a current league war.

This simplifies what would otherwise be 2-3 function calls to find a war.

If you don’t wish to search for CWL wars, use Client.get_clan_war().

This method will consume the PrivateWarLog error, instead returning None.

Note

You can differentiate between a regular clan war and a clan war league (CWL) war by using the helper property, ClanWar.is_cwl.

Parameters:
  • clan_tag (str) – An iterable of clan tag to search for.

  • cwl_round (WarRound) – An enum detailing the type of round to get. Could be coc.WarRound.previous_war, coc.WarRound.current_war or coc.WarRound.preparation. This defaults to coc.WarRound.current_war.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of ClanWar.

  • NotFound – No clan was found with the supplied tag.

  • PrivateWarLog – The clan’s warlog is private.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The clan’s current war. Could be None.

If the clan is in CWL, the league group can be accessed via ClanWar.league_group.

If you pass in a WarRound and that round doesn’t exist (yet), this will return None.

Return type:

ClanWar

get_current_wars(clan_tags: ~typing.Iterable[str], cls: ~typing.Type[~coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) AsyncIterator[ClanWar]

Retrieve information multiple clan’s current wars.

See Client.get_current_war() for more information.

This returns a CurrentWarIterator which fetches the requested clan tags in parallel.

Note

This will skip any clans who have a private war-log.

Note

This will fetch CWL wars, which may result in a slower operation due to multiple API calls. If you only wish to get regular wars, consider Client.get_clan_wars().

Example

tags = [...]
async for war in Client.get_current_wars(tags):
    print(war.type)
Parameters:
  • clan_tags (Iterable[str]) – An iterable of clan tags to search for.

  • cls – Target class to use to model that data returned

Raises:

TypeError – The cls parameter must be a subclass of ClanWar.

Yields:

ClanWar – The clan war of a requested tag.

get_hero(name: str, level: int = None, townhall: int = None) Optional[Union[Type[Hero], Hero]]

Get an uninitiated Hero object with the given name.

Note

You must have Hero metadata loaded in order to use this method. This means load_game_metadata of Client must be anything but LoadGameData.never.

Note

Please see Game Data for more info on how to use initiated vs uninitiated models.

Example

hero = client.get_hero("Archer Queen")

for level, cost in enumerate(hero.upgrade_cost, start=1):
    print(f"{hero.name} has an upgrade cost of {cost} at Lv{level}")
Parameters:
  • name (str) – The hero name, which must match in-game exactly, but is case-insensitive.

  • level (Optional[int]) – The level to pass into the construction of the Hero object. If this is present this will return an Initiated Objects.

  • townhall (Optional[int]) – The TH level to pass into the construction of the Hero object. If this is None, this will default to the TH level the level parameter is unlocked at.

Raises:

RuntimeError – Hero game metadata must be loaded to use this feature.

Returns:

If level is not None, this will return an Initiated Objects otherwise, this will return an Uninitiated Objects

If the hero is not found, this will return None.

Return type:

Hero

async get_league(league_id: int) League

Get league information

Parameters:

league_id (str) – The League ID to search for.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

  • NotFound – No league was found with the supplied league ID.

Returns:

The league with the requested ID

Return type:

League

async get_league_group(clan_tag: str, cls: ~typing.Type[~coc.wars.ClanWarLeagueGroup] = <class 'coc.wars.ClanWarLeagueGroup'>, **kwargs) ClanWarLeagueGroup

Retrieve information about clan’s current clan war league group.

Parameters:
  • clan_tag (str) – The clan tag to search for.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of ClanWarLeagueGroup.

  • NotFound – No clan was found with the supplied tag.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception. This may be due to an API bug whereby requesting the league group of a clan searching for a CWL match will time out.

Returns:

The clan’s war league group.

Return type:

ClanWarLeagueGroup

async get_league_named(league_name: str) Optional[League]

Get a league by name.

This is somewhat equivalent to

leagues = await client.search_leagues(limit=None)
return utils.get(leagues, name=league_name)
Parameters:

league_name (str) – The league name to search for

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The first league matching the league name. Could be None if not found.

Return type:

League

async get_league_war(war_tag: str, cls: ~typing.Type[~coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) ClanWar

Retrieve information about a clan war league war.

Parameters:
  • war_tag (str) – The league war tag to search for.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of ClanWar.

  • NotFound – No clan was found with the supplied tag.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The league war associated with the war tag

Return type:

ClanWar

get_league_wars(war_tags: ~typing.Iterable[str], clan_tag: ~typing.Optional[str] = None, cls: ~typing.Type[~coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) AsyncIterator[ClanWar]

Retrieve information about multiple league wars

This returns a LeagueWarIterator which fetches the requested clan tags in parallel.

Example

tags = [...]
async for league_war in Client.get_league_wars(tags):
    print(league_war.opponent)
Parameters:
  • war_tags (Iterable[str]) – An iterable of war tags to search for.

  • clan_tag (str) – An optional clan tag. If present, this will only return wars which belong to this clan.

  • cls – Target class to use to model that data returned

Raises:

TypeError – The cls parameter must be a subclass of ClanWar.

Yields:

ClanWar – A war matching one of the tags requested.

async get_location(location_id: int) Location

Get information about specific location

Parameters:

location_id (int) – The Location ID to search for.

Raises:
  • NotFound – No location was found with the supplied ID.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The requested location.

Return type:

Location

async get_location_clans(location_id: int = 'global', *, limit: ~typing.Optional[int] = None, before: ~typing.Optional[str] = None, after: ~typing.Optional[str] = None, cls: ~typing.Type[~coc.clans.RankedClan] = <class 'coc.clans.RankedClan'>) List[RankedClan]

Get clan rankings for a specific location

Parameters:
  • location_id (int) – The Location ID to search for. Defaults to all locations (global).

  • limit (int) – The number of results to fetch.

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of RankedClan.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The top clans for the requested location.

Return type:

List[RankedClan]

async get_location_clans_builder_base(location_id: int = 'global', *, limit: ~typing.Optional[int] = None, before: ~typing.Optional[str] = None, after: ~typing.Optional[str] = None, cls: ~typing.Type[~coc.clans.RankedClan] = <class 'coc.clans.RankedClan'>) List[RankedClan]

Get clan builder base rankings for a specific location

Parameters:
  • location_id (int) – The Location ID to search for. Defaults to all locations (global).

  • limit (int) – The number of results to fetch.

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of RankedClan.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The top builder base-clans for the requested location.

Return type:

List[RankedClan]

async get_location_clans_capital(location_id: int = 'global', *, limit: ~typing.Optional[int] = None, before: ~typing.Optional[str] = None, after: ~typing.Optional[str] = None, cls: ~typing.Type[~coc.clans.RankedClan] = <class 'coc.clans.RankedClan'>) List[RankedClan]

Get clan capital rankings for a specific location

Parameters:
  • location_id (int) – The Location ID to search for. Defaults to all locations (global).

  • limit (int) – The number of results to fetch.

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of RankedClan.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The top clans for the requested location.

Return type:

List[RankedClan]

async get_location_named(location_name: str) Optional[Location]

Get a location by name.

This is equivalent to:

locations = await client.search_locations(limit=None)
return utils.get(locations, name=location_name)
Parameters:

location_name (str) – The location name to search for

Returns:

The first location matching the location name.

Return type:

Location

async get_location_players(location_id: int = 'global', *, limit: ~typing.Optional[int] = None, before: ~typing.Optional[str] = None, after: ~typing.Optional[str] = None, cls: ~typing.Type[~coc.players.RankedPlayer] = <class 'coc.players.RankedPlayer'>) List[RankedPlayer]

Get player rankings for a specific location

Parameters:
  • location_id (int) – The Location ID to search for. Defaults to all locations (global).

  • limit (int) – The number of results to fetch.

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of RankedPlayer.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The top players for the requested location.

Return type:

List[RankedPlayer]

async get_location_players_builder_base(location_id: int = 'global', *, limit: ~typing.Optional[int] = None, before: ~typing.Optional[str] = None, after: ~typing.Optional[str] = None, cls: ~typing.Type[~coc.players.RankedPlayer] = <class 'coc.players.RankedPlayer'>) List[RankedPlayer]

Get player builder base rankings for a specific location

Parameters:
  • location_id (int) – The Location ID to search for. Defaults to all locations (global).

  • limit (int) – The number of results to fetch.

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of RankedPlayer.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The top builder base players for the requested location.

Return type:

List[RankedPlayer]

async get_members(clan_tag: str, *, limit: int = 0, after: str = '', before: str = '', cls: ~typing.Type[~coc.players.ClanMember] = <class 'coc.players.ClanMember'>, **kwargs) List[ClanMember]

List clan members.

This is equivilant to (await Client.get_clan('tag')).members.

Parameters:
  • clan_tag (str) – The clan tag to search for.

  • cls – Target class to use to model that data returned

  • limit – class:int: Number of members to retrieve

  • after – class:str: Pagination string to get page after

  • before – class:str: Pagination string to get page before

Raises:
  • TypeError – The cls parameter must be a subclass of ClanMember.

  • NotFound – No clan was found with the supplied tag.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

A list of members in the clan.

Return type:

List[ClanMember]

get_pet(name: str, level: int = None, townhall: int = None) Optional[Union[Type[Pet], Pet]]

Get an uninitiated Pet object with the given name.

Note

You must have Pet metadata loaded in order to use this method. This means load_game_metadata of Client must be anything but LoadGameData.never.

Note

Please see Game Data for more info on how to use initiated vs uninitiated models.

Example

troop = client.get_pet("Electro Owl")

for level, cost in enumerate(pet.upgrade_cost, start=1):
    print(f"{pet.name} has an upgrade cost of {cost} at Lv{level}")
Parameters:
  • name (str) – The pet name, which must match in-game exactly, but is case-insensitive.

  • level (Optional[int]) – The level to pass into the construction of the Pet object. If this is present this will return an Initiated Objects.

  • townhall (Optional[int]) – The TH level to pass into the construction of the Pet object. If this is None, this will default to the TH level the level parameter is unlocked at.

Raises:

RuntimeError – Pet game metadata must be loaded to use this feature.

Returns:

If level is not None, this will return an Initiated Objects otherwise, this will return an Uninitiated Objects

If the pet is not found, this will return None.

Return type:

Pet

async get_player(player_tag: str, cls: ~typing.Type[~coc.players.Player] = <class 'coc.players.Player'>, load_game_data: ~typing.Optional[bool] = None, **kwargs) Player

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

Parameters:
  • player_tag (str) – The player tag to search for.

  • cls – Target class to use to model that data returned

Raises:
  • TypeError – The cls parameter must be a subclass of Player.

  • NotFound – No player was found with the supplied tag.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The player with the tag.

Return type:

Player

async get_player_labels(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[Label]

Fetch all possible player labels.

Parameters:
  • limit (int) – The number of results to fetch.

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

A list of all possible player labels.

Return type:

List[Label]

get_players(player_tags: ~typing.Iterable[str], cls: ~typing.Type[~coc.players.Player] = <class 'coc.players.Player'>, load_game_data: ~typing.Optional[bool] = None, **kwargs) AsyncIterator[Player]

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

This returns a PlayerIterator which fetches the requested player tags in parallel.

Example

tags = [...]
async for player in Client.get_players(tags):
    print(player)
Parameters:
  • player_tags (Iterable[str]) – An iterable of player tags to search for.

  • cls – Target class to use to model that data returned

Raises:

TypeError – The cls parameter must be a subclass of Player.

Yields:

Player – A player matching one of the tags requested.

async get_raid_log(clan_tag: str, cls: ~typing.Type[~coc.raid.RaidLogEntry] = <class 'coc.raid.RaidLogEntry'>, page: bool = False, *, limit: int = 0, after: str = '', before: str = '') RaidLog

Retrieve a clan’s Capital Raid Log. By default, this will return all the clan’s log available in the API. This will of course consume memory. The option of limiting the amount of log items fetched can be controlled with the limit parameter. Additionally, if paginate is set to True, and an async for loop is performed on this object, then additional log items will be fetched but only consume the same amount of memory space at all time.

Parameters:
  • clan_tag – class:str: The clan tag to search for.

  • cls – Target class to use to model that data returned

  • page – class:bool: Enable fetching logs while only holding the same amount of logs as limit. If paginate is set to True, and limit is set to default of 0, then limit will be set to 10 automatically.

  • limit – class:int: Number of logs to retrieve

  • after – class:str: Pagination string to get page after

  • before – class:str: Pagination string to get page before

Raises:
  • TypeError – The cls parameter must be a subclass of RaidLogEntry.

  • NotFound – No clan was found with the supplied tag.

  • PrivateWarLog – The clan’s warlog is private.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

Entries in the capital raid seasons of the requested clan.

Return type:

RaidLog

async get_season_rankings(league_id: int, season_id: int) List[RankedPlayer]

Get league season rankings.

Note

League season information is available only for Legend League, with a league ID 29000021.

Parameters:
  • league_id (str) – The League ID to search for.

  • season_id (str) – The Season ID to search for.

Raises:
  • InvalidArgument – An invalid league_id or season_id was supplied. Currently the only league supported is legends.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

Top players for the requested season and league.

Return type:

List[RankedPlayer]

async get_seasons(league_id: int = 29000021) List[str]

Get league seasons.

Note

League season information is available only for Legend League, with a league ID 29000021.

Parameters:

league_id (str) – The League ID to search for. Defaults to the only league you can get season information for, legends.

Raises:
  • InvalidArgument – An invalid league_id was supplied. Currently the only league supported is legends.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The legend season IDs, in the form YYYY-MM, ie. 2020-04.

Return type:

List[str]

get_spell(name: str, level: int = None, townhall: int = None) Optional[Union[Type[Spell], Spell]]

Get an uninitiated Spell object with the given name.

Note

You must have Spell metadata loaded in order to use this method. This means load_game_metadata of Client must be anything but LoadGameData.never.

Note

Please see Game Data for more info on how to use initiated vs uninitiated models.

Example

troop = client.get_spell("Healing Spell")

for level, cost in enumerate(spell.upgrade_cost, start=1):
    print(f"{spell.name} has an upgrade cost of {cost} at Lv{level}")
Parameters:
  • name (str) – The troop name, which must match in-game exactly, but is case-insensitive.

  • level (Optional[int]) – The level to pass into the construction of the Spell object. If this is present this will return an Initiated Objects. This can be None, and you will get an uninitiated object.

  • townhall (Optional[int]) – The TH level to pass into the construction of the Spell object. If this is None, this will default to the TH level the level parameter is unlocked at.

Raises:

RuntimeError – Troop and Spell game metadata must be loaded to use this feature.

Returns:

If level is not None, this will return an Initiated Objects otherwise, this will return an Uninitiated Objects

If the spell is not found, this will return None.

Return type:

Spell

get_troop(name: str, is_home_village: bool = True, level: int = None, townhall: int = None) Optional[Union[Type[Troop], Troop]]

Get an uninitiated Troop object with the given name.

Note

You must have Troop metadata loaded in order to use this method. This means load_game_metadata of Client must be anything but LoadGameData.never.

Note

Please see Game Data for more info on how to use initiated vs uninitiated models.

Example

troop = client.get_troop("Barbarian")

for level, dps in enumerate(troop.dps, start=1):
    print(f"{troop.name} has {dps} DPS at Lv{level}")
Parameters:
  • name (str) – The troop name, which must match in-game exactly, but is case-insensitive.

  • is_home_village (bool) – Whether the troop belongs to the home village or not. Defaults to True.

  • level (Optional[int]) – The level to pass into the construction of the Troop object. If this is present this will return an Initiated Objects.

  • townhall (Optional[int]) – The TH level to pass into the construction of the Troop object. If this is None, this will default to the TH level the level parameter is unlocked at.

Raises:

RuntimeError – Troop and Spell game metadata must be loaded to use this feature.

Returns:

If level is not None, this will return an Initiated Objects otherwise, this will return an Uninitiated Objects

If the troop is not found, this will return None.

Return type:

Troop

async get_war_league(league_id: int) BaseLeague

Get war league information

Parameters:

league_id (str) – The League ID to search for.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

  • NotFound – No league was found with the supplied league ID.

Returns:

The league with the requested ID

Return type:

BaseLeague

async get_war_league_named(league_name: str) Optional[BaseLeague]

Get a war league by name.

This is somewhat equivalent to

leagues = await client.search_war_leagues(limit=None)
return utils.get(leagues, name=league_name)
Parameters:

league_name (str) – The war league name to search for

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The first league matching the league name. Could be None if not found.

Return type:

BaseLeague

async get_war_log(clan_tag: str, cls: ~typing.Type[~coc.wars.ClanWarLogEntry] = <class 'coc.wars.ClanWarLogEntry'>, page: bool = False, *, limit: int = 0, after: str = '', before: str = '') ClanWarLog

Retrieve a clan’s clan war log. By default, this will return all the clan’s log available in the API. This will of course consume memory. The option of limiting the amount of log items fetched can be controlled with the limit parameter. Additionally, if paginate is set to True, and an async for loop is performed on this object, then additional log items will be fetched but only consume the same amount of memory space at all time.

Note

Please see documentation for ClanWarLogEntry for different attributes which are present when the entry is a regular clan war or a league clan war. The difference can be found with ClanWarLogEntry.is_league_entry.

Parameters:
  • clan_tag – class:str: The clan tag to search for.

  • cls – Target class to use to model that data returned

  • page – class:bool: Enable fetching logs while only holding the same amount of logs as limit. If paginate is set to True, and limit is set to default of 0, then limit will be set to 10 automatically.

  • limit – class:int: Number of logs to retrieve

  • after – class:str: Pagination string to get page after

  • before – class:str: Pagination string to get page before

Raises:
Returns:

Entries in the warlog of the requested clan.

Return type:

ClanWarLog

async login(email: str, password: str) None

Retrieves all keys and creates an HTTP connection ready for use.

Parameters:
login_with_keys(*keys: str) None

Creates an HTTP connection ready for use with the keys you provide.

Deprecated since version v2.3.0: This function has been deemed deprecated to allow asyncio to clean up the async structures. Please use Client.login_with_tokens() instead.

Parameters:

keys (list[str]) – Keys or tokens as found from https://developer.clashofclans.com.

async login_with_tokens(*tokens: str) None

Creates an HTTP connection ready for use with the tokens you provide.

Parameters:

tokens (list[str]) – Tokens as found from https://developer.clashofclans.com under “My account” -> <your key> -> “token”.

Transform an army link from in-game into a list of troops and spells.

Note

You must have Troop and Spell game metadata loaded in order to use this method. This means load_game_metadata of Client must be anything but LoadGameData.never.

Example

troops, spells = client.parse_army_link("https://link.clashofclans.com/en?action=CopyArmy&army=u10x0-2x3s1x9-3x2")

for troop, quantity in troops:
    print("The user wants {} {}s. They each have {} DPS.".format(quantity, troop.name, troops.dps))

for spell, quantity in spells:
    print("The user wants {} {}s.".format(quantity, troop.name))
Parameters:

link (str) – The army share link, as copied from in-game. It should look something like: https://link.clashofclans.com/en?action=CopyArmy&army=u10x0-2x3s1x9-3x2

Raises:

RuntimeError – Troop and Spell game metadata must be loaded to use this feature.

Returns:

A list of tuples containing the Troop or Spell object, and a quantity (1, 2, 3, 12 etc.) If none is found, this will still return 2 empty lists. If a troop isn’t found, it will default to a Barbarian, as this is how the game parses the links.

Return type:

List[Tuple[Troop, int]], List[Tuple[Spell, int]]

async search_builder_base_leagues(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[BaseLeague]

Get list of builder base leagues.

Parameters:
  • limit (int) – Number of items to fetch. Defaults to None (all leagues).

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The requested leagues.

Return type:

List[BaseLeague]

async search_capital_leagues(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[BaseLeague]

Get list of capital leagues.

Parameters:
  • limit (int) – Number of items to fetch. Defaults to None (all leagues).

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The requested leagues.

Return type:

List[BaseLeague]

async search_clans(*, name: ~typing.Optional[str] = None, war_frequency: ~typing.Optional[str] = None, location_id: ~typing.Optional[int] = None, min_members: ~typing.Optional[int] = None, max_members: ~typing.Optional[int] = None, min_clan_points: ~typing.Optional[int] = None, min_clan_level: ~typing.Optional[int] = None, label_ids: ~typing.List[~typing.Union[~coc.miscmodels.Label, int]] = [], limit: ~typing.Optional[int] = None, before: ~typing.Optional[str] = None, after: ~typing.Optional[str] = None, cls: ~typing.Type[~coc.clans.Clan] = <class 'coc.clans.Clan'>, **kwargs) List[Clan]

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.

Parameters:
  • name (str, optional) – The clan name.

  • war_frequency (str, optional) – The war frequency.

  • location_id (int, optional) – The location id.

  • min_members (int, optional) – The minimum number of members.

  • max_members (int, optional) – The maximum number of members.

  • min_clan_points (int, optional) – The minumum clan points.

  • min_clan_level (int, optional) – The minimum clan level.

  • label_ids (List`[Union[:class:`coc.Label, int]]) – List of Labels or Label ids

  • limit (int) – The number of clans to search for.

  • cls – Target class to use to model that data returned

Raises:
  • RuntimeError – At least one filtering parameter must be passed.

  • TypeError – The cls parameter must be a subclass of Clan.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

A list of all clans found matching criteria provided.

Return type:

List[Clan]

async search_leagues(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[League]

Get list of leagues.

Parameters:
  • limit (int) – Number of items to fetch. Defaults to None (all leagues).

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The requested leagues.

Return type:

List[League]

async search_locations(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[Location]

List all available locations

Parameters:
  • limit (int, optional) – Number of items to fetch. Default is None, which returns all available locations

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The requested locations.

Return type:

List[Location]

async search_war_leagues(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[BaseLeague]

Get list of war leagues.

Parameters:
  • limit (int) – Number of items to fetch. Defaults to None (all leagues).

  • before (str, optional) – For use with paging. Not implemented yet.

  • after (str, optional) – For use with paging. Not implemented yet.

Raises:
  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

The requested leagues.

Return type:

List[BaseLeague]

async verify_player_token(player_tag: str, token: str) bool

Verify player API token that can be found from the game settings.

This can be used to check that players own the game accounts they claim to own as they need to provide the one-time use API token that exists inside the game.

Parameters:
  • player_tag (str) – The player tag to verify.

  • token (str) – The player’s API token to verify.

Raises:
  • NotFound – No player was found with the supplied tag.

  • Maintenance – The API is currently in maintenance.

  • GatewayError – The API hit an unexpected gateway exception.

Returns:

Whether the player tag and API token were a valid match.

Return type:

bool