Source code for lol.client
import asyncio
import aiohttp
import lol
import lol.champion
[docs]class Client:
"""Adds most of the base functionality for the module.
Allows you interact and get things to interact with the API.
Parameters:
token (:class:`str`): The token to use when requesting the API.
default_request_region (Optional[:class:`Region`]): The region to request when no other region is supplied.
Defaults to :attr:`Region.NA1`.
session (Optional[:class:`aiohttp.ClientSession`]): Used to supply a session if you dont want the Client
creating it's own.
loop (Optional[:class:`asyncio.AbstractEventLoop`]): Used to supply a loop if you dont want the Client
using :meth:`asyncio.get_event_loop`
Attributes:
loop (:class:`asyncio.AbstractEventLoop`): The used event loop.
default_request_region (:class:`lol.Region`): The region to request when no other region is supplied.
"""
def __init__(self, token: str, default_request_region: lol.Region = lol.Region.NA1,
session: aiohttp.ClientSession = None, loop=None):
self._token = token
self.default_request_region = default_request_region
self.loop = asyncio.get_event_loop() if loop is None else loop
if session is None:
self.session = None
self.loop.create_task(self._create_client_session())
else:
self.session = session
self._champion_data = None
self.loop.run_until_complete(self.get_all_champion_data())
async def get_all_champion_data(self):
self._champion_data = (await self.request("GET", lol.BASE_DATA_DRAGON, "cdn/7.8.1/data/en_US/champion.json", token=False))["data"]
def get_champion_data(self, name: str = None, id: str = None):
if name is not None:
name = name.lower().capitalize()
return self._champion_data[name]
if id is not None:
for champ in self._champion_data.values():
if int(champ["key"]) == id:
return champ
return None
async def _create_client_session(self):
self.session = aiohttp.ClientSession()
@property
def session_created(self):
if self.session is None:
return False
return True
async def request(self, method: str, url: str, path: str, token: bool = True, headers: dict = None, **kwargs):
if not self.session_created:
raise lol.ClientSessionNotCreated(
"The session hasn't been created yet. If this problem persists, "
"try passing an aiohttp.ClientSession to lol.Client's init."
)
if headers is None:
headers = {}
if token:
headers.update({"X-Riot-Token": self._token})
async with self.session.request(method, url + path, headers=headers, **kwargs) as request:
try:
content = await request.json()
except aiohttp.client_exceptions.ContentTypeError:
content = await request.read()
if 300 > request.status >= 200:
return content
else:
exception = lol.exception_from_code(request.status)
if isinstance(content, dict):
message = content.get("status", {}).get("message", exception.default_message)
else:
message = exception.default_message
raise exception(message)
[docs] async def close(self, close_loop=False):
"""This is used to close the session, which will disable all functionality.
Parameters:
close_loop (:class:`bool`): This is used to decide whether or not to close the event loop. Defaults to False.
"""
self.session.close()
if close_loop:
self.loop.close()
[docs] async def fetch_summoner(self, id=None, puuid=None, account_id=None, name=None, region: lol.Region = None):
"""This is used to get a :class:`Summoner`.
It requires only one of the parameters (not including region) to get a summoner.
Parameters:
id (:class:`str`): The id to search by.
puuid (:class:`str`): The puuid to search by.
account_id (:class:`str`): The id to search by.
id (:class:`str`): The id to search by.
Returns:
(Optional[:class:`Summoner`]): Will return the summoner or will return None and raise
and error if the summoner couldn't be found.
Raises:
:class:`DataNotFound`
No summoner with that information was found.
"""
if region is not None and getattr(region, "base_url", None) is None:
raise ValueError("The region argument must be an instance of lol.Region")
if region is None:
region = self.default_request_region
if id is not None:
path = f"summoner/v4/summoners/{id}"
elif puuid is not None:
path = f"summoner/v4/summoners/by-puuid/{puuid}"
elif account_id is not None:
path = f"summoner/v4/summoners/by-account/{account_id}"
elif name is not None:
path = f"summoner/v4/summoners/by-name/{name}"
else:
raise ValueError("No valid information was passed to Client.fetch_summoner")
try:
data = await self.request("GET", region.base_url, path)
except lol.HTTPCodeException as e:
raise e
return lol.Summoner(self, region, **data)