1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-24 03:54:20 +00:00
This commit is contained in:
Steffo 2018-02-26 16:38:47 +01:00
parent 0ccc8202d7
commit a4078dd336
WARNING! Although there is a key with this ID in the database it does not verify this commit! This commit is SUSPICIOUS.
GPG key ID: C27544372FBB445D

View file

@ -1,4 +1,6 @@
import random import random
import re
import discord import discord
import discord.opus import discord.opus
import discord.voice_client import discord.voice_client
@ -15,6 +17,9 @@ import os
import asyncio import asyncio
import configparser import configparser
# Queue emojis
queue_emojis = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "🔟"]
# Init the event loop # Init the event loop
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
@ -22,7 +27,6 @@ loop = asyncio.get_event_loop()
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read("config.ini") config.read("config.ini")
class DurationError(Exception): class DurationError(Exception):
pass pass
@ -46,16 +50,13 @@ class Video:
async def download(self): async def download(self):
# Retrieve info before downloading # Retrieve info before downloading
try: with youtube_dl.YoutubeDL() as ytdl:
with youtube_dl.YoutubeDL() as ytdl: info = await loop.run_in_executor(executor, functools.partial(ytdl.extract_info, self.ytdl_url, download=False))
info = await loop.run_in_executor(executor, functools.partial(ytdl.extract_info, self.ytdl_url, download=False)) file_id = info.get("title", str(hash(self.ytdl_url)))
file_id = info["entries"][0].get("title", hash(self.ytdl_url)) file_id = re.sub(r"(?:\/|\\|\?|\*|\"|<|>|\||:)", "_", file_id)
except Exception as e:
print(e)
raise e
if os.path.exists(f"opusfiles/{file_id}.opus"): if os.path.exists(f"opusfiles/{file_id}.opus"):
return return
if info["entries"][0]["duration"] > int(config["YouTube"]["max_duration"]): if info.get("duration", 1) > int(config["YouTube"]["max_duration"]):
raise DurationError(f"File duration is over the limit " raise DurationError(f"File duration is over the limit "
f"set in the config ({config['YouTube']['max_duration']}).") f"set in the config ({config['YouTube']['max_duration']}).")
ytdl_args = {"noplaylist": True, ytdl_args = {"noplaylist": True,
@ -70,14 +71,10 @@ class Video:
ytdl_args["username"] = config["YouTube"]["username"] ytdl_args["username"] = config["YouTube"]["username"]
ytdl_args["password"] = config["YouTube"]["password"] ytdl_args["password"] = config["YouTube"]["password"]
# Download the video # Download the video
try: with youtube_dl.YoutubeDL(ytdl_args) as ytdl:
with youtube_dl.YoutubeDL(ytdl_args) as ytdl: await loop.run_in_executor(executor, functools.partial(ytdl.download, [self.ytdl_url]))
await loop.run_in_executor(executor, functools.partial(ytdl.download, [self.ytdl_url]))
except Exception as e:
print(e)
raise e
# Set the filename to the downloaded video # Set the filename to the downloaded video
self.filename = f"opusfiles/{file_id}.opus" self.filename = file_id
if __debug__: if __debug__:
@ -90,7 +87,7 @@ else:
os.chdir(os.path.dirname(__file__)) os.chdir(os.path.dirname(__file__))
version = str(subprocess.check_output(["git", "describe", "--tags"]), encoding="utf8").strip() version = str(subprocess.check_output(["git", "describe", "--tags"]), encoding="utf8").strip()
except Exception: except Exception:
version = "v???" version = ""
finally: finally:
os.chdir(old_wd) os.chdir(old_wd)
@ -199,7 +196,7 @@ async def on_message(message: discord.Message):
f"L'elaborazione potrebbe richiedere un po' di tempo.") f"L'elaborazione potrebbe richiedere un po' di tempo.")
# If target is a single video # If target is a single video
video = await Video.init(user=message.author, ytdl_url=url) video = await Video.init(user=message.author, ytdl_url=url)
await client.send_message(message.channel, f"✅ Aggiunto alla coda: `{url}`") await client.send_message(message.channel, f"✅ Aggiunto alla coda: <{url}>")
voice_queue.append(video) voice_queue.append(video)
elif message.content.startswith("!search"): elif message.content.startswith("!search"):
await client.send_typing(message.channel) await client.send_typing(message.channel)
@ -233,10 +230,6 @@ async def on_message(message: discord.Message):
await client.send_message(message.channel, "⚠️ Non hai specificato il nome del file!\n" await client.send_message(message.channel, "⚠️ Non hai specificato il nome del file!\n"
"Sintassi corretta: `!file <nomefile>`") "Sintassi corretta: `!file <nomefile>`")
return return
# Ensure the filename ends with .opus
if not text.endswith(".opus"):
await client.send_message(message.channel, "⚠️ Il nome file specificato non è valido.")
return
# If target is a single video # If target is a single video
video = await Video.init(user=message.author, filename=text) video = await Video.init(user=message.author, filename=text)
await client.send_message(message.channel, f"✅ Aggiunto alla coda: `{text}`") await client.send_message(message.channel, f"✅ Aggiunto alla coda: `{text}`")
@ -274,16 +267,16 @@ async def on_message(message: discord.Message):
voice_player = None voice_player = None
await client.send_message(message.channel, f"⏹ Riproduzione interrotta e playlist svuotata.") await client.send_message(message.channel, f"⏹ Riproduzione interrotta e playlist svuotata.")
elif message.content.startswith("!queue"): elif message.content.startswith("!queue"):
message = "Video in coda:\n" msg = "Video in coda:\n"
for text, emoji in voice_queue[0:10], ["▶️", "1", "2", "3", "4", "5", "6", "7", "8", "9", "🔟"]: for position in range(10) if len(voice_queue) > 10 else range(len(voice_queue)):
message += f"{emoji} `{text}`\n" msg += f"{queue_emojis[position]} {'`' + voice_queue[position].filename + '`' if voice_queue[position].filename is not None else '<' + voice_queue[position].ytdl_url + '>'}\n"
await client.send_message(message.channel, message) await client.send_message(message.channel, msg)
elif message.content.startswith("!cast"): elif message.content.startswith("!cast"):
try: try:
spell = message.content.split(" ", 1)[1] spell = message.content.split(" ", 1)[1]
except IndexError: except IndexError:
await client.send_message("⚠️ Non hai specificato nessun incantesimo!\n" await client.send_message(message.channel, "⚠️ Non hai specificato nessun incantesimo!\n"
"Sintassi corretta: `!cast <nome_incantesimo>`") "Sintassi corretta: `!cast <nome_incantesimo>`")
return return
target = random.sample(list(message.server.members), 1)[0] target = random.sample(list(message.server.members), 1)[0]
# Seed the rng with the spell name # Seed the rng with the spell name
@ -354,12 +347,12 @@ async def update_music_queue():
f"{e}\n" f"{e}\n"
f"```") f"```")
continue continue
voice_player = voice_client.create_ffmpeg_player(video.filename) voice_player = voice_client.create_ffmpeg_player(f"opusfiles/{video.filename}.opus")
voice_player.start() voice_player.start()
await client.send_message(client.get_channel(config["Discord"]["main_channel"]), await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
f"▶ Ora in riproduzione in <#{voice_client.channel.id}>:\n" f"▶ Ora in riproduzione in <#{voice_client.channel.id}>:\n"
f"`{video.filename}`") f"`{video.filename}`")
await client.change_presence(game=discord.Game(name="youtube-dl", type=2)) await client.change_presence(game=discord.Game(name=video.filename, type=2))
def process(users_connection=None): def process(users_connection=None):