From aae8cb90ff1eec89ae7093ed6c35106a5a7665a4 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Mon, 12 Mar 2018 13:29:12 +0100 Subject: [PATCH] a lot of stuff --- db.py | 8 ++++---- discordbot.py | 27 +++++++++++++++------------ requirements.txt | 4 +++- templates/music.html | 27 +++++++++++++++++++++++++-- webserver.py | 11 ++++++++--- 5 files changed, 55 insertions(+), 22 deletions(-) diff --git a/db.py b/db.py index 675236a2..ef17bcd3 100644 --- a/db.py +++ b/db.py @@ -497,7 +497,7 @@ class Discord(Base): avatar_hex = Column(String) def __str__(self): - return f"{self.username}#{self.discriminator}" + return f"{self.name}#{self.discriminator}" def __repr__(self): return f"" @@ -526,7 +526,7 @@ class Discord(Base): def avatar_url(self, size=256): if self.avatar_hex is None: return "https://discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png" - return f"https://cdn.discordapp.com/avatars/{self.id}/{self.avatar}.png?size={size}" + return f"https://cdn.discordapp.com/avatars/{self.discord_id}/{self.avatar_hex}.png?size={size}" class Overwatch(Base): @@ -665,8 +665,8 @@ class PlayedMusic(Base): __tablename__ = "playedmusic" id = Column(Integer, primary_key=True) - enqueuer_id = Column(Integer, ForeignKey("royals.id")) - enqueuer = relationship("Royal", lazy="joined") + enqueuer_id = Column(BigInteger, ForeignKey("discord.discord_id")) + enqueuer = relationship("Discord", lazy="joined") filename = Column(String) def __repr__(self): diff --git a/discordbot.py b/discordbot.py index 0dab0c86..5e52c332 100644 --- a/discordbot.py +++ b/discordbot.py @@ -27,12 +27,14 @@ loop = asyncio.get_event_loop() config = configparser.ConfigParser() config.read("config.ini") + async def find_user(user: discord.User): session = await loop.run_in_executor(executor, db.Session) user = await loop.run_in_executor(executor, session.query(db.Discord).filter_by(discord_id=user.id).join(db.Royal).first) await loop.run_in_executor(executor, session.close) return user + class DurationError(Exception): pass @@ -44,12 +46,11 @@ class Video: self.ytdl_url = None @staticmethod - async def init(user, filename=None, ytdl_url=None): + async def init(user_id: str, *, filename=None, ytdl_url=None): if filename is None and ytdl_url is None: raise Exception("Filename or url must be specified") self = Video() - discord_user = await find_user(user) - self.enqueuer = discord_user.royal if discord_user is not None else None + self.enqueuer = int(user_id) self.filename = filename self.ytdl_url = ytdl_url return self @@ -61,7 +62,7 @@ class Video: if "entries" in info: info = info["entries"][0] file_id = info.get("title", str(hash(self.ytdl_url))) - file_id = re.sub(r"(?:\/|\\|\?|\*|\"|<|>|\||:)", "_", file_id) + file_id = re.sub(r'[/\\?*"<>|]', "_", file_id) # Set the filename to the downloaded video self.filename = file_id if os.path.exists(f"opusfiles/{file_id}.opus"): @@ -86,12 +87,13 @@ class Video: async def add_to_db(self): session = await loop.run_in_executor(executor, db.Session) - pm = db.PlayedMusic(enqueuer=self.enqueuer, + pm = db.PlayedMusic(enqueuer_id=self.enqueuer, filename=self.filename) session.add(pm) await loop.run_in_executor(executor, session.commit) await loop.run_in_executor(executor, session.close) + if __debug__: version = "Dev" else: @@ -120,8 +122,9 @@ voice_queue: typing.List[Video] = [] # Init the executor executor = concurrent.futures.ThreadPoolExecutor(max_workers=3) + async def on_error(event, *args, **kwargs): - type, exception, traceback = sys.exc_info() + t, exception, traceback = sys.exc_info() try: await client.send_message(client.get_channel(config["Discord"]["main_channel"]), f"☢️ ERRORE CRITICO NELL'EVENTO `{event}`\n" @@ -200,10 +203,10 @@ async def on_message(message: discord.Message): return # Se è una playlist, informa che potrebbe essere richiesto un po' di tempo if "playlist" in url: - await client.send_message(message.channel, f"ℹ️ Hai inviato una playlist al bot.\n" - f"L'elaborazione potrebbe richiedere un po' di tempo.") + await client.send_message(message.channel, f"⚠ Le playlist non sono ancora supportate dal bot.\n" + f"Prova mettendo i video singoli a mano!") # If target is a single video - video = await Video.init(user=message.author, ytdl_url=url) + video = await Video.init(user_id=message.author.id, ytdl_url=url) await client.send_message(message.channel, f"✅ Aggiunto alla coda: <{url}>") voice_queue.append(video) elif message.content.startswith("!search"): @@ -221,7 +224,7 @@ async def on_message(message: discord.Message): "Sintassi corretta: `!search `") return # If target is a single video - video = await Video.init(user=message.author, ytdl_url=f"ytsearch:{text}") + video = await Video.init(user_id=message.author.id, ytdl_url=f"ytsearch:{text}") await client.send_message(message.channel, f"✅ Aggiunto alla coda: `ytsearch:{text}`") voice_queue.append(video) elif message.content.startswith("!file"): @@ -239,7 +242,7 @@ async def on_message(message: discord.Message): "Sintassi corretta: `!file `") return # If target is a single video - video = await Video.init(user=message.author, filename=text) + video = await Video.init(user_id=message.author.id, filename=text) await client.send_message(message.channel, f"✅ Aggiunto alla coda: `{text}`") voice_queue.append(video) elif message.content.startswith("!skip"): @@ -264,7 +267,7 @@ async def on_message(message: discord.Message): if not len(voice_queue) > 1: await client.send_message(message.channel, f"⚠ Non ci sono video da annullare.") return - video = voice_queue.pop() + voice_queue.pop() await client.send_message(message.channel, f"❌ L'ultimo video aggiunto alla playlist è stato rimosso.") elif message.content.startswith("!stop"): if voice_player is None: diff --git a/requirements.txt b/requirements.txt index d575dfb7..6ef6f60e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,4 +3,6 @@ python-telegram-bot flask sqlalchemy youtube-dl -requests \ No newline at end of file +requests +psycopg2 +PyNaCl \ No newline at end of file diff --git a/templates/music.html b/templates/music.html index 50e1cbac..d9738ab8 100644 --- a/templates/music.html +++ b/templates/music.html @@ -26,14 +26,37 @@ - {% for record in music_data %} + {% for record in music_counts %} - {{ record.filename }} + {{ record.filename }} {{ record[1] }} volt{{ 'a' if record[1] == 1 else 'e' }} {% endfor %} +

+ Cronologia +

+ + + + + + + + + {% for record in music_last %} + + + {% if record.enqueuer is not none %} + + {% else %} + + {% endif %} + + {% endfor %} + +
FileAggiunto da
{{ record.filename }} {{ record.enqueuer }}
diff --git a/webserver.py b/webserver.py index ea03682d..a4923569 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, Diario, Telegram, PlayedMusic +from db import Session, Royal, Steam, RocketLeague, Dota, Osu, Overwatch, LeagueOfLegends, Diario, Telegram, PlayedMusic, Discord from sqlalchemy import func app = Flask(__name__) @@ -7,10 +7,12 @@ 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() @@ -18,6 +20,7 @@ def page_diario(): session.close() return render_template("diario.html", diario_data=diario_data) + @app.route("/leaderboards") def page_leaderboards(): session = Session() @@ -29,12 +32,14 @@ def page_leaderboards(): 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) + @app.route("/music") def page_music(): session = Session() - music_data = session.query(PlayedMusic.filename, func.count(PlayedMusic.filename)).group_by(PlayedMusic.filename).all() + music_counts = session.query(PlayedMusic.filename, func.count(PlayedMusic.filename)).group_by(PlayedMusic.filename).all() + music_last = session.query(PlayedMusic).join(Discord).join(Royal).order_by(PlayedMusic.id.desc()).limit(50).all() session.close() - return render_template("music.html", music_data=music_data) + return render_template("music.html", music_counts=music_counts, music_last=music_last) if __name__ == "__main__":