From a646761c9abd2ac9e6b1ae71384c1eb0e9a4a68a Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Tue, 18 Sep 2018 00:07:00 +0200 Subject: [PATCH] Megaupdate --- bots.py | 35 +++++++++---- cast.py | 25 +++++++++- db.py | 73 +++++++++++++++++++++------ discordbot.py | 23 ++++----- errors.py | 2 + redditbot.py | 2 +- requirements.txt | 1 - stagismo.py | 2 +- statsupdater.py | 88 +++++++++++++++++++++++++++++++++ telegrambot.py | 16 ++---- update.py | 126 ----------------------------------------------- webserver.py | 6 ++- 12 files changed, 214 insertions(+), 185 deletions(-) create mode 100644 statsupdater.py delete mode 100644 update.py diff --git a/bots.py b/bots.py index a94bdcf9..4d84375c 100644 --- a/bots.py +++ b/bots.py @@ -1,8 +1,8 @@ import multiprocessing -import os import telegrambot import discordbot import redditbot +import statsupdater import time import logging @@ -13,38 +13,53 @@ discord_telegram_pipe = multiprocessing.Pipe() discord = multiprocessing.Process(target=discordbot.process, args=(discord_telegram_pipe[0],), daemon=True) telegram = multiprocessing.Process(target=telegrambot.process, args=(discord_telegram_pipe[1],), daemon=True) reddit = multiprocessing.Process(target=redditbot.process, daemon=True) +stats = multiprocessing.Process(target=statsupdater.process, daemon=True) if __name__ == "__main__": - logging.info("Starting Discord process...") + logging.info("Starting Discord Bot process...") discord.start() - logging.info("Starting Telegram process...") + logging.info("Starting Telegram Bot process...") telegram.start() - logging.info("Starting Reddit process...") + logging.info("Starting Reddit Bot process...") reddit.start() + logging.info("Starting StatsUpdater process...") + stats.start() try: while True: if discord.exitcode is not None: logging.warning(f"Discord Bot exited with {discord.exitcode}") del discord - logging.info("Restarting Discord process...") + logging.info("Restarting Discord Bot process...") discord = multiprocessing.Process(target=discordbot.process, args=(discord_telegram_pipe[0],), daemon=True) discord.start() if telegram.exitcode is not None: logging.warning(f"Telegram Bot exited with {telegram.exitcode}") del telegram telegram = multiprocessing.Process(target=telegrambot.process, args=(discord_telegram_pipe[1],), daemon=True) - logging.info("Restarting Telegram process...") + logging.info("Restarting Telegram Bot process...") telegram.start() if reddit.exitcode is not None: logging.warning(f"Reddit Bot exited with {reddit.exitcode}") del reddit reddit = multiprocessing.Process(target=redditbot.process, daemon=True) - logging.info("Restarting Reddit process...") - telegram.start() + logging.info("Restarting Reddit Bot process...") + reddit.start() + if stats.exitcode is not None: + logging.warning(f"StatsUpdater exited with {stats.exitcode}") + del stats + stats = multiprocessing.Process(target=statsupdater.process, daemon=True) + logging.info("Restarting StatsUpdater process...") + stats.start() time.sleep(10) except KeyboardInterrupt: logging.info("Now stopping...") logging.info("Asking Discord process to stop...") discord_telegram_pipe[0].send("stop") - logging.info("Waiting for Discord process to stop...") - time.sleep(30) + logging.info("Waiting for Discord Bot process to stop...") + discord.join() + logging.info("Waiting for Telegram Bot process to stop...") + telegram.join() + logging.info("Waiting for Reddit Bot process to stop...") + reddit.join() + logging.info("Waiting for StatsUpdater process to stop...") + stats.join() diff --git a/cast.py b/cast.py index 6028dfab..ccfb939e 100644 --- a/cast.py +++ b/cast.py @@ -1,6 +1,5 @@ import random import math -import dice def cast(spell_name: str, target_name: str, platform: str) -> str: @@ -40,6 +39,17 @@ def cast(spell_name: str, target_name: str, platform: str) -> str: else: crit_msg = "" if platform == "telegram": + if dmg_dice == 10 and dmg_max == 100 and dmg_mod == 20: + return f"❇️‼️ Ho lanciato {spell} su " \ + f"{target_name}.\n" \ + f"Una grande luce illumina il cielo, seguita poco dopo da un fungo di fumo nel luogo" \ + f" in cui si trovava {target_name}.\n" \ + f"Il fungo si espande a velocità smodata, finchè il fumo non ricopre la Terra intera e le tenebre" \ + f" cadono su di essa.\n" \ + f"Dopo qualche minuto, la temperatura ambiente raggiunge gli 0 °C, e continua a diminuire.\n" \ + f"L'Apocalisse Nucleare è giunta, e tutto per polverizzare {target_name}" \ + f" con {spell}.\n" \ + f"{target_name} subisce 10d100+20=1020 danni apocalittici!" return f"❇️ Ho lanciato {spell} su " \ f"{target_name}.\n" \ f"{crit_msg}" \ @@ -48,10 +58,21 @@ def cast(spell_name: str, target_name: str, platform: str) -> str: f"{'×' + str(crit) if crit > 1 else ''}" \ f"={total if total > 0 else 0} danni {dmg_type}!" elif platform == "discord": + if dmg_dice == 10 and dmg_max == 100 and dmg_mod == 20: + return f"❇️‼️ Ho lanciato **{spell}** su " \ + f"_{target_name}_.\n" \ + f"Una grande luce illumina il cielo, seguita poco dopo da un fungo di fumo nel luogo" \ + f" in cui si trovava _{target_name}_.\n" \ + f"Il fungo si espande a velocità smodata, finchè il fumo non ricopre la Terra intera e le tenebre" \ + f" cadono su di essa.\n" \ + f"Dopo qualche minuto, la temperatura ambiente raggiunge gli 0 °C, e continua a diminuire.\n" \ + f"L'Apocalisse Nucleare è giunta, e tutto per polverizzare _{target_name}_" \ + f" con **{spell}**.\n" \ + f"_{target_name}_ subisce 10d100+20=**1020** danni apocalittici!" return f"❇️ Ho lanciato **{spell}** su " \ f"_{target_name}_.\n" \ f"{crit_msg}" \ f"_{target_name}_ subisce {dmg_dice}d{dmg_max}" \ f"{'+' if dmg_mod > 0 else ''}{str(dmg_mod) if dmg_mod != 0 else ''}" \ f"{'×' + str(crit) if crit > 1 else ''}" \ - f"=**{total if total > 0 else 0}** danni {dmg_type}!" \ No newline at end of file + f"=**{total if total > 0 else 0}** danni {dmg_type}!" diff --git a/db.py b/db.py index bf470bf5..9a1b1fc3 100644 --- a/db.py +++ b/db.py @@ -39,7 +39,7 @@ class Royal(Base): return Royal(username=username) def __repr__(self): - return f"" + return f"" class Telegram(Base): @@ -71,7 +71,7 @@ class Telegram(Base): username=telegram_user.username) def __repr__(self): - return f"" + return f"" def mention(self): if self.username is not None: @@ -101,7 +101,9 @@ class Steam(Base): most_played_game_id = Column(BigInteger) def __repr__(self): - return f"" + if not self.persona_name: + return f"" + return f"" def __str__(self): if self.persona_name is not None: @@ -196,7 +198,7 @@ class RocketLeague(Base): wins = Column(Integer) def __repr__(self): - return f"" + return f"" def update(self, data=None): raise NotImplementedError("rlstats API is no longer available.") @@ -243,6 +245,9 @@ class Dota(Base): most_played_hero = Column(Integer) + def __repr__(self): + return f"" + def get_rank_icon_url(self): # Rank icon is determined by the first digit of the rank tier return f"https://www.opendota.com/assets/images/dota2/rank_icons/rank_icon_{str(self.rank_tier)[0] if self.rank_tier is not None else '0'}.png" @@ -293,7 +298,7 @@ class Dota(Base): new_record.update() return new_record - def update(self) -> None: + def update(self) -> bool: r = requests.get(f"https://api.opendota.com/api/players/{Steam.to_steam_id_3(self.steam_id)}") if r.status_code != 200: raise RequestError("OpenDota / returned {r.status_code}") @@ -306,10 +311,12 @@ class Dota(Base): if r.status_code != 200: raise RequestError("OpenDota /heroes returned {r.status_code}") heroes = r.json() + changed = self.rank_tier != data["rank_tier"] self.rank_tier = data["rank_tier"] self.wins = wl["win"] self.losses = wl["lose"] self.most_played_hero = heroes[0]["hero_id"] + return changed class LeagueOfLegendsRanks(enum.Enum): @@ -349,6 +356,11 @@ class LeagueOfLegends(Base): highest_mastery_champ = Column(Integer) + def __repr__(self): + if not self.summoner_name: + return f"" + return f"" + @staticmethod def create(session: Session, royal_id, summoner_name=None, summoner_id=None): if summoner_name: @@ -374,18 +386,18 @@ class LeagueOfLegends(Base): lol.update() return lol - def update(self): + def update(self) -> 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']}") if r.status_code != 200: - return RequestError(f"League of Legends API /summoner returned {r.status_code}") + raise RequestError(f"League of Legends API /summoner returned {r.status_code}") data = r.json() r = requests.get(f"https://euw1.api.riotgames.com/lol/league/v3/positions/by-summoner/{self.summoner_id}?api_key={config['League of Legends']['riot_api_key']}") if r.status_code != 200: - return RequestError(f"League of Legends API /league returned {r.status_code}") + raise RequestError(f"League of Legends API /league returned {r.status_code}") rank = r.json() r = requests.get(f"https://euw1.api.riotgames.com/lol/champion-mastery/v3/champion-masteries/by-summoner/{self.summoner_id}?api_key={config['League of Legends']['riot_api_key']}") if r.status_code != 200: - return RequestError(f"League of Legends API /champion-mastery returned {r.status_code}") + raise RequestError(f"League of Legends API /champion-mastery returned {r.status_code}") mastery = r.json() solo_rank = None flex_rank = None @@ -477,6 +489,11 @@ class Osu(Base): self.catch_pp = j2["pp_raw"] self.mania_pp = j3["pp_raw"] + def __repr__(self): + if not self.osu_name: + return f"" + return f"" + class Discord(Base): __tablename__ = "discord" @@ -494,7 +511,7 @@ class Discord(Base): return f"{self.name}#{self.discriminator}" def __repr__(self): - return f"" + return f"" @staticmethod def create(session: Session, royal_username, discord_user: DiscordUser): @@ -542,7 +559,7 @@ class Overwatch(Base): return f"{self.battletag}{separator}{self.discriminator}" def __repr__(self): - return f"" + return f"" @staticmethod def create(session: Session, royal_id, battletag, discriminator=None): @@ -614,7 +631,7 @@ class Diario(Base): text = Column(String) def __repr__(self): - return f"" + return f"" def __str__(self): return f"{self.id} - {self.timestamp} - {self.author}: {self.text}" @@ -668,7 +685,7 @@ class BaluRage(Base): reason = Column(String) def __repr__(self): - return f"" + return f"" class PlayedMusic(Base): @@ -681,7 +698,7 @@ class PlayedMusic(Base): timestamp = Column(DateTime, nullable=False) def __repr__(self): - return f"" + return f"" class VoteQuestion(Base): @@ -694,7 +711,7 @@ class VoteQuestion(Base): open = Column(Boolean, default=True) def __repr__(self): - return f"" + return f"" def generate_text(self, session: Session): text = f"{self.question}\n\n" @@ -746,7 +763,7 @@ class VoteAnswer(Base): __table_args__ = (PrimaryKeyConstraint("question_id", "user_id"),) def __repr__(self): - return f"" + return f"" class ProfileData(Base): @@ -758,6 +775,9 @@ class ProfileData(Base): css = Column(Text) bio = Column(Text) + def __repr__(self): + return f"" + class WikiEntry(Base): __tablename__ = "wikientries" @@ -765,6 +785,9 @@ class WikiEntry(Base): key = Column(String, primary_key=True) content = Column(Text, nullable=False) + def __repr__(self): + return f"" + class WikiLog(Base): __tablename__ = "wikilog" @@ -777,6 +800,9 @@ class WikiLog(Base): timestamp = Column(DateTime, nullable=False) reason = Column(Text) + def __repr__(self): + return f"" + class Event(Base): __tablename__ = "events" @@ -798,6 +824,9 @@ class Event(Base): raise TypeError("time_left should be a datetime.timedelta") self.time = datetime.datetime.now() + value + def __repr__(self): + return f"" + class Reddit(Base): __tablename__ = "reddit" @@ -808,6 +837,9 @@ class Reddit(Base): username = Column(String, primary_key=True) karma = Column(BigInteger) + def __repr__(self): + return f"" + class GameLog(Base): __tablename__ = "gamelog" @@ -822,6 +854,9 @@ class GameLog(Base): completed_games = Column(Integer) mastered_games = Column(Integer) + def __repr__(self): + return f"" + class ParsedRedditPost(Base): __tablename__ = "parsedredditposts" @@ -830,6 +865,9 @@ class ParsedRedditPost(Base): author_username = Column(String) + def __repr__(self): + return f"" + class LoginToken(Base): __tablename__ = "logintoken" @@ -840,6 +878,9 @@ class LoginToken(Base): token = Column(String, primary_key=True) expiration = Column(DateTime, nullable=False) + def __repr__(self): + return f"" + # If run as script, create all the tables in the db if __name__ == "__main__": diff --git a/discordbot.py b/discordbot.py index c69583c4..c0f0e317 100644 --- a/discordbot.py +++ b/discordbot.py @@ -1,10 +1,7 @@ import random import re -# noinspection PyPackageRequirements import discord -# noinspection PyPackageRequirements import discord.opus -# noinspection PyPackageRequirements import discord.voice_client import functools import sys @@ -15,7 +12,6 @@ import typing import os import asyncio import configparser -import subprocess import async_timeout import raven import logging @@ -25,6 +21,7 @@ import sqlalchemy.exc logging.getLogger().setLevel(level=logging.ERROR) logger = logging.getLogger(__name__) +logger.addHandler(logging.StreamHandler()) logger.setLevel(level=logging.DEBUG) # Queue emojis @@ -194,6 +191,7 @@ def command(func): result = await func(self, channel=channel, author=author, params=params, *args, **kwargs) except Exception: ei = sys.exc_info() + # noinspection PyBroadException try: await channel.send(f"☢ **ERRORE DURANTE L'ESECUZIONE DEL COMANDO {params[0]}**\n" f"Il comando è stato ignorato.\n" @@ -283,7 +281,7 @@ class RoyalDiscordBot(discord.Client): self.inactivity_timer = 0 asyncio.ensure_future(self.queue_predownload_videos()) asyncio.ensure_future(self.queue_play_next_video()) - asyncio.ensure_future(self.inactivity_timer()) + asyncio.ensure_future(self.inactivity_countdown()) async def on_ready(self): # Get the main channel @@ -461,7 +459,7 @@ class RoyalDiscordBot(discord.Client): while True: # Fun things will happen with multiple voice clients! for voice_client in self.voice_clients: - if not voice_client.is_connected() or not voice_client.is_done(): + if not voice_client.is_connected() or not voice_client.is_playing(): continue if len(self.video_queue) == 0: self.now_playing = None @@ -508,8 +506,8 @@ class RoyalDiscordBot(discord.Client): continue for voice_client in self.voice_clients: if voice_client.is_connected(): - voice_client.disconnect() - self.send_message(self.main_channel, "💤 Mi sono disconnesso dalla cv per inattività.") + await voice_client.disconnect() + await self.main_channel.send("💤 Mi sono disconnesso dalla cv per inattività.") async def add_video_from_url(self, url, index: typing.Optional[int] = None, enqueuer: discord.Member = None): # Retrieve info @@ -816,12 +814,9 @@ def process(users_connection=None): logger.info("Logging in...") loop.run_until_complete(bot.login(config["Discord"]["bot_token"], bot=True)) logger.info("Connecting...") - try: - loop.run_until_complete(bot.connect()) - except KeyboardInterrupt: - logger.info("Now stopping...") - loop.run_until_complete(bot.logout()) - exit(0) + loop.run_until_complete(bot.connect()) + logger.info("Now stopping...") + loop.run_until_complete(bot.logout()) if __name__ == "__main__": diff --git a/errors.py b/errors.py index 022ca7ec..ddc9edee 100644 --- a/errors.py +++ b/errors.py @@ -1,8 +1,10 @@ class RequestError(Exception): pass + class NotFoundError(Exception): pass + class AlreadyExistingError(Exception): pass diff --git a/redditbot.py b/redditbot.py index 46a517f3..5216bdfc 100644 --- a/redditbot.py +++ b/redditbot.py @@ -6,7 +6,6 @@ import telegram import time import raven import os -import subprocess import sys # Init the config reader @@ -15,6 +14,7 @@ config.read("config.ini") logging.getLogger().setLevel(level=logging.ERROR) logger = logging.getLogger(__name__) +logger.addHandler(logging.StreamHandler()) logger.setLevel(level=logging.DEBUG) sentry = raven.Client(config["Sentry"]["token"], diff --git a/requirements.txt b/requirements.txt index 70b981cc..bed0da61 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,3 @@ -discord.py[rewrite] python-telegram-bot flask sqlalchemy diff --git a/stagismo.py b/stagismo.py index 1adcba30..36bc9ebf 100644 --- a/stagismo.py +++ b/stagismo.py @@ -42,4 +42,4 @@ listona = ["della secca", "del seccatore", "del secchiello", "del secchio", "del "della scatola", "del supercalifragilistichespiralidoso", "del sale", "del salame", "di (Town of) Salem", "di Stronghold", "di SOMA", "dei Saints", "di S.T.A.L.K.E.R.", "di Sanctum", "dei Sims", "di Sid", "delle Skullgirls", "di Sonic", "di Spiral (Knights)", "di Spore", "di Starbound", "di SimCity", "di Sensei", - "di Ssssssssssssss... Boom! E' esploso il dizionario", "della scala"] + "di Ssssssssssssss... Boom! E' esploso il dizionario", "della scala", "di Sakura"] diff --git a/statsupdater.py b/statsupdater.py new file mode 100644 index 00000000..d9fd797f --- /dev/null +++ b/statsupdater.py @@ -0,0 +1,88 @@ +import db +import time +import logging +import raven +import configparser +import os +import typing +import telegram +import sys + +logging.getLogger().setLevel(level=logging.ERROR) +logger = logging.getLogger(__name__) +logger.addHandler(logging.StreamHandler()) +logger.setLevel(level=logging.DEBUG) + +# Init the config reader +config = configparser.ConfigParser() +config.read("config.ini") + +# Init the Sentry client +sentry = raven.Client(config["Sentry"]["token"], + release=raven.fetch_git_sha(os.path.dirname(__file__)), + install_logging_hook=False, + hook_libraries=[]) + +telegram_bot = telegram.Bot(config["Telegram"]["bot_token"]) + + +def update_block(block: list, delay: float=0, change_callback: typing.Callable=None): + for item in block: + logger.debug(f"Updating {repr(item)}.") + t = time.clock() + try: + change = item.update() + except Exception as e: + logger.error(f"Error {sys.exc_info()} while updating {repr(item)}.") + sentry.extra_context({ + "item": repr(item) + }) + sentry.captureException() + continue + if change: + change_callback(item) + sleep_time = delay - time.clock() + t + time.sleep(sleep_time if sleep_time > 0 else 0) + + +def new_dota_rank(item: db.Dota): + try: + telegram_bot.send_message(config["Telegram"]["main_group"], + f"✳️ {item.steam.royal.username} è salito a" + f" {item.get_rank_name()} {item.get_rank_number()} su Dota 2!") + except Exception: + logger.warning(f"Couldn't notify on Telegram: {item}") + + +def new_lol_rank(item: db.LeagueOfLegends): + try: + telegram_bot.send_message(config["Telegram"]["main_group"], + f"✳️ {item.royal.username} è salito di rank su League of Legends!") + except Exception: + logger.warning(f"Couldn't notify on Telegram: {item}") + + +def process(): + while True: + session = db.Session() + #logger.info("Now updating Steam data.") + #update_block(session.query(db.Steam).all()) + #session.commit() + #logger.info("Now updating Dota data.") + #update_block(session.query(db.Dota).all(), delay=1, change_callback=new_dota_rank) + #session.commit() + #logger.info("Now updating League of Legends data.") + #update_block(session.query(db.LeagueOfLegends).all(), delay=0.3, change_callback=new_lol_rank) + #session.commit() + #logger.info("Now updating osu! data.") + #update_block(session.query(db.Osu).all(), delay=0.3) + #session.commit() + logger.info("Now updating Overwatch data.") + update_block(session.query(db.Overwatch).all(), delay=1) + session.commit() + logger.info("Pausing for 30 minutes.") + time.sleep(1800) + + +if __name__ == "__main__": + process() diff --git a/telegrambot.py b/telegrambot.py index d0137c55..e4bc31b4 100644 --- a/telegrambot.py +++ b/telegrambot.py @@ -27,6 +27,7 @@ except Exception: logging.getLogger().setLevel(level=logging.ERROR) logger = logging.getLogger(__name__) +logger.addHandler(logging.StreamHandler()) logger.setLevel(level=logging.DEBUG) # Init the config reader @@ -605,18 +606,9 @@ def process(arg_discord_connection): u.dispatcher.add_handler(CommandHandler("exception", cmd_exception)) u.dispatcher.add_handler(CallbackQueryHandler(on_callback_query)) logger.info("Handlers registered.") - while True: - try: - u.start_polling() - logger.info("Polling started.") - u.idle() - except telegram.error.TimedOut: - logger.warning("Timed out, restarting in 1 minute.") - time.sleep(60) - logger.info("Now restarting...") - except KeyboardInterrupt: - logger.info("Now stopping...") - break + u.start_polling() + logger.info("Polling started.") + u.idle() if __name__ == "__main__": diff --git a/update.py b/update.py deleted file mode 100644 index f4f827ad..00000000 --- a/update.py +++ /dev/null @@ -1,126 +0,0 @@ -import db -import errors -import time - -session = None -# Stop updating if Ctrl-C is pressed -try: - while True: - session = db.Session() - # Update Steam - print("STEAM") - for user in session.query(db.Steam).all(): - t = time.clock() - print(f"Updating {user.royal.username}", end="\t\t", flush=True) - try: - user.update() - except errors.RequestError: - print("Request Error") - except errors.NotFoundError: - print("Not Found Error (?)") - else: - print("OK") - finally: - sleep_time = 1 - time.clock() + t - time.sleep(sleep_time if sleep_time > 0 else 0) - # Update Rocket League - # print("ROCKET LEAGUE") - # for user in session.query(db.RocketLeague).all(): - # t = time.clock() - # print(f"Updating {user.steam.royal.username}", end="\t\t", flush=True) - # try: - # user.update() - # except errors.RequestError: - # print("Request Error") - # except errors.NotFoundError: - # print("Not Found Error (?)") - # else: - # print("OK") - # finally: - # sleep_time = 1 - time.clock() + t - # time.sleep(sleep_time if sleep_time > 0 else 0) - # Update Dota 2 - print("DOTA 2") - for user in session.query(db.Dota).all(): - t = time.clock() - print(f"Updating {user.steam.royal.username}", end="\t\t", flush=True) - try: - user.update() - except errors.RequestError: - print("Request Error") - except errors.NotFoundError: - print("Not Found Error (?)") - else: - print("OK") - finally: - sleep_time = 1 - time.clock() + t - time.sleep(sleep_time if sleep_time > 0 else 0) - # Update League of Legends - print("LEAGUE OF LEGENDS") - for user in session.query(db.LeagueOfLegends).all(): - t = time.clock() - print(f"Updating {user.royal.username}", end="\t\t", flush=True) - try: - user.update() - except errors.RequestError: - print("Request Error") - except errors.NotFoundError: - print("Not Found Error (?)") - else: - print("OK") - finally: - sleep_time = 1 - time.clock() + t - time.sleep(sleep_time if sleep_time > 0 else 0) - # Update Osu! - print("OSU!") - for user in session.query(db.Osu).all(): - t = time.clock() - print(f"Updating {user.royal.username}", end="\t\t", flush=True) - try: - user.update() - except errors.RequestError: - print("Request Error") - except errors.NotFoundError: - print("Not Found Error (?)") - else: - print("OK") - finally: - sleep_time = 1 - time.clock() + t - time.sleep(sleep_time if sleep_time > 0 else 0) - # Update Overwatch - print("OVERWATCH") - for user in session.query(db.Overwatch).all(): - t = time.clock() - print(f"Updating {user.royal.username}", end="\t\t", flush=True) - try: - user.update() - except errors.RequestError: - print("Request Error") - except errors.NotFoundError: - print("Not Found Error (?)") - else: - print("OK") - finally: - sleep_time = 1 - time.clock() + t - time.sleep(sleep_time if sleep_time > 0 else 0) - print("Committing...", end="\t\t") - session.commit() - print("OK") - print("Closing...", end="\n\n") - session.close() - print("OK") - print("Waiting 1800s...", end="\t\t") - for i in range(0, 20): - time.sleep(90) - print("█", end="") -except KeyboardInterrupt: - pass -finally: - print("Committing...", end="\t\t") - session.commit() - print("OK") - print("Closing...") - try: - session.close() - except Exception: - print("Maybe") diff --git a/webserver.py b/webserver.py index 8d0fabb6..9687c23b 100644 --- a/webserver.py +++ b/webserver.py @@ -88,6 +88,7 @@ def page_profile(name: str): ow = db_session.query(db.Overwatch).filter_by(royal=user).one_or_none() tg = db_session.query(db.Telegram).filter_by(royal=user).one_or_none() discord = db_session.execute(query_discord_music.one_query, {"royal": user.id}).fetchone() + gamelog = db_session.query(db.GameLog).filter_by(royal=user).one_or_none() db_session.close() if css is not None: converted_bio = Markup(markdown2.markdown(css.bio.replace("<", "<"), @@ -95,7 +96,7 @@ def page_profile(name: str): else: converted_bio = "" return render_template("profile.html", ryg=user, css=css, osu=osu, dota=dota, lol=lol, steam=steam, ow=ow, - tg=tg, discord=discord, rygconf=config, bio=converted_bio) + tg=tg, discord=discord, rygconf=config, bio=converted_bio, gamelog=gamelog) @app.route("/login") @@ -205,7 +206,8 @@ def page_game(name: str): query = db_session.query(db.Dota).join(db.Steam).order_by(db.Dota.rank_tier.desc().nullslast()).all() elif name == "lol": game_name = "League of Legends" - query = db_session.query(db.LeagueOfLegends).order_by(db.LeagueOfLegends.solo_division.desc().nullslast()).all() + query = db_session.query(db.LeagueOfLegends).order_by(db.LeagueOfLegends.solo_division.desc().nullslast(), + db.LeagueOfLegends.solo_rank).all() elif name == "osu": game_name = "osu!" query = db_session.query(db.Osu).order_by(db.Osu.mania_pp.desc().nullslast()).all()