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
orEventsClient
, depending on which you wish to use.**kwargs – Any kwargs you wish to pass into the Client object.
- coc.login_with_keys(*keys: str, client: Type[Union[coc.client.Client, coc.events.EventsClient]] = <class 'coc.client.Client'>, **kwargs) Union[coc.client.Client, coc.events.EventsClient] ¶
Logs into the coc.py Client using premade keys from the developer site.
Unlike
coc.login()
, this login method will not automatically update and manage your keys, including when your IP address changes. It is recommended that you use thecoc.login()
method.client = coc.login_with_keys("eabfcd.adk.token1", "eacjuth.haetg.token2", throttle_limit=20)
- Parameters
*keys (str) – Keys or tokens as found from https://developer.clashofclans.com.
client – The type of coc.py client to use. This could either be a
Client
orEventsClient
, 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.
Special Parameters¶
This details special parameters passed to the Client
which may have more than 1 option (True/False).
Currently this only includes LoadGameData
, but may be expanded in the future.
LoadGameData¶
- class coc.LoadGameData(**kwargs)¶
Pass this into the
load_game_data
parameter ofClient
.See game_data for more information.
- Parameters
always (bool) – Whether to always inject game metadata into objects.
default (bool) – Always inject game metadata into objects, except when running events tasks.
startup_only (bool) – Never automatically inject game metadata into objects, but load it up on startup regardless for use with the
load_game_data
parameter ofClient.get_player()
orClient.parse_army_link()
.never (bool) – Never inject game metadata, and don’t load it on startup.
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: Optional[asyncio.events.AbstractEventLoop] = None, correct_tags: bool = True, throttler: Type[Union[coc.http.BasicThrottler, coc.http.BatchThrottler]] = <class 'coc.http.BasicThrottler'>, connector=None, timeout: float = 30.0, cache_max_size: int = 10000, stats_max_size: int = 1000, load_game_data: coc.miscmodels.LoadGameData = <coc.miscmodels.LoadGameData object>, **_)¶
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) – Theasyncio.AbstractEventLoop
to use for HTTP requests. Anasyncio.get_event_loop()
will be used ifNone
is passedcorrect_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 toTrue
.connector (
aiohttp.BaseConnector
) – The aiohttp connector to use. By default this isNone
.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 toNone
to remove any cache layer.load_game_data (
LoadGameData
) – The option for how coc.py will load game data. See initialising_game_data for more info.
- loop¶
The loop that is used for HTTP requests
Methods:
close
()Closes the HTTP connection
create_army_link
(**kwargs)Transform troops and spells into an in-game army share link.
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])Fetch all possible 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_hero
(name[, level, townhall])Get an uninitiated Hero object with the given name.
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_pet
(name[, level, townhall])Get an uninitiated Pet object with the given name.
get_player
(player_tag[, cls, load_game_data])Get information about a single player by player tag.
get_player_labels
(*[, limit, before, after])Fetch all possible player labels.
get_players
(player_tags[, cls, load_game_data])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_spell
(name[, level, townhall])Get an uninitiated Spell object with the given name.
get_troop
(name[, is_home_village, level, …])Get an uninitiated Troop object with the given name.
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.
login_with_keys
(*keys)Retrieves all keys and creates an HTTP connection ready for use.
parse_army_link
(link)Transform an army link from in-game into a list of troops and spells.
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
verify_player_token
(player_tag, token)Verify player API token that can be found from the game settings.
- create_army_link(**kwargs)¶
Transform troops and spells into an in-game army share link.
Note
You must have Troop and Spell game metadata loaded in order to use this method. This means
load_game_metadata
ofClient
must be anything butLoadGameData.never
.Example
link = client.create_army_link( barbarian=10, archer=20, hog_rider=30, healing_spell=3, poison_spell=2, rage_spell=2 ) print(link) # prints https://link.clashofclans.com/en?action=CopyArmy&army=u0x10-1x20-11x30s1x3-9x2-2x2
- Parameters
**kwargs – Troop name to quantity mapping. See the example for more info. The troop name must match in-game exactly, and is case-insensitive. Replace spaces (” “) with an underscore. The quantity must be an integer.
- Raises
RuntimeError – Troop and Spell game metadata must be loaded to use this feature.
- Returns
The army share link.
- Return type
- dispatch(event_name: str, *args, **kwargs) None ¶
Dispatches an event listener matching the event_name parameter.
- await get_clan(tag: str, cls: Type[coc.clans.Clan] = <class 'coc.clans.Clan'>, **kwargs) coc.clans.Clan ¶
Get information about a single clan by clan tag.
Clan tags can be found using clan search operation.
- Parameters
tag (str) – The clan tag to search for.
- Raises
NotFound – No clan was found with the supplied tag.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The clan with provided tag.
- Return type
- await get_clan_labels(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[coc.miscmodels.Label] ¶
Fetch all possible clan labels.
- Parameters
- Raises
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
A list of all possible clan labels.
- Return type
List[
Label
]
- await get_clan_war(clan_tag: str, cls: Type[coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) coc.wars.ClanWar ¶
Retrieve information about clan’s current clan war
- Parameters
clan_tag (str) – The clan tag to search for.
- Raises
TypeError – The
cls
parameter must be a subclass ofClanWar
.NotFound – No clan was found with the supplied tag.
PrivateWarLog – The clan’s warlog is private.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The clan’s current war.
- Return type
- get_clan_wars(clan_tags: Iterable[str], cls: Type[coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) AsyncIterator[coc.wars.ClanWar] ¶
Retrieve information multiple clan’s current clan wars
This returns a
coc.WarIterator
which fetches the requested wars in parallel.Note
This will skip any clans who have a private war-log.
Note
This will not fetch any CWL wars. Use
Client.get_current_wars()
for that.Example
tags = [...] async for clan_war in Client.get_clan_wars(tags): print(clan_war.opponent)
- Parameters
clan_tags (Iterable[
str
]) – An iterable of clan tags to search for.- Raises
TypeError – The
cls
parameter must be a subclass ofClanWar
.NotFound – No clan was found with the supplied tag.
PrivateWarLog – The clan’s warlog is private.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Yields
ClanWar
– A war matching one of the tags requested.
- get_clans(tags: Iterable[str], cls: Type[coc.clans.Clan] = <class 'coc.clans.Clan'>, **kwargs) AsyncIterator[coc.clans.Clan] ¶
Get information about multiple clans by clan tag. Refer to Client.get_clan for more information.
This returns a
ClanIterator
which fetches the requested clan tags in parallel.Example
tags = [...] async for clan in client.get_clans(tags): print(clan.name)
- await get_current_war(clan_tag: str, cwl_round: coc.enums.WarRound = WarRound.current_war, cls: Type[coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) Optional[coc.wars.ClanWar] ¶
Retrieve a clan’s current war.
Unlike
Client.get_clan_war
orClient.get_league_war
, this method will search for a regular war, and if the clan is innotInWar
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 returningNone
.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
- Raises
TypeError – The
cls
parameter must be a subclass ofClanWar
.NotFound – No clan was found with the supplied tag.
PrivateWarLog – The clan’s warlog is private.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The clan’s current war. Could be
None
.If the clan is in CWL, the league group can be accessed via
ClanWar.league_group
.If you pass in a
WarRound
and that round doesn’t exist (yet), this will returnNone
.- Return type
- get_current_wars(clan_tags: Iterable[str], cls: Type[coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) AsyncIterator[coc.wars.ClanWar] ¶
Retrieve information multiple clan’s current wars.
See
Client.get_current_war()
for more information.This returns a
CurrentWarIterator
which fetches the requested clan tags in parallel.Note
This will skip any clans who have a private war-log.
Note
This will fetch CWL wars, which may result in a slower operation due to multiple API calls. If you only wish to get regular wars, consider
Client.get_clan_wars()
.Example
tags = [...] async for war in Client.get_current_wars(tags): print(war.type)
- get_hero(name: str, level: int = None, townhall: int = None) Optional[Union[Type[Hero], Hero]] ¶
Get an uninitiated Hero object with the given name.
Note
You must have Hero metadata loaded in order to use this method. This means
load_game_metadata
ofClient
must be anything butLoadGameData.never
.Note
Please see game_data for more info on how to use initiated vs uninitiated models.
Example
hero = client.get_hero("Archer Queen") for level, cost in enumerate(hero.upgrade_cost, start=1): print(f"{hero.name} has an upgrade cost of {cost} at Lv{level}")
- Parameters
name (str) – The hero name, which must match in-game exactly, but is case-insensitive.
level (Optional[int]) – The level to pass into the construction of the
Hero
object. If this is present this will return an initiated_objects.townhall (Optional[int]) – The TH level to pass into the construction of the
Hero
object. If this isNone
, this will default to the TH level thelevel
parameter is unlocked at.
- Raises
RuntimeError – Hero game metadata must be loaded to use this feature.
- Returns
If
level
is notNone
, this will return an initiated_objects otherwise, this will return an uninitiated_objectsIf the hero is not found, this will return
None
.- Return type
- await get_league(league_id: int) coc.miscmodels.League ¶
Get league information
- Parameters
league_id (str) – The League ID to search for.
- Raises
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
NotFound – No league was found with the supplied league ID.
- Returns
The league with the requested ID
- Return type
- await get_league_group(clan_tag: str, cls: Type[coc.wars.ClanWarLeagueGroup] = <class 'coc.wars.ClanWarLeagueGroup'>, **kwargs) coc.wars.ClanWarLeagueGroup ¶
Retrieve information about clan’s current clan war league group.
- Parameters
clan_tag (str) – The clan tag to search for.
- Raises
TypeError – The
cls
parameter must be a subclass ofClanWarLeagueGroup
.NotFound – No clan was found with the supplied tag.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception. This may be due to an API bug whereby requesting the league group of a clan searching for a CWL match will time out.
- Returns
The clan’s war league group.
- Return type
- await get_league_named(league_name: str) Optional[coc.miscmodels.League] ¶
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
- Raises
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The first location matching the location name. Could be
None
if not found.- Return type
- await get_league_war(war_tag: str, cls: Type[coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) coc.wars.ClanWar ¶
Retrieve information about a clan war league war.
- Parameters
war_tag (str) – The league war tag to search for.
- Raises
TypeError – The
cls
parameter must be a subclass ofClanWar
.NotFound – No clan was found with the supplied tag.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The league war assosiated with the war tag
- Return type
- get_league_wars(war_tags: Iterable[str], clan_tag: Optional[str] = None, cls: Type[coc.wars.ClanWar] = <class 'coc.wars.ClanWar'>, **kwargs) AsyncIterator[coc.wars.ClanWar] ¶
Retrieve information about multiple league wars
This returns a
LeagueWarIterator
which fetches the requested clan tags in parallel.Example
tags = [...] async for league_war in Client.get_league_wars(tags): print(league_war.opponent)
- await get_location(location_id: int) coc.miscmodels.Location ¶
Get information about specific location
- Parameters
location_id (int) – The Location ID to search for.
- Raises
NotFound – No location was found with the supplied ID.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The requested location.
- Return type
- await get_location_clans(location_id: int = 'global', *, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[coc.clans.RankedClan] ¶
Get clan rankings for a specific location
- Parameters
- Raises
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The top clans for the requested location.
- Return type
List[
RankedClan
]
- await get_location_clans_versus(location_id: int = 'global', *, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[coc.clans.RankedClan] ¶
Get clan versus rankings for a specific location
- Parameters
- Raises
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The top versus-clans for the requested location.
- Return type
List[
RankedClan
]
- await get_location_named(location_name: str) Optional[coc.miscmodels.Location] ¶
Get a location by name.
This is equivalent to:
locations = await client.search_locations(limit=None) return utils.get(locations, name=location_name)
- await get_location_players(location_id: int = 'global', *, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[coc.players.RankedPlayer] ¶
Get player rankings for a specific location
- Parameters
- Raises
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The top players for the requested location.
- Return type
List[
RankedPlayer
]
- await get_location_players_versus(location_id: int = 'global', *, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[coc.players.RankedPlayer] ¶
Get player versus rankings for a specific location
- Parameters
- Raises
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The top versus players for the requested location.
- Return type
List[
RankedPlayer
]
- await get_members(clan_tag: str, cls: Type[coc.players.ClanMember] = <class 'coc.players.ClanMember'>, **kwargs) List[coc.players.ClanMember] ¶
List clan members.
This is equivilant to
(await Client.get_clan('tag')).members
.- Parameters
clan_tag (str) – The clan tag to search for.
- Raises
TypeError – The
cls
parameter must be a subclass ofClanMember
.NotFound – No clan was found with the supplied tag.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
A list of members in the clan.
- Return type
List[
ClanMember
]
- get_pet(name: str, level: int = None, townhall: int = None) Optional[Union[Type[Pet], Pet]] ¶
Get an uninitiated Pet object with the given name.
Note
You must have Pet metadata loaded in order to use this method. This means
load_game_metadata
ofClient
must be anything butLoadGameData.never
.Note
Please see game_data for more info on how to use initiated vs uninitiated models.
Example
troop = client.get_pet("Electro Owl") for level, cost in enumerate(pet.upgrade_cost, start=1): print(f"{pet.name} has an upgrade cost of {cost} at Lv{level}")
- Parameters
name (str) – The pet name, which must match in-game exactly, but is case-insensitive.
level (Optional[int]) – The level to pass into the construction of the
Pet
object. If this is present this will return an initiated_objects.townhall (Optional[int]) – The TH level to pass into the construction of the
Pet
object. If this isNone
, this will default to the TH level thelevel
parameter is unlocked at.
- Raises
RuntimeError – Pet game metadata must be loaded to use this feature.
- Returns
If
level
is notNone
, this will return an initiated_objects otherwise, this will return an uninitiated_objectsIf the pet is not found, this will return
None
.- Return type
Pet
- await get_player(player_tag: str, cls: Type[coc.players.Player] = <class 'coc.players.Player'>, load_game_data: Optional[bool] = None, **kwargs) coc.players.Player ¶
Get information about a single player by player tag. Player tags can be found either in game or by from clan member lists.
- Parameters
player_tag (str) – The player tag to search for.
- Raises
NotFound – No player was found with the supplied tag.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The player with the tag.
- Return type
- await get_player_labels(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[coc.miscmodels.Label] ¶
Fetch all possible player labels.
- Parameters
- Raises
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
A list of all possible player labels.
- Return type
List[
Label
]
- get_players(player_tags: Iterable[str], cls: Type[coc.players.Player] = <class 'coc.players.Player'>, load_game_data: Optional[bool] = None, **kwargs) AsyncIterator[coc.players.Player] ¶
Get information about a multiple players by player tag. Player tags can be found either in game or by from clan member lists.
This returns a
PlayerIterator
which fetches the requested player tags in parallel.Example
tags = [...] async for player in Client.get_players(tags): print(player)
- await get_season_rankings(league_id: int, season_id: int) List[coc.players.RankedPlayer] ¶
Get league season rankings.
Note
League season information is available only for Legend League, with a league ID 29000021.
- Parameters
- Raises
InvalidArgument – An invalid league_id or season_id was supplied. Currently the only league supported is legends.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
Top players for the requested season and league.
- Return type
List[
RankedPlayer
]
- await get_seasons(league_id: int = 29000021) List[str] ¶
Get league seasons.
Note
League season information is available only for Legend League, with a league ID 29000021.
- Parameters
league_id (str) – The League ID to search for. Defaults to the only league you can get season information for, legends.
- Raises
InvalidArgument – An invalid league_id was supplied. Currently the only league supported is legends.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The legend season IDs, in the form
YYYY-MM
, ie.2020-04
.- Return type
List[str]
- get_spell(name: str, level: int = None, townhall: int = None) Optional[Union[Type[Spell], Spell]] ¶
Get an uninitiated Spell object with the given name.
Note
You must have Spell metadata loaded in order to use this method. This means
load_game_metadata
ofClient
must be anything butLoadGameData.never
.Note
Please see game_data for more info on how to use initiated vs uninitiated models.
Example
troop = client.get_spell("Healing Spell") for level, cost in enumerate(spell.upgrade_cost, start=1): print(f"{spell.name} has an upgrade cost of {cost} at Lv{level}")
- Parameters
name (str) – The troop name, which must match in-game exactly, but is case-insensitive.
level (Optional[int]) – The level to pass into the construction of the
Spell
object. If this is present this will return an initiated_objects. This can beNone
, and you will get an uninitiated object.townhall (Optional[int]) – The TH level to pass into the construction of the
Spell
object. If this isNone
, this will default to the TH level thelevel
parameter is unlocked at.
- Raises
RuntimeError – Troop and Spell game metadata must be loaded to use this feature.
- Returns
If
level
is notNone
, this will return an initiated_objects otherwise, this will return an uninitiated_objectsIf the spell is not found, this will return
None
.- Return type
- get_troop(name: str, is_home_village: bool = True, level: int = None, townhall: int = None) Optional[Union[Type[Troop], Troop]] ¶
Get an uninitiated Troop object with the given name.
Note
You must have Troop metadata loaded in order to use this method. This means
load_game_metadata
ofClient
must be anything butLoadGameData.never
.Note
Please see game_data for more info on how to use initiated vs uninitiated models.
Example
troop = client.get_troop("Barbarian") for level, dps in enumerate(troop.dps, start=1): print(f"{troop.name} has {dps} DPS at Lv{level}")
- Parameters
name (str) – The troop name, which must match in-game exactly, but is case-insensitive.
is_home_village (bool) – Whether the troop belongs to the home village or not. Defaults to True.
level (Optional[int]) – The level to pass into the construction of the
Troop
object. If this is present this will return an initiated_objects.townhall (Optional[int]) – The TH level to pass into the construction of the
Troop
object. If this isNone
, this will default to the TH level thelevel
parameter is unlocked at.
- Raises
RuntimeError – Troop and Spell game metadata must be loaded to use this feature.
- Returns
If
level
is notNone
, this will return an initiated_objects otherwise, this will return an uninitiated_objectsIf the troop is not found, this will return
None
.- Return type
- await get_warlog(clan_tag: str, cls: Type[coc.wars.ClanWarLogEntry] = <class 'coc.wars.ClanWarLogEntry'>, **kwargs) List[coc.wars.ClanWarLogEntry] ¶
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 withClanWarLogEntry.is_league_entry
.- Parameters
clan_tag (str) – The clan tag to search for.
- Raises
TypeError – The
cls
parameter must be a subclass ofClanWarLogEntry
.NotFound – No clan was found with the supplied tag.
PrivateWarLog – The clan’s warlog is private.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
Entries in the warlog of the requested clan.
- Return type
List[
ClanWarLogEntry
]
- await login(email: str, password: str) None ¶
Retrieves all keys and creates an HTTP connection ready for use.
- 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
- login_with_keys(*keys: str) None ¶
Retrieves all keys and creates an HTTP connection ready for use.
- Parameters
keys –
- parse_army_link(link: str)¶
Transform an army link from in-game into a list of troops and spells.
Note
You must have Troop and Spell game metadata loaded in order to use this method. This means
load_game_metadata
ofClient
must be anything butLoadGameData.never
.Example
troops, spells = client.parse_army_link("https://link.clashofclans.com/en?action=CopyArmy&army=u10x0-2x3s1x9-3x2") for troop, quantity in troops: print("The user wants {} {}s. They each have {} DPS.".format(quantity, troop.name, troops.dps)) for spell, quantity in spells: print("The user wants {} {}s.".format(quantity, troop.name))
- Parameters
link (str) – The army share link, as copied from in-game. It should look something like: https://link.clashofclans.com/en?action=CopyArmy&army=u10x0-2x3s1x9-3x2
- Raises
RuntimeError – Troop and Spell game metadata must be loaded to use this feature.
- Returns
A list of tuples containing the Troop or Spell object, and a quantity (1, 2, 3, 12 etc.) If none is found, this will still return 2 empty lists. If a troop isn’t found, it will default to a Barbarian, as this is how the game parses the links.
- Return type
- await reset_keys(number_of_keys: Optional[int] = None) 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: Optional[str] = None, war_frequency: Optional[str] = None, location_id: Optional[int] = None, min_members: Optional[int] = None, max_members: Optional[int] = None, min_clan_points: Optional[int] = None, min_clan_level: Optional[int] = None, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None, cls: Type[coc.clans.Clan] = <class 'coc.clans.Clan'>, **kwargs) List[coc.clans.Clan] ¶
Search all clans by name and/or filtering the results using various criteria.
At least one filtering criteria must be defined and if name is used as part of search, it is required to be at least three characters long.
- Parameters
name (str, optional) – The clan name.
war_frequency (str, optional) – The war frequency.
location_id (int, optional) – The location id.
min_members (int, optional) – The minimum number of members.
max_members (int, optional) – The maximum number of members.
min_clan_points (int, optional) – The minumum clan points.
min_clan_level (int, optional) – The minimum clan level.
limit (int) – The number of clans to search for.
- Raises
RuntimeError – At least one filtering parameter must be passed.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
A list of all clans found matching criteria provided.
- Return type
List[
Clan
]
- await search_leagues(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[coc.miscmodels.League] ¶
Get list of leagues.
- Parameters
- Raises
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The requested leagues.
- Return type
List[
League
]
- await search_locations(*, limit: Optional[int] = None, before: Optional[str] = None, after: Optional[str] = None) List[coc.miscmodels.Location] ¶
List all available locations
- Parameters
- Raises
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
The requested locations.
- Return type
List[
Location
]
- await verify_player_token(player_tag: str, token: str) bool ¶
Verify player API token that can be found from the game settings.
This can be used to check that players own the game accounts they claim to own as they need to provide the one-time use API token that exists inside the game.
- Parameters
- Raises
NotFound – No player was found with the supplied tag.
Maintenance – The API is currently in maintenance.
GatewayError – The API hit an unexpected gateway exception.
- Returns
Whether the player tag and API token were a valid match.
- Return type
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) – Theasyncio.AbstractEventLoop
to use for HTTP requests. Anasyncio.get_event_loop()
will be used ifNone
is passedcorrect_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 toTrue
.connector (
aiohttp.BaseConnector
) – The aiohttp connector to use. By default this isNone
.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 toNone
to remove any cache layer.load_game_data (
LoadGameData
) – The option for how coc.py will load game data. See initialising_game_data for more info.
- loop¶
The loop that is used for HTTP requests
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.
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()