1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-24 03:54:20 +00:00

asdfasfarewtw

This commit is contained in:
Steffo 2018-10-08 00:42:45 +02:00
parent bb6d32547a
commit 1560130261
4 changed files with 57 additions and 22 deletions

43
db.py
View file

@ -163,7 +163,7 @@ class Steam(Base):
else: else:
return f"{int(steam_id) - 76561197960265728}" return f"{int(steam_id) - 76561197960265728}"
def update(self, raise_if_private: bool=False): def update(self, session=None, raise_if_private: bool=False):
r = requests.get(f"https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={config['Steam']['api_key']}&steamids={self.steam_id}") r = requests.get(f"https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={config['Steam']['api_key']}&steamids={self.steam_id}")
if r.status_code != 200: if r.status_code != 200:
raise RequestError(f"Steam returned {r.status_code}") raise RequestError(f"Steam returned {r.status_code}")
@ -212,7 +212,7 @@ class RocketLeague(Base):
def __repr__(self): def __repr__(self):
return f"<db.RocketLeague {self.steam_id}>" return f"<db.RocketLeague {self.steam_id}>"
def update(self, data=None): def update(self, session=None, data=None):
raise NotImplementedError("rlstats API is no longer available.") raise NotImplementedError("rlstats API is no longer available.")
def solo_rank_image(self): def solo_rank_image(self):
@ -310,7 +310,7 @@ class Dota(Base):
new_record.update() new_record.update()
return new_record return new_record
def update(self) -> bool: def update(self, session=None) -> bool:
r = requests.get(f"https://api.opendota.com/api/players/{Steam.to_steam_id_3(self.steam_id)}") r = requests.get(f"https://api.opendota.com/api/players/{Steam.to_steam_id_3(self.steam_id)}")
if r.status_code != 200: if r.status_code != 200:
raise RequestError("OpenDota / returned {r.status_code}") raise RequestError("OpenDota / returned {r.status_code}")
@ -374,7 +374,7 @@ class LeagueOfLegends(Base):
return f"<LeagueOfLegends {self.summoner_id}>" return f"<LeagueOfLegends {self.summoner_id}>"
return f"<LeagueOfLegends {(''.join([x if x.isalnum else '' for x in self.summoner_name]))}>" return f"<LeagueOfLegends {(''.join([x if x.isalnum else '' for x in self.summoner_name]))}>"
def update(self) -> bool: def update(self, session=None) -> bool:
r = requests.get(f"https://euw1.api.riotgames.com/lol/summoner/v3/summoners/{self.summoner_id}?api_key={config['League of Legends']['riot_api_key']}") r = requests.get(f"https://euw1.api.riotgames.com/lol/summoner/v3/summoners/{self.summoner_id}?api_key={config['League of Legends']['riot_api_key']}")
if r.status_code != 200: if r.status_code != 200:
raise RequestError(f"League of Legends API /summoner returned {r.status_code}") raise RequestError(f"League of Legends API /summoner returned {r.status_code}")
@ -468,7 +468,7 @@ class Osu(Base):
mania_pp=j3["pp_raw"]) mania_pp=j3["pp_raw"])
return new_record return new_record
def update(self): def update(self, session=None):
r0 = requests.get(f"https://osu.ppy.sh/api/get_user?k={config['Osu!']['ppy_api_key']}&u={self.osu_name}&m=0") r0 = requests.get(f"https://osu.ppy.sh/api/get_user?k={config['Osu!']['ppy_api_key']}&u={self.osu_name}&m=0")
r1 = requests.get(f"https://osu.ppy.sh/api/get_user?k={config['Osu!']['ppy_api_key']}&u={self.osu_name}&m=1") r1 = requests.get(f"https://osu.ppy.sh/api/get_user?k={config['Osu!']['ppy_api_key']}&u={self.osu_name}&m=1")
r2 = requests.get(f"https://osu.ppy.sh/api/get_user?k={config['Osu!']['ppy_api_key']}&u={self.osu_name}&m=2") r2 = requests.get(f"https://osu.ppy.sh/api/get_user?k={config['Osu!']['ppy_api_key']}&u={self.osu_name}&m=2")
@ -574,7 +574,7 @@ class Overwatch(Base):
def icon_url(self): def icon_url(self):
return f"https://d1u1mce87gyfbn.cloudfront.net/game/unlocks/{self.icon}.png" return f"https://d1u1mce87gyfbn.cloudfront.net/game/unlocks/{self.icon}.png"
def update(self): def update(self, session=None):
r = requests.get(f"https://owapi.net/api/v3/u/{self.battletag}-{self.discriminator}/stats", headers={ r = requests.get(f"https://owapi.net/api/v3/u/{self.battletag}-{self.discriminator}/stats", headers={
"User-Agent": "Royal-Bot/4.1", "User-Agent": "Royal-Bot/4.1",
"From": "ste.pigozzi@gmail.com" "From": "ste.pigozzi@gmail.com"
@ -963,6 +963,37 @@ class Halloween(Base):
completed[i] = True completed[i] = True
return started, completed return started, completed
def update(self, session):
if self[1] is None:
# Dota last match
dota = session.query(Dota).join(Steam).join(Royal).filter_by(id=self.royal.id).one_or_none()
if dota is not None:
dota_id = Steam.to_steam_id_3(dota.steam_id)
r = requests.get(f"https://api.opendota.com/api/players/{dota_id}/recentMatches")
if r.status_code != 200:
raise RequestError("Error in the Halloween Dota check.")
j = r.json()
match = j[0]
if match["hero_id"] == 81 and (match["radiant_win"] ^ match["player_slot"] // 128):
logging.debug(f"{self.royal.username} has obtained Moon A via Dota.")
self[1] = datetime.datetime.now()
else:
logging.debug(f"{self.royal.username} hasn't passed the LoL challenge yet.")
# LoL last match
lol = session.query(LeagueOfLegends).join(Royal).filter_by(id=self.royal.id).one_or_none()
if lol is not None:
r = requests.get(f"https://euw1.api.riotgames.com/lol/match/v3/matchlists/by-account/207525171"
f"?api_key={config['League of Legends']['riot_api_key']}")
if r.status_code != 200:
raise RequestError("Error in the Halloween LoL check.")
j = r.json()
match = j["matches"][0]
if match["champion"] == 120:
self[1] = datetime.datetime.now()
logging.debug(f"{self.royal.username} has obtained Moon A via LoL.")
else:
logging.debug(f"{self.royal.username} hasn't passed the LoL challenge yet.")
# If run as script, create all the tables in the db # If run as script, create all the tables in the db
if __name__ == "__main__": if __name__ == "__main__":
print("Creating new tables...") print("Creating new tables...")

View file

@ -1,3 +1,5 @@
import requests
import errors
import db import db
import time import time
import logging import logging
@ -8,6 +10,7 @@ import typing
import telegram import telegram
import sys import sys
import coloredlogs import coloredlogs
import datetime
logging.getLogger().disabled = True logging.getLogger().disabled = True
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -27,12 +30,12 @@ sentry = raven.Client(config["Sentry"]["token"],
telegram_bot = telegram.Bot(config["Telegram"]["bot_token"]) telegram_bot = telegram.Bot(config["Telegram"]["bot_token"])
def update_block(block: list, delay: float=0, change_callback: typing.Callable=None): def update_block(session: db.Session, block: list, delay: float=0, change_callback: typing.Callable=None):
for item in block: for item in block:
logger.debug(f"Updating {repr(item)}.") logger.debug(f"Updating {repr(item)}.")
t = time.clock() t = time.clock()
try: try:
change = item.update() change = item.update(session=session)
except Exception as e: except Exception as e:
logger.error(f"Error {sys.exc_info()} while updating {repr(item)}.") logger.error(f"Error {sys.exc_info()} while updating {repr(item)}.")
sentry.extra_context({ sentry.extra_context({
@ -63,29 +66,28 @@ def new_lol_rank(item: db.LeagueOfLegends):
logger.warning(f"Couldn't notify on Telegram: {item}") logger.warning(f"Couldn't notify on Telegram: {item}")
def halloween_checks(item: db.Halloween, session: db.Session):
# Dota last matches
session.query(db.Dota).join(db.Steam).filter_by(id=item.royal).one_or_none()
def process(): def process():
while True: while True:
logger.info("Pausing for 30 minutes.") # logger.info("Pausing for 30 minutes.")
time.sleep(1800) # time.sleep(1800)
session = db.Session() session = db.Session()
logger.info("Now updating Halloween data.")
update_block(session, session.query(db.Halloween).all())
session.commit()
logger.info("Now updating Steam data.") logger.info("Now updating Steam data.")
update_block(session.query(db.Steam).all()) update_block(session, session.query(db.Steam).all())
session.commit() session.commit()
logger.info("Now updating Dota data.") logger.info("Now updating Dota data.")
update_block(session.query(db.Dota).all(), delay=5, change_callback=new_dota_rank) update_block(session, session.query(db.Dota).all(), delay=5, change_callback=new_dota_rank)
session.commit() session.commit()
logger.info("Now updating League of Legends data.") logger.info("Now updating League of Legends data.")
update_block(session.query(db.LeagueOfLegends).all(), delay=5, change_callback=new_lol_rank) update_block(session, session.query(db.LeagueOfLegends).all(), delay=5, change_callback=new_lol_rank)
session.commit() session.commit()
logger.info("Now updating osu! data.") logger.info("Now updating osu! data.")
update_block(session.query(db.Osu).all(), delay=5) update_block(session, session.query(db.Osu).all(), delay=5)
session.commit() session.commit()
logger.info("Now updating Overwatch data.") logger.info("Now updating Overwatch data.")
update_block(session.query(db.Overwatch).all(), delay=5) update_block(session, session.query(db.Overwatch).all(), delay=5)
session.commit() session.commit()

View file

@ -7,8 +7,10 @@
<div class="game-panel"> <div class="game-panel">
<div class="game-grid lol"> <div class="game-grid lol">
<div class="player"> <div class="player">
<img src="http://avatar.leagueoflegends.com/EUW1/{{ record.summoner_name }}.png" class="player-image"> <a href="https://matchhistory.euw.leagueoflegends.com/en/#match-history/EUW1/{{ record.account_id }}">
<span class="player-name">{{ record.summoner_name }}</span> <img src="http://avatar.leagueoflegends.com/EUW1/{{ record.summoner_name }}.png" class="player-image">
<span class="player-name">{{ record.summoner_name }}</span>
</a>
</div> </div>
<div class="game-title level"> <div class="game-title level">
LIVELLO LIVELLO

View file

@ -83,7 +83,7 @@
</h2> </h2>
<div class="description"> <div class="description">
you'll need the help of the horsemen of the apocalypse to dispel the curse.<br> you'll need the help of the horsemen of the apocalypse to dispel the curse.<br>
lead Chaos to victory in the battle of the ancients, or the War from the shadow isles to victory on the rift, and you'll gain their support. lead Chaos to victory in the battle of the ancients, or summon War from the shadow isles on the rift, and you'll gain their support.
</div> </div>
{% elif loop.index == 2 %} {% elif loop.index == 2 %}
{# la zucca di balu e max #} {# la zucca di balu e max #}