API Reference

The following section outlines the API Reference of coc.py

Logging in and client creation

coc.login(email: str, password: str, client: Type[coc.client.Client] = <class 'coc.client.Client'>, **kwargs) → Union[coc.client.Client, coc.events.EventsClient]

Eases logging into the coc.py Client.

This function makes logging into the client easy, returning the created client.

Parameters:
  • email (str) – Your password email from https://developer.clashofclans.com This is used when updating keys automatically if your IP changes
  • password (str) – Your password login from https://developer.clashofclans.com This is used when updating keys automatically if your IP changes
  • client – The type of coc.py client to use. This could either be a Client or EventsClient, depending on which you wish to use.
  • **kwargs – Any kwargs you wish to pass into the Client object.

Clients

Basic Client

class coc.Client(*, key_count: int = 1, key_names: str = 'Created with coc.py Client', throttle_limit: int = 10, loop: asyncio.events.AbstractEventLoop = None, cache=<class 'coc.cache.Cache'>, correct_tags: bool = False)

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
  • cache (Cache, optional) – The Cache used for interaction with the clients cache. If passed, this must inherit from Cache. The default cache will be used if nothing 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 False.
loop

The loop that is used for HTTP requests

Type:asyncio.AbstractEventLoop
close()

Closes the HTTP connection

create_cache()

Creates all cache instances and registers settings.

This is called automatically in coc.login()

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

Dispatches an event listener matching the event_name parameter.

get_clan(tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

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.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

The clan with provided tag.

Return type:

SearchClan

get_clan_labels(*, limit: int = None, before: str = None, after: str = None)

List 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.
Returns:

Return type:

list of Label

get_clan_war(clan_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True, cls=<class 'coc.wars.ClanWar'>)

Retrieve information about clan’s current clan war

Parameters:
  • clan_tag (str) – The clan tag to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
  • cls – The factory class that will be used to create the war. By default, this is ClanWar, however if a custom class is provided, this must inherit ClanWar.
Returns:

Return type:

ClanWar or the custom class provided to the cls parameter.

get_clan_wars(clan_tags: collections.abc.Iterable, cache: bool = True, fetch: bool = True, update_cache: bool = True, **extra_options)

Retrieve information multiple clan’s current clan wars

Example

tags = [...]
async for clan_war in Client.get_clan_wars(tags):
    print(clan_war.opponent)
Parameters:
  • clan_tags (collections.Iterable) – An iterable of clan tags to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True.
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True.
  • **extra_options

    Extra options to use when passing in iterables other than normal lists. These kwargs could be any of the following:

    • index: bool - whether to index the values contained inside the iterable. Defaults to False
    • index_type: Union[str, int] - the string or integer slice to index each value inside the iterable with.
    • attribute: str - the attribute to get for each item in the iterable. Defaults to None.
    • index_before_attribute: bool - whether to index the item before getting an attribute (defaults to True)

    If none of these options are passed, the iterable passed in should be an instance of collections.Iterable.

Returns:

Return type:

coc.iterators.WarIterator of ClanWar

get_clans(tags: collections.abc.Iterable, cache: bool = True, fetch: bool = True, update_cache: bool = True, **extra_options)

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

Example

tags = [...]
async for clan in Client.get_clans(tags):
    print(clan.name)
Parameters:
  • tags (collections.Iterable) – An iterable of clan tags to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
  • **extra_options

    Extra options to use when passing in iterables other than normal lists. These kwargs could be any of the following:

    • index: bool - whether to index the values contained inside the iterable. Defaults to False
    • index_type: Union[str, int] - the string or integer slice to index each value inside the iterable with.
    • attribute: str - the attribute to get for each item in the iterable. Defaults to None.
    • index_before_attribute: bool - whether to index the item before getting an attribute (defaults to True)

    If none of these options are passed, the iterable passed in should be an instance of collections.Iterable.

Returns:

Return type:

ClanIterator of SearchClan

get_current_war(clan_tag: str, *, league_war: bool = True, cache: bool = True, fetch: bool = True, update_cache: bool = True)

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.

Parameters:
  • clan_tag (str) – An iterable of clan tag to search for.
  • league_war (bool) – Indicates whether the client should search for a league war. If this is False, consider using Client.get_clan_war. Defaults to True.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True.
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True.
Returns:

  • Either a ClanWar or LeagueWar, depending on the type of war in progress.
  • These can be differentiated by through an isinstance(..) method,
  • or by comparing type attributes.
  • If no league group is found, or the group is in preparation, this method will return the
  • ClanWar, which appears notInWar, rather than returning None.

get_current_wars(clan_tags: collections.abc.Iterable, cache: bool = True, fetch: bool = True, update_cache: bool = True, **extra_options)

Retrieve information multiple clan’s current wars.

These may be ClanWar or LeagueWar.

Example

tags = [...]
async for war in Client.get_current_wars(tags):
    print(war.type)
Parameters:
  • clan_tags (collections.Iterable) – An iterable of clan tags to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True.
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True.
  • **extra_options

    Extra options to use when passing in iterables other than normal lists. These kwargs could be any of the following:

    • index: bool - whether to index the values contained inside the iterable. Defaults to False
    • index_type: Union[str, int] - the string or integer slice to index each value inside the iterable with.
    • attribute: str - the attribute to get for each item in the iterable. Defaults to None.
    • index_before_attribute: bool - whether to index the item before getting an attribute (defaults to True)

    If none of these options are passed, the iterable passed in should be an instance of collections.Iterable.

Returns:

get_league(league_id: int, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Get league information

Parameters:
  • league_id (str) – The League ID to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

League

get_league_group(clan_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Retrieve information about clan’s current clan war league group

Parameters:
  • clan_tag (str) – The clan tag to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True.
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True.
Returns:

Return type:

LeagueGroup

get_league_named(league_name: str)

Get a location by name.

This is somewhat equivilant 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
Returns:The first location matching the location name
Return type:League
get_league_war(war_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Retrieve information about a clan war league war

Parameters:
  • war_tag (str) – The league war tag to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

LeagueWar

get_league_wars(war_tags: collections.abc.Iterable, cache: bool = True, fetch: bool = True, update_cache: bool = True, **extra_options)

Retrieve information multiple clan’s current league wars

Example

tags = [...]
async for league_war in Client.get_league_wars(tags):
    print(league_war.opponent)
Parameters:
  • war_tags (collections.Iterable) – An iterable of war tags to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True.
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True.
  • **extra_options

    Extra options to use when passing in iterables other than normal lists. These kwargs could be any of the following:

    • index: bool - whether to index the values contained inside the iterable. Defaults to False
    • index_type: Union[str, int] - the string or integer slice to index each value inside the iterable with.
    • attribute: str - the attribute to get for each item in the iterable. Defaults to None.
    • index_before_attribute: bool - whether to index the item before getting an attribute (defaults to True)

    If none of these options are passed, the iterable passed in should be an instance of collections.Iterable.

Returns:

Return type:

coc.iterators.LeagueWarIterator of LeagueWar

get_location(location_id: int, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Get information about specific location

Parameters:
  • location_id (int) – The Location ID to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

Location

get_location_clan(location_id: int = 'global', *, limit: int = None, before: str = None, after: str = None)

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.
Returns:

Return type:

list of Clan

get_location_clans_versus(location_id: int = 'global', *, limit: int = None, before: str = None, after: str = None)

Get clan versus 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.
Returns:

Return type:

list of Clan

get_location_named(location_name: str)

Get a location by name.

This is somewhat equivilant 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
get_location_players(location_id: int = 'global', *, limit: int = None, before: str = None, after: str = None)

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.
Returns:

Return type:

list of Player

get_location_players_versus(location_id: int = 'global', *, limit: int = None, before: str = None, after: str = None)

Get player versus 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.
Returns:

Return type:

list of Player

get_members(clan_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

List clan members.

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

Parameters:
  • clan_tag (str) – The clan tag to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

list of BasicPlayer

get_player(player_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

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.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

SearchPlayer

get_player_labels(*, limit: int = None, before: str = None, after: str = None)

List 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.
Returns:

Return type:

list of Label

get_players(player_tags: collections.abc.Iterable, cache: bool = True, fetch: bool = True, update_cache: bool = True, **extra_options)

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

Example

tags = [...]
async for player in Client.get_players(tags):
    print(player)
Parameters:
  • player_tags (collections.Iterable) – An iterable of player tags to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
  • **extra_options

    Extra options to use when passing in iterables other than normal lists. These kwargs could be any of the following:

    • index: bool - whether to index the values contained inside the iterable. Defaults to False
    • index_type: Union[str, int] - the string or integer slice to index each value inside the iterable with.
    • attribute: str - the attribute to get for each item in the iterable. Defaults to None.
    • index_before_attribute: bool - whether to index the item before getting an attribute (defaults to True)

    If none of these options are passed, the iterable passed in should be an instance of collections.Iterable.

Returns:

Return type:

PlayerIterator of SearchPlayer

get_season_rankings(league_id: int, season_id: int, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Get league season rankings. Note that league season information is available only for Legend League.

Parameters:
  • league_id (str) – The League ID to search for.
  • season_id (str) – The Season ID to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

list of LeagueRankedPlayer

get_seasons(league_id: int)

Get league seasons. Note that league season information is available only for Legend League.

Parameters:league_id (str) – The League ID to search for.
Returns:In the form
{
    "id": "string"
}

where id is the Season ID

Return type:dict
get_warlog(clan_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Retrieve clan’s clan war log

Parameters:
  • clan_tag (str) – The clan tag to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type will depend on what kind of war it is. These two classes have different attributes.

Return type:

list of either WarLog or LeagueWarLogEntry

login(email: str, password: str)

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

Parameters:
reset_keys(number_of_keys: int = None)

Manually reset any number of keys.

Under normal circumstances, this method should not need to be called.

Parameters:number_of_keys (int) – The number of keys to reset. Defaults to None - all keys.
search_clans(*, name: str = None, war_frequency: str = None, location_id: int = None, min_members: int = None, max_members: int = None, min_clan_points: int = None, min_clan_level: int = None, limit: int = None, before: str = None, after: str = None)

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.
  • limit (int) – The number of clans to search for.
Returns:

A list of all clans found matching criteria provided.

Return type:

list of SearchClan

Raises:

HTTPException – No options were passed.

search_leagues(*, limit: int = None, before: str = None, after: str = None)

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.
Returns:

Returns a list of all leagues found. Could be None

Return type:

list of League

search_locations(*, limit: int = None, before: str = None, after: str = None)

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.
Returns:

Return type:

list of Location

Events Client

class coc.EventsClient(**options)

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
  • cache (Cache, optional) – The Cache used for interaction with the clients cache. If passed, this must inherit from Cache. The default cache will be used if nothing 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 False.
loop

The loop that is used for HTTP requests

Type:asyncio.AbstractEventLoop
add_clan_update(tags: Union[collections.abc.Iterable, str], retry_interval=600)

Subscribe clan tags to events.

Parameters:
  • tags (Union[collections.Iterable, str]) – The clan tags to add. Could be an Iterable of tags or just a string tag.
  • retry_interval (int) – In seconds, how often the client ‘checks’ for updates. Defaults to 600 (10min)
add_events(*functions, function_dicts: dict = None)

Provides an alternative method to adding events.

You can either provide functions as named args or as a dict of {name: function…} values.

Example

client.add_events(on_member_update, on_clan_update, on_war_attack)
# or, using a dict:
client.add_events(function_dicts={'on_member_update': on_update,
                                  'on_clan_update': on_update_2
                                  }
                 )
Parameters:
  • functions (function) – Named args of functions to register. The name of event is dictated by function name.
  • function_dicts (dict) – Dictionary of {'event_name': function} values.
add_player_update(tags: Union[collections.abc.Iterable, str], retry_interval=600)

Subscribe player tags to player update events.

Parameters:
  • tags (collections.Iterable) – The player tags to add. Could be an Iterable of tags or just a string tag.
  • retry_interval (int) – In seconds, how often the client ‘checks’ for updates. Defaults to 600 (10min)
add_war_update(tags: Union[collections.abc.Iterable, str], retry_interval=600)

Subscribe clan tags to war events.

Parameters:
  • tags (Union[collections.Iterable, str]) – The clan tags to add. Could be an Iterable of tags or just a string tag.
  • retry_interval (int) – In seconds, how often the client ‘checks’ for updates. Defaults to 600 (10min)
close()

Closes the client and all running tasks.

create_cache()

Creates all cache instances and registers settings.

This is called automatically in coc.login()

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

Dispatches an event listener matching the event_name parameter.

event(function_, name=None)

A decorator or regular function that registers an event.

The function must be a coroutine.

Parameters:
  • function (function) – The function to be registered (not needed if used with a decorator)
  • name (str) – The name of the function to be registered. Defaults to the function name.

Example

@client.event
async def on_player_update(old_player, new_player):
    print('{} has updated their profile!'.format(old_player))
Returns:function
Return type:The function registered
get_clan(tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

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.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

The clan with provided tag.

Return type:

SearchClan

get_clan_labels(*, limit: int = None, before: str = None, after: str = None)

List 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.
Returns:

Return type:

list of Label

get_clan_war(clan_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True, cls=<class 'coc.wars.ClanWar'>)

Retrieve information about clan’s current clan war

Parameters:
  • clan_tag (str) – The clan tag to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
  • cls – The factory class that will be used to create the war. By default, this is ClanWar, however if a custom class is provided, this must inherit ClanWar.
Returns:

Return type:

ClanWar or the custom class provided to the cls parameter.

get_clan_wars(clan_tags: collections.abc.Iterable, cache: bool = True, fetch: bool = True, update_cache: bool = True, **extra_options)

Retrieve information multiple clan’s current clan wars

Example

tags = [...]
async for clan_war in Client.get_clan_wars(tags):
    print(clan_war.opponent)
Parameters:
  • clan_tags (collections.Iterable) – An iterable of clan tags to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True.
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True.
  • **extra_options

    Extra options to use when passing in iterables other than normal lists. These kwargs could be any of the following:

    • index: bool - whether to index the values contained inside the iterable. Defaults to False
    • index_type: Union[str, int] - the string or integer slice to index each value inside the iterable with.
    • attribute: str - the attribute to get for each item in the iterable. Defaults to None.
    • index_before_attribute: bool - whether to index the item before getting an attribute (defaults to True)

    If none of these options are passed, the iterable passed in should be an instance of collections.Iterable.

Returns:

Return type:

coc.iterators.WarIterator of ClanWar

get_clans(tags: collections.abc.Iterable, cache: bool = True, fetch: bool = True, update_cache: bool = True, **extra_options)

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

Example

tags = [...]
async for clan in Client.get_clans(tags):
    print(clan.name)
Parameters:
  • tags (collections.Iterable) – An iterable of clan tags to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
  • **extra_options

    Extra options to use when passing in iterables other than normal lists. These kwargs could be any of the following:

    • index: bool - whether to index the values contained inside the iterable. Defaults to False
    • index_type: Union[str, int] - the string or integer slice to index each value inside the iterable with.
    • attribute: str - the attribute to get for each item in the iterable. Defaults to None.
    • index_before_attribute: bool - whether to index the item before getting an attribute (defaults to True)

    If none of these options are passed, the iterable passed in should be an instance of collections.Iterable.

Returns:

Return type:

ClanIterator of SearchClan

get_current_war(clan_tag: str, *, league_war: bool = True, cache: bool = True, fetch: bool = True, update_cache: bool = True)

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.

Parameters:
  • clan_tag (str) – An iterable of clan tag to search for.
  • league_war (bool) – Indicates whether the client should search for a league war. If this is False, consider using Client.get_clan_war. Defaults to True.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True.
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True.
Returns:

  • Either a ClanWar or LeagueWar, depending on the type of war in progress.
  • These can be differentiated by through an isinstance(..) method,
  • or by comparing type attributes.
  • If no league group is found, or the group is in preparation, this method will return the
  • ClanWar, which appears notInWar, rather than returning None.

get_current_wars(clan_tags: collections.abc.Iterable, cache: bool = True, fetch: bool = True, update_cache: bool = True, **extra_options)

Retrieve information multiple clan’s current wars.

These may be ClanWar or LeagueWar.

Example

tags = [...]
async for war in Client.get_current_wars(tags):
    print(war.type)
Parameters:
  • clan_tags (collections.Iterable) – An iterable of clan tags to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True.
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True.
  • **extra_options

    Extra options to use when passing in iterables other than normal lists. These kwargs could be any of the following:

    • index: bool - whether to index the values contained inside the iterable. Defaults to False
    • index_type: Union[str, int] - the string or integer slice to index each value inside the iterable with.
    • attribute: str - the attribute to get for each item in the iterable. Defaults to None.
    • index_before_attribute: bool - whether to index the item before getting an attribute (defaults to True)

    If none of these options are passed, the iterable passed in should be an instance of collections.Iterable.

Returns:

get_league(league_id: int, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Get league information

Parameters:
  • league_id (str) – The League ID to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

League

get_league_group(clan_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Retrieve information about clan’s current clan war league group

Parameters:
  • clan_tag (str) – The clan tag to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True.
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True.
Returns:

Return type:

LeagueGroup

get_league_named(league_name: str)

Get a location by name.

This is somewhat equivilant 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
Returns:The first location matching the location name
Return type:League
get_league_war(war_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Retrieve information about a clan war league war

Parameters:
  • war_tag (str) – The league war tag to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

LeagueWar

get_league_wars(war_tags: collections.abc.Iterable, cache: bool = True, fetch: bool = True, update_cache: bool = True, **extra_options)

Retrieve information multiple clan’s current league wars

Example

tags = [...]
async for league_war in Client.get_league_wars(tags):
    print(league_war.opponent)
Parameters:
  • war_tags (collections.Iterable) – An iterable of war tags to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True.
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True.
  • **extra_options

    Extra options to use when passing in iterables other than normal lists. These kwargs could be any of the following:

    • index: bool - whether to index the values contained inside the iterable. Defaults to False
    • index_type: Union[str, int] - the string or integer slice to index each value inside the iterable with.
    • attribute: str - the attribute to get for each item in the iterable. Defaults to None.
    • index_before_attribute: bool - whether to index the item before getting an attribute (defaults to True)

    If none of these options are passed, the iterable passed in should be an instance of collections.Iterable.

Returns:

Return type:

coc.iterators.LeagueWarIterator of LeagueWar

get_location(location_id: int, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Get information about specific location

Parameters:
  • location_id (int) – The Location ID to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

Location

get_location_clan(location_id: int = 'global', *, limit: int = None, before: str = None, after: str = None)

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.
Returns:

Return type:

list of Clan

get_location_clans_versus(location_id: int = 'global', *, limit: int = None, before: str = None, after: str = None)

Get clan versus 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.
Returns:

Return type:

list of Clan

get_location_named(location_name: str)

Get a location by name.

This is somewhat equivilant 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
get_location_players(location_id: int = 'global', *, limit: int = None, before: str = None, after: str = None)

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.
Returns:

Return type:

list of Player

get_location_players_versus(location_id: int = 'global', *, limit: int = None, before: str = None, after: str = None)

Get player versus 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.
Returns:

Return type:

list of Player

get_members(clan_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

List clan members.

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

Parameters:
  • clan_tag (str) – The clan tag to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

list of BasicPlayer

get_player(player_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

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.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

SearchPlayer

get_player_labels(*, limit: int = None, before: str = None, after: str = None)

List 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.
Returns:

Return type:

list of Label

get_players(player_tags: collections.abc.Iterable, cache: bool = True, fetch: bool = True, update_cache: bool = True, **extra_options)

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

Example

tags = [...]
async for player in Client.get_players(tags):
    print(player)
Parameters:
  • player_tags (collections.Iterable) – An iterable of player tags to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
  • **extra_options

    Extra options to use when passing in iterables other than normal lists. These kwargs could be any of the following:

    • index: bool - whether to index the values contained inside the iterable. Defaults to False
    • index_type: Union[str, int] - the string or integer slice to index each value inside the iterable with.
    • attribute: str - the attribute to get for each item in the iterable. Defaults to None.
    • index_before_attribute: bool - whether to index the item before getting an attribute (defaults to True)

    If none of these options are passed, the iterable passed in should be an instance of collections.Iterable.

Returns:

Return type:

PlayerIterator of SearchPlayer

get_season_rankings(league_id: int, season_id: int, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Get league season rankings. Note that league season information is available only for Legend League.

Parameters:
  • league_id (str) – The League ID to search for.
  • season_id (str) – The Season ID to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type:

list of LeagueRankedPlayer

get_seasons(league_id: int)

Get league seasons. Note that league season information is available only for Legend League.

Parameters:league_id (str) – The League ID to search for.
Returns:In the form
{
    "id": "string"
}

where id is the Season ID

Return type:dict
get_warlog(clan_tag: str, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Retrieve clan’s clan war log

Parameters:
  • clan_tag (str) – The clan tag to search for.
  • cache (bool) – Indicates whether to search the cache before making an HTTP request. Defaults to True
  • fetch (bool) – Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (bool) – Indicated whether the cache should be updated if an HTTP call is made. Defaults to True
Returns:

Return type will depend on what kind of war it is. These two classes have different attributes.

Return type:

list of either WarLog or LeagueWarLogEntry

login(email: str, password: str)

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

Parameters:
on_event_error(event_name, exception, *args, **kwargs)

Event called when an event fails.

By default this will print the traceback This can be overridden by either using @client.event or through subclassing EventsClient.

Example

@client.event
async def on_event_error(event_name, exception, *args, **kwargs):
    print('Ignoring exception in {}'.format(event_name))

class Client(events.EventClient):
    async def on_event_error(event_name, exception, *args, **kwargs):
        print('Ignoring exception in {}'.format(event_name))
remove_events(*functions, function_dicts: dict = None)

Removes registered events from the client.

Similar to coc.add_events(), you can pass in functions as named args, or a list of {name: function…} values.

Example

client.remove_events(on_member_update, on_clan_update, on_war_attack)
# or, using a dict:
client.remove_events(function_dicts={'on_member_update': on_update,
                                     'on_clan_update': on_update_2
                                    }
                    )
Parameters:
  • functions (function) – Named args of functions to register. The name of event is dictated by function name.
  • function_dicts (dict) – Dictionary of {'event_name': function} values.
reset_keys(number_of_keys: int = None)

Manually reset any number of keys.

Under normal circumstances, this method should not need to be called.

Parameters:number_of_keys (int) – The number of keys to reset. Defaults to None - all keys.
run_forever()

A blocking call which runs the loop and script.

This is useful if you have no other clients to deal with and just wish to run the script and receive updates indefinately.

Roughly equivilant to:

try:
    client.loop.run_forever()
except KeyboardInterrupt:
    client.close()
finally:
    client.loop.close()
search_clans(*, name: str = None, war_frequency: str = None, location_id: int = None, min_members: int = None, max_members: int = None, min_clan_points: int = None, min_clan_level: int = None, limit: int = None, before: str = None, after: str = None)

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.
  • limit (int) – The number of clans to search for.
Returns:

A list of all clans found matching criteria provided.

Return type:

list of SearchClan

Raises:

HTTPException – No options were passed.

search_leagues(*, limit: int = None, before: str = None, after: str = None)

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.
Returns:

Returns a list of all leagues found. Could be None

Return type:

list of League

search_locations(*, limit: int = None, before: str = None, after: str = None)

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.
Returns:

Return type:

list of Location

start_updates(event_group='all')

Starts an, or all, events.

Note

This method must be called before any events are run.

Parameters:event_group (str) – The event group to start updates for. Could be player, clan, war or all. Defaults to ‘all’

Example

client.start_updates('clan')
# or, for all events:
client.start_updates('all')
stop_updates(event_type='all')

Stops an, or all, events.

Note

This method must be called in order to stop any events.

Parameters:event_type (str) – See EventsClient.start_updates() for which string corresponds to events. Defaults to ‘all’

Example

client.stop_updates('clan')
# or, for all events:
client.stop_updates('all')

Custom Cache

Cache Class

class coc.Cache(client)

The base Cache class for the library.

The library’s cache system works perfectly fine out-of-the box, and this class is purely for the purposes of creating a custom cache, if the library does not provide the functionality you require.

Some examples of implementation of this cache are:

  1. Compatibility with an async-cache, for example aioredis
  2. Compatibility with a C-binding or other cache which has performance improvements
  3. Additional logging, debugging and other things you wish to do when creating, getting and setting items to the cache
  4. Using a database for the cache (not recommended for regular use)

While all methods can be overridden, only the documented ones will be supported. What this means is that if something breaks because you override other methods, you’re on your own.

By default, the cache-type implemented mixes a LRU (least-recently used) and TTL (time to live) cache. This is a custom class, DefaultCache, that checks both these properties before returning an object.

Other classes, MaxSizeCache and TimeToLiveCache are provided for easy of use with Cache.create_default_cache().

client

The coc.py client that created this cache instance.

Type:coc.Client
clan_config

Override the default max size and expiry of the clan caches.

This must return a named tuple, coc.ClashConfig with max_size and ttl attributes.

By default, the cache uses a max size of 1024 and TTL of 3600 (1 hour).

clear(cache_type)

This function is a coroutine.

This method is used to remove all items from the cache instance.

By default, this implements the cache.clear() function. If your cache instance does not implement this method, you must override this method.

As this function is a coroutine, you can await calls.

This function does not need to return anything.

static create_default_cache(max_size, ttl)

This method creates and returns a cache instance.

It takes the parameters max_size and ttl, and should return an appropriate instance of a cache object that reflects these parameters.

This should be where you reference your “other” cache type, instance, object etc.

get(cache_type, key)

This function is a coroutine.

This method is used to get an item from a cache instance.

By default, it gets the cache instance, set as an attribute of Cache with the same name, then tries to use __getitem__ on the cache instance. If that fails, it will try and get the object via the cache.get call.

If your cache does not either implement __getitem__ or the .get(key) methods, you must override this with the alternate approach to getting items from your cache.

As this function is a coroutine, you can await calls.

This function must return the object in the cache with the given key.

get_cache(cache_name)

Retrieve the cache instance for a cache name.

get_limit(cache_type, limit: int = None)

Custom implementation of the limits() function to properly return values without timestamps.

get_max_size(cache_name)

Finds the custom max-size for a cache name.

get_ttl(cache_name)

Finds the custom expiry for a cache name.

items(cache_type)

This function is a coroutine.

This method is used to get all items from a cache instance.

By default, this implements the cache.items() function. If your cache instance does not implement this method, you must override this method.

As this function is a coroutine, you can await calls.

This function must return a list of {k, v} values: the items of the cache.

keys(cache_type)

This function is a coroutine.

This method is used to get all keys from a cache instance.

By default, this implements the cache.keys() function. If your cache instance does not implement this method, you must override this method.

As this function is a coroutine, you can await calls.

This function must return a list of strings; the keys of the cache.

player_config

Override the default max size and expiry of the player caches.

This must return a named tuple, coc.ClashConfig with max_size and ttl attributes.

By default, the cache uses a max size of 1024 and TTL of 3600 (1 hour).

pop(cache_type, key)

This function is a coroutine.

This method is used to get an item from a cache instance, deleting it at the same time.

By default, it gets the cache instance, set as an attribute of Cache with the same name, then tries to use __getitem__ on the cache instance to get the item, then del call to remove it. If that fails, it will try and get the object and delete it at the same time via the cache.pop call.

If your cache does not either implement __getitem__ and del, or the .pop(key) methods, you must override this with the alternate approach to popping items from your cache.

As this function is a coroutine, you can await calls.

This function must return a value with the given key.

register_cache_types()

Reset the cache types according to max-size and expiry values set.

These can be set in Cache.clan_config, Cache.player_config, Cache.war_config and Cache.static_config.

reset_event_cache(cache_name: str)

Register cache types seperately for the EventsClient.

They cannot have a TTL otherwise events may be missed. Ideally the Cache.get_max_size() should return None, however this may cause memory bloats.

set(cache_type, key, value)

This function is a coroutine.

This method is used to add a key/value pair to a cache instance.

By default, it gets the cache instance, set as an attribute of Cache with the same name, then tries to use __setitem__ on the cache instance. If that fails, it will try and set the object via the cache.set call.

If your cache does not either implement __setitem__ or the .set(key) methods, you must override this with the alternate approach to setting items to your cache.

As this function is a coroutine, you can await calls.

This function must set the key/value pair in the cache. Nothing is required to be returned.

static_config

Override the default max size and expiry of the static group of caches.

This must return a named tuple, coc.ClashConfig with max_size and ttl attributes.

By default, the cache uses a max size of 1024 and TTL of 3600 (1 hour).

values(cache_type)

This function is a coroutine.

This method is used to get all values from a cache instance.

By default, this implements the cache.values() function. If your cache instance does not implement this method, you must override this method.

As this function is a coroutine, you can await calls.

This function must return a list of objects; the values of the cache.

war_config

Override the default max size and expiry of the war group of caches.

This must return a named tuple, coc.ClashConfig with max_size and ttl attributes.

By default, the cache uses a max size of 1024 and TTL of 3600 (1 hour).

Max Size Cache

class coc.MaxSizeCache(max_size)

Implements a basic Cache type which has a defined max size.

This can be used with Cache and should be created in the :meth`Cache.create_default_cache`.

Once the cache has reached a set max size, it will eject the least recently used object.

Time To Live Cache

class coc.TimeToLiveCache(ttl)

Implements a basic Cache type which has a defined expiry/time to live.

This can be used with Cache and should be created in the :meth`Cache.create_default_cache`.

Each object will be set with a timestamp, and upon retrieval, the cache will check to ensure the object has not surpassed the given expiry. If it has, it will eject the item from the cache and return None.

Default Cache

class coc.DefaultCache(max_size, ttl)

Implements the default Cache Type used within the library.

This class inherits from collections.OrderedDict and implements a mix of a max-size LRU and expiry TTL cache.

When the cache exceeds a given maximum size, it will eject objects least recently used.

All items have a timestamp attached to them upon setting, and upon retrieval this is compared to ensure it does not exceed the expiry limit. If it does, the object will be disgarded and None returned.

Event Reference

Events are called when using the EventsClient client, clans/players/wars have been registered, and have been started.

Events need to be registered in order to be called by the client. You can register events by using either EventsClient.event(), or EventsClient.add_events().

All events the client will dispatch are listed below.

Event Error

coc.on_event_error(event_name, *args, **kwargs)

This event is called when another event raises an exception and fails. By default, it will print the traceback to stderr and the exception will be ignored.

The information of the exception raised and the exception itself can be retrieved with a standard call to sys.exc_info().

Parameters:
  • event_name – The event which caused the error
  • args – The positional args for the event which raised the error
  • kwargs – The keyword-args for the event which raised the error

Clan Events

These events are all related to clan changes and changes to players within the clan. Clans can be added by registering clan tags and relevant events.

Clan Update

coc.on_clan_update(old_clan, new_clan)

This event is called when a clan has been updated. This could be a member join/leave, settings or other update. This is called before, and regardless whether, any other events are called, ie. on_clan_member_join()

Parameters:
  • old_clan (SearchClan) – The clan object before the change
  • new_clan (SearchClan) – The clan object after the change

Clan Level Change

coc.on_clan_level_change(old_level, new_level, clan)

This event is called when the clan level changes.

Parameters:
  • old_level (int) – The old clan level
  • new_level (int) – The new clan level
  • clan (SearchClan) – The clan who’s level changed

Clan Description Change

coc.on_clan_description_change(old_description, new_description, clan)

This event is called when the clan description changes.

Parameters:
  • old_description (str) – The old clan’s description
  • new_description (str) – The new clan description
  • clan (SearchClan) – The clan who’s description changed

Clan Public WarLog Change

coc.on_clan_public_war_log_change(old_toggle, new_toggle, clan)

This event is called when the clan’s toggle changes.

Parameters:
  • old_toggle (bool) – The old clan toggle
  • new_toggle (bool) – The new clan toggle
  • clan (SearchClan) – The clan who’s toggle changed

Clan Type Change

coc.on_clan_type_change(old_type, new_type, clan)

This event is called when the clan’s type changes.

Parameters:
  • old_type (str) – The old clan type
  • new_type (str) – The new clan type
  • clan (SearchClan) – The clan who’s type changed

Clan Badge Change

coc.on_clan_badge_change(old_badge, new_badge, clan)

This event is called when the clan’s badge changes.

Parameters:
  • old_badge (Badge) – The old clan badge
  • new_badge (Badge) – The new clan badge
  • clan (SearchClan) – The clan who’s badge changed

Clan Required Trophies Change

coc.on_clan_required_trophies_change(old_requirement, new_requirement, clan)

This event is called when the clan’s trophy requirement changes.

Parameters:
  • old_requirement (int) – The old clan requirement
  • new_requirement (int) – The new clan requirement
  • clan (SearchClan) – The clan who’s requirement changed

Clan War Frequency Change

coc.on_clan_war_frequency_change(old_frequency, new_frequency, clan)

This event is called when the clan’s war frequency changes.

Parameters:
  • old_frequency (str) – The old clan war frequency
  • new_frequency (str) – The new clan war frequency
  • clan (SearchClan) – The clan who’s war frequency changed

Clan War Win Streak Change

coc.on_clan_war_win_streak_change(old_streak, new_streak, clan)

This event is called when the clan’s war win streak changes.

Parameters:
  • old_streak (int) – The old clan streak
  • new_streak (int) – The new clan streak
  • clan (SearchClan) – The clan who’s streak changed

Clan War Wins Change

coc.on_clan_war_win_change(old_wins, new_wins, clan)

This event is called when the clan’s war wins change.

Parameters:
  • old_wins (int) – The old clan wins
  • new_wins (int) – The new clan wins
  • clan (SearchClan) – The clan who’s wins changed

Clan War Ties Change

coc.on_clan_war_tie_change(old_ties, new_ties, clan)

This event is called when the clan’s war ties change.

Parameters:
  • old_ties (int) – The old clan ties
  • new_ties (int) – The new clan ties
  • clan (SearchClan) – The clan who’s ties changed

Clan War Losses Change

coc.on_clan_war_loss_change(old_losses, new_losses, clan)

This event is called when the clan’s war losses change.

Parameters:
  • old_losses (int) – The old clan losses
  • new_losses (int) – The new clan losses
  • clan (SearchClan) – The clan who’s losses changed

Clan Member Join

coc.on_clan_member_join(member, clan)

This event is called when a member joins a clan.

Parameters:

Clan Member Leave

coc.on_clan_member_leave(member, clan)

This event is called when a member leaves a clan.

Parameters:

Clan Member Name Change

coc.on_clan_member_name_change(old_name, new_name, player)

This event is called when a clan member’s name changes. The player’s clan can be accessed through BasicPlayer.clan and is of type SearchClan

Parameters:
  • old_name (str) – The player’s old name
  • new_name (str) – The player’s new name
  • player (BasicPlayer) – The player object which changed

Clan Member Donations

coc.on_clan_member_donation(old_donations, new_donations, player)

This event is called when a clan member’s donations changes. The player’s clan can be accessed through BasicPlayer.clan and is of type SearchClan

Parameters:
  • old_donations (int) – The player’s old donations
  • new_donations (int) – The player’s new donations
  • player (BasicPlayer) – The player object which changed

Clan Member Received

coc.on_clan_member_received(old_received, new_received, player)

This event is called when a clan member’s donations received changes. The player’s clan can be accessed through BasicPlayer.clan and is of type SearchClan

Parameters:
  • old_received (int) – The player’s old received
  • new_received (int) – The player’s new received
  • player (BasicPlayer) – The player object which changed

Clan Member Trophy Count Change

coc.on_clan_member_trophies_change(old_trophies, new_trophies, player)

This event is called when a clan member’s trophy count has changed. The player’s clan can be accessed through BasicPlayer.clan and is of type SearchClan

Parameters:
  • old_received (int) – The player’s old trophy count
  • new_received (int) – The player’s new trophy count
  • player (BasicPlayer) – The player object which changed

Clan Member Versus Trophy Count Change

coc.on_clan_member_versus_trophies_change(old_trophies, new_trophies, player)

This event is called when a clan member’s versus trophy count has changed. The player’s clan can be accessed through BasicPlayer.clan and is of type SearchClan

Parameters:
  • old_received (int) – The player’s old versus trophy count
  • new_received (int) – The player’s new versus trophy count
  • player (BasicPlayer) – The player object which changed

Clan Member Role Change

coc.on_clan_member_role_change(old_role, new_role, player)

This event is called when a clan member’s role changes. The player’s clan can be accessed through BasicPlayer.clan and is of type SearchClan

Parameters:
  • old_role (str) – The player’s old role
  • new_role (str) – The player’s new role
  • player (BasicPlayer) – The player object which changed

Clan Member Rank Change

coc.on_clan_member_rank_change(old_rank, new_rank, player)

This event is called when a clan member’s rank changes. The player’s clan can be accessed through BasicPlayer.clan and is of type SearchClan

Parameters:
  • old_rank (int) – The player’s old rank
  • new_rank (int) – The player’s new rank
  • player (BasicPlayer) – The player object which changed

Clan Member Level Change

coc.on_clan_member_level_change(old_level, new_level, player)

This event is called when a clan member’s level changes. The player’s clan can be accessed through BasicPlayer.clan and is of type SearchClan

Parameters:
  • old_level (str) – The player’s old level
  • new_level (str) – The player’s new level
  • player (BasicPlayer) – The player object which changed

Clan Member League Change

coc.on_clan_member_league_change(old_league, new_league, player)

This event is called when a clan member’s league changes. The player’s clan can be accessed through BasicPlayer.clan and is of type SearchClan

Parameters:
  • old_level (League) – The player’s old league
  • new_level (League) – The player’s new league
  • player (BasicPlayer) – The player object which changed
  • clan (SearchClan) – The player’s clan

War Events

These events are all related to war changes, such as war attacks and state changes. Clans can be added by registering clan tags and relevant events.

War Update

coc.on_war_update(old_war, new_war)

This event is called when a war update occurs, regardless of it’s nature. This could be an attack, state change or other.

Parameters:
  • old_war (War) – The war object before the change
  • new_war (War) – The war object after the change

New War Attack

coc.on_war_attack(attack, war)

This event is called when a new war attack has been made. This could be an offensive or defensive attack. This will be called once per new attack, even if multiple new attacks are found.

Parameters:
  • attack (WarAttack) – The new attack.
  • war (War) – The war this attack belongs to.

War State Change

coc.on_war_state_change(current_state, war)

This event is called when a change of war state occurs. This will not necessarily be called when the client checks for a change, as a task will be created at the last update to wait for new state changes.

Parameters:
  • current_state (str) – The current war state it has changed to.
  • war (War) – The war that has changed state

Player Events

These events are all related to player changes and changes to clans within the player. Clans can be added by registering clan tags and relevant events.

Player Update

coc.on_player_update(old_player, new_player)

This event is called when a player changes. This event will be called regardless of the update that follows. This could be a name or level change, or a troop/spell upgrade.

Parameters:
  • old_war (SearchPlayer) – The player object before the change
  • new_war (SearchPlayer) – The player object after the change

Player Name Change

coc.on_player_name_change(old_name, new_name, player)

This event is called when a player’s name has changed.

Parameters:
  • old_name (str) – The player’s old name
  • new_name (str) – The player’s new name
  • player (SearchPlayer) – The new player object

Player Town Hall Change

coc.on_player_townhall_upgrade(old_townhall, new_townhall, player)

This event is called when a player’s townhall has been upgraded.

Parameters:
  • old_townhall (int) – The player’s old townhall level
  • new_townhall (int) – The player’s new townhall level
  • player (SearchPlayer) – The new player object

Player Builder Hall Change

coc.on_player_builderhall_upgrade(old_builderhall, new_builderhall, player)

This event is called when a player’s builder hall has been upgraded.

Parameters:
  • old_builderhall (int) – The player’s old builder hall level
  • new_builderhall (int) – The player’s new builder hall level
  • player (SearchPlayer) – The new player object

Player Best Trophies Change

coc.on_player_best_trophies_change(old_best, new_best, player)

This event is called when a player’s best trophy count changes.

Parameters:
  • old_best (int) – The player’s old best trophy count
  • new_best (int) – The player’s new best trophy count
  • player (SearchPlayer) – The player in question

Player Best Versus Trophies Change

coc.on_player_best_versus_trophies_change(old_best, new_best, player)

This event is called when a player’s best versus trophy count changes.

Parameters:
  • old_best (int) – The player’s old best versus trophy count
  • new_best (int) – The player’s new best versus trophy count
  • player (SearchPlayer) – The player in question

Player War Stars Change

coc.on_player_war_stars_change(old_stars, new_stars, player)

This event is called when a player’s war stars changes.

Parameters:
  • old_stars (int) – The player’s old war stars
  • new_stars (int) – The player’s new war stars
  • player (SearchPlayer) – The player in question

Player Attack Wins Change

coc.on_player_attack_wins_change(old_attacks, new_attacks, player)

This event is called when a player’s attacks count changes.

Parameters:
  • old_attacks (int) – The player’s old attacks count
  • new_attacks (int) – The player’s new attacks count
  • player (SearchPlayer) – The player in question

Player Defense Wins Change

coc.on_player_defense_wins_change(old_defenses, new_defenses, player)

This event is called when a player’s defenses trophy count changes.

Parameters:
  • old_defenses (int) – The player’s old defenses count
  • new_defenses (int) – The player’s new defenses count
  • player (SearchPlayer) – The player in question

Player Versus Attack Change

coc.on_player_versus_attack_change(old_attacks, new_attacks, player)

This event is called when a player’s versus attack count changes.

Parameters:
  • old_attacks (int) – The player’s old versus attack count
  • new_attacks (int) – The player’s new versus attack count
  • player (SearchPlayer) – The player in question

Player Trophies Change

coc.on_player_trophies_change(old_trophies, new_trophies, player)

This event is called when a player’s trophy count changes.

Parameters:
  • old_trophies (int) – The player’s old trophy count
  • new_trophies (int) – The player’s new trophy count
  • player (SearchPlayer) – The player in question

Player League Change

coc.on_player_league_change(old_league, new_league, player)

This event is called when a player’s league changes.

Parameters:
  • old_league (League) – The player’s old league
  • new_league (League) – The player’s new league
  • player (SearchPlayer) – The player in question

Player Role Change

coc.on_player_role_change(old_role, new_role, player)

This event is called when a player’s clan role.

Parameters:
  • old_role (str) – The player’s old role
  • new_role (str) – The player’s new role
  • player (SearchPlayer) – The player in question

Player Donations Change

coc.on_player_donations_change(old_donations, new_donations, player)

This event is called when a player’s donation count changes.

Parameters:
  • old_donations (int) – The player’s old donation count
  • new_donations (int) – The player’s new donation count
  • player (SearchPlayer) – The player in question

Player Received Change

coc.on_player_received_change(old_received, new_received, player)

This event is called when a player’s donations received count changes.

Parameters:
  • old_received (int) – The player’s old received count
  • new_received (int) – The player’s new received count
  • player (SearchPlayer) – The player in question

Player’s Clan Rank Change

coc.on_player_clan_rank_change(old_rank, new_rank, player)

This event is called when a player’s clan rank changes.

Parameters:
  • old_rank (int) – The player’s old rank
  • new_rank (int) – The player’s new rank
  • player (SearchPlayer) – The player in question

Player’s Previous Clan Rank Change

coc.on_player_previous_clan_rank_change(old_rank, new_rank, player)

This event is called when a player’s previous clan rank changes. This would typically be at the end of the season.

Parameters:
  • old_rank (int) – The player’s old previous rank
  • new_rank (int) – The player’s new previous rank
  • player (SearchPlayer) – The player in question

Player Achievement Change

coc.on_player_achievement_change(old_achievement, new_achievement, player)

This event is called when a player’s achievement has changed.

Parameters:
  • old_achievement (Achievement) – The player’s old achievement.
  • new_achievement (Achievement) – The player’s new achievement.
  • player (SearchPlayer) – The new player object

Player Troop Upgrade

coc.on_player_troop_upgrade(old_troop, new_troop, player)

This event is called when a player’s troop has been upgraded.

Parameters:
  • old_troop (Troop) – The player’s old troop.
  • new_troop (Troop) – The player’s new troop.
  • player (SearchPlayer) – The new player object

Player Spell Upgrade

coc.on_player_spell_upgrade(old_spell, new_spell, player)

This event is called when a player’s spell has been upgraded.

Parameters:
  • old_spell (Spell) – The player’s old spell.
  • new_spell (Spell) – The player’s new spell.
  • player (SearchPlayer) – The new player object

Player Hero Upgrade

coc.on_player_hero_upgrade(old_hero, new_hero, player)

This event is called when a player’s hero has been upgraded.

Parameters:
  • old_hero (Hero) – The player’s old hero.
  • new_hero (Hero) – The player’s new hero.
  • player (SearchPlayer) – The new player object

Player Clan Join

coc.on_player_clan_join(player, clan)

This event is called when a player joins a clan.

Parameters:
  • member (SearchPlayer) – The player who joined.
  • clan (Clan) – The clan the player joined.

Player Clan Leave

coc.on_player_clan_leave(player, clan)

This event is called when a player leaves a clan.

Parameters:
  • member (SearchPlayer) – The member who left.
  • clan (Clan) – The clan the member left.

Player’s Clan Level Change

coc.on_player_clan_level_change(old_level, new_level, clan, player)

This event is called when a player’s clan’s level changes.

Parameters:
  • old_level (int) – The old clan level
  • new_level (int) – The new clan level
  • clan (Clan) – The clan who’s level changed
  • player (SearchPlayer) – The player who’s clan’s level changed.

Player’s Clan Badge Change

coc.on_player_clan_badge_change(old_badge, new_badge, clan, player)

This event is called when the clan’s badge changes.

Parameters:
  • old_badge (Badge) – The old clan badge
  • new_badge (Badge) – The new clan badge
  • clan (Clan) – The clan who’s badge changed
  • player (SearchPlayer) – The player who’s clan’s badge changed.

Data Models

These are the data models used by the API. All calls will return one of these

Due to the unpredictable nature of the API and what Supercell returns, all attributes have the possibility of being None. However, as much as possible, the library tries to return an object most appropriate to results returned.

Due to this, there are many objects for what may seem like similar things.

Note: If a SearchPlayer inherits BasicPlayer, it will inherit all attributes of both Player and BasicPlayer, however it will not necessarily inherit WarMember

Clans

class coc.Clan

Represents the most stripped down version of clan info. All other clan classes inherit this.

tag

The clan tag.

Type:str
name

The clan name.

Type:str
level

int - The clan level.

badge

Badge - The clan badges

str - A formatted link to open the clan in-game

class coc.BasicClan

Represents a Basic Clan that the API returns. Depending on which method calls this, some attributes may be None.

This class inherits Clan, and thus all attributes of Clan can be expected to be present.

points

int - The clan trophy points.

versus_points

int - The clan versus trophy points.

member_count

int - The member count of the clan

rank

int - The clan rank for it’s location this season

previous_rank

int - The clan rank for it’s location in the previous season

badge

Badge - The clan badges

location

Location - The clan’s location

str - A formatted link to open the clan in-game

class coc.SearchClan

Represents a Searched Clan that the API returns. Depending on which method calls this, some attributes may be None.

This class inherits both Clan and BasicClan, and thus all attributes of these classes can be expected to be present.

type

str - The clan type: open, closed, invite-only etc.

required_trophies

int - The required trophies to join

war_frequency

str - The war frequency of the clan

war_win_streak

int - The current war win streak of the clan

war_wins

int - The total war wins of the clan

war_ties

int - The total war ties of the clan

war_losses

int - The total war losses of the clan

public_war_log

bool - Indicates whether the war log is public

description

str - The clan description

war_league

WarLeague - the clan’s CWL league name and ID.

badge

Badge - The clan badges

get_detailed_members(cache: bool = False, fetch: bool = True, update_cache: bool = True)

Get detailed player information for every player in the clan. This will return an AsyncIterator of SearchPlayer.

Example

clan = await client.get_clan('tag')

async for player in clan.get_detailed_members(cache=True):
    print(player.name)
Parameters:
  • cache – Optional[bool] Indicates whether to search the cache before making an HTTP request
  • fetch – Optional[bool] Indicates whether an HTTP call should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache – Optional[bool] Indicates whether the client should update the cache when requesting members. Defaults to True. This should only be set to False if you do not require the cache at all.
Returns:

AsyncIterator of SearchPlayer

get_member(**attrs)

Returns the first BasicPlayer that meets the attributes passed

This will return the first member matching the attributes passed.

An example of this looks like:

member = SearchClan.get_member(tag='tag')

This search implements the coc.utils.get() function

iterlabels

This returns an iterator.

Returns an iterable of Label: the player’s labels.

itermembers

This returns an iterator.

Returns an iterable of BasicPlayer: A list of clan members.

labels

List of the player’s labels.

Type:List[Label]
location

Location - The clan’s location

members

A list of clan members

Type:List[BasicPlayer]
members_dict

A dict of clan members by tag.

For Example:

members_dict = {attr_value: member for member in clan_members}

# calling SearchClan.members_dict would give:
members_dict = {member.tag: member for member in clan.members}

# calling SearchClan.members_dict(attr="name") would give:
members_dict = {member.name: member for member in clan.members}

Pass in an attribute of BasicPlayer to get that attribute as the key

str - A formatted link to open the clan in-game

class coc.WarClan

Represents a War Clan that the API returns. Depending on which method calls this, some attributes may be None.

This class inherits Clan, and thus all attributes of Clan can be expected to be present.

stars

int - Number of stars by clan this war

destruction

float - Destruction as a percentage

exp_earned

int - Total XP earned by clan this war

attacks_used

int - Total attacks used by clan this war

max_stars

int - Total possible stars achievable

attacks

List of all attacks used this war.

Type:List[WarAttack]
badge

Badge - The clan badges

defenses

List of all defenses by clan members this war.

Type:List[WarAttack]
iterattacks

This returns an iterator.

Returns an iterable of WarAttack: all attacks used by the clan this war.

iterdefenses

This returns an iterator.

Returns an iterable of WarAttack: all defenses by clan members this war.

itermembers

This returns an iterator.

Returns an iterable of WarMember: all clan members in war.

members

List of all clan members in war

Type:List[WarMember]
members_dict

A dict of clan members in war by tag.

See SearchClan.member_dict for more info on what this returns.

Pass in an attribute of WarMember to get that attribute as the key.

str - A formatted link to open the clan in-game

Players

class coc.Player

Represents the most stripped down version of a player. All other player classes inherit this.

tag

str - The clan tag

name

str - The clan name

str - A formatted link to open the player in-game

class coc.BasicPlayer

Represents a Basic Player that the API returns. Depending on which method calls this, some attributes may be None.

This class inherits Player, and thus all attributes of Player can be expected to be present.

clan

Basic Clan - The clan the member belongs to. May be None

exp_level

int - The player’s experience level.

trophies

int - The player’s trophy count.

versus_trophies

int - The player’s versus trophy count.

clan_rank

int - The members clan rank

clan_previous_rank

int - The members clan rank last season

league_rank

int - The player’s current rank in their league for this season

donations

int - The members current donation count

received

int - The member’s current donation received count

attack_wins

int - The players current attack wins for this season

defense_wins

int - The players current defense wins for this season

league

The player’s current league.

Type:League
role

The members role in the clan - member, elder, etc.

Type:str

str - A formatted link to open the player in-game

class coc.WarMember

Represents a War Member that the API returns. Depending on which method calls this, some attributes may be None.

This class inherits Player, and thus all attributes of Player can be expected to be present.

town_hall

int - The members TH level

map_position

int - The members map position this war

war

War - The war this member belongs to

clan

WarClan - The war clan this member belongs to.

attacks

The member’s attacks this war. Could be an empty list

Type:List[WarAttack]
best_opponent_attack

The best opponent attack on this member. None if the member hasn’t been attacked.

Type:WarAttack
defenses

The member’s defenses this war. Could be an empty list

Type:List[WarAttack]
is_opponent

Indicates whether the member is from the opponent clan or not.

Type:Bool
iterattacks

This returns an iterator.

Returns an iterable of WarAttack: the member’s attacks this war

iterdefenses

This returns an iterator.

Returns an iterable of WarAttack: the member’s defenses this war

str - A formatted link to open the player in-game

class coc.SearchPlayer

Represents a Searched Player that the API returns. Depending on which method calls this, some attributes may be None.

This class inherits both Player and BasicPlayer, and thus all attributes of these classes can be expected to be present

best_trophies

int - The players top trophy count

best_versus_trophies

int - The players top versus trophy count

war_stars

int - The players war star count

town_hall

int - The players TH level

town_hall_weapon

int - The weapon level of the TH (will be 0 for TH11 and below)

builder_hall

int - The players BH level (will be 0 if player does not have a builder hall)

versus_attack_wins

int - The players total BH wins

achievements

List of the player’s achievements

Type:List[Achievement]
achievements_dict

Achievement} A dict of achievements by name.

Pass in an attribute of Achievement to get that attribute as the key

Type:dict - {name
builder_troops_dict

A dict of builder base troops by name.

Pass in an attribute of Troop to get that attribute as the key

Type:dict - ``{name
Type:Troop}``
get_ordered_troops(valid_troops)

Get an ordered dict of a player’s troops against a predefined list of troops.

The most common use of this will be passing in one of the following:

  • coc.ELIXIR_TROOP_ORDER
  • coc.DARK_ELIXIR_TROOP_ORDER
  • coc.SIEGE_MACHINE_ORDER
  • coc.SUPER_TROOP_ORDER
  • coc.HOME_TROOP_ORDER
  • coc.BUILDER_TROOPS_ORDER

Which will yield an ordered dict of the player’s troops, ordered as found in both barracks and labatory in-game.

Example

# to get an ordered dict of a player's elixir troops.
import coc

player = client.get_player(...)
elixir_troops = player.get_ordered_troops(coc.ELIXIR_TROOP_ORDER)

for troop_name, troop in elixir_troops.items():
   ...
Returns:
Return type:collections.OrderedDict - An ordered dict of troops by name.
heroes

List of the player’s heroes

Type:List[Hero]
heroes_dict

A dict of heroes by name.

Pass in an attribute of Hero to get that attribute as the key

Type:dict - ``{name
Type:Hero}``
home_troops_dict

A dict of home base troops by name.

Pass in an attribute of Troop to get that attribute as the key

Type:dict - {name
Type:Troop}
iterachievements

This returns an iterator.

Returns an iterable of Achievement: the player’s achievements.

iterlabels

This returns an iterator.

Returns an iterable of Label: the player’s labels.

labels

List of the player’s labels.

Type:List[Label]
league

The player’s current league.

Type:League
ordered_builder_troops

collections.OrderedDict - An ordered dict of builder base troops by name.

This will return troops in the order found in both barracks and labatory in-game.

ordered_heroes

collections.OrderedDict - An ordered dict of heroes by name.

This will return heroes in the order found in the labatory in-game.

ordered_home_troops

collections.OrderedDict - An ordered dict of troops by name.

This will return troops in the order found in both barracks and labatory in-game.

ordered_siege_machines

collections.OrderedDict - An ordered dict of siege machines by name.

This will return siege machines in the order found in both barracks and labatory in-game.

ordered_spells

collections.OrderedDict - An ordered dict of spells by name.

This will return spells in the order found in both spell factory and labatory in-game.

ordered_super_troops

collections.OrderedDict - An ordered dict of super troops by name.

This will return super troops in the order found in game.

role

The members role in the clan - member, elder, etc.

Type:str

str - A formatted link to open the player in-game

siege_machines_dict

A dict of siege machines by name.

Pass in an attribute of Troop to get that attribute as the key

Type:dict - ``{name
Type:Troop}``
spells

List of the player’s spells

Type:List[Spell]
spells_dict

A dict of spells by name.

Pass in an attribute of Spell to get that attribute as the key

Type:dict - ``{name
Type:Spell}``
super_troops_dict

A dict of super troops by name.

Pass in an attribute of Troop to get that attribute as the key

Type:dict - {name
Type:Troop}
troops

List of the player’s troops

Type:List[Troop]

Wars

class coc.BaseWar

Represents the most basic Clash of Clans War

team_size

int - The number of players per clan in war

clan_tag

str - The clan tag passed for the request. This attribute is always present regardless of the war state.

clan

The offensive clan

Type:WarClan
opponent

The opposition clan

Type:WarClan
class coc.WarLog

Represents a Clash of Clans War Log Entry

This class inherits BaseWar, and thus all attributes of BaseWar can be expected to be present.

result

str - The result of the war - win or loss

end_time

Timestamp - The end time of the war as a Timestamp object

clan

The offensive clan

Type:WarClan
opponent

The opposition clan

Type:WarClan
class coc.ClanWar

Represents a Current Clash of Clans War

This class inherits BaseWar, and thus all attributes of BaseWar can be expected to be present.

state

str - The clan’s current war state

preparation_start_time

Timestamp - The start time of preparation day as a Timestamp object

start_time

Timestamp - The start time of battle day as a Timestamp object

end_time

Timestamp - The end time of battle day as a Timestamp object

attacks

A list of all attacks this war

Type:List[WarAttack]
clan

The offensive clan

Type:WarClan
get_member(**attrs)

Returns the first WarMember that meets the attributes passed

This will return the first member matching the attributes passed.

An example of this looks like:

member = ClanWar.get_member(tag='tag')

This search implements the coc.utils.get() function

iterattacks

This returns an iterator.

Returns an iterable of WarAttack: all attacks this war

itermembers

This returns an iterator.

Returns an iterable of WarMember: all members this war

members

A list of all members this war

Type:List[WarMember]
opponent

The opposition clan

Type:WarClan
status

The war status, based off the home clan.

Strings returned are determined by result and state and are below:

inWar warEnded
winning won
tied tie
losing lost
Type:str
type

Either friendly or random - the war type. Returns None if the clan is not in war.

Possibilities for the length of preparation time for a friendly war include: 15 minutes, 30 minutes, 1 hour, 2 hours, 4 hours, 6 hours, 8 hours, 12 hours, 16 hours, 20 hours or 24 hours.

Type:str

WarAttack

class coc.WarAttack

Represents a Clash of Clans War Attack

war

ClanWar - The war this attack belongs to

stars

int - The stars achieved

destruction

float - The destruction achieved as a percentage (of 100)

order

int - The attack order in this war

attacker_tag

str - The attacker tag

defender_tag

str - The defender tag

attacker

The attacker.

Type:WarMember
defender

The defender.

Type:WarMember

Achievement

class coc.Achievement

Represents a Clash of Clans Achievement.

player

SearchPlayer - The player this achievement is assosiated with

name

str - The name of the achievement

stars

int - The current stars achieved for the achievement

value

int - The number of X things attained for this achievement

target

int - The number of X things required to complete this achievement

info

str - Information regarding the achievement

completion_info

str - Information regarding completion of the achievement

village

str - Either home or builderBase

is_builder_base

Helper property to tell you if the achievement belongs to the builder base

Type:bool
is_completed

Indicates whether the achievement is completed (3 stars achieved) i

Type:bool
is_home_base

Helper property to tell you if the achievement belongs to the home base

Type:bool

Troop

class coc.Troop

Represents a Clash of Clans Troop.

player

SearchPlayer - player this troop is assosiated with

name

str - The name of the troop

level

int - The level of the troop

max_level

int - The overall max level of the troop, excluding townhall limitations

village

str - Either home or builderBase

is_builder_base

Helper property to tell you if the troop belongs to the builder base

Type:bool
is_home_base

Helper property to tell you if the troop belongs to the home base

Type:bool
is_max

Helper property to tell you if the troop is the max level

Type:bool

Hero

class coc.Hero

Represents a Clash of Clans Hero.

player

SearchPlayer - The player this hero is assosiated with

name

str - The name of the hero

level

int - The level of the hero

max_level

int - The overall max level of the hero, excluding townhall limitations

village

str - Either home or builderBase

is_builder_base

Helper property to tell you if the hero belongs to the builder base

Type:bool
is_home_base

Helper property to tell you if the hero belongs to the home base

Type:bool
is_max

Helper property to tell you if the hero is the max level

Type:bool

Spell

class coc.Spell

Represents a Clash of Clans Spell.

player

SearchPlayer - The player this spell is assosiated with

name

str - The name of the spell

level

int - The level of the spell

max_level

int - The overall max level of the spell, excluding townhall limitations

village

str - Either home or builderBase

is_builder_base

Helper property to tell you if the spell belongs to the builder base

Type:bool
is_home_base

Helper property to tell you if the spell belongs to the home base

Type:bool
is_max

Helper property to tell you if the spell is the max level

Type:bool

Location

class coc.Location

Represents a Clash of Clans Location

id

str - The location ID

name

str - The location name

is_country

bool - Indicates whether the location is a country

country_code

str - The shorthand country code, if the location is a country

localised_name

str - A localised name of the location. The extent of the use of this is unknown at present.

League Objects

class coc.League

Represents a Clash of Clans League

id

str - The league ID

name

str - The league name

localised_name

str - A localised name of the location. The extent of the use of this is unknown at present.

localised_short_name

str - A localised short name of the location. The extent of the use of this is unknown at present.

badge

The league’s badge

Type:Badge
class coc.LeagueRankedPlayer

Represents a Clash of Clans League Ranked Player. Note that league season information is available only for Legend League.

This class inherits both Player and BasicPlayer, and thus all attributes of these classes can be expected to be present.

rank

int - The players rank in their league for this season

league

The player’s current league.

Type:League
role

The members role in the clan - member, elder, etc.

Type:str

str - A formatted link to open the player in-game

class coc.LegendStatistics

Represents the Legend Statistics for a player.

player

Player - The player

legend_trophies

int - The player’s legend trophies

best_season

Legend trophies for the player’s best season.

Type:int
current_season

Legend trophies for this season.

Type:int
previous_season

Legend trophies for the previous season.

Type:int

Badge

class coc.Badge

Represents a Clash Of Clans Badge.

small

str - URL for a small sized badge

medium

str - URL for a medium sized badge

large

str - URL for a large sized badge

url

str - Medium, the default URL badge size

save(filepath, size=None)

This function is a coroutine.

Save this badge as a file-like object.

Parameters:
  • filepathos.PathLike The filename to save the badge to
  • size – Optional[str] Either small, medium or large. The default is medium
Raises:
Returns:

int The number of bytes written

Timestamp

class coc.Timestamp

Represents a Clash of Clans Timestamp

raw_time
Type:str: The raw timestamp string (ISO8601) as given by the API.
now

The time in UTC now as a datetime object

Type:datetime
seconds_until

Number of seconds until the timestamp. This may be negative.

Type:int
time

The timestamp as a UTC datetime object

Type:datetime

Label

class coc.Label

Represents a clan or player label.

id
Type:int: The label’s unique ID as given by the API.
name
Type:str: The label’s name.
badge

Badge - The label’s badge.

League War Objects

class coc.LeaguePlayer

Represents a Clash of Clans League Player

tag

str - The player’s tag

name

str - The player’s name

town_hall

int - The player’s town hall level

str - A formatted link to open the player in-game

class coc.LeagueClan

Represents a Clash of Clans League Clan

This class inherits both Clan and BasicClan, and thus all attributes of these classes can be expected to be present.

badge

Badge - The clan badges

itermembers

This returns an iterator.

Returns an iterable of LeaguePlayer: all players participating in this league season

location

Location - The clan’s location

members

List[LeaguePlayer} A list of players participating in this league season

str - A formatted link to open the clan in-game

class coc.LeagueGroup

Represents a Clash of Clans League Group

state

str - The current state of the league group (inWar, preparation etc.)

season

str - The current season of the league group

clans

A list of participating clans.

Type:List[class
Type:LeagueClan]
get_wars(round_index: int = -1, cache: bool = True, fetch: bool = True, update_cache: bool = True)

Get war information for every war in a league round. This will return an AsyncIterator of LeagueWar.

Example

group = await client.get_league_group('clan_tag')

async for war in group.get_wars():
    print(war.clan_tag)
Parameters:
  • round_index (Optional[int] - Indicates the round number to get wars from.) – These rounds can be found with LeagueGroup.rounds and defaults to the most recent round (index of -1).
  • cache (Optional[bool] Indicates whether to search) – the cache before making an HTTP request
  • fetch (Optional[bool] Indicates whether an HTTP call) – should be made if cache is empty. Defaults to True. If this is False and item in cache was not found, None will be returned
  • update_cache (Optional[bool] Indicates whether the client should update) – the cache when requesting members. Defaults to True. This should only be set to False if you do not require the cache at all.
Returns:

Return type:

AsyncIterator of LeagueWar

iterclans

This returns an iterator.

Returns an iterable of class:LeagueClan: all participating clans

number_of_rounds

int The number of rounds this league group contains.

rounds

A list of lists containing all war tags for each round.

Type:List[List[]]
class coc.LeagueWar

Represents a Clash of Clans LeagueWar

This class inherits both BaseWar and ClanWar, and thus all attributes of these classes can be expected to be present.

tag

str - The war tag

attacks

A list of all attacks this war

Type:List[WarAttack]
clan

The offensive clan

Type:WarClan
get_member(**attrs)

Returns the first WarMember that meets the attributes passed

This will return the first member matching the attributes passed.

An example of this looks like:

member = ClanWar.get_member(tag='tag')

This search implements the coc.utils.get() function

iterattacks

This returns an iterator.

Returns an iterable of WarAttack: all attacks this war

itermembers

This returns an iterator.

Returns an iterable of WarMember: all members this war

members

A list of all members this war

Type:List[WarMember]
opponent

The opposition clan

Type:WarClan
status

The war status, based off the home clan.

Strings returned are determined by result and state and are below:

inWar warEnded
winning won
tied tie
losing lost
Type:str
type

The war type. For league wars, this is cwl.

Type:str
class coc.LeagueWarLogEntry

Represents a Clash of Clans War Log entry for a League Season

end_time

Timestamp - The end time of the war as a Timestamp object

team_size

int - The number of players per clan in war

clan

Clan - The offensive clan. Note this is only a Clan, unlike that of a WarLog

enemy_stars

int - Total enemy stars for all wars

attack_count

int - The total attacks completed by your clan over all wars

stars

int The total stars by your clan over all wars

destruction

float - The total destruction by your clan over all wars

clan_level

int - Your clan level.

clan_tag

str - The clan tag searched for. This attribute is always present regardless of the state of war.

Exceptions

The following exceptions are thrown by the library.

exception coc.ClashOfClansException

Base exception for coc.py

exception coc.HTTPException(response, data)

Base exception for when a HTTP request fails

response

aiohttp.ClientResponse - The response of the failed HTTP request.

status

int - The status code of the HTTP request

reason
str - The reason provided by the API.
This could be an empty string if nothing was given.
message
str - The more detailed message provided by the API.
This could be an empty string if nothing was given
exception coc.InvalidArgument

Thrown when an error status 400 occurs.

Client provided incorrect parameters for the request.

Subclass of HTTPException

exception coc.InvalidCredentials(response, data)

Thrown when an error status 403 occurs and the reason is invalid credentials.

Special Exception thrown when missing/incorrect credentials were passed. This is when your email/password pair is incorrect. Subclass of HTTPException

exception coc.Forbidden(response, data)

Thrown when an error status 403 occurs.

API token does not grant access to the requested resource.

Subclass of HTTPException

exception coc.NotFound(response, data)

Thrown when an error status 404 occurs.

The resource was not found.

Subclass of HTTPException

exception coc.Maintenance(response, data)

Thrown when an error status 503 occurs.

Service is temporarily unavailable because of maintenance.

Subclass of HTTPException

exception coc.GatewayError(response, data)

Thrown when a gateway error occurs. These are either status 502 or 504

Error code 502: Bad Gateway Error code 504: The Gateway has timed-out.

Subclass of HTTPException

exception coc.PrivateWarLog(response, data)

Thrown when an error status 403 occurs when trying to get a clan’s war info.

This is a special subclass of Forbidden for when a clan’s war log is private.