From 12382e9c790e847cf68444aab63f7c2de89afd8b Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Thu, 25 Jan 2018 15:24:17 +0100 Subject: [PATCH] ho regalato undertale al papa --- bots.py | 6 +++ db.py | 66 ++++++++++++++++++------- discordbot.py | 6 ++- stagismo.py | 1 + static/royal.css | 23 +++++++++ telegrambot.py | 96 +++++++++++++++++++++++++++++++++++-- templates/diario.html | 44 +++++++++++++++++ templates/index.html | 30 ++++++++++++ templates/leaderboards.html | 3 ++ webserver.py | 23 ++++++--- 10 files changed, 270 insertions(+), 28 deletions(-) create mode 100644 stagismo.py create mode 100644 templates/diario.html create mode 100644 templates/index.html diff --git a/bots.py b/bots.py index 7fa97f74..b3bdd464 100644 --- a/bots.py +++ b/bots.py @@ -13,6 +13,12 @@ if __name__ == "__main__": while True: if discord.exitcode is not None: print("Restarting Discord Bot...") + del discord discord = multiprocessing.Process(target=discordbot.process, args=(discord_telegram_pipe[0],), daemon=True) discord.start() + if telegram.exitcode is not None: + print("Restarting Telegram Bot...") + del telegram + telegram = multiprocessing.Process(target=telegrambot.process, args=(discord_telegram_pipe[1],), daemon=True) + telegram.start() time.sleep(60) \ No newline at end of file diff --git a/db.py b/db.py index fbff18dd..1620ec25 100644 --- a/db.py +++ b/db.py @@ -41,7 +41,7 @@ class Telegram(Base): __tablename__ = "telegram" royal_id = Column(Integer, ForeignKey("royals.id"), nullable=False) - royal = relationship("Royal") + royal = relationship("Royal", lazy="joined") telegram_id = Column(BigInteger, primary_key=True) first_name = Column(String, nullable=False) @@ -82,7 +82,7 @@ class Steam(Base): __tablename__ = "steam" royal_id = Column(Integer, ForeignKey("royals.id"), nullable=False) - royal = relationship("Royal") + royal = relationship("Royal", lazy="joined") steam_id = Column(String, primary_key=True) persona_name = Column(String, nullable=False) @@ -150,7 +150,7 @@ class RocketLeague(Base): __tablename__ = "rocketleague" steam_id = Column(String, ForeignKey("steam.steam_id"), primary_key=True) - steam = relationship("Steam") + steam = relationship("Steam", lazy="joined") season = Column(Integer) @@ -249,7 +249,7 @@ class Dota(Base): __tablename__ = "dota" steam_id = Column(String, ForeignKey("steam.steam_id"), primary_key=True) - steam = relationship("Steam") + steam = relationship("Steam", lazy="joined") rank_tier = Column(Integer) @@ -348,7 +348,7 @@ class LeagueOfLegends(Base): __tablename__ = "leagueoflegends" royal_id = Column(Integer, ForeignKey("royals.id"), nullable=False) - royal = relationship("Royal") + royal = relationship("Royal", lazy="joined") summoner_id = Column(BigInteger, primary_key=True) summoner_name = Column(String, nullable=False) @@ -432,7 +432,7 @@ class Osu(Base): __tablename__ = "osu" royal_id = Column(Integer, ForeignKey("royals.id"), nullable=False) - royal = relationship("Royal") + royal = relationship("Royal", lazy="joined") osu_id = Column(Integer, primary_key=True) osu_name = Column(String, nullable=False) @@ -490,7 +490,7 @@ class Discord(Base): __table_args__ = tuple(UniqueConstraint("name", "discriminator")) royal_id = Column(Integer, ForeignKey("royals.id"), nullable=False) - royal = relationship("Royal") + royal = relationship("Royal", lazy="joined") discord_id = Column(BigInteger, primary_key=True) name = Column(String, nullable=False) @@ -534,7 +534,7 @@ class Overwatch(Base): __tablename__ = "overwatch" royal_id = Column(Integer, ForeignKey("royals.id"), nullable=False) - royal = relationship("Royal") + royal = relationship("Royal", lazy="joined") battletag = Column(String, primary_key=True) discriminator = Column(Integer, primary_key=True) @@ -599,9 +599,9 @@ class Diario(Base): id = Column(Integer, primary_key=True) timestamp = Column(DateTime, nullable=False) saver_id = Column(Integer, ForeignKey("telegram.telegram_id")) - saver = relationship("Telegram", foreign_keys=saver_id) + saver = relationship("Telegram", foreign_keys=saver_id, lazy="joined") author_id = Column(Integer, ForeignKey("telegram.telegram_id")) - author = relationship("Telegram", foreign_keys=author_id) + author = relationship("Telegram", foreign_keys=author_id, lazy="joined") text = Column(String) def __repr__(self): @@ -616,20 +616,52 @@ class Diario(Base): session = Session() file = open(file, "r") j = json.load(file) - for entry in j: - if "sender" in entry: - author = session.query(Telegram).filter_by(username=entry["sender"].lstrip("@")).first() - else: - author = None + author_ids = { + "@Steffo": 25167391, + "@GoodBalu": 19611986, + "@gattopandacorno": 200821462, + "@Albertino04": 131057096, + "@Francesco_Cuoghi": 48371848, + "@VenomousDoc": 48371848, + "@MaxSensei": 1258401, + "@Protoh": 125711787, + "@McspKap": 304117728, + "@FrankRekt": 31436195, + "@EvilBalu": 26842090, + "@Dailir": 135816455, + "@Paltri": 186843362, + "@Doom_darth_vader": 165792255, + "@httpIma": 292086686, + "@DavidoMessori": 509208316, + "@DavidoNiichan": 509208316, + "@Peraemela99": 63804599, + "@infopz": 20403805, + "@Baithoven": 121537369, + "@Tauei": 102833717 + } + for n, entry in enumerate(j): + author = author_ids[entry["sender"]] if "sender" in entry and entry["sender"] in author_ids else None d = Diario(timestamp=datetime.datetime.fromtimestamp(float(entry["timestamp"])), - author=author, + author_id=author, text=entry["text"]) - print(d) + print(f"{n} - {d}") session.add(d) session.commit() session.close() +class BaluRage(Base): + __tablename__ = "balurage" + + id = Column(Integer, primary_key=True) + royal_id = Column(Integer, ForeignKey("royals.id")) + royal = relationship("Royal", lazy="joined") + reason = Column(String) + + def __repr__(self): + return f"" + + # If run as script, create all the tables in the db if __name__ == "__main__": Base.metadata.create_all(bind=engine) \ No newline at end of file diff --git a/discordbot.py b/discordbot.py index 2616d0b9..cfaa072c 100644 --- a/discordbot.py +++ b/discordbot.py @@ -8,6 +8,7 @@ import db import errors import youtube_dl import concurrent.futures +import stagismo # Init the event loop import asyncio @@ -286,7 +287,7 @@ async def on_message(message: discord.Message): voice_player = None await client.send_message(message.channel, f"⏹ Riproduzione interrotta e playlist svuotata.") elif message.content.startswith("!np"): - if voice_player is None: + if voice_player is None or not voice_player.is_playing(): await client.send_message(message.channel, f"ℹ Non c'è nulla in riproduzione al momento.") return await client.send_message(message.channel, f"▶️ Ora in riproduzione in <#{voice_client.channel.id}>:", embed=voice_playing.create_embed()) @@ -323,6 +324,9 @@ async def on_message(message: discord.Message): for dice in range(0, dmg_dice): total += random.randrange(1, dmg_max+1) await client.send_message(message.channel, f"❇️ Ho lanciato **{spell}** su **{target.nick if target.nick is not None else target.name}** per {dmg_dice}d{dmg_max}{'+' if dmg_mod > 0 else ''}{str(dmg_mod) if dmg_mod != 0 else ''}=**{total if total > 0 else 0}** danni!") + elif message.content.startswith("!smecds"): + ds = random.sample(stagismo.listona, 1)[0] + await client.send_message(message.channel, f"Secondo me, è colpa {ds}.", tts=True) elif __debug__ and message.content.startswith("!exception"): raise Exception("!exception was called") diff --git a/stagismo.py b/stagismo.py new file mode 100644 index 00000000..6ffb1b49 --- /dev/null +++ b/stagismo.py @@ -0,0 +1 @@ +listona = ["della secca", "del seccatore", "del secchiello", "del secchio", "del secchione", "del secondino", "del sedano", "del sedativo", "della sedia", "del sedicente", "del sedile", "della sega", "del segale", "della segatura", "della seggiola", "del seggiolino", "della seggiovia", "della segheria", "del seghetto", "del segnalibro", "del segnaposto", "del segno", "del segretario", "della segreteria", "del seguace", "del segugio", "della selce", "della sella", "della selz", "della selva", "della selvaggina", "del semaforo", "del seme", "del semifreddo", "del seminario", "della seminarista", "della semola", "del semolino", "del semplicione", "della senape", "del senatore", "del seno", "del sensore", "della sentenza", "della sentinella", "del sentore", "della seppia", "del sequestratore", "della serenata", "del sergente", "del sermone", "della serpe", "del serpente", "della serpentina", "della serra", "del serraglio", "del serramanico", "della serranda", "della serratura", "del servitore", "della servitù", "del servizievole", "del servo", "del set", "della seta", "della setola", "del sidecar", "del siderurgico", "del sidro", "della siepe", "del sifone", "della sigaretta", "del sigaro", "del sigillo", "della signora", "della signorina", "del silenziatore", "della silhouette", "del silicio", "del silicone", "del siluro", "della sinagoga", "della sindacalista", "del sindacato", "del sindaco", "della sindrome", "della sinfonia", "del sipario", "del sire", "della sirena", "della siringa", "del sismografo", "del sobborgo", "del sobillatore", "del sobrio", "del soccorritore", "del socio", "del sociologo", "della soda", "del sofà", "della soffitta", "del software", "dello sogghignare", "del soggiorno", "della sogliola", "del sognatore", "della soia", "del solaio", "del solco", "del soldato", "del soldo", "del sole", "della soletta", "della solista", "del solitario", "del sollazzare", "del sollazzo", "del sollecito", "del solleone", "del solletico", "del sollevare", "del sollievo", "del solstizio", "del solubile", "del solvente", "della soluzione", "del somaro", "del sombrero", "del sommergibile", "del sommo", "della sommossa", "del sommozzatore", "del sonar", "della sonda", "del sondaggio", "del sondare", "del sonnacchioso", "del sonnambulo", "del sonnellino", "del sonnifero", "del sonno", "della sonnolenza", "del sontuoso", "del soppalco", "del soprabito", "del sopracciglio", "del sopraffare", "del sopraffino", "del sopraluogo", "del sopramobile", "del soprannome", "del soprano", "del soprappensiero", "del soprassalto", "del soprassedere", "del sopravvento", "del sopravvivere", "del soqquadro", "del sorbetto", "del sordido", "della sordina", "del sordo", "della sorella", "della sorgente", "del sornione", "del sorpasso", "della sorpresa", "del sorreggere", "del sorridere", "della sorsata", "del sorteggio", "del sortilegio", "del sorvegliante", "del sorvolare", "del sosia", "del sospettoso", "del sospirare", "della sosta", "della sostanza", "del sostegno", "del sostenitore", "del sostituto", "del sottaceto", "della sottana", "del sotterfugio", "del sotterraneo", "del sottile", "del sottilizzare", "del sottintendere", "del sottobanco", "del sottobosco", "del sottomarino", "del sottopassaggio", "del sottoposto", "del sottoscala", "della sottoscrizione", "del sottostare", "del sottosuolo", "del sottotetto", "del sottotitolo", "del sottovalutare", "del sottovaso", "della sottoveste", "del sottovuoto", "del sottufficiale", "della soubrette", "del souvenir", "del soverchiare", "del sovrano", "del sovrapprezzo", "della sovvenzione", "del sovversivo", "del sozzo", "dello suadente", "del sub", "del subalterno", "del subbuglio", "del subdolo", "del sublime", "del suburbano", "del successore", "del succo", "della succube", "del succulento", "della succursale", "del sudario", "della sudditanza", "del suddito", "del sudicio", "del suffisso", "del suffragio", "del suffumigio", "del suggeritore", "del sughero", "del sugo", "del suino", "della suite", "del sulfureo", "del sultano", "di Steffo", "di Spaggia", "di Sabrina", "del sas", "del ses", "del sis", "del sos", "del sus", "della supremazia", "del Santissimo", "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"] \ No newline at end of file diff --git a/static/royal.css b/static/royal.css index a2050f10..f3445d9e 100644 --- a/static/royal.css +++ b/static/royal.css @@ -73,4 +73,27 @@ table.dota th { th { cursor: pointer !important; +} + +.scatola { + background-color: #fff2cc; + border-radius: 5px; + padding-left: 12px; + padding-right: 12px; + margin-left: 5px; + margin-right: 5px; + font-size: large; +} + +.diario-entry { + margin-top: 8px; + margin-bottom: 8px; +} + +.diario-data { + font-size: small; +} + +.timestamp-data { + text-align: right; } \ No newline at end of file diff --git a/telegrambot.py b/telegrambot.py index cee4f14e..39d6a065 100644 --- a/telegrambot.py +++ b/telegrambot.py @@ -1,9 +1,9 @@ +import datetime import random - import math - import db import errors +import stagismo from telegram import Bot, Update, Message from telegram.ext import Updater, CommandHandler from discord import Status as DiscordStatus @@ -34,6 +34,7 @@ def cmd_register(bot: Bot, update: Update): username = update.message.text.split(" ", 1)[1] except IndexError: bot.send_message(update.message.chat.id, "⚠️ Non hai specificato un username!") + session.close() return try: t = db.Telegram.create(session, @@ -41,6 +42,7 @@ def cmd_register(bot: Bot, update: Update): telegram_user=update.message.from_user) except errors.AlreadyExistingError: bot.send_message(update.message.chat.id, "⚠ Il tuo account Telegram è già collegato a un account RYG o l'account RYG che hai specificato è già collegato a un account Telegram.") + session.close() return session.add(t) session.commit() @@ -139,7 +141,86 @@ def cmd_cast(bot: Bot, update: Update): total = dmg_mod for dice in range(0, dmg_dice): total += random.randrange(1, dmg_max + 1) - bot.send_message(update.message.chat.id, f"❇️ Ho lanciato {spell} su @​{target.username if target.username is not None else target.first_name} per {dmg_dice}d{dmg_max}{'+' if dmg_mod > 0 else ''}{str(dmg_mod) if dmg_mod != 0 else ''}={total if total > 0 else 0} danni!") + bot.send_message(update.message.chat.id, f"❇️ Ho lanciato {spell} su {target.username if target.username is not None else target.first_name} per {dmg_dice}d{dmg_max}{'+' if dmg_mod > 0 else ''}{str(dmg_mod) if dmg_mod != 0 else ''}={total if total > 0 else 0} danni!") + + +def cmd_color(bot: Bot, update: Update): + bot.send_message(update.message.chat.id, "I am sorry, unknown error occured during working with your request, Admin were notified") + + +def cmd_smecds(bot: Bot, update: Update): + ds = random.sample(stagismo.listona, 1)[0] + bot.send_message(update.message.chat.id, f"Secondo me, è colpa {ds}.") + + +def cmd_ciaoruozi(bot: Bot, update: Update): + if update.message.from_user.username.lstrip("@") == "MeStakes": + bot.send_message(update.message.chat.id, "Ciao me!") + else: + bot.send_message(update.message.chat.id, "Ciao Ruozi!") + + +def cmd_ahnonlosoio(bot: Bot, update: Update): + if update.message.reply_to_message is not None and update.message.reply_to_message.text in ["/ahnonlosoio", "/ahnonlosoio@royalgamesbot", "Ah, non lo so io!"]: + bot.send_message(update.message.chat.id, "Ah, non lo so neppure io!") + else: + bot.send_message(update.message.chat.id, "Ah, non lo so io!") + + +def cmd_balurage(bot: Bot, update: Update): + session = db.Session() + try: + user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none() + if user is None: + bot.send_message(update.message.chat.id, "⚠ Il tuo account Telegram non è registrato al RYGdb! Registrati con `/register@royalgamesbot `.") + return + try: + reason = update.message.text.split(" ", 1)[1] + except IndexError: + reason = None + br = db.BaluRage(royal_id=user.royal_id, reason=reason) + session.add(br) + session.commit() + bot.send_message(update.message.chat.id, f"😡 Stai sfogando la tua ira sul bot!") + except Exception as e: + raise + finally: + session.close() + + +def cmd_diario(bot: Bot, update: Update): + session = db.Session() + try: + user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none() + if user is None: + bot.send_message(update.message.chat.id, "⚠ Il tuo account Telegram non è registrato al RYGdb! Registrati con `/register@royalgamesbot `.") + return + try: + text = update.message.text.split(" ", 1)[1] + author = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none() + saver = author + except IndexError: + if update.message.reply_to_message is None: + bot.send_message(update.message.chat.id, f"⚠ Non hai specificato cosa aggiungere al diario! Puoi rispondere `/diario@royalgamesbot` al messaggio che vuoi salvare nel diario oppure scrivere `/diario@royalgamesbot ` per aggiungere quel messaggio nel diario.\n" + f"Se l'hai fatto, e continua a comparire questo errore, allora Telegram è stupido e non mi vuole far vedere il messaggio a cui hai risposto.") + return + text = update.message.reply_to_message.text + author = session.query(db.Telegram).filter_by(telegram_id=update.message.reply_to_message.from_user.id).one_or_none() + saver = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none() + if text is None: + bot.send_message(update.message.chat.id, f"⚠ Il messaggio a cui hai risposto non contiene testo.") + return + diario = db.Diario(timestamp=datetime.datetime.now(), + saver=saver, + author=author, + text=text) + session.add(diario) + session.commit() + bot.send_message(update.message.chat.id, f"✅ Aggiunto al diario!") + except Exception: + raise + finally: + session.close() def process(arg_discord_connection): @@ -150,9 +231,16 @@ def process(arg_discord_connection): u = Updater(config["Telegram"]["bot_token"]) u.dispatcher.add_handler(CommandHandler("register", cmd_register)) u.dispatcher.add_handler(CommandHandler("discord", cmd_discord)) + u.dispatcher.add_handler(CommandHandler("cv", cmd_discord)) u.dispatcher.add_handler(CommandHandler("cast", cmd_cast)) + u.dispatcher.add_handler(CommandHandler("color", cmd_color)) + u.dispatcher.add_handler(CommandHandler("smecds", cmd_smecds)) + u.dispatcher.add_handler(CommandHandler("ciaoruozi", cmd_ciaoruozi)) + u.dispatcher.add_handler(CommandHandler("ahnonlosoio", cmd_ahnonlosoio)) + u.dispatcher.add_handler(CommandHandler("balurage", cmd_balurage)) + u.dispatcher.add_handler(CommandHandler("diario", cmd_diario)) u.start_polling() u.idle() if __name__ == "__main__": - process(None) + process(None) \ No newline at end of file diff --git a/templates/diario.html b/templates/diario.html new file mode 100644 index 00000000..a5047b4d --- /dev/null +++ b/templates/diario.html @@ -0,0 +1,44 @@ + + + + + + Diario - RYG + + + + +
+

+ Diario Royal Games +

+ {% for entry in diario_data %} +
+
+
+ {% if entry.author %} +
+ {{ entry.author.royal.username }} +
+ {% endif %} + {% if entry.saver %} +
+ {{ entry.saver.royal.username }} +
+ {% endif %} +
+
+
+ {{ entry.timestamp.ctime() }} +
+
+
+
+ {{ entry.text }} +
+
+ {% endfor %} +
+ + \ No newline at end of file diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 00000000..cfe29f48 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,30 @@ + + + + + + Index - RYG + + + + +
+

+ Royal Games +

+

+ Prima o poi, qui ci sarà un sito bellissimo. + Molto poi che prima, secondo me. + Probabilmente farà prima ad uscire Half-Life 3 che il sito della Royal Games, ma almeno l'intenzione c'è. +

+
+ Queste sono le pagine che sono più o meno finite: + +
+
+ + \ No newline at end of file diff --git a/templates/leaderboards.html b/templates/leaderboards.html index 6f53ee4a..787602e4 100644 --- a/templates/leaderboards.html +++ b/templates/leaderboards.html @@ -14,6 +14,9 @@

Royal Games Leaderboards

+
+ Le classifiche si aggiornano ogni orga +

Dota 2 diff --git a/webserver.py b/webserver.py index 0f0f33d7..ecc24d72 100644 --- a/webserver.py +++ b/webserver.py @@ -1,5 +1,5 @@ from flask import Flask, render_template -from db import Session, Royal, Steam, RocketLeague, Dota, Osu, Overwatch, LeagueOfLegends +from db import Session, Royal, Steam, RocketLeague, Dota, Osu, Overwatch, LeagueOfLegends, Diario, Telegram from sqlalchemy.orm import joinedload app = Flask(__name__) @@ -7,14 +7,25 @@ app = Flask(__name__) app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True +@app.route("/") +def page_index(): + return render_template("index.html") + +@app.route("/diario") +def page_diario(): + session = Session() + diario_data = session.query(Diario).outerjoin((Telegram, Diario.author), aliased=True).outerjoin(Royal, aliased=True).outerjoin((Telegram, Diario.saver), aliased=True).outerjoin(Royal, aliased=True).all() + session.close() + return render_template("diario.html", diario_data=diario_data) + @app.route("/leaderboards") def page_leaderboards(): session = Session() - dota_data = session.query(Dota).options(joinedload(Dota.steam).joinedload(Steam.royal)).join(Steam).join(Royal).order_by(Dota.rank_tier).all() - rl_data = session.query(RocketLeague).options(joinedload(RocketLeague.steam).joinedload(Steam.royal)).join(Steam).join(Royal).order_by(RocketLeague.doubles_mmr).all() - ow_data = session.query(Overwatch).options(joinedload(Overwatch.royal)).join(Royal).order_by(Overwatch.rank).all() - osu_data = session.query(Osu).options(joinedload(Osu.royal)).join(Royal).order_by(Osu.std_pp).all() - lol_data = session.query(LeagueOfLegends).options(joinedload(LeagueOfLegends.royal)).join(Royal).order_by(LeagueOfLegends.summoner_name).all() + dota_data = session.query(Dota).join(Steam).join(Royal).order_by(Dota.rank_tier).all() + rl_data = session.query(RocketLeague).join(Steam).join(Royal).order_by(RocketLeague.doubles_mmr).all() + ow_data = session.query(Overwatch).join(Royal).order_by(Overwatch.rank).all() + osu_data = session.query(Osu).join(Royal).order_by(Osu.std_pp).all() + lol_data = session.query(LeagueOfLegends).join(Royal).order_by(LeagueOfLegends.summoner_name).all() session.close() return render_template("leaderboards.html", dota_data=dota_data, rl_data=rl_data, ow_data=ow_data, osu_data=osu_data, lol_data=lol_data)