|
| 1 | +import coc |
| 2 | +import asyncio |
| 3 | +import logging |
| 4 | + |
| 5 | +log = logging.getLogger('coc') |
| 6 | +log.setLevel(logging.DEBUG) |
| 7 | + |
| 8 | + |
| 9 | +class COCClient(coc.Client): |
| 10 | + def __init__(self, token, **kwargs): |
| 11 | + super().__init__(token, **kwargs) |
| 12 | + |
| 13 | + def on_token_reset(self, new_token): |
| 14 | + """We want to override how the default on_token_reset is run |
| 15 | + """ |
| 16 | + log.info('New token {} was created!'.format(new_token)) |
| 17 | + |
| 18 | + |
| 19 | +# because we want to update our token if our IP changes, we need to pass in our email and password |
| 20 | +# from https://developer.clashofclans.com |
| 21 | +cocclient = COCClient('token', email='email', password='password', update_tokens=True) |
| 22 | + |
| 23 | + |
| 24 | +async def get_warlog_for_clans(clan_tags: list): |
| 25 | + war_logs = {} |
| 26 | + for tag in clan_tags: |
| 27 | + # if we're not allowed to view warlog (private in game), this will raise an exception |
| 28 | + try: |
| 29 | + warlog = await cocclient.get_warlog(tag, cache=True) |
| 30 | + except coc.Forbidden: |
| 31 | + warlog = [] |
| 32 | + |
| 33 | + war_logs[tag] = warlog |
| 34 | + |
| 35 | + # return a dict of list of war logs: {'tag': [list_of_warlog_objects]} |
| 36 | + return war_logs |
| 37 | + |
| 38 | + |
| 39 | +async def get_clan_tags_names(name: str, limit: int): |
| 40 | + clans = await cocclient.search_clans(name=name, limit=limit) |
| 41 | + # return a list of tuples of name/tag pair ie. [(name, tag), (another name, another tag)] |
| 42 | + return [(n.name, n.tag) for n in clans] |
| 43 | + |
| 44 | + |
| 45 | +async def get_warlog_opponents_from_clan_name(name: str, no_of_clans: int): |
| 46 | + clan_tags_names = await get_clan_tags_names(name, no_of_clans) |
| 47 | + |
| 48 | + # search for war logs with clan tags found |
| 49 | + war_logs = await get_warlog_for_clans([n[1] for n in clan_tags_names]) |
| 50 | + |
| 51 | + for name, tag in clan_tags_names: |
| 52 | + # iterate over the wars |
| 53 | + for war in war_logs[tag]: |
| 54 | + # if it is a league war we will error below because it does not return a WarLog object, |
| 55 | + # and thus no opponent |
| 56 | + if isinstance(war, coc.LeagueWarLogEntry): |
| 57 | + print('League War Season - No opponent info available') |
| 58 | + continue |
| 59 | + |
| 60 | + print('War: {} vs {}'.format(name, war.opponent.name)) |
| 61 | + |
| 62 | +if __name__ == '__main__': |
| 63 | + loop = asyncio.get_event_loop() |
| 64 | + |
| 65 | + loop.run_until_complete(get_warlog_opponents_from_clan_name('name', 5)) |
| 66 | + loop.run_until_complete(cocclient.close()) |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | + |
0 commit comments