mirror of
https://github.com/RYGhub/royalnet.git
synced 2024-11-27 13:34:28 +00:00
Complete updater
This commit is contained in:
parent
d49f1f39eb
commit
3a7e4d72f9
4 changed files with 91 additions and 47 deletions
|
@ -2,12 +2,12 @@ import typing
|
||||||
import riotwatcher
|
import riotwatcher
|
||||||
import logging
|
import logging
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import sentry_sdk
|
||||||
from royalnet.commands import *
|
from royalnet.commands import *
|
||||||
from royalnet.utils import *
|
from royalnet.utils import *
|
||||||
from ..tables import LeagueOfLegends
|
from ..tables import LeagueOfLegends
|
||||||
from ..utils import LeagueLeague
|
from ..utils import LeagueLeague
|
||||||
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@ -29,9 +29,10 @@ class LeagueoflegendsCommand(Command):
|
||||||
def __init__(self, interface: CommandInterface):
|
def __init__(self, interface: CommandInterface):
|
||||||
super().__init__(interface)
|
super().__init__(interface)
|
||||||
self._riotwatcher = riotwatcher.RiotWatcher(api_key=self.interface.bot.get_secret("leagueoflegends"))
|
self._riotwatcher = riotwatcher.RiotWatcher(api_key=self.interface.bot.get_secret("leagueoflegends"))
|
||||||
...
|
if self.interface.name == "telegram":
|
||||||
|
self.loop.create_task(self._updater(900))
|
||||||
|
|
||||||
def _notify(self,
|
async def _notify(self,
|
||||||
obj: LeagueOfLegends,
|
obj: LeagueOfLegends,
|
||||||
attribute_name: str,
|
attribute_name: str,
|
||||||
old_value: typing.Any,
|
old_value: typing.Any,
|
||||||
|
@ -44,37 +45,46 @@ class LeagueoflegendsCommand(Command):
|
||||||
return
|
return
|
||||||
# Prepare the message
|
# Prepare the message
|
||||||
if new_value > old_value:
|
if new_value > old_value:
|
||||||
message = f"📈 [b]{obj.user}[/b] è salito a {new_value} su League of Legends!"
|
message = f"📈 [b]{obj.user}[/b] è salito a {new_value} su League of Legends! Congratulazioni!"
|
||||||
else:
|
else:
|
||||||
message = "📉 [b]{obj.user}[/b] è sceso a {new_value} su League of Legends."
|
message = f"📉 [b]{obj.user}[/b] è sceso a {new_value} su League of Legends."
|
||||||
# Send the message
|
# Send the message
|
||||||
|
client = self.interface.bot.client
|
||||||
|
await self.interface.bot.safe_api_call(client.send_message,
|
||||||
|
chat_id=self._telegram_group_id,
|
||||||
|
text=telegram_escape(message),
|
||||||
|
parse_mode="HTML",
|
||||||
|
disable_webpage_preview=True)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _change(obj: LeagueOfLegends,
|
async def _change(obj: LeagueOfLegends,
|
||||||
attribute_name: str,
|
attribute_name: str,
|
||||||
new_value: typing.Any,
|
new_value: typing.Any,
|
||||||
callback: typing.Callable[[LeagueOfLegends, str, typing.Any, typing.Any], None]):
|
callback: typing.Callable[
|
||||||
|
[LeagueOfLegends, str, typing.Any, typing.Any], typing.Awaitable[None]]):
|
||||||
old_value = obj.__getattribute__(attribute_name)
|
old_value = obj.__getattribute__(attribute_name)
|
||||||
if old_value != new_value:
|
if old_value != new_value:
|
||||||
callback(obj, attribute_name, old_value, new_value)
|
await callback(obj, attribute_name, old_value, new_value)
|
||||||
obj.__setattr__(attribute_name, new_value)
|
obj.__setattr__(attribute_name, new_value)
|
||||||
|
|
||||||
async def _update(self, lol: LeagueOfLegends):
|
async def _update(self, lol: LeagueOfLegends):
|
||||||
log.info(f"Updating: {lol}")
|
log.info(f"Updating: {lol}")
|
||||||
log.debug(f"Getting summoner data: {lol}")
|
log.debug(f"Getting summoner data: {lol}")
|
||||||
summoner = self._riotwatcher.summoner.by_id(region=self._region, encrypted_summoner_id=lol.summoner_id)
|
summoner = await asyncify(self._riotwatcher.summoner.by_id, region=self._region,
|
||||||
self._change(lol, "profile_icon_id", summoner["profileIconId"], self._notify)
|
encrypted_summoner_id=lol.summoner_id)
|
||||||
self._change(lol, "summoner_name", summoner["name"], self._notify)
|
await self._change(lol, "profile_icon_id", summoner["profileIconId"], self._notify)
|
||||||
self._change(lol, "puuid", summoner["puuid"], self._notify)
|
await self._change(lol, "summoner_name", summoner["name"], self._notify)
|
||||||
self._change(lol, "summoner_level", summoner["summonerLevel"], self._notify)
|
await self._change(lol, "puuid", summoner["puuid"], self._notify)
|
||||||
self._change(lol, "summoner_id", summoner["id"], self._notify)
|
await self._change(lol, "summoner_level", summoner["summonerLevel"], self._notify)
|
||||||
self._change(lol, "account_id", summoner["accountId"], self._notify)
|
await self._change(lol, "summoner_id", summoner["id"], self._notify)
|
||||||
|
await self._change(lol, "account_id", summoner["accountId"], self._notify)
|
||||||
log.debug(f"Getting leagues data: {lol}")
|
log.debug(f"Getting leagues data: {lol}")
|
||||||
leagues = self._riotwatcher.league.by_summoner(region=self._region, encrypted_summoner_id=lol.summoner_id)
|
leagues = await asyncify(self._riotwatcher.league.by_summoner, region=self._region,
|
||||||
soloq = None
|
encrypted_summoner_id=lol.summoner_id)
|
||||||
flexq = None
|
soloq = LeagueLeague()
|
||||||
twtrq = None
|
flexq = LeagueLeague()
|
||||||
tftq = None
|
twtrq = LeagueLeague()
|
||||||
|
tftq = LeagueLeague()
|
||||||
for league in leagues:
|
for league in leagues:
|
||||||
if league["queueType"] == "RANKED_SOLO_5x5":
|
if league["queueType"] == "RANKED_SOLO_5x5":
|
||||||
soloq = LeagueLeague.from_dict(league)
|
soloq = LeagueLeague.from_dict(league)
|
||||||
|
@ -84,20 +94,32 @@ class LeagueoflegendsCommand(Command):
|
||||||
twtrq = LeagueLeague.from_dict(league)
|
twtrq = LeagueLeague.from_dict(league)
|
||||||
if league["queueType"] == "RANKED_TFT":
|
if league["queueType"] == "RANKED_TFT":
|
||||||
tftq = LeagueLeague.from_dict(league)
|
tftq = LeagueLeague.from_dict(league)
|
||||||
self._change(lol, "rank_soloq", soloq, self._notify)
|
await self._change(lol, "rank_soloq", soloq, self._notify)
|
||||||
self._change(lol, "rank_flexq", flexq, self._notify)
|
await self._change(lol, "rank_flexq", flexq, self._notify)
|
||||||
self._change(lol, "rank_twtrq", twtrq, self._notify)
|
await self._change(lol, "rank_twtrq", twtrq, self._notify)
|
||||||
self._change(lol, "rank_tftq", tftq, self._notify)
|
await self._change(lol, "rank_tftq", tftq, self._notify)
|
||||||
log.debug(f"Getting mastery data: {lol}")
|
log.debug(f"Getting mastery data: {lol}")
|
||||||
mastery = self._riotwatcher.champion_mastery.scores_by_summoner(region=self._region, encrypted_summoner_id=lol.summoner_id)
|
mastery = await asyncify(self._riotwatcher.champion_mastery.scores_by_summoner, region=self._region,
|
||||||
self._change(lol, "mastery_score", mastery, self._notify)
|
encrypted_summoner_id=lol.summoner_id)
|
||||||
|
await self._change(lol, "mastery_score", mastery, self._notify)
|
||||||
|
|
||||||
async def _updater(self, period: int):
|
async def _updater(self, period: int):
|
||||||
|
log.info(f"Started updater with {period}s period")
|
||||||
while True:
|
while True:
|
||||||
|
log.info(f"Updating...")
|
||||||
session = self.alchemy.Session()
|
session = self.alchemy.Session()
|
||||||
|
log.info("")
|
||||||
lols = session.query(self.alchemy.LeagueOfLegends).all()
|
lols = session.query(self.alchemy.LeagueOfLegends).all()
|
||||||
for lol in lols:
|
for lol in lols:
|
||||||
|
try:
|
||||||
await self._update(lol)
|
await self._update(lol)
|
||||||
|
except Exception as e:
|
||||||
|
sentry_sdk.capture_exception(e)
|
||||||
|
log.error(f"Error while updating {lol.user.username}: {e}")
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
await asyncify(session.commit)
|
||||||
|
session.close()
|
||||||
|
log.info(f"Sleeping for {period}s")
|
||||||
await asyncio.sleep(period)
|
await asyncio.sleep(period)
|
||||||
|
|
||||||
def _display(self, lol: LeagueOfLegends):
|
def _display(self, lol: LeagueOfLegends):
|
||||||
|
@ -132,10 +154,10 @@ class LeagueoflegendsCommand(Command):
|
||||||
# Get rank information
|
# Get rank information
|
||||||
log.debug(f"Getting leagues data: {name}")
|
log.debug(f"Getting leagues data: {name}")
|
||||||
leagues = self._riotwatcher.league.by_summoner(region=self._region, encrypted_summoner_id=summoner["id"])
|
leagues = self._riotwatcher.league.by_summoner(region=self._region, encrypted_summoner_id=summoner["id"])
|
||||||
soloq = None
|
soloq = LeagueLeague()
|
||||||
flexq = None
|
flexq = LeagueLeague()
|
||||||
twtrq = None
|
twtrq = LeagueLeague()
|
||||||
tftq = None
|
tftq = LeagueLeague()
|
||||||
for league in leagues:
|
for league in leagues:
|
||||||
if league["queueType"] == "RANKED_SOLO_5x5":
|
if league["queueType"] == "RANKED_SOLO_5x5":
|
||||||
soloq = LeagueLeague.from_dict(league)
|
soloq = LeagueLeague.from_dict(league)
|
||||||
|
@ -173,10 +195,14 @@ class LeagueoflegendsCommand(Command):
|
||||||
# Update and display the League of Legends stats for the current account
|
# Update and display the League of Legends stats for the current account
|
||||||
if len(author.leagueoflegends) == 0:
|
if len(author.leagueoflegends) == 0:
|
||||||
raise CommandError("Nessun account di League of Legends trovato.")
|
raise CommandError("Nessun account di League of Legends trovato.")
|
||||||
for account in author.leagueoflegends:
|
|
||||||
await self._update(account)
|
|
||||||
await data.session_commit()
|
|
||||||
message = ""
|
message = ""
|
||||||
for account in author.leagueoflegends:
|
for account in author.leagueoflegends:
|
||||||
|
try:
|
||||||
|
await self._update(account)
|
||||||
message += self._display(account)
|
message += self._display(account)
|
||||||
|
except riotwatcher.ApiError as e:
|
||||||
|
message += f"⚠️ [b]{account.summoner_name}[/b]\n" \
|
||||||
|
f"{e}"
|
||||||
|
message += "\n"
|
||||||
|
await data.session_commit()
|
||||||
await data.reply(message)
|
await data.reply(message)
|
||||||
|
|
|
@ -31,12 +31,14 @@ class LeagueLeague:
|
||||||
emojis += "🔥"
|
emojis += "🔥"
|
||||||
if self.fresh_blood:
|
if self.fresh_blood:
|
||||||
emojis += "⭐️"
|
emojis += "⭐️"
|
||||||
return f"[b]{self.tier} {self.rank}[/b] ({self.points} LP) {emojis}"
|
return f"[b]{self.tier} {self.rank}[/b] ({self.points} LP){' ' if emojis else ''}{emojis}"
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
return f"<{self.__class__.__qualname__} {self}>"
|
return f"<{self.__class__.__qualname__} {self}>"
|
||||||
|
|
||||||
def __eq__(self, other) -> bool:
|
def __eq__(self, other) -> bool:
|
||||||
|
if other is None:
|
||||||
|
return False
|
||||||
if not isinstance(other, LeagueLeague):
|
if not isinstance(other, LeagueLeague):
|
||||||
raise TypeError(f"Can't compare {self.__class__.__qualname__} with {other.__class__.__qualname__}")
|
raise TypeError(f"Can't compare {self.__class__.__qualname__} with {other.__class__.__qualname__}")
|
||||||
equal = True
|
equal = True
|
||||||
|
@ -64,6 +66,8 @@ class LeagueLeague:
|
||||||
return not self.__eq__(other)
|
return not self.__eq__(other)
|
||||||
|
|
||||||
def __gt__(self, other) -> bool:
|
def __gt__(self, other) -> bool:
|
||||||
|
if other is None:
|
||||||
|
return True
|
||||||
if not isinstance(other, LeagueLeague):
|
if not isinstance(other, LeagueLeague):
|
||||||
raise TypeError(f"Can't compare {self.__class__.__qualname__} with {other.__class__.__qualname__}")
|
raise TypeError(f"Can't compare {self.__class__.__qualname__} with {other.__class__.__qualname__}")
|
||||||
if not (bool(self) and bool(other)):
|
if not (bool(self) and bool(other)):
|
||||||
|
@ -73,7 +77,7 @@ class LeagueLeague:
|
||||||
return self.tier > other.tier
|
return self.tier > other.tier
|
||||||
elif self.rank != other.rank:
|
elif self.rank != other.rank:
|
||||||
# Silver I is better than Silver IV
|
# Silver I is better than Silver IV
|
||||||
return self.rank < other.rank
|
return self.rank > other.rank
|
||||||
elif self.points != other.points:
|
elif self.points != other.points:
|
||||||
# Silver I (100 LP) is better than Silver I (0 LP)
|
# Silver I (100 LP) is better than Silver I (0 LP)
|
||||||
return self.points > other.points
|
return self.points > other.points
|
||||||
|
@ -118,8 +122,8 @@ class LeagueLeague:
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_dict(cls, d: dict):
|
def from_dict(cls, d: dict):
|
||||||
return cls(
|
return cls(
|
||||||
tier=d["tier"],
|
tier=LeagueTier.from_string(d["tier"]),
|
||||||
rank=d["rank"],
|
rank=LeagueRank.from_string(d["rank"]),
|
||||||
points=d["leaguePoints"],
|
points=d["leaguePoints"],
|
||||||
wins=d["wins"],
|
wins=d["wins"],
|
||||||
losses=d["losses"],
|
losses=d["losses"],
|
||||||
|
|
|
@ -12,3 +12,10 @@ class LeagueRank(enum.Enum):
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"{self.__class__.__qualname__}.{self.name}"
|
return f"{self.__class__.__qualname__}.{self.name}"
|
||||||
|
|
||||||
|
def __gt__(self, other):
|
||||||
|
return self.value < other.value
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_string(cls, string: str):
|
||||||
|
return cls.__members__.get(string)
|
||||||
|
|
|
@ -17,3 +17,10 @@ class LeagueTier(enum.Enum):
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"{self.__class__.__qualname__}.{self.name}"
|
return f"{self.__class__.__qualname__}.{self.name}"
|
||||||
|
|
||||||
|
def __gt__(self, other):
|
||||||
|
return self.value > other.value
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_string(cls, string: str):
|
||||||
|
return cls.__members__.get(string)
|
||||||
|
|
Loading…
Reference in a new issue