import random import re import discord import discord.opus import discord.voice_client import functools import sys import db import errors import youtube_dl import concurrent.futures import stagismo import platform import typing import os import asyncio import configparser # Queue emojis queue_emojis = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"] # Init the event loop loop = asyncio.get_event_loop() # Init the config reader config = configparser.ConfigParser() config.read("config.ini") class DurationError(Exception): pass class Video: def __init__(self): self.user = None self.filename = None self.ytdl_url = None @staticmethod async def init(user, 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.user = discord_user.royal if discord_user is not None else None self.filename = filename self.ytdl_url = ytdl_url return self async def download(self): # Retrieve info before downloading with youtube_dl.YoutubeDL() as ytdl: info = await loop.run_in_executor(executor, functools.partial(ytdl.extract_info, self.ytdl_url, download=False)) 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) if os.path.exists(f"opusfiles/{file_id}.opus"): return if info.get("duration", 1) > int(config["YouTube"]["max_duration"]): raise DurationError(f"File duration is over the limit " f"set in the config ({config['YouTube']['max_duration']}).") ytdl_args = {"noplaylist": True, "format": "best", "postprocessors": [{ "key": 'FFmpegExtractAudio', "preferredcodec": 'opus' }], "outtmpl": f"opusfiles/{file_id}.opus", "quiet": True} if "youtu" in self.ytdl_url: ytdl_args["username"] = config["YouTube"]["username"] ytdl_args["password"] = config["YouTube"]["password"] # Download the video with youtube_dl.YoutubeDL(ytdl_args) as ytdl: await loop.run_in_executor(executor, functools.partial(ytdl.download, [self.ytdl_url])) # Set the filename to the downloaded video self.filename = file_id if __debug__: version = "Dev" else: # Find the latest git tag import subprocess old_wd = os.getcwd() try: os.chdir(os.path.dirname(__file__)) version = str(subprocess.check_output(["git", "describe", "--tags"]), encoding="utf8").strip() except Exception: version = "❓" finally: os.chdir(old_wd) # Init the discord bot client = discord.Client() if platform.system() == "Linux": discord.opus.load_opus("/usr/lib/x86_64-linux-gnu/libopus.so") elif platform.system() == "Windows": discord.opus.load_opus("libopus-0.dll") voice_client: typing.Optional[discord.VoiceClient] = None voice_player: typing.Optional[discord.voice_client.StreamPlayer] = None voice_queue: typing.List[Video] = [] # Init the executor executor = concurrent.futures.ThreadPoolExecutor(max_workers=3) 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) return user async def on_error(event, *args, **kwargs): type, exception, traceback = sys.exc_info() try: await client.send_message(client.get_channel(config["Discord"]["main_channel"]), f"☢️ ERRORE CRITICO NELL'EVENTO `{event}`\n" f"Il bot si è chiuso e si dovrebbe riavviare entro qualche minuto.\n\n" f"Dettagli dell'errore:\n" f"```python\n" f"{repr(exception)}\n" f"```") await voice_client.disconnect() await client.change_presence(status=discord.Status.invisible) await client.close() except Exception as e: print("ERRORE CRITICO PIU' CRITICO:\n" + repr(e) + "\n" + repr(sys.exc_info())) loop.stop() os._exit(1) pass @client.event async def on_ready(): await client.send_message(client.get_channel("368447084518572034"), f"ℹ Royal Bot {version} avviato e pronto a ricevere comandi!") await client.change_presence(game=None, status=discord.Status.online) @client.event async def on_message(message: discord.Message): global voice_queue global voice_player if message.content.startswith("!register"): await client.send_typing(message.channel) session = await loop.run_in_executor(executor, db.Session()) try: username = message.content.split(" ", 1)[1] except IndexError: await client.send_message(message.channel, "⚠️ Non hai specificato un username!\n" "Sintassi corretta: `!register `") return try: d = db.Discord.create(session, royal_username=username, discord_user=message.author) except errors.AlreadyExistingError: await client.send_message(message.channel, "⚠ Il tuo account Discord è già collegato a un account RYG " "o l'account RYG che hai specificato è già collegato a un account Discord.") return session.add(d) session.commit() session.close() await client.send_message(message.channel, "✅ Sincronizzazione completata!") elif message.content.startswith("!cv"): await client.send_typing(message.channel) if message.author.voice.voice_channel is None: await client.send_message(message.channel, "⚠ Non sei in nessun canale!") return global voice_client if voice_client is not None and voice_client.is_connected(): await voice_client.move_to(message.author.voice.voice_channel) else: voice_client = await client.join_voice_channel(message.author.voice.voice_channel) await client.send_message(message.channel, f"✅ Mi sono connesso in <#{message.author.voice.voice_channel.id}>.") elif message.content.startswith("!play"): await client.send_typing(message.channel) # The bot should be in voice chat if voice_client is None: await client.send_message(message.channel, "⚠️ Non sono connesso alla cv!\n" "Fammi entrare scrivendo `!cv` mentre sei in chat vocale.") return # Find the sent url try: url = message.content.split(" ", 1)[1] except IndexError: await client.send_message(message.channel, "⚠️ Non hai specificato un url!\n" "Sintassi corretta: `!play