Skip to content

Commit

Permalink
Refactor typing again and minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
janaSunrise committed Feb 8, 2023
1 parent 1ce919b commit 388ebcc
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 70 deletions.
7 changes: 2 additions & 5 deletions hypixelio/_async/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ async def _fetch(
data: Optional[dict]
The GET Request's Key-Value Pair. Example: {"uuid": "abc"} is converted to `?uuid=abc`. Defaults to None.
api_key: bool
If key is needed for the endpoin
If key is needed for the endpoint.
Returns
-------
Expand Down Expand Up @@ -164,11 +164,8 @@ async def _filter_name_uuid(name: Optional[str] = None, uuid: Optional[str] = No

# Context managers
async def __aenter__(self) -> "AsyncClient":
# Initialize the session
self._session = aiohttp.ClientSession()

await self._session.__aenter__()

return self

async def __aexit__(
Expand All @@ -178,7 +175,7 @@ async def __aexit__(
exc_tb: Optional[TracebackType],
) -> None:
if self._session is not None:
await self._session.__aexit__(exc_type, exc_val, exc_tb)
await self._session.close()

# Hypixel API endpoint methods
async def get_key_info(self, api_key: Optional[str] = None) -> Key:
Expand Down
10 changes: 5 additions & 5 deletions hypixelio/_async/converters.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
__all__ = ("AsyncConverters",)

import typing as t
from typing import Any, Dict, Union, cast

import aiohttp

Expand All @@ -13,7 +13,7 @@ class AsyncConverters:
url = API_PATH["MOJANG"]

@classmethod
async def _fetch(cls, url: str) -> t.Union[dict, list]:
async def _fetch(cls, url: str) -> Union[dict, list]:
"""
The internal function for fetching info from the Mojang API.
Expand All @@ -24,7 +24,7 @@ async def _fetch(cls, url: str) -> t.Union[dict, list]:
Returns
-------
t.Union[dict, list]
Union[dict, list]
The JSON response from the Mojang API.
"""
session = aiohttp.ClientSession()
Expand Down Expand Up @@ -63,8 +63,8 @@ async def username_to_uuid(cls, username: str) -> str:
str
returns the converted UUID for the respective username.
"""
json = t.cast(
t.Dict[str, t.Any],
json = cast(
Dict[str, Any],
await AsyncConverters._fetch(
AsyncConverters.url["username_to_uuid"].format(username)
),
Expand Down
34 changes: 17 additions & 17 deletions hypixelio/_async/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
__all__ = ("Utils",)

import typing as t
from typing import Optional, Union

import aiohttp

Expand Down Expand Up @@ -46,7 +46,7 @@ async def _crafatar_fetch(cls, url: str) -> str:

@staticmethod
async def _filter_name_uuid(
name: t.Optional[str] = None, uuid: t.Optional[str] = None
name: Optional[str] = None, uuid: Optional[str] = None
) -> str:
if not name and not uuid:
raise InvalidArgumentError(
Expand Down Expand Up @@ -78,25 +78,25 @@ def _form_crafatar_url(cls, route: str) -> str:
@classmethod
async def get_name_history(
cls,
name: t.Optional[str] = None,
uuid: t.Optional[str] = None,
name: Optional[str] = None,
uuid: Optional[str] = None,
changed_at: bool = False,
) -> t.Union[list, dict]:
) -> Union[list, dict]:
"""
Get the name history with records for a player.
Parameters
----------
name: t.Optional[str]
name: Optional[str]
The username of the player. Defaults to None.
uuid: t.Optional[str]
uuid: Optional[str]
The UUID of the player. Defaults to None.
changed_at: bool
Toggle to true, if you need when the player changed name. Defaults to False.
Returns
-------
t.Union[list, dict]
Union[list, dict]
The list or dictionary with the name history and records.
"""
uuid = await cls._filter_name_uuid(name, uuid)
Expand All @@ -113,16 +113,16 @@ async def get_name_history(

@classmethod
async def get_avatar(
cls, name: t.Optional[str] = None, uuid: t.Optional[str] = None
cls, name: Optional[str] = None, uuid: Optional[str] = None
) -> str:
"""
Get the avatar of the specified player.
Parameters
----------
name: t.Optional[str]
name: Optional[str]
The username of the player. Defaults to None.
uuid: t.Optional[str]
uuid: Optional[str]
The UUID of the player. Defaults to None.
Returns
Expand All @@ -137,16 +137,16 @@ async def get_avatar(

@classmethod
async def get_head(
cls, name: t.Optional[str] = None, uuid: t.Optional[str] = None
cls, name: Optional[str] = None, uuid: Optional[str] = None
) -> str:
"""
Get the head skin of the specified player.
Parameters
----------
name: t.Optional[str]
name: Optional[str]
The username of the player. Defaults to None.
uuid: t.Optional[str]
uuid: Optional[str]
The UUID of the player. Defaults to None.
Returns
Expand All @@ -161,16 +161,16 @@ async def get_head(

@classmethod
async def get_body(
cls, name: t.Optional[str] = None, uuid: t.Optional[str] = None
cls, name: Optional[str] = None, uuid: Optional[str] = None
) -> str:
"""
Get the whole body's skin of the specified player
Parameters
----------
name: t.Optional[str]
name: Optional[str]
The username of the player. Defaults to None.
uuid: t.Optional[str]
uuid: Optional[str]
The UUID of the player. Defaults to None.
Returns
Expand Down
43 changes: 2 additions & 41 deletions hypixelio/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,10 @@ class InvalidArgumentError(Exception):
...


# API exceptions
class APIError(Exception):
"""Base class for all API exceptions."""

def __init__(self, service: str, reason: t.Optional[str] = None) -> None:
"""
Parameters
----------
reason: str
The reason for the Error. Defaults to None.
"""
error = f"There was an issue with the {service} API."
if reason:
error += f" Reason: {reason}."
Expand All @@ -45,54 +38,30 @@ class HypixelAPIError(APIError):
"""Raised when there is an issue with the Hypixel API or during fetch."""

def __init__(self, reason: t.Optional[str] = None) -> None:
"""
Parameters
----------
reason: str
The reason for the Error. Defaults to None.
"""
super().__init__("Hypixel", reason)


class CrafatarAPIError(APIError):
"""Raised during issues faced by Crafatar API."""

def __init__(self, reason: t.Optional[str] = None) -> None:
"""
Parameters
----------
reason: str
The reason for the Error. Defaults to None.
"""
super().__init__("Crafatar", reason)


class MojangAPIError(APIError):
"""Raised when the Mojang API is facing some problems."""

def __init__(self, reason: t.Optional[str] = None) -> None:
"""
Parameters
----------
reason: str
The reason for the Error. Defaults to None.
"""
super().__init__("Mojang", reason)


# Rate-limit exception
class RateLimitError(Exception):
"""Raised when the Rate-limit for the Hypixel API is hit."""
"""Raised when the ratelimit for the hypixel API is hit."""

def __init__(self, retry_after: datetime) -> None:
"""
Parameters
----------
retry_after: datetime
The time when the API will be available again for fetching.
"""
error = (
"The rate-limit for the Hypixel API was hit. Try again after"
"The ratelimit for the hypixel API was hit. Try again after"
f"{retry_after.strftime('%Y-%m-%d %H:%M:%S')}."
)

Expand All @@ -110,14 +79,6 @@ class PlayerNotFoundError(Exception):
def __init__(
self, reason: t.Optional[str] = None, user: t.Optional[str] = None
) -> None:
"""
Parameters
----------
reason: str
The reason for the error.
user: t.Optional[str]
The user not found when searched for.
"""
error = "Player not found."
if reason:
error += f" {reason}."
Expand Down
3 changes: 1 addition & 2 deletions hypixelio/lib/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,7 @@ def get_key_info(self, api_key: Optional[str] = None) -> Key:
Key
The Key object created for the API key specified.
"""
if not api_key:
api_key = random.choice(self._api_key)
api_key = api_key or random.choice(self._api_key)

json = self._fetch(self.url["api_key"], {"key": api_key})
return Key(json["record"])
Expand Down

0 comments on commit 388ebcc

Please sign in to comment.