Clients and Logging In

Logging In

A coc.py client instance can be created through the utility function, coc.login():

coc.login(email: str, password: str, client: Type[Union[coc.client.Client, coc.events.EventsClient]] = <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.

Example

import coc

client = coc.login("email", "password", key_names="keys for my windows pc", key_count=5)

With the returned instance, you can complete any of the operations detailed below.

Basic Client Interface

The following details all operations on the basic client instance.

class coc.Client(*, key_count: int = 1, key_names: str = 'Created with coc.py Client', key_scopes: str = 'clash', throttle_limit: int = 10, loop: asyncio.events.AbstractEventLoop = None, correct_tags: bool = False, throttler=<class 'coc.http.BasicThrottler'>, connector=None, timeout: float = 30.0, cache_max_size: int = 10000, **_)

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

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

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

  • throttle_limit (int) –

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

    Note

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

    Warning

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

    Defaults to 10 requests per token, per second.

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

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

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

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

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

loop

The loop that is used for HTTP requests

Type

asyncio.AbstractEventLoop

Methods:

close()

Closes the HTTP connection

dispatch(event_name, *args, **kwargs)

Dispatches an event listener matching the event_name parameter.

get_clan(tag[, cls])

Get information about a single clan by clan tag.

get_clan_labels(*[, limit, before, after])

List clan labels.

get_clan_war(clan_tag[, cls])

Retrieve information about clan’s current clan war

get_clan_wars(clan_tags[, cls])

Retrieve information multiple clan’s current clan wars

get_clans(tags[, cls])

Get information about multiple clans by clan tag.

get_current_war(clan_tag[, cwl_round, cls])

Retrieve a clan’s current war.

get_current_wars(clan_tags[, cls])

Retrieve information multiple clan’s current wars.

get_league(league_id)

Get league information

get_league_group(clan_tag[, cls])

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

get_league_named(league_name)

Get a location by name.

get_league_war(war_tag[, cls])

Retrieve information about a clan war league war.

get_league_wars(war_tags[, clan_tag, cls])

Retrieve information about multiple league wars

get_location(location_id)

Get information about specific location

get_location_clans([location_id, limit, …])

Get clan rankings for a specific location

get_location_clans_versus([location_id, …])

Get clan versus rankings for a specific location

get_location_named(location_name)

Get a location by name.

get_location_players([location_id, limit, …])

Get player rankings for a specific location

get_location_players_versus([location_id, …])

Get player versus rankings for a specific location

get_members(clan_tag[, cls])

List clan members.

get_player(player_tag[, cls])

Get information about a single player by player tag.

get_player_labels(*[, limit, before, after])

List player labels.

get_players(player_tags[, cls])

Get information about a multiple players by player tag.

get_season_rankings(league_id, season_id)

Get league season rankings.

get_seasons(league_id)

Get league seasons.

get_warlog(clan_tag[, cls])

Retrieve a clan’s clan war log.

login(email, password)

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

reset_keys([number_of_keys])

Manually reset any number of keys.

search_clans(*[, name, war_frequency, …])

Search all clans by name and/or filtering the results using various criteria.

search_leagues(*[, limit, before, after])

Get list of leagues.

search_locations(*[, limit, before, after])

List all available locations

close()

Closes the HTTP connection

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

Dispatches an event listener matching the event_name parameter.

await get_clan(tag: str, cls=<class 'coc.clans.Clan'>, **kwargs)

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.

Returns

The clan with provided tag.

Return type

SearchClan

await 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

await get_clan_war(clan_tag: str, cls=<class 'coc.wars.ClanWar'>, **kwargs)

Retrieve information about clan’s current clan war

Parameters

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

Returns

The clan’s current war.

Return type

ClanWar

Raises

PrivateWarLog

get_clan_wars(clan_tags: collections.abc.Iterable, cls=<class 'coc.wars.ClanWar'>, **kwargs)

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.

Returns

An iterator of all clan wars. This will skip clans who have a private war-log.

Return type

coc.iterators.WarIterator of ClanWar

get_clans(tags: collections.abc.Iterable, cls=<class 'coc.clans.Clan'>, **kwargs)

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.

Returns

An iterable of the requested clans.

Return type

ClanIterator of Clan

await get_current_war(clan_tag: str, cwl_round=<WarRound.current_war: 1>, cls=<class 'coc.wars.ClanWar'>, **kwargs)

Retrieve a clan’s current war.

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

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

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

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

Note

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

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

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

Returns

The clan’s current war.

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.

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

Return type

ClanWar

get_current_wars(clan_tags: collections.abc.Iterable, cls=<class 'coc.wars.ClanWar'>, **kwargs)

Retrieve information multiple clan’s current wars.

See Client.get_current_war() for more information.

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.

Returns

Current wars for the clans.

Return type

coc.iterators.CurrentWarIterator of ClanWar

await get_league(league_id: int)

Get league information

Parameters

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

Returns

Return type

League

await get_league_group(clan_tag: str, cls=<class 'coc.wars.ClanWarLeagueGroup'>, **kwargs)

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

Parameters

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

Returns

The clan’s war league group.

Return type

ClanWarLeagueGroup

Raises

PrivateWarLog

await 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

await get_league_war(war_tag: str, cls=<class 'coc.wars.ClanWar'>, **kwargs)

Retrieve information about a clan war league war.

Parameters

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

Returns

The league war assosiated with the war tag

Return type

ClanWar

get_league_wars(war_tags: collections.abc.Iterable, clan_tag: str = None, cls=<class 'coc.wars.ClanWar'>, **kwargs)

Retrieve information about multiple 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.

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

Returns

An iterator of wars.

Return type

coc.iterators.LeagueWarIterator of ClanWar

await get_location(location_id: int)

Get information about specific location

Parameters

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

Returns

Return type

Location

await get_location_clans(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

await 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

await 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

await 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

await 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

await get_members(clan_tag: str, cls=<class 'coc.players.ClanMember'>, **kwargs)

List clan members.

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

Parameters

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

Returns

A list of :class:`ClanMember`s in the clan.

Return type

List[ClanMember]

await get_player(player_tag: str, cls=<class 'coc.players.Player'>, **kwargs)

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.

Returns

The player with the tag.

Return type

Player

await 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, cls=<class 'coc.players.Player'>, **kwargs)

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.

Returns

Return type

PlayerIterator of SearchPlayer

await get_season_rankings(league_id: int, season_id: int)

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.

Returns

Return type

list of RankedPlayer

await 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

await get_warlog(clan_tag: str, cls=<class 'coc.wars.ClanWarLogEntry'>, **kwargs)

Retrieve a clan’s clan war log.

Note

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

Parameters

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

Returns

A list of the ClanWarLogEntry in the warlog.

Return type

List[ClanWarLogEntry]

Raises

PrivateWarLog

await login(email: str, password: str)

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

Parameters
await 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.

await 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, cls=<class 'coc.clans.Clan'>, **kwargs)

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.

await 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

await 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

The following details all valid operations for the EventsClient. This extends the Client class, and all methods from Client are valid with the EventsClient, too.

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

  • 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.

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

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

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

loop

The loop that is used for HTTP requests

Type

asyncio.AbstractEventLoop

Methods:

add_clan_updates(*tags)

Add clan tags to receive updates for.

add_events(*events)

Shortcut to add many events at once.

add_player_updates(*tags)

Add player tags to receive events for.

add_war_updates(*tags)

Add clan tags to receive war events for.

close()

Closes the client and all running tasks.

dispatch(event_name, *args, **kwargs)

Dispatches an event listener matching the event_name parameter.

event(function)

A decorator or regular function that registers an event.

remove_clan_updates(*tags)

Remove clan tags that you receive events updates for.

remove_events(*events)

Shortcut to remove many events at once.

remove_player_updates(*tags)

Remove player tags that you receive events updates for.

remove_war_updates(*tags)

Remove player tags that you receive events updates for.

run_forever()

A blocking call which runs the loop and script.

add_clan_updates(*tags)

Add clan tags to receive updates for.

Parameters

*tags (str) – The clan tags to add. If you wish to pass in an iterable, you must unpack it with *.

Example

client.add_clan_updates("#tag1", "#tag2", "#tag3")

tags = ["#tag4", "#tag5", "#tag6"]
client.add_clan_updates(*tags)
add_events(*events)

Shortcut to add many events at once.

This method just iterates over EventsClient.listener().

Parameters

*events (function) – The event listener functions to add.

add_player_updates(*tags)

Add player tags to receive events for.

Parameters

\*tags (str) – The player tags to add. If you wish to pass in an iterable, you must unpack it with *.

Example

client.add_player_updates("#tag1", "#tag2", "#tag3")

tags = ["#tag4", "#tag5", "#tag6"]
client.add_player_updates(*tags)
add_war_updates(*tags)

Add clan tags to receive war events for.

Parameters

\*tags (str) – The clan tags to add that will receive war events. If you wish to pass in an iterable, you must unpack it with *.

Example

client.add_war_updates("#tag1", "#tag2", "#tag3")

tags = ["#tag4", "#tag5", "#tag6"]
client.add_war_updates(*tags)
close()

Closes the client and all running tasks.

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

Dispatches an event listener matching the event_name parameter.

event(function)

A decorator or regular function that registers an event.

The function may be be a coroutine.

Parameters

function (function) – The function to be registered (not needed if used with a decorator)

Example

import coc

client = coc.login(...)

@client.event
@coc.ClanEvents.description_change()
async def player_donated_troops(old_player, new_player):
    print('{} has donated troops!'.format(new_player))
import coc

client = coc.login(...)

@client.event
@coc.ClientEvents.maintenance_start()
async def maintenance_has_started():
    print('maintenance has started!')

Note

The order of decorators is important - the @client.event one must lay above

Returns

function

Return type

The function registered

remove_clan_updates(*tags)

Remove clan tags that you receive events updates for.

Parameters

*tags (str) – The clan tags to remove. If you wish to pass in an iterable, you must unpack it with *.

Example

client.remove_clan_updates("#tag1", "#tag2", "#tag3")

tags = ["#tag4", "#tag5", "#tag6"]
client.remove_clan_updates(*tags)
remove_events(*events)

Shortcut to remove many events at once.

Parameters

*events (function) – The event listener functions to remove.

remove_player_updates(*tags)

Remove player tags that you receive events updates for.

Parameters

\*tags (str) – The player tags to remove. If you wish to pass in an iterable, you must unpack it with *.

Example

client.remove_player_updates("#tag1", "#tag2", "#tag3")

tags = ["#tag4", "#tag5", "#tag6"]
client.remove_player_updates(*tags)
remove_war_updates(*tags)

Remove player tags that you receive events updates for.

Parameters

\*tags (str) – The clan tags to remove that will receive war events. If you wish to pass in an iterable, you must unpack it with *.

Example

client.remove_war_updates("#tag1", "#tag2", "#tag3")

tags = ["#tag4", "#tag5", "#tag6"]
client.remove_war_updates(*tags)
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()