1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-24 03:54:20 +00:00

add queue

This commit is contained in:
Steffo 2018-02-26 10:48:17 +01:00
parent a31da80fe5
commit 0ccc8202d7

View file

@ -12,19 +12,21 @@ import stagismo
import platform import platform
import typing import typing
import os import os
import asyncio
import configparser
# Init the event loop # Init the event loop
import asyncio
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
# Init the config reader # Init the config reader
import configparser
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read("config.ini") config.read("config.ini")
class DurationError(Exception): class DurationError(Exception):
pass pass
class Video: class Video:
def __init__(self): def __init__(self):
self.user = None self.user = None
@ -54,7 +56,8 @@ class Video:
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["entries"][0]["duration"] > int(config["YouTube"]["max_duration"]):
raise DurationError(f"File duration is over the limit set in the config ({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, ytdl_args = {"noplaylist": True,
"format": "best", "format": "best",
"postprocessors": [{ "postprocessors": [{
@ -76,6 +79,7 @@ class Video:
# Set the filename to the downloaded video # Set the filename to the downloaded video
self.filename = f"opusfiles/{file_id}.opus" self.filename = f"opusfiles/{file_id}.opus"
if __debug__: if __debug__:
version = "Dev" version = "Dev"
else: else:
@ -85,7 +89,7 @@ else:
try: try:
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: except Exception:
version = "v???" version = "v???"
finally: finally:
os.chdir(old_wd) os.chdir(old_wd)
@ -104,6 +108,7 @@ voice_queue: typing.List[Video] = []
# Init the executor # Init the executor
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3) executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
async def find_user(user: discord.User): async def find_user(user: discord.User):
session = await loop.run_in_executor(executor, db.Session) 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) user = await loop.run_in_executor(executor, session.query(db.Discord).filter_by(discord_id=user.id).join(db.Royal).first)
@ -113,12 +118,13 @@ async def find_user(user: discord.User):
async def on_error(event, *args, **kwargs): async def on_error(event, *args, **kwargs):
type, exception, traceback = sys.exc_info() type, exception, traceback = sys.exc_info()
try: try:
await client.send_message(client.get_channel(config["Discord"]["main_channel"]), f"☢️ ERRORE CRITICO NELL'EVENTO `{event}`\n" await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
f"Il bot si è chiuso e si dovrebbe riavviare entro qualche minuto.\n\n" f"☢️ ERRORE CRITICO NELL'EVENTO `{event}`\n"
f"Dettagli dell'errore:\n" f"Il bot si è chiuso e si dovrebbe riavviare entro qualche minuto.\n\n"
f"```python\n" f"Dettagli dell'errore:\n"
f"{repr(exception)}\n" f"```python\n"
f"```") f"{repr(exception)}\n"
f"```")
await voice_client.disconnect() await voice_client.disconnect()
await client.change_presence(status=discord.Status.invisible) await client.change_presence(status=discord.Status.invisible)
await client.close() await client.close()
@ -131,7 +137,8 @@ async def on_error(event, *args, **kwargs):
@client.event @client.event
async def on_ready(): async def on_ready():
await client.send_message(client.get_channel("368447084518572034"), f" Royal Bot {version} avviato e pronto a ricevere comandi!") 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) await client.change_presence(game=None, status=discord.Status.online)
@ -153,7 +160,9 @@ async def on_message(message: discord.Message):
royal_username=username, royal_username=username,
discord_user=message.author) discord_user=message.author)
except errors.AlreadyExistingError: 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.") 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 return
session.add(d) session.add(d)
session.commit() session.commit()
@ -238,7 +247,8 @@ async def on_message(message: discord.Message):
await client.send_message(message.channel, f"⏩ Video saltato.") await client.send_message(message.channel, f"⏩ Video saltato.")
elif message.content.startswith("!pause"): elif message.content.startswith("!pause"):
if voice_player is None or not voice_player.is_playing(): if voice_player is None or not voice_player.is_playing():
await client.send_message(message.channel, f"⚠️ Non è in corso la riproduzione di un video, pertanto non c'è niente da pausare.") await client.send_message(message.channel, f"⚠️ Non è in corso la riproduzione di un video, "
f"pertanto non c'è niente da pausare.")
return return
voice_player.pause() voice_player.pause()
await client.send_message(message.channel, f"⏸ Riproduzione messa in pausa.\n" await client.send_message(message.channel, f"⏸ Riproduzione messa in pausa.\n"
@ -263,23 +273,11 @@ async def on_message(message: discord.Message):
voice_player.stop() voice_player.stop()
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("!np"): elif message.content.startswith("!queue"):
# if voice_player is None or not voice_player.is_playing(): message = "Video in coda:\n"
# await client.send_message(message.channel, f" Non c'è nulla in riproduzione al momento.") for text, emoji in voice_queue[0:10], ["▶️", "1", "2", "3", "4", "5", "6", "7", "8", "9", "🔟"]:
# return message += f"{emoji} `{text}`\n"
# await client.send_message(message.channel, f"▶️ Ora in riproduzione in <#{voice_client.channel.id}>:", embed=voice_playing.create_embed()) await client.send_message(message.channel, message)
#elif message.content.startswith("!queue"):
# if voice_player is None:
# await client.send_message(message.channel, f" Non c'è nulla in riproduzione al momento.")
# return
# to_send = ""
# to_send += f"0. {voice_playing.info['title'] if voice_playing.info['title'] is not None else '_Senza titolo_'} - <{voice_playing.info['webpage_url'] if voice_playing.info['webpage_url'] is not None else ''}>\n"
# for n, video in enumerate(voice_queue):
# to_send += f"{n+1}. {video.info['title'] if video.info['title'] is not None else '_Senza titolo_'} - <{video.info['webpage_url'] if video.info['webpage_url'] is not None else ''}>\n"
# if len(to_send) >= 2000:
# to_send = to_send[0:1997] + "..."
# break
# await client.send_message(message.channel, to_send)
elif message.content.startswith("!cast"): elif message.content.startswith("!cast"):
try: try:
spell = message.content.split(" ", 1)[1] spell = message.content.split(" ", 1)[1]
@ -300,7 +298,12 @@ async def on_message(message: discord.Message):
total = dmg_mod total = dmg_mod
for dice in range(0, dmg_dice): for dice in range(0, dmg_dice):
total += random.randrange(1, dmg_max+1) 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!") await client.send_message(message.channel,
f"❇️ Ho lanciato **{spell}** "
f"su **{target.nick if target.nick is not None else target.name}** "
f"per {dmg_dice}d{dmg_max}"
f"{'+' if dmg_mod > 0 else ''}{str(dmg_mod) if dmg_mod != 0 else ''}"
f"=**{total if total > 0 else 0}** danni!")
elif message.content.startswith("!smecds"): elif message.content.startswith("!smecds"):
ds = random.sample(stagismo.listona, 1)[0] ds = random.sample(stagismo.listona, 1)[0]
await client.send_message(message.channel, f"Secondo me, è colpa {ds}.", tts=True) await client.send_message(message.channel, f"Secondo me, è colpa {ds}.", tts=True)
@ -335,22 +338,27 @@ async def update_music_queue():
continue continue
video = voice_queue.pop() video = voice_queue.pop()
if video.ytdl_url: if video.ytdl_url:
await client.send_message(client.get_channel(config["Discord"]["main_channel"]), f" E' iniziato il download di `{video.ytdl_url}`.") await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
f" E' iniziato il download di `{video.ytdl_url}`.")
try: try:
await video.download() await video.download()
except DurationError: except DurationError:
await client.send_message(client.get_channel(config["Discord"]["main_channel"]), f"⚠ Il file supera il limite di durata impostato in config.ini (`{config['YouTube']['max_duration']}` secondi).") await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
f"⚠ Il file supera il limite di durata impostato in config.ini "
f"(`{config['YouTube']['max_duration']}` secondi).")
continue continue
except Exception as e: except Exception as e:
await client.send_message(client.get_channel(config["Discord"]["main_channel"]), f"⚠️ C'è stato un errore durante il download di `{video.ytdl_url}`:\n" await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
f"```\n" f"⚠️ C'è stato un errore durante il download di `{video.ytdl_url}`:\n"
f"{e}\n" f"```\n"
f"```") f"{e}\n"
f"```")
continue continue
voice_player = voice_client.create_ffmpeg_player(video.filename) voice_player = voice_client.create_ffmpeg_player(video.filename)
voice_player.start() voice_player.start()
await client.send_message(client.get_channel(config["Discord"]["main_channel"]), f"▶ Ora in riproduzione in <#{voice_client.channel.id}>:\n" await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
f"`{video.filename}`") f"▶ Ora in riproduzione in <#{voice_client.channel.id}>:\n"
f"`{video.filename}`")
await client.change_presence(game=discord.Game(name="youtube-dl", type=2)) await client.change_presence(game=discord.Game(name="youtube-dl", type=2))