Skip to content

Commit 22ecada

Browse files
committed
Add examples
1 parent a3a6573 commit 22ecada

File tree

2 files changed

+125
-0
lines changed

2 files changed

+125
-0
lines changed

examples/discord_bot.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# this example assumes you have discord.py > v1.0.0 installed via `python -m pip install -U discord.py`
2+
# for more info on using discord.py, see the docs at: https://discordpy.readthedocs.io/en/latest/api.html#message
3+
import discord
4+
from discord.ext import commands
5+
6+
import coc
7+
8+
bot = commands.Bot(command_prefix='?')
9+
coc_client = coc.Client('coc token')
10+
11+
12+
@bot.command()
13+
async def player_heroes(ctx, player_tag):
14+
player = await coc_client.get_player(player_tag)
15+
16+
to_send = ''
17+
for hero in player.heroes:
18+
to_send += '{}: Lv{}/{}'.format(str(hero), hero.level, hero.max_level)
19+
20+
await ctx.send(to_send)
21+
22+
23+
@bot.command()
24+
async def current_war_status(ctx, clan_tag):
25+
e = discord.Embed(colour=discord.Colour.blue())
26+
27+
try:
28+
war = await coc_client.get_current_war(clan_tag)
29+
except coc.Forbidden:
30+
return await ctx.send('Clan has a private war log!')
31+
32+
e.add_field(name=war.clan.name,
33+
value=war.clan.tag)
34+
35+
e.add_field(name='War State:',
36+
value=war.state,
37+
inline=False)
38+
39+
if war.end_time: # if state is notInWar we will get errors
40+
41+
hours, remainder = divmod(int(war.end_time.seconds_until), 3600)
42+
minutes, seconds = divmod(remainder, 60)
43+
44+
e.add_field(name='Opponent:',
45+
value=f"{war.opponent.name}\n"
46+
f"{war.opponent.tag}",
47+
inline=False)
48+
e.add_field(name="War End Time:",
49+
value=f'{hours} hours {minutes} minutes {seconds} seconds',
50+
inline=False)
51+
52+
await ctx.send(embed=e)
53+
54+
bot.run('bot token')
55+

examples/war_logs.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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

Comments
 (0)