Skip to content

Commit 5d27709

Browse files
committed
resolve some of mathsmans reviews
1 parent ba903e4 commit 5d27709

File tree

7 files changed

+44
-47
lines changed

7 files changed

+44
-47
lines changed

coc/abc.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,7 @@ def __str__(self):
137137
return self.name
138138

139139
def __repr__(self):
140-
return "<%s tag=%s name=%s>" % (
141-
self.__class__.__name__, self.tag, self.name,)
140+
return f"<{self.__class__.__name__} tag={self.tag} name={self.name}>"
142141

143142
def __eq__(self, other):
144143
return isinstance(other, BasePlayer) and self.tag == other.tag
@@ -180,7 +179,7 @@ def __repr__(self):
180179
("is_active", self.is_active),
181180
]
182181
return "<%s %s>" % (
183-
self.__class__.__name__, " ".join("%s=%r" % t for t in attrs),)
182+
self.__class__.__name__, " ".join("%s=%r" % t for t in attrs),)
184183

185184
@classmethod
186185
def _load_json_meta(cls, troop_meta, id, name, lab_to_townhall):
@@ -280,14 +279,11 @@ def _load_json_meta(cls, troop_meta, id, name, lab_to_townhall):
280279

281280
# only heroes
282281
cls.ability_time = try_enum(UnitStat, troop_meta.get("AbilityTime"))
283-
cls.ability_troop_count = try_enum(UnitStat, troop_meta.get(
284-
"AbilitySummonTroopCount"))
285-
cls.required_th_level = try_enum(UnitStat, troop_meta.get(
286-
"RequiredTownHallLevel") or laboratory_levels)
287-
cls.regeneration_time = try_enum(UnitStat,
288-
[TimeDelta(minutes=value) for value in
289-
troop_meta.get(
290-
"RegenerationTimeMinutes", [])])
282+
cls.ability_troop_count = try_enum(UnitStat, troop_meta.get("AbilitySummonTroopCount"))
283+
cls.required_th_level = try_enum(UnitStat, troop_meta.get("RequiredTownHallLevel") or laboratory_levels)
284+
cls.regeneration_time = try_enum(
285+
UnitStat, [TimeDelta(minutes=value) for value in troop_meta.get("RegenerationTimeMinutes", [])]
286+
)
291287

292288
cls.is_loaded = True
293289
return cls
@@ -336,7 +332,7 @@ def _load_json(self, object_ids, english_aliases, lab_to_townhall):
336332
with open(self.FILE_PATH) as fp:
337333
data = ujson.load(fp)
338334

339-
for c, [supercell_name, meta] in enumerate(data.items()):
335+
for supercell_name, meta in data.items():
340336
# Not interested if it doesn't have a TID, since it likely isn't a real troop.
341337
if not meta.get("TID"):
342338
continue

coc/client.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ class Client:
120120
Defaults to ``True``.
121121
122122
connector : :class:`aiohttp.BaseConnector`
123-
The aiohttp connector to use. By default this is ``None``.
123+
The aiohttp connector to use. By default, this is ``None``.
124124
125125
timeout: :class:`float`
126126
The number of seconds before timing out with an API query. Defaults to 30.
@@ -138,7 +138,10 @@ class Client:
138138
bool to True.
139139
140140
raw_attribute: :class:`bool`
141-
The option to enable the _raw_data attribute for classes
141+
The option to enable the _raw_data attribute for most objects in the library. This attribute will contain
142+
the original json data as returned by the API. This can be useful if you want to store a response in a database
143+
for later use or are interested in new things that coc.py does not support otherwise yet. But because this
144+
increases the memory footprint and is not needed for most use cases, this defaults to ``False``.
142145
143146
Attributes
144147
----------

coc/events.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ def _setup(self):
420420
"maintenance": self.loop.create_task(self._maintenance_poller()),
421421
"season": self.loop.create_task(self._end_of_season_poller()),
422422
"raid_weekend": self.loop.create_task(self._raid_poller()),
423-
"clangames": self.loop.create_task(self._clangames_poller())
423+
"clan_games": self.loop.create_task(self._clan_games_poller())
424424
}
425425

426426
for task in self._updater_tasks.values():
@@ -822,20 +822,20 @@ async def _end_of_season_poller(self):
822822
self.dispatch("event_error", exception)
823823
return await self._end_of_season_poller()
824824

825-
async def _clangames_poller(self):
825+
async def _clan_games_poller(self):
826826
try:
827827
while self.loop.is_running():
828828
mute = now = datetime.utcnow()
829829
if now.day > 28 or (now.day == 28 and now.hour > 8):
830830
mute += timedelta(days=7)
831831
mute = datetime(year=mute.year, month=mute.month, day=22, hour=8, minute=0, second=0)
832-
event = "clangames_start"
832+
event = "clan_games_start"
833833
elif now.day > 22 or (now.day == 22 and now.hour > 8):
834834
mute = datetime(year=now.year, month=now.month, day=28, hour=8, minute=0, second=0)
835-
event = "clangames_end"
835+
event = "clan_games_end"
836836
else:
837837
mute = datetime(year=now.year, month=now.month, day=22, hour=8, minute=0, second=0)
838-
event = "clangames_start"
838+
event = "clan_games_start"
839839
await asyncio.sleep((mute - now).total_seconds())
840840
self.dispatch(event)
841841
except asyncio.CancelledError:

coc/events.pyi

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,9 +150,9 @@ class ClientEvents:
150150
@classmethod
151151
def raid_weekend_end(cls): ...
152152
@classmethod
153-
def clangames_start(cls): ...
153+
def clan_games_start(cls): ...
154154
@classmethod
155-
def clangames_end(cls): ...
155+
def clan_games_end(cls): ...
156156
@classmethod
157157
def keys_reset(cls): ...
158158
@classmethod

coc/ext/fullwarapi/__init__.py

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@
77

88
from collections import namedtuple
99
from datetime import datetime
10-
from typing import List, Optional, Union
10+
from typing import List, Optional, Union, Any, Generator
1111

1212
import aiohttp
1313

14+
from ... import ClanWar
1415
from ...http import json_or_text
1516
from ...utils import correct_tag
1617
from ...wars import ClanWar
@@ -45,7 +46,7 @@ def extract_expiry_from_jwt_token(token: Union[str, bytes]) -> Optional[datetime
4546
return None
4647

4748

48-
async def login(username: str, password: str, clash_client) -> "FullWarClient":
49+
async def login(username: str, password: str, coc_client) -> "FullWarClient":
4950
"""Eases logging into the API client.
5051
5152
For more information on this project, please join the discord server - <discord.gg/Eaja7gJ>
@@ -59,17 +60,16 @@ async def login(username: str, password: str, clash_client) -> "FullWarClient":
5960
Your username as given on the discord server.
6061
password : str
6162
Your password as given on the discord server
62-
loop : Optional[:class:`asyncio.AbstractEventLoop`]
63-
The :class:`asyncio.AbstractEventLoop` to use for HTTP requests.
64-
An :func:`asyncio.get_event_loop()` will be used if ``None`` is passed
63+
coc_client: coc.Client
64+
Client to use
6565
"""
6666
if not isinstance(username, str) or not isinstance(password, str):
6767
raise TypeError("username and password must both be a string")
6868
if not username or not password:
6969
raise ValueError("username or password must not be an empty string.")
7070

7171
loop = asyncio.get_running_loop()
72-
return FullWarClient(username, password, clash_client, loop)
72+
return FullWarClient(username, password, coc_client, loop)
7373

7474

7575
class FullWarClient:
@@ -86,7 +86,7 @@ class FullWarClient:
8686
Your username as given on the discord server.
8787
password : str
8888
Your password as given on the discord server
89-
clash_client: coc.Client
89+
coc_client: coc.Client
9090
Client to use
9191
9292
loop : Optional[:class:`asyncio.AbstractEventLoop`]
@@ -97,12 +97,12 @@ class FullWarClient:
9797

9898
BASE_URL = "https://fw-api.teamutils.com"
9999

100-
__slots__ = ("username", "password", "clash_client", "loop", "key", "http_session")
100+
__slots__ = ("username", "password", "coc_client", "loop", "key", "http_session")
101101

102-
def __init__(self, username: str, password: str, clash_client, loop: asyncio.AbstractEventLoop = None):
102+
def __init__(self, username: str, password: str, coc_client, loop: asyncio.AbstractEventLoop = None):
103103
self.username = username
104104
self.password = password
105-
self.clash_client = clash_client
105+
self.coc_client = coc_client
106106

107107
self.loop = loop or asyncio.get_event_loop()
108108
self.key = None # set in get_key()
@@ -150,13 +150,11 @@ async def _refresh_key(self):
150150
payload = await self._request("POST", "/login", token_request=True, json=data)
151151
self.key = AccessToken(payload["access_token"], extract_expiry_from_jwt_token(payload["access_token"]))
152152

153-
async def war_result(self, clan_tag: str, preparation_start: int = 0) -> ClanWar:
153+
async def war_result(self, clan_tag: str, preparation_start: int = 0) -> ClanWar | None:
154154
"""Get a stored war result.
155155
156156
Parameters
157157
----------
158-
client: coc.Client
159-
instance of the clash client
160158
clan_tag: str
161159
The clan tag to find war result for.
162160
preparation_start: int
@@ -172,21 +170,17 @@ async def war_result(self, clan_tag: str, preparation_start: int = 0) -> ClanWar
172170
f"/war_result?clan_tag={correct_tag(clan_tag, '%23')}"
173171
f"&prep_start={str(preparation_start)}")
174172
try:
175-
return ClanWar(data=data["response"], client=self.clash_client)
173+
return ClanWar(data=data["response"], client=self.coc_client)
176174
except (IndexError, KeyError, TypeError, ValueError):
177175
return None
178176

179-
async def war_result_log(self, clan_tag: str, preparation_start: int = 0) -> List[ClanWar]:
177+
async def war_result_log(self, clan_tag: str) -> Generator[ClanWar, Any, None] | None:
180178
"""Get all stored war results for a clan.
181179
182180
Parameters
183181
----------
184-
client: coc.Client
185-
instance of the clash client
186182
clan_tag: str
187183
The clan tag to find war result for.
188-
preparation_start: int
189-
Preparation start of a specific war result to find.
190184
191185
Returns
192186
--------
@@ -199,12 +193,11 @@ async def war_result_log(self, clan_tag: str, preparation_start: int = 0) -> Lis
199193
try:
200194
responses = data["log"]
201195

202-
generator = (ClanWar(data=response["response"], client=self.clash_client) for response in responses)
196+
generator = (ClanWar(data=response["response"], client=self.coc_client) for response in responses)
203197
return generator
204198
except (IndexError, KeyError, TypeError, ValueError):
205199
return None
206200

207-
208201
async def register_war(self, clan_tag: str, preparation_start: int = 0):
209202
"""Registers a war.
210203
@@ -218,4 +211,3 @@ async def register_war(self, clan_tag: str, preparation_start: int = 0):
218211
return await self._request("POST",
219212
f"/register_war?clan_tag={correct_tag(clan_tag, '%23')}"
220213
f"&prep_start={str(preparation_start)}")
221-

coc/players.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -627,7 +627,7 @@ def heroes(self) -> List[Hero]:
627627

628628
def get_hero(self, name: str, default_value=None) -> Optional[Hero]:
629629
"""
630-
Gets the player
630+
Gets the hero
631631
Parameters
632632
----------
633633
name

docs/advanced/event.rst

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -300,15 +300,21 @@ coc.py has a few events that are unique to the library, and which provide some u
300300
+------------------------------------------------+-------------------------+--------------------------------------------------+
301301
| ``@coc.ClientEvents.maintenance_completion()`` | start_datetime | Fired when API (and in-game) maintenance ends. |
302302
+------------------------------------------------+-------------------------+--------------------------------------------------+
303-
| ``@coc.ClientEvents.new_season_start()`` | None | Fired when a season starts. |
303+
| ``@coc.ClientEvents.new_season_start()`` | None | Fired when a season starts. This goes by the |
304+
| | | assumption that the season resets at 5am UTC at |
305+
| | | every last monday of the month. |
304306
+------------------------------------------------+-------------------------+--------------------------------------------------+
305307
| ``@coc.ClientEvents.raid_weekend_start()`` | None | Fired when a raid weekend starts. |
306308
+------------------------------------------------+-------------------------+--------------------------------------------------+
307309
| ``@coc.ClientEvents.raid_weekend_end()`` | None | Fired when a raid weekend ends. |
308310
+------------------------------------------------+-------------------------+--------------------------------------------------+
309-
| ``@coc.ClientEvents.clangames_start()`` | None | Fired when clan games starts. |
311+
| ``@coc.ClientEvents.clan_games_start()`` | None | Fired when clan games starts. This goes by the |
312+
| | | assumption that clan games start at 8am UTC at |
313+
| | | the 22nd of each month. |
310314
+------------------------------------------------+-------------------------+--------------------------------------------------+
311-
| ``@coc.ClientEvents.clangames_end()`` | None | Fired when clan games ends. |
315+
| ``@coc.ClientEvents.clan_games_end()`` | None | Fired when clan games ends. This goes by the |
316+
| | | assumption that clan games end at 8am UTC at |
317+
| | | the 28th of each month. |
312318
+------------------------------------------------+-------------------------+--------------------------------------------------+
313319
| ``@coc.ClientEvents.event_error()`` | exception | Fired when an event hits an unhandled exception |
314320
+------------------------------------------------+-------------------------+--------------------------------------------------+

0 commit comments

Comments
 (0)