1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00
royalnet/statsupdate.py

178 lines
7.5 KiB
Python
Raw Normal View History

2018-09-17 22:07:00 +00:00
import db
import time
import logging
import raven
import configparser
import os
import typing
2019-01-02 20:10:54 +00:00
# python-telegram-bot has a different name
# noinspection PyPackageRequirements
2018-09-17 22:07:00 +00:00
import telegram
import sys
2018-09-17 22:26:01 +00:00
import coloredlogs
2019-01-02 18:37:05 +00:00
import requests
2019-03-01 16:28:25 +00:00
import strings
from utils import Dirty, DirtyDelta, reply_msg
2018-09-17 22:07:00 +00:00
2018-09-18 22:02:39 +00:00
logging.getLogger().disabled = True
2018-09-17 22:07:00 +00:00
logger = logging.getLogger(__name__)
2018-09-18 22:13:41 +00:00
os.environ["COLOREDLOGS_LOG_FORMAT"] = "%(asctime)s %(levelname)s %(name)s %(message)s"
2018-09-17 22:26:01 +00:00
coloredlogs.install(level="DEBUG", logger=logger)
2018-09-17 22:07:00 +00:00
# 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"])
2019-03-01 16:28:25 +00:00
main_chat_id = config["Telegram"]["main_group"]
2018-09-17 22:07:00 +00:00
2019-02-11 11:29:21 +00:00
def update_block(session: db.Session, block: list, delay: float = 0, change_callback: typing.Callable = None):
2018-09-17 22:07:00 +00:00
for item in block:
logger.debug(f"Updating {repr(item)}.")
t = time.clock()
try:
2018-10-07 22:42:45 +00:00
change = item.update(session=session)
2019-01-02 18:37:05 +00:00
except requests.exceptions.HTTPError as e:
2019-02-28 20:25:24 +00:00
logger.error(f"Error {sys.exc_info()} while updating {repr(item)}.")
2019-01-02 18:37:05 +00:00
sentry.extra_context({
"item": repr(item),
"response": {
"code": e.response.status_code,
"text": e.response.text
}
})
sentry.captureException()
continue
2019-01-02 20:10:54 +00:00
except Exception:
2018-11-07 18:41:49 +00:00
logger.warning(f"Error {sys.exc_info()} while updating {repr(item)}.")
2018-09-17 22:07:00 +00:00
sentry.extra_context({
"item": repr(item)
})
sentry.captureException()
continue
if change:
2018-12-18 16:34:34 +00:00
change_callback(item, change)
2018-09-17 22:07:00 +00:00
sleep_time = delay - time.clock() + t
time.sleep(sleep_time if sleep_time > 0 else 0)
2019-01-02 20:10:54 +00:00
# noinspection PyUnusedLocal
2018-12-18 16:34:34 +00:00
def new_dota_rank(item: db.Dota, change):
2018-09-17 22:07:00 +00:00
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}")
2019-01-23 14:12:18 +00:00
sentry.captureException()
2018-09-17 22:07:00 +00:00
2019-01-23 14:00:30 +00:00
def new_lol_rank(item, change: typing.Tuple[Dirty, Dirty, Dirty]):
2018-12-18 16:34:34 +00:00
# It always gets called, even when there is no change
solo, flex, twtr = change
2018-09-17 22:07:00 +00:00
try:
2018-12-18 16:34:34 +00:00
if solo:
telegram_bot.send_message(config["Telegram"]["main_group"],
2019-01-02 20:10:54 +00:00
f"✳️ {item.royal.username} ha un nuovo rank in **SOLO/DUO**"
f" su League of Legends!\n"
f"{solo.initial_value[0]} {solo.initial_value[1]} ->"
f" **{solo.value[0]} {solo.value[1]}**",
2018-12-18 16:34:34 +00:00
parse_mode="Markdown")
if flex:
telegram_bot.send_message(config["Telegram"]["main_group"],
2019-01-02 20:10:54 +00:00
f"✳️ {item.royal.username} ha un nuovo rank in **FLEX**"
f" su League of Legends!\n"
f"{flex.initial_value[0]} {flex.initial_value[1]} ->"
f" **{flex.value[0]} {flex.value[1]}**",
2018-12-18 16:34:34 +00:00
parse_mode="Markdown")
if twtr:
telegram_bot.send_message(config["Telegram"]["main_group"],
2019-01-02 20:10:54 +00:00
f"✳️ {item.royal.username} ha un nuovo rank in **3V3**"
f" su League of Legends!\n"
f"{twtr.initial_value[0]} {twtr.initial_value[1]} ->"
f" **{twtr.value[0]} {twtr.value[1]}**",
2018-12-18 16:34:34 +00:00
parse_mode="Markdown")
2018-09-17 22:07:00 +00:00
except Exception:
logger.warning(f"Couldn't notify on Telegram: {item}")
2019-01-23 14:12:18 +00:00
sentry.captureException()
2019-01-23 14:00:30 +00:00
def osu_pp_change(item, change: typing.Tuple[DirtyDelta, DirtyDelta, DirtyDelta, DirtyDelta]):
std, taiko, catch, mania = change
try:
if std.delta >= 1:
telegram_bot.send_message(config["Telegram"]["main_group"],
2019-01-23 18:41:29 +00:00
f"✳️ {item.royal.username} ha ora <b>{int(std.value)}pp</b> (+{int(std.delta)}) su osu!",
parse_mode="HTML")
2019-01-23 14:00:30 +00:00
if taiko.delta >= 1:
telegram_bot.send_message(config["Telegram"]["main_group"],
2019-01-23 18:41:29 +00:00
f"✳️ {item.royal.username} ha ora <b>{int(taiko.value)}pp</b> (+{int(taiko.delta)}) su osu!taiko!",
parse_mode="HTML")
2019-01-23 14:00:30 +00:00
if catch.delta >= 1:
telegram_bot.send_message(config["Telegram"]["main_group"],
2019-01-23 18:41:29 +00:00
f"✳️ {item.royal.username} ha ora <b>{int(catch.value)}pp</b> (+{int(catch.delta)}) su osu!catch!",
parse_mode="HTML")
2019-01-23 14:00:30 +00:00
if mania.delta >= 1:
telegram_bot.send_message(config["Telegram"]["main_group"],
2019-01-23 18:41:29 +00:00
f"✳️ {item.royal.username} ha ora <b>{int(mania.value)}pp</b> (+{int(mania.delta)}) su osu!mania!",
parse_mode="HTML")
2019-01-23 14:00:30 +00:00
except Exception:
logger.warning(f"Couldn't notify on Telegram: {item}")
2019-01-23 14:12:18 +00:00
sentry.captureException()
2018-09-17 22:07:00 +00:00
2019-03-01 16:28:25 +00:00
def brawlhalla_rank_change(item, change: typing.Tuple[DirtyDelta, Dirty]):
solo, team = change
try:
if solo.delta >= 10:
reply_msg(telegram_bot, main_chat_id, strings.STATSUPDATE.BRAWLHALLA.SOLO,
username=item.steam.royal.username,
rating=solo.value,
2019-03-05 09:03:43 +00:00
delta=solo.delta_string())
2019-03-01 16:28:25 +00:00
if team.is_dirty():
2019-03-01 17:00:12 +00:00
partner = item.best_team_partner
if partner is None:
other = "???"
else:
other = partner.steam.royal.username
2019-03-01 16:28:25 +00:00
reply_msg(telegram_bot, main_chat_id, strings.STATSUPDATE.BRAWLHALLA.TEAM,
username=item.steam.royal.username,
2019-03-01 17:07:22 +00:00
rating=team.value[1],
2019-03-01 17:00:12 +00:00
other=other)
2019-03-01 16:28:25 +00:00
except Exception:
logger.warning(f"Couldn't notify on Telegram: {item}")
sentry.captureException()
2018-09-17 22:07:00 +00:00
def process():
while True:
session = db.Session()
2019-03-01 16:28:25 +00:00
logger.info("Now updating League of Legends data.")
update_block(session, session.query(db.Brawlhalla).all(), delay=5, change_callback=brawlhalla_rank_change)
session.commit()
2019-01-23 14:09:27 +00:00
logger.info("Now updating osu! data.")
update_block(session, session.query(db.Osu).all(), delay=5, change_callback=osu_pp_change)
session.commit()
2018-09-17 22:11:28 +00:00
logger.info("Now updating Steam data.")
2018-10-07 22:42:45 +00:00
update_block(session, session.query(db.Steam).all())
2018-09-17 22:11:28 +00:00
session.commit()
logger.info("Now updating Dota data.")
2018-10-07 22:42:45 +00:00
update_block(session, session.query(db.Dota).all(), delay=5, change_callback=new_dota_rank)
2018-09-17 22:11:28 +00:00
session.commit()
logger.info("Now updating League of Legends data.")
2018-10-07 22:42:45 +00:00
update_block(session, session.query(db.LeagueOfLegends).all(), delay=5, change_callback=new_lol_rank)
2018-09-17 22:11:28 +00:00
session.commit()
2018-12-18 18:34:34 +00:00
logger.info("Pausing for 30 minutes.")
time.sleep(1800)
2018-09-17 22:07:00 +00:00
if __name__ == "__main__":
process()