Skip to content
/ coc-api Public

Wrapper around Clash of Clans API implemented in Python.

License

Notifications You must be signed in to change notification settings

bim-ba/coc-api

Repository files navigation


coc-api

Asynchronous wrapper around Clash of Clans API.

Getting started

Basic usage

import asyncio

from cocapi import Client

client = Client('TOKEN') # your token

async def main():
    clantags = await client.clans(name='bomb', location='ru', max_members=30)
    print(clantags)
    # ['#2P8QU22L2', '#2PPYL9928', '#22GLLRQYY', ...]

if __name__ == '__main__':
    asyncio.run(main())

Asynchronous usage

import asyncio

from cocapi import Client

client = Client('TOKEN') # your token

async def main():
    clantags = await client.clans(name='bomb', location='ru', max_members=30)
    
    first_clan, second_clan, third_clan = await asyncio.gather(
        client.clan(clantags[0]),
        client.clan(clantags[1]),
        client.clan(clantags[2]),
    )

    print(first_clan.name)
    # ...

    print(second_clan.description)
    # ...

    print(third_clan.location)
    # ...

if __name__ == '__main__':
    asyncio.run(main())

Installation

Now you can install it only from source. This package will be available on PyPi as soon as code will be a lot of tests, I think now it is only a raw version. For the main branch I am using a poetry to manage the packages, but you can use whatever you want (there are requirements.txt and dev-requirements.txt for backward comatibility).

git clone https://github.com/bim-ba/coc-api.git
cd coc-api

Using poetry

poetry install --no-dev

Using pip

pip install -r requirements.txt

Dev requirements

If you want to contribute, you need to install some dev packages.

poetry install

or, using pip

pip install -r dev-requirements.txt

Contents

General API documentation

Methods

clans

At least one filtering criteria must be used
Use this method to query all clans by name and/or filtering the results using various criteria. If name is used as part of search, it is required to be at least three characters long. It is not possible to specify ordering for results so clients should not rely on any specific ordering as that may change in the future releases of the API.

Normally, method makes 1 request , but there are some exclusions:

  • If location parameter is not None, method can make 1 additional request in order to convert location name to its id.
  • If labels parameter is not None, method can make 1 additional request in order to convert label/labels name to its id/ids.

So the maximum number of request this method can make is 3

Returns list of clan tags.

Parameter Type Description
name str optional. Clan name. Must be at least 3 characters long
min_members int optional. Minimum clan members
max_members int optional. Maximum clan members
min_clan_points int optional. Minimum clan points
min_clan_level int optional. Minimum clan level
war_frequency str optional. Clan war frequency
location str optional. Clan location. May be either country code or full location name (e.g. Russia == RU)
labels str | list[str] optional. Clan label or labels

Examples:

>>> clans = await client.clans(location='ru', war_frequency='never')
>>> print(clans)
# ['#RLU20URV', '#RV9RCQV', '#2LVV8RCJJ', ...]

clan

Get information about a single clan by clan tag.

Normally, method makes 1 request, but there are some exclusions:

  • If clan war log is public, method makes 2 additional requests to gather information about clan war state and clan war log.

Returns Clan model.

Parameter Type Description
tag str required. Clan tag

Examples:

>>> clan = await client.clan('#2P8QU22L2')
>>> print(clan.name, clan.location)
# bomb Location(id=32000193, isCountry=true, name='russia', countryCode='ru')

player

Get information about a single player by player tag.

Returns Player model.

Parameter Type Description
tag str required. Player tag

Examples:

>>> player = await client.player('#LJJOUY2U8')
>>> print(player.name)
# bone_appettit

clan_rankings

Get clan rankings for a specific location.

Normally, this method makes 1 request, but there is some exclusion:

  • Method can make 1 additional request in order to convert location name to its id.

Returns list of clan tags.

Parameter Type Description
location str required. Location name or country code

Examples:

>>> clans = await client.clan_rankings('ru')
>>> print(clans[0])
# TODO: ...

player_rankings

Get player rankings for a specific location.

Normally, this method makes 1 request, but there is some exclusion:

  • Method can make 1 additional request in order to convert location name to its id.

Returns list of player tags.

Parameter Type Description
location str required. Location name or country code

Examples:

>>> players = await client.player_rankings('ru')
>>> print(players[0])
# TODO: ...

clan_versus_rankings

Get clan versus rankings for a specific location.

Normally, this method makes 1 request, but there is some exclusion:

  • Method can make 1 additional request in order to convert location name to its id.

Returns list of clan tags.

Parameter Type Description
location str required. Location name or country code

Examples:

>>> clans = await client.clan_versus_rankings('ru')
>>> print(clans[0])
# TODO: ...

player_versus_rankings

Get player versus rankings for a specific location.

Normally, this method makes 1 request, but there is some exclusion:

  • Method can make 1 additional request in order to convert location name to its id.

Returns list of player tags.

Parameter Type Description
location str required. Location name or country code

Examples:

>>> players = await client.player_versus_rankings('ru')
>>> print(players[0])
# TODO: ...

goldpass

Get information about the current gold pass season.

Returns GoldPass model.

Examples:

>>> goldpass = await client.goldpass()
>>> print(goldpass.startTime)
# TODO: ...

all_locations

List locations.

Returns dictionary with key: value pairs like LocationName | Country Code: Location.

Examples:

>>> locations = await client.all_locations()
>>> assert locations['ru'] == locations['russia']
>>> print(locations['ru']) # not recommended, use ``client.get_location`` instead
# TODO: Location(...)

get_location

Get location information.

Returns Location model.

Parameter Type Description
location_name str required. Location name or country code

Examples:

>>> location1 = await client.get_location('rU')
>>> location2 = await client.get_location('ruSSia')
>>> assert location1.id == location2.id

>>> location3 = await client.get_location('kenya')
>>> print(location3.id, location3.country_code)
# TODO: ...

all_clan_labels

List clan labels.

Returns dictionary with key: value pairs like str: ClanLabel.

Examples:

>>> labels = await client.all_clan_labels()
>>> print(labels['clan wars']) # not recommended, use ``client.get_clan_label`` instead
# TODO: ClanLabel(...)

get_clan_label

Get clan label information.

Returns ClanLabel model.

Parameter Type Description
label_name str required. Label name

Examples:

>>> label = await client.get_clan_label('clAn Wars')
>>> print(label.id, label.name)
# TODO: ...

all_clan_leagues

List clan leagues.

Returns dictionary with key: value pairs like str: ClanLeague.

Examples:

>>> leagues = await client.all_clan_leagues()
>>> print(leagues['international']) # not recommended, use ``client.get_clan_league`` instead
# TODO: League(...)

get_clan_league

Get information about clan league.

Returns ClanLeague model.

Parameter Type Description
league_name str required. League name

Examples:

>>> league = await client.get_clan_league('international')
>>> print(league.id, league.name)
# TODO: ...

all_player_labels

List player labels.

Returns dictionary with key: value pairs like str: PlayerLabel.

Examples:

>>> labels = await client.all_player_labels()
>>> print(labels['...']) # not recommended, use ``client.get_player_label`` instead
# TODO: PlayerLabel(...)

get_player_label

Get player label information.

Returns PlayerLabel model.

Parameter Type Description
label_name str required. Label name

Examples:

>>> label = await client.get_player_label('...')
>>> print(label.id, label.name)
# TODO: ...

all_player_leagues

List player leagues.

Returns dictionary with key: value pairs like str: PlayerLeague.

Examples:

>>> leagues = await client.all_player_leagues()
>>> print(leagues['...']) # not recommended, use ``client.get_player_league`` instead
# TODO: League(...)

get_player_league

Get information about player league.

Returns PlayerLeague model.

Parameter Type Description
league_name str required. League name

Examples:

>>> league = await client.get_player_league('...')
>>> print(league.id, league.name)
# TODO: ...

Models

Models are corresponds to the original Clash of Clans API Models, but with some changes. I have made small of these models (comparing them to the original ones) due to the fact that I have undertaken a slightly different design of these models in order to simplify and unify them.
In code all models are readonly, you cant change its contents - only read.

Base Label

This model stores information about label id, name and icon_urls. This model is just a parent for PlayerLabel and ClanLabel. It will never be created directly.

Field Type Description
id str Field unique id
name str case insensitive. Field unique name
icon_urls BadgeURLs | None optional. Field icons, some labels dont have icons. None if label does not have icons
classDiagram
    BaseLabel <|-- PlayerLabel
    BaseLabel <|-- ClanLabel
Loading

Base League

This model stores information about league id, its name and icon_urls. There are 2 types of leagues: playerLeague and clanLeague

Field Type Description
id str Field unique id
name str case insensitive. Field unique name
icon_urls BadgeURLs | None optional. Field icons, some leagues dont have icons. None if league does not have icons
classDiagram
    BaseLeague <|-- PlayerLeague
    BaseLeague <|-- ClanWarLeague
Loading

Location

This model stores information about location id, its name and country code. Location is not always a country (e.g. International), thats why is_country field is exist and country_code may be None.

Field Type Description
id int Location unique id
name str case insensitive. Location unique name
is_country bool True if location is country
country_code str | None optional. Location country code. None if location is not country

BadgeURLs

This model stores information about small, medium and large image urls. Urls for some models may be missing, also a few models can have missing fields, thats why it is either str or None.

Field Type Description
small str | None optional. Small icon url. None if missing
medium str | None optional. Medium icon url. None if missing
large str | None optional. Large icon url. None if missing

Player

This model describes all information about player.

Field Type Description
tag str Player unique tag
name str Player name
town_hall_level int Player townhall level
builder_hall_level int Player builder hall level
exp_level int Player experience
trophies int Player trophies
best_trophies int Player best trophies
war_stars int Player summary war stars
attack_wins int Player summary attack wins
defense_wins int Player summary defense wins
versus_trophies int Player versus trophies (builder base)
best_versus_trophies int Player best versus trophies (builder base)
versus_battle_wins int Player summary versus battle wins
donations int Player summary donations
donations_received int Player summary donations received
troops list[PlayerTroop] Player troops leveling
heroes list[PlayerTroop] Player heroes leveling
spells list[PlayerTroop] Player spells leveling
league PlayerLeague | None optional. Player league. None if player does not have league
clan str | None optional. Clan tag. It is not Clan due to recursion and object weight. None if player does not have clan
role str | None optional. Player role in clan. None if player does not have clan
war_preference str | None optional. Player war preference. None if player does not specify it
town_hall_weapon_level int | None optional. Player town hall weapon level (it is unlocked for player from 13 townhall level). None if player town hall is less than 13

PlayerLabel

Inherited from Label.
This model describes player label information.

PlayerLeague

Inherited from League.
This model describes player league information.

PlayerAchievment

This model describes information about some player achievment.

Field Type Description
name str Achievment name
stars int How many stars player have in this achievment
value int Progress
target int How much is needed to go to the next star
info str Detailed information about this achievment
village str In what village it achievment can obtained be
completion_info str | None optional. Completion info. None if ... #TODO

PlayerTroop

This model describes information about player troops leveling (troops/spells/heroes). This is not describes cuurent troops in player army camp, this describes troops leveling.

Field Type Description
name str Troop name
level int Troop level
max_level int Max troop level to which it can be upgraded
village str Which village this warrior belongs to
super_troop_is_active bool | None optional. True if player activated Super Troop Potion. None if troop can not be Super (spells and heroes can not be in super form also)

Clan

This model describes all information about clan.

Field Type Description
tag str Clan unique tag
name str Clan name
type str Clan type
description str Clan description
badge_urls BadgeURLs Clan icon urls
required_trophies int Required trophies to join this clan
required_versus_trophies int Required versus trophies (builder base) to join this clan
required_townhall_level int Required town hall level to join this clan
labels list[ClanLabel] List of clan labels
level int Clan level
points int Clan points
versus_points int Clan versus points
member_list list[str] List of tags of clan members
war ClanWar Information about war
location Location | None optional. Information about clan location. None if clan did not specify it
chat_language ClanChatLanguage | None optional. Information about clan chat primary language. None if clan did not specify it

ClanWar

This model describes all summary information about clan war state. If is_war_log_public is False you can not access current war information (including state) and war log.

Field Type Description
wins int How many times clan has won wars
losses int How many times clan has lost wars
ties int How many times clan has played a draw in wars
winstreak int War winstreak
is_war_log_public bool True if clan war log is public
frequency str Clan war frequency preference
state ClanWarState | None optional. Current war state. None if is_war_log_public is False
currentwar ClanWarInfo | None optional. Information about current war. None if is_war_log_public is False
log ClanWarResult | None optional. War log. None if is_war_log_public is False

ClanLabel

Inherited from BaseLabel.
Clan label is clan label.

ClanWarInfo

This model describes information about current war.

Field Type Description
clan ClanWarInfoClan Current war information about this clan
opponent ClanWarInfoClan Current war information about opponent clan
start_time datetime.datetime | None optional. Current war start time (UTC). None if ... #TODO
end_time datetime.datetime | None optional. Current war end time (UTC). None if ... #TODO
preparation_start_time datetime.datetime | None optional. Current war preparation start time (UTC). None if ... #TODO
team_size int | None optional. Clan team size in current war. None if ... #TODO
attacks_per_member int | None optional. How many attacks one member can perform. None if ... #TODO

ClanWarAttack

This model describes information about clan war attack. Every attack has attacker and defender, as for it, this model stores only attacker and defender tags, not full Player because of recursion.

Field Type Description
attacker_tag str Attacker tag
defender_tag str Defender tag
stars int How many stars attacker obtain
destruction_percentage float Destruction percentage in range 0.0 to 100.0%
order int Map position where attacked base is located
duration datetime.timedelta How long did the attack last
pendulum may be good here

ClanWarLeague

Inherited from BaseLeague.
Clan war league is war league of clan.

ClanWarPlayer

This model describes information about player in current clan war and his attacks (if made).

Field Type Description
tag str Player tag
map_position int Player map position
opponent_attacks int Available opponent attacks
attacks list[ClanWarAttack] | None optional. Attacks against opponents. None if no were made
best_opponent_attack ClanWarAttack | None optional. Best attack in attacks. None if no were made

ClanWarResult

This model describes result of clan war. Used in clan war logs.

Field Type Description
result str War result
end_time datetime.datetime When this war is ended (UTC).
pendulum may be good here
team_size int War team size
attacks_per_member int How many attacks one member could make
clan ClanWarInfoClan War information about this clan
opponent ClanWarInfoClan War information about opponent clan

ClanWarInfoClan

This model describes information about some clan in war.

Field Type Description
clan_level int Clan level
stars int Total stars received
destruction_percentage float Total destruction percentage
attacks int | None optional. Total maded attacks. None if no were made
members ClanWarPlayer | None optional. Participating clan members in war. None if there are no such

ClanChatLanguage

Clan chat language stores information about primary clan chat language.

Field Type Description
id int Language unique id
name str case insensitive. Language unique name
language_code str case insensitive. Language code (like country code)

GoldPass

This model describes information about current gold pass.

Field Type Description
start_time datetime.datetime Current season start time (UTC)
pendulum may be good here
end_time datetime.datetime Current season end time (UTC)
pendulum may be good here

Exceptions

ClientRequestError

Raises when something went wrong while making request.

Field Type Description
response aiohttp.ClientResponse Response from server
message str vary. Detailed message on whats going on
data Any | None optional. Extra data about response from server

IncorrectParameters

AccessDenied

ResourceNotFound

TooManyRequests

UnknownError

ServiceUnavailable

UnknownDataError

Raises when something went wrong while passing some data to method.

Field Type Description
data Any Data that has been passed
message str | None optional. vary. Detailed message on whats going on

UnknownLocationError

UnknownClanLabelError

UnknownClanLeagueError

UnknownPlayerLabelError

UnknownPlayerLeagueError

Aliases

Tag

Represents clan tag or player tag.
Starts with #, may have only digits and capital letters, length in range 1 to 9 (except # symbol) <-- unverified
Equivalent to str.

Must match r'#[1-9A-Z]{1,9}' regex, but in fact there is no check.

Tag = str

ClanType

constant. Represents clan type.

ClanType = 'open' | 'closed' | 'inviteOnly'

ClanRole

constant. Represents player clan role.

ClanRole = 'leader' | 'coLeader' | 'admin' | 'member'

ClanWarFrequency

constant. Represents clan war frequency.

ClanWarFrequency = 'always' | 'moreThanOncePerWeek' | 'oncePerWeek' | 'lessThanOncePerWeek' | 'never' | 'unknown'

ClanWarPreference

constant. Represents clan war preference.

ClanWarPreference = 'in' | 'out'

ClanWarResultL

constant. Represents clan war result.

ClanWarResultL = 'win' | 'lost' | 'tie'

ClanWarState

constant. Represents current war state.

ClanWarState = 'notInWar' | 'preparation' | 'inWar'

Village

constant. Represents game village.

Village = 'home' | 'builderBase'

API Completness

According to the original API.

Method Path Completness Description
GET /clans ✔️ (clans) Search clans
GET /clans/{clanTag} ✔️ (clan) Get clan information
GET /clans/{clanTag}/members ✔️ (clan) List clan members
GET /clans/{clanTag}/warlog ✔️ (clan) Retrieve clans clan war log
GET /clans/{clanTag}/currentwar ✔️ (clan) Retrieve information about clans current war
GET /clans/{clanTag}/currentwar/leaguegroup Retrieve information about clans current clan war league group
GET /clanwarleagues/wars/{warTag} Retrieve information about individual clan war league war
GET /players/{playerTag} ✔️ (player) Get player information
POST /players/{playerTag}/verifytoken Verify player API token that can be found from the game settings
GET /leagues ✔️ (all_player_leagues) List leagues
GET /leagues/{leagueId} ✔️ (get_player_league) Get league information
GET /leagues/{leagueId}/seasons Get league seasons
GET /leagues/{leagueId}/seasons/{seasonId} Get league season rankings
GET /warleagues ✔️ (all_clan_leagues) List war leagues
GET /warleagues/{leagueId} ✔️ (get_clan_league) Get war league information
GET /labels/players ✔️ (all_player_labels, get_player_label) List player labels
GET /labels/clans ✔️ (all_clan_labels, get_clan_label) List clan labels
GET /locations ✔️ (all_locations) List locations
GET /locations/{locationId} ✔️ (get_location) Get location information
GET /locations/{locationId}/rankings/clans ✔️ (clan_rankings) Get clan rankings for specific location
GET /locations/{locationId}/rankings/players ✔️ (player_rankings) Get player rankings for specific location
GET /locations/{locationId}/rankings/clans-versus ✔️ (clan_versus_rankings) Get clan versus rankings for specific location
GET /locations/{locationId}/rankings/players-versus ✔️ (player_versus_rankings) Get player versus rankings for specific location
GET /goldpass/seasons/current ✔️ (goldpass) Get information about the current gold pass season

TODO

  • Event system

About

Wrapper around Clash of Clans API implemented in Python.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages