2017-11-11 17:55:13 +00:00
|
|
|
|
import random
|
2018-02-26 15:38:47 +00:00
|
|
|
|
import re
|
2017-10-27 11:38:32 +00:00
|
|
|
|
import discord
|
2017-10-31 22:50:05 +00:00
|
|
|
|
import discord.opus
|
2018-02-25 18:50:57 +00:00
|
|
|
|
import discord.voice_client
|
2017-11-01 18:23:11 +00:00
|
|
|
|
import functools
|
2017-11-09 19:34:18 +00:00
|
|
|
|
import sys
|
2017-10-27 11:38:32 +00:00
|
|
|
|
import db
|
2017-11-05 21:50:37 +00:00
|
|
|
|
import youtube_dl
|
2018-01-15 12:42:40 +00:00
|
|
|
|
import concurrent.futures
|
2018-01-25 14:24:17 +00:00
|
|
|
|
import stagismo
|
2018-02-25 18:50:57 +00:00
|
|
|
|
import platform
|
|
|
|
|
import typing
|
2018-02-25 19:47:12 +00:00
|
|
|
|
import os
|
2018-02-26 09:48:17 +00:00
|
|
|
|
import asyncio
|
|
|
|
|
import configparser
|
2018-04-09 17:51:05 +00:00
|
|
|
|
import subprocess
|
2018-04-09 20:55:48 +00:00
|
|
|
|
import async_timeout
|
2018-04-12 16:04:13 +00:00
|
|
|
|
import raven
|
2018-04-20 17:46:33 +00:00
|
|
|
|
import cast
|
2017-10-27 11:38:32 +00:00
|
|
|
|
|
2018-02-26 15:38:47 +00:00
|
|
|
|
# Queue emojis
|
2018-05-25 17:58:30 +00:00
|
|
|
|
queue_emojis = [":one:",
|
|
|
|
|
":two:",
|
|
|
|
|
":three:",
|
|
|
|
|
":four:",
|
|
|
|
|
":five:",
|
|
|
|
|
":six:",
|
|
|
|
|
":seven:",
|
|
|
|
|
":eight:",
|
|
|
|
|
":nine:",
|
|
|
|
|
":keycap_ten:"]
|
2018-02-26 15:38:47 +00:00
|
|
|
|
|
2017-10-27 11:38:32 +00:00
|
|
|
|
# Init the event loop
|
|
|
|
|
loop = asyncio.get_event_loop()
|
|
|
|
|
|
|
|
|
|
# Init the config reader
|
|
|
|
|
config = configparser.ConfigParser()
|
|
|
|
|
config.read("config.ini")
|
|
|
|
|
|
2018-02-25 19:47:12 +00:00
|
|
|
|
class DurationError(Exception):
|
|
|
|
|
pass
|
|
|
|
|
|
2018-05-26 08:50:54 +00:00
|
|
|
|
class LocalFileError(Exception):
|
|
|
|
|
pass
|
2018-02-26 09:48:17 +00:00
|
|
|
|
|
2018-05-26 08:50:54 +00:00
|
|
|
|
|
|
|
|
|
class OldVideo:
|
2017-11-06 15:54:36 +00:00
|
|
|
|
def __init__(self):
|
2018-05-25 17:58:30 +00:00
|
|
|
|
self.enqueuer = None # type: typing.Optional[discord.User]
|
|
|
|
|
self.filename = None # type: typing.Optional[str]
|
|
|
|
|
self.ytdl_url = None # type: typing.Optional[str]
|
|
|
|
|
self.data = None # type: typing.Optional[dict]
|
2017-11-01 18:23:11 +00:00
|
|
|
|
|
2017-11-06 15:54:36 +00:00
|
|
|
|
@staticmethod
|
2018-05-25 17:58:30 +00:00
|
|
|
|
async def init(user_id: str, *, filename=None, ytdl_url=None, data=None):
|
2018-02-25 18:50:57 +00:00
|
|
|
|
if filename is None and ytdl_url is None:
|
|
|
|
|
raise Exception("Filename or url must be specified")
|
2018-05-26 08:50:54 +00:00
|
|
|
|
self = OldVideo()
|
2018-03-12 12:29:12 +00:00
|
|
|
|
self.enqueuer = int(user_id)
|
2018-02-25 18:50:57 +00:00
|
|
|
|
self.filename = filename
|
|
|
|
|
self.ytdl_url = ytdl_url
|
2018-05-25 17:58:30 +00:00
|
|
|
|
self.data = data if data is not None else {}
|
2017-11-06 15:54:36 +00:00
|
|
|
|
return self
|
2018-01-25 14:30:07 +00:00
|
|
|
|
|
2018-02-25 19:47:12 +00:00
|
|
|
|
async def download(self):
|
|
|
|
|
# Retrieve info before downloading
|
2018-02-26 15:38:47 +00:00
|
|
|
|
with youtube_dl.YoutubeDL() as ytdl:
|
|
|
|
|
info = await loop.run_in_executor(executor, functools.partial(ytdl.extract_info, self.ytdl_url, download=False))
|
2018-02-28 16:05:45 +00:00
|
|
|
|
if "entries" in info:
|
|
|
|
|
info = info["entries"][0]
|
2018-02-26 15:38:47 +00:00
|
|
|
|
file_id = info.get("title", str(hash(self.ytdl_url)))
|
2018-03-12 12:29:12 +00:00
|
|
|
|
file_id = re.sub(r'[/\\?*"<>|]', "_", file_id)
|
2018-03-11 17:23:18 +00:00
|
|
|
|
# Set the filename to the downloaded video
|
|
|
|
|
self.filename = file_id
|
2018-02-25 19:47:12 +00:00
|
|
|
|
if os.path.exists(f"opusfiles/{file_id}.opus"):
|
|
|
|
|
return
|
2018-02-26 15:38:47 +00:00
|
|
|
|
if info.get("duration", 1) > int(config["YouTube"]["max_duration"]):
|
2018-02-26 09:48:17 +00:00
|
|
|
|
raise DurationError(f"File duration is over the limit "
|
|
|
|
|
f"set in the config ({config['YouTube']['max_duration']}).")
|
2018-02-25 18:50:57 +00:00
|
|
|
|
ytdl_args = {"noplaylist": True,
|
2018-02-25 19:47:12 +00:00
|
|
|
|
"format": "best",
|
2018-02-25 18:50:57 +00:00
|
|
|
|
"postprocessors": [{
|
|
|
|
|
"key": 'FFmpegExtractAudio',
|
|
|
|
|
"preferredcodec": 'opus'
|
|
|
|
|
}],
|
2018-02-25 19:47:12 +00:00
|
|
|
|
"outtmpl": f"opusfiles/{file_id}.opus",
|
|
|
|
|
"quiet": True}
|
2018-02-25 18:50:57 +00:00
|
|
|
|
if "youtu" in self.ytdl_url:
|
|
|
|
|
ytdl_args["username"] = config["YouTube"]["username"]
|
|
|
|
|
ytdl_args["password"] = config["YouTube"]["password"]
|
|
|
|
|
# Download the video
|
2018-02-26 15:38:47 +00:00
|
|
|
|
with youtube_dl.YoutubeDL(ytdl_args) as ytdl:
|
|
|
|
|
await loop.run_in_executor(executor, functools.partial(ytdl.download, [self.ytdl_url]))
|
2018-02-25 18:50:57 +00:00
|
|
|
|
|
2018-03-11 19:03:21 +00:00
|
|
|
|
async def add_to_db(self):
|
|
|
|
|
session = await loop.run_in_executor(executor, db.Session)
|
2018-03-12 12:29:12 +00:00
|
|
|
|
pm = db.PlayedMusic(enqueuer_id=self.enqueuer,
|
2018-03-11 19:03:21 +00:00
|
|
|
|
filename=self.filename)
|
|
|
|
|
session.add(pm)
|
|
|
|
|
await loop.run_in_executor(executor, session.commit)
|
|
|
|
|
await loop.run_in_executor(executor, session.close)
|
2018-02-26 09:48:17 +00:00
|
|
|
|
|
2018-05-25 17:58:30 +00:00
|
|
|
|
def __str__(self):
|
|
|
|
|
if self.data.get("title") is not None:
|
|
|
|
|
return f"{self.data.get('title')}"
|
|
|
|
|
elif self.filename is not None:
|
|
|
|
|
return f"`{self.filename}`"
|
|
|
|
|
else:
|
|
|
|
|
return f"<{self.ytdl_url}>"
|
|
|
|
|
|
2018-03-12 12:29:12 +00:00
|
|
|
|
|
2018-05-26 08:50:54 +00:00
|
|
|
|
class Video:
|
|
|
|
|
def __init__(self, url=None, file=None):
|
|
|
|
|
self.url = url
|
|
|
|
|
self.file = file
|
|
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
async def retrieve_info(self):
|
|
|
|
|
if url is None:
|
|
|
|
|
raise LocalFileError()
|
|
|
|
|
with youtube_dl.YoutubeDL({"quiet": True,
|
|
|
|
|
"ignoreerrors": True,
|
|
|
|
|
"simulate": True}) as ytdl:
|
|
|
|
|
await loop.run_in_executor(executor, functools.partial(ytdl.extract_info, url=self.url, download=False)
|
|
|
|
|
# TODO
|
|
|
|
|
|
|
|
|
|
|
2018-02-25 18:50:57 +00:00
|
|
|
|
if __debug__:
|
|
|
|
|
version = "Dev"
|
2018-04-15 11:50:51 +00:00
|
|
|
|
commit_msg = "_in sviluppo_"
|
2018-02-25 18:50:57 +00:00
|
|
|
|
else:
|
|
|
|
|
# Find the latest git tag
|
|
|
|
|
old_wd = os.getcwd()
|
|
|
|
|
try:
|
|
|
|
|
os.chdir(os.path.dirname(__file__))
|
|
|
|
|
version = str(subprocess.check_output(["git", "describe", "--tags"]), encoding="utf8").strip()
|
2018-04-15 11:50:51 +00:00
|
|
|
|
commit_msg = str(subprocess.check_output(["git", "log", "-1", "--pretty=%B"]), encoding="utf8").strip()
|
2018-02-26 09:48:17 +00:00
|
|
|
|
except Exception:
|
2018-02-26 15:38:47 +00:00
|
|
|
|
version = "❓"
|
2018-02-25 18:50:57 +00:00
|
|
|
|
finally:
|
|
|
|
|
os.chdir(old_wd)
|
2017-11-06 15:54:36 +00:00
|
|
|
|
|
2018-02-25 18:50:57 +00:00
|
|
|
|
# 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":
|
2018-05-25 17:58:30 +00:00
|
|
|
|
discord.opus.load_opus("libopus-0.dll")
|
2018-02-25 18:50:57 +00:00
|
|
|
|
|
|
|
|
|
voice_client: typing.Optional[discord.VoiceClient] = None
|
|
|
|
|
voice_player: typing.Optional[discord.voice_client.StreamPlayer] = None
|
2018-05-26 08:50:54 +00:00
|
|
|
|
voice_queue: typing.List[OldVideo] = []
|
2018-02-25 18:50:57 +00:00
|
|
|
|
|
|
|
|
|
# Init the executor
|
|
|
|
|
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
|
2017-11-06 15:54:36 +00:00
|
|
|
|
|
2018-04-12 16:04:13 +00:00
|
|
|
|
# Init the Sentry client
|
|
|
|
|
sentry = raven.Client(config["Sentry"]["token"],
|
2018-05-25 17:58:30 +00:00
|
|
|
|
release=version,
|
|
|
|
|
install_logging_hook=False,
|
|
|
|
|
hook_libraries=[])
|
2018-04-12 16:04:13 +00:00
|
|
|
|
|
2018-03-12 12:29:12 +00:00
|
|
|
|
|
2017-11-10 07:53:48 +00:00
|
|
|
|
async def on_error(event, *args, **kwargs):
|
2018-04-12 16:04:13 +00:00
|
|
|
|
ei = sys.exc_info()
|
|
|
|
|
print("ERRORE CRITICO:\n" + repr(ei[1]) + "\n\n" + repr(ei))
|
2017-11-10 07:53:48 +00:00
|
|
|
|
try:
|
2018-02-26 09:48:17 +00:00
|
|
|
|
await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
|
2018-04-15 11:43:24 +00:00
|
|
|
|
f"☢️ **ERRORE CRITICO NELL'EVENTO** `{event}`\n"
|
2018-04-12 16:04:13 +00:00
|
|
|
|
f"Il bot si è chiuso e si dovrebbe riavviare entro qualche minuto.\n"
|
|
|
|
|
f"Una segnalazione di errore è stata automaticamente mandata a Steffo.\n\n"
|
2018-02-26 09:48:17 +00:00
|
|
|
|
f"Dettagli dell'errore:\n"
|
|
|
|
|
f"```python\n"
|
2018-04-12 16:04:13 +00:00
|
|
|
|
f"{repr(ei[1])}\n"
|
2018-02-26 09:48:17 +00:00
|
|
|
|
f"```")
|
2018-04-12 16:04:13 +00:00
|
|
|
|
if voice_client is not None:
|
|
|
|
|
await voice_client.disconnect()
|
2017-11-10 07:53:48 +00:00
|
|
|
|
await client.change_presence(status=discord.Status.invisible)
|
|
|
|
|
await client.close()
|
|
|
|
|
except Exception as e:
|
2018-04-12 16:04:13 +00:00
|
|
|
|
print("ERRORE CRITICO PIU' CRITICO:\n" + repr(e) + "\n\n" + repr(sys.exc_info()))
|
2017-11-10 07:53:48 +00:00
|
|
|
|
loop.stop()
|
2018-04-12 16:04:13 +00:00
|
|
|
|
sentry.captureException(exc_info=ei)
|
2017-11-15 09:48:58 +00:00
|
|
|
|
os._exit(1)
|
|
|
|
|
pass
|
2017-11-09 19:34:18 +00:00
|
|
|
|
|
|
|
|
|
|
2017-11-10 07:53:48 +00:00
|
|
|
|
@client.event
|
|
|
|
|
async def on_ready():
|
2018-03-15 15:51:51 +00:00
|
|
|
|
await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
|
2018-04-15 11:50:51 +00:00
|
|
|
|
f"ℹ Royal Bot avviato e pronto a ricevere comandi!\n"
|
|
|
|
|
f"Ultimo aggiornamento: `{version}: {commit_msg}`")
|
2017-11-10 07:53:48 +00:00
|
|
|
|
await client.change_presence(game=None, status=discord.Status.online)
|
|
|
|
|
|
|
|
|
|
|
2017-10-27 11:38:32 +00:00
|
|
|
|
@client.event
|
|
|
|
|
async def on_message(message: discord.Message):
|
2017-11-07 17:44:00 +00:00
|
|
|
|
global voice_queue
|
|
|
|
|
global voice_player
|
2018-04-12 16:04:13 +00:00
|
|
|
|
if not message.content.startswith("!"):
|
|
|
|
|
return
|
|
|
|
|
sentry.user_context({
|
|
|
|
|
"discord": {
|
|
|
|
|
"discord_id": message.author.id,
|
|
|
|
|
"name": message.author.name,
|
|
|
|
|
"discriminator": message.author.discriminator
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
await client.send_typing(message.channel)
|
|
|
|
|
session = await loop.run_in_executor(executor, db.Session)
|
|
|
|
|
user = session.query(db.Discord).filter_by(discord_id=message.author.id).one_or_none()
|
|
|
|
|
if user is None:
|
|
|
|
|
user = db.Discord(discord_id=message.author.id,
|
|
|
|
|
name=message.author.name,
|
|
|
|
|
discriminator=message.author.discriminator,
|
|
|
|
|
avatar_hex=message.author.avatar)
|
2018-04-15 11:43:24 +00:00
|
|
|
|
session.add(user)
|
2018-04-12 16:04:13 +00:00
|
|
|
|
await loop.run_in_executor(executor, session.commit)
|
|
|
|
|
else:
|
|
|
|
|
sentry.user_context({
|
2018-04-12 16:04:30 +00:00
|
|
|
|
"discord": {
|
|
|
|
|
"discord_id": message.author.id,
|
|
|
|
|
"name": message.author.name,
|
|
|
|
|
"discriminator": message.author.discriminator
|
|
|
|
|
},
|
2018-04-12 16:04:13 +00:00
|
|
|
|
"royal": {
|
|
|
|
|
"user_id": user.royal_id
|
|
|
|
|
}
|
|
|
|
|
})
|
2018-05-25 17:58:30 +00:00
|
|
|
|
if message.content.startswith("!ping"):
|
2018-05-26 08:50:54 +00:00
|
|
|
|
await cmd_ping(channel=message.channel,
|
|
|
|
|
author=message.author,
|
|
|
|
|
params=["/ping"])
|
2018-05-25 17:58:30 +00:00
|
|
|
|
elif message.content.startswith("!link"):
|
2018-04-12 16:04:13 +00:00
|
|
|
|
if user.royal_id is None:
|
|
|
|
|
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
|
2017-11-01 18:23:11 +00:00
|
|
|
|
try:
|
|
|
|
|
username = message.content.split(" ", 1)[1]
|
|
|
|
|
except IndexError:
|
2017-11-05 21:50:37 +00:00
|
|
|
|
await client.send_message(message.channel, "⚠️ Non hai specificato un username!\n"
|
2018-04-12 16:04:13 +00:00
|
|
|
|
"Sintassi corretta: `!link <username_ryg>`")
|
2017-11-01 18:23:11 +00:00
|
|
|
|
return
|
2018-04-12 16:04:13 +00:00
|
|
|
|
royal = session.query(db.Royal).filter_by(username=username).one_or_none()
|
|
|
|
|
if royal is None:
|
2018-02-26 09:48:17 +00:00
|
|
|
|
await client.send_message(message.channel,
|
2018-04-12 16:04:13 +00:00
|
|
|
|
"⚠️ Non esiste nessun account RYG con questo nome.")
|
2017-11-01 18:23:11 +00:00
|
|
|
|
return
|
2018-04-12 16:04:13 +00:00
|
|
|
|
user.royal_id = royal.id
|
2017-11-01 18:23:11 +00:00
|
|
|
|
session.commit()
|
2017-10-30 12:45:38 +00:00
|
|
|
|
session.close()
|
2017-11-01 18:23:11 +00:00
|
|
|
|
await client.send_message(message.channel, "✅ Sincronizzazione completata!")
|
2017-11-11 17:55:13 +00:00
|
|
|
|
elif message.content.startswith("!cv"):
|
2018-05-25 17:58:30 +00:00
|
|
|
|
cmd_cv(channel=message.channel,
|
|
|
|
|
author=message.author,
|
|
|
|
|
params=message.content.split(" "))
|
2017-11-09 19:34:18 +00:00
|
|
|
|
elif message.content.startswith("!play"):
|
2017-11-05 21:50:37 +00:00
|
|
|
|
# Find the sent url
|
2017-11-01 18:23:11 +00:00
|
|
|
|
try:
|
|
|
|
|
url = message.content.split(" ", 1)[1]
|
|
|
|
|
except IndexError:
|
2017-11-05 21:50:37 +00:00
|
|
|
|
await client.send_message(message.channel, "⚠️ Non hai specificato un url!\n"
|
2017-11-11 17:55:13 +00:00
|
|
|
|
"Sintassi corretta: `!play <video>`")
|
2017-11-01 18:23:11 +00:00
|
|
|
|
return
|
2017-11-05 21:50:37 +00:00
|
|
|
|
if "playlist" in url:
|
2018-05-25 17:58:30 +00:00
|
|
|
|
# If target is a playlist
|
|
|
|
|
await client.send_message(message.channel,
|
|
|
|
|
f"ℹ️ Il link che hai inviato contiene una playlist.\n"
|
|
|
|
|
f"L'elaborazione delle playlist solitamente richiede molto tempo.")
|
|
|
|
|
with youtube_dl.YoutubeDL({"quiet": True,
|
|
|
|
|
"ignoreerrors": True,
|
|
|
|
|
"simulate": True}) as ytdl:
|
|
|
|
|
playlist_data = await loop.run_in_executor(executor,
|
|
|
|
|
functools.partial(ytdl.extract_info, url, download=False))
|
|
|
|
|
for entry in playlist_data["entries"]:
|
|
|
|
|
# Ignore empty videos
|
|
|
|
|
if entry is None:
|
|
|
|
|
continue
|
|
|
|
|
# Add the video to the queue
|
2018-05-26 08:50:54 +00:00
|
|
|
|
video = await OldVideo.init(user_id=message.author.id, ytdl_url=entry["webpage_url"], data=entry)
|
2018-05-25 17:58:30 +00:00
|
|
|
|
voice_queue.append(video)
|
|
|
|
|
await client.send_message(message.channel,
|
|
|
|
|
f"✅ Aggiunti alla coda **{len(playlist_data['entries']) } video**.")
|
|
|
|
|
else:
|
|
|
|
|
# If target is a single video
|
2018-05-26 08:50:54 +00:00
|
|
|
|
video = await OldVideo.init(user_id=message.author.id, ytdl_url=url)
|
2018-05-25 17:58:30 +00:00
|
|
|
|
await client.send_message(message.channel, f"✅ Aggiunto alla coda: {str(video)}")
|
|
|
|
|
voice_queue.append(video)
|
2017-11-09 19:34:18 +00:00
|
|
|
|
elif message.content.startswith("!search"):
|
2017-11-07 17:44:00 +00:00
|
|
|
|
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.")
|
2017-11-09 19:34:18 +00:00
|
|
|
|
return
|
2017-11-07 17:44:00 +00:00
|
|
|
|
# Find the sent text
|
|
|
|
|
try:
|
|
|
|
|
text = message.content.split(" ", 1)[1]
|
|
|
|
|
except IndexError:
|
|
|
|
|
await client.send_message(message.channel, "⚠️ Non hai specificato il titolo!\n"
|
2017-11-11 17:55:13 +00:00
|
|
|
|
"Sintassi corretta: `!search <titolo>`")
|
2017-11-07 17:44:00 +00:00
|
|
|
|
return
|
2018-02-25 18:50:57 +00:00
|
|
|
|
# If target is a single video
|
2018-05-26 08:50:54 +00:00
|
|
|
|
video = await OldVideo.init(user_id=message.author.id, ytdl_url=f"ytsearch:{text}")
|
2018-05-25 17:58:30 +00:00
|
|
|
|
await client.send_message(message.channel, f"✅ Aggiunto alla coda: {str(video)}")
|
2018-02-25 18:50:57 +00:00
|
|
|
|
voice_queue.append(video)
|
|
|
|
|
elif message.content.startswith("!file"):
|
|
|
|
|
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 text
|
2017-11-07 17:44:00 +00:00
|
|
|
|
try:
|
2018-04-09 17:51:05 +00:00
|
|
|
|
text: str = message.content.split(" ", 1)[1]
|
2018-02-25 18:50:57 +00:00
|
|
|
|
except IndexError:
|
|
|
|
|
await client.send_message(message.channel, "⚠️ Non hai specificato il nome del file!\n"
|
|
|
|
|
"Sintassi corretta: `!file <nomefile>`")
|
|
|
|
|
return
|
2017-11-07 17:44:00 +00:00
|
|
|
|
# If target is a single video
|
2018-05-26 08:50:54 +00:00
|
|
|
|
video = await OldVideo.init(user_id=message.author.id, filename=text)
|
2018-05-25 17:58:30 +00:00
|
|
|
|
await client.send_message(message.channel, f"✅ Aggiunto alla coda: {str(video)}")
|
2017-11-07 17:44:00 +00:00
|
|
|
|
voice_queue.append(video)
|
2017-11-09 19:34:18 +00:00
|
|
|
|
elif message.content.startswith("!skip"):
|
2017-11-07 17:44:00 +00:00
|
|
|
|
global voice_player
|
|
|
|
|
voice_player.stop()
|
|
|
|
|
await client.send_message(message.channel, f"⏩ Video saltato.")
|
2017-11-09 19:34:18 +00:00
|
|
|
|
elif message.content.startswith("!pause"):
|
2017-11-07 17:44:00 +00:00
|
|
|
|
if voice_player is None or not voice_player.is_playing():
|
2018-02-26 09:48:17 +00:00
|
|
|
|
await client.send_message(message.channel, f"⚠️ Non è in corso la riproduzione di un video, "
|
|
|
|
|
f"pertanto non c'è niente da pausare.")
|
2017-11-07 17:44:00 +00:00
|
|
|
|
return
|
|
|
|
|
voice_player.pause()
|
|
|
|
|
await client.send_message(message.channel, f"⏸ Riproduzione messa in pausa.\n"
|
2017-11-11 17:55:13 +00:00
|
|
|
|
f"Riprendi con `!resume`.")
|
2017-11-09 19:34:18 +00:00
|
|
|
|
elif message.content.startswith("!resume"):
|
2017-11-07 17:44:00 +00:00
|
|
|
|
if voice_player is None or voice_player.is_playing():
|
|
|
|
|
await client.send_message(message.channel, f"⚠️ Non c'è nulla in pausa da riprendere!")
|
|
|
|
|
return
|
|
|
|
|
voice_player.resume()
|
|
|
|
|
await client.send_message(message.channel, f"▶️ Riproduzione ripresa.")
|
2017-11-09 19:34:18 +00:00
|
|
|
|
elif message.content.startswith("!cancel"):
|
2018-04-03 18:26:47 +00:00
|
|
|
|
if not len(voice_queue) > 0:
|
2018-02-25 18:50:57 +00:00
|
|
|
|
await client.send_message(message.channel, f"⚠ Non ci sono video da annullare.")
|
2017-11-07 17:44:00 +00:00
|
|
|
|
return
|
2018-03-12 12:29:12 +00:00
|
|
|
|
voice_queue.pop()
|
2018-02-25 18:50:57 +00:00
|
|
|
|
await client.send_message(message.channel, f"❌ L'ultimo video aggiunto alla playlist è stato rimosso.")
|
2017-11-09 19:34:18 +00:00
|
|
|
|
elif message.content.startswith("!stop"):
|
2017-11-07 17:44:00 +00:00
|
|
|
|
if voice_player is None:
|
|
|
|
|
await client.send_message(message.channel, f"⚠ Non c'è nulla da interrompere!")
|
|
|
|
|
return
|
|
|
|
|
voice_queue = []
|
|
|
|
|
voice_player.stop()
|
|
|
|
|
voice_player = None
|
|
|
|
|
await client.send_message(message.channel, f"⏹ Riproduzione interrotta e playlist svuotata.")
|
2018-04-09 17:51:05 +00:00
|
|
|
|
elif message.content.startswith("!disconnect"):
|
|
|
|
|
if voice_client is None:
|
|
|
|
|
await client.send_message(message.channel, "⚠ Il bot in questo momento non è in chat vocale.")
|
|
|
|
|
return
|
|
|
|
|
if voice_player is not None:
|
|
|
|
|
await client.send_message(message.channel, "⚠ Prima di disconnettere il bot, interrompi la riproduzione di "
|
|
|
|
|
"una canzone scrivendo `!stop`.")
|
|
|
|
|
return
|
|
|
|
|
await voice_client.disconnect()
|
|
|
|
|
voice_client = None
|
|
|
|
|
await client.send_message(message.channel, "✅ Mi sono disconnesso dalla chat vocale.")
|
2018-02-26 09:48:17 +00:00
|
|
|
|
elif message.content.startswith("!queue"):
|
2018-05-25 17:58:30 +00:00
|
|
|
|
msg = "**Video in coda:**\n"
|
|
|
|
|
for position, video in enumerate(voice_queue[:10]):
|
|
|
|
|
msg += f"{queue_emojis[position]} {str(voice_queue[position])}\n"
|
|
|
|
|
if len(voice_queue) > 10:
|
|
|
|
|
msg += f"e altri {len(voice_queue) - 10} video!\n"
|
2018-02-26 15:38:47 +00:00
|
|
|
|
await client.send_message(message.channel, msg)
|
2017-11-11 17:55:13 +00:00
|
|
|
|
elif message.content.startswith("!cast"):
|
|
|
|
|
try:
|
|
|
|
|
spell = message.content.split(" ", 1)[1]
|
|
|
|
|
except IndexError:
|
2018-02-26 15:38:47 +00:00
|
|
|
|
await client.send_message(message.channel, "⚠️ Non hai specificato nessun incantesimo!\n"
|
|
|
|
|
"Sintassi corretta: `!cast <nome_incantesimo>`")
|
2017-11-11 17:55:13 +00:00
|
|
|
|
return
|
2018-04-20 17:46:33 +00:00
|
|
|
|
target: discord.Member = random.sample(list(message.server.members), 1)[0]
|
|
|
|
|
await client.send_message(message.channel, cast.cast(spell_name=spell, target_name=target.name,
|
|
|
|
|
platform="discord"))
|
2018-01-25 14:24:17 +00:00
|
|
|
|
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)
|
2017-11-09 19:34:18 +00:00
|
|
|
|
elif __debug__ and message.content.startswith("!exception"):
|
2017-11-10 07:53:48 +00:00
|
|
|
|
raise Exception("!exception was called")
|
2017-11-05 21:50:37 +00:00
|
|
|
|
|
2017-10-30 12:45:38 +00:00
|
|
|
|
|
|
|
|
|
async def update_users_pipe(users_connection):
|
|
|
|
|
await client.wait_until_ready()
|
|
|
|
|
while True:
|
2018-01-15 12:42:40 +00:00
|
|
|
|
msg = await loop.run_in_executor(executor, users_connection.recv)
|
2017-10-30 12:45:38 +00:00
|
|
|
|
if msg == "/cv":
|
|
|
|
|
discord_members = list(client.get_server(config["Discord"]["server_id"]).members)
|
|
|
|
|
users_connection.send(discord_members)
|
|
|
|
|
|
|
|
|
|
|
2018-05-25 17:58:30 +00:00
|
|
|
|
def command(func):
|
|
|
|
|
"""Decorator. Runs the function as a Discord command."""
|
|
|
|
|
async def new_func(channel: discord.Channel, author: discord.Member, params: typing.List[str], *args, **kwargs):
|
|
|
|
|
sentry.user_context({
|
|
|
|
|
"discord_id": author.id,
|
|
|
|
|
"username": f"{author.name}#{author.discriminator}"
|
|
|
|
|
})
|
|
|
|
|
try:
|
|
|
|
|
result = await func(channel=channel, author=author, params=params, *args, **kwargs)
|
|
|
|
|
except Exception:
|
|
|
|
|
try:
|
|
|
|
|
await client.send_message(channel,
|
|
|
|
|
f"☢ **ERRORE DURANTE L'ESECUZIONE DEL COMANDO {params[0]}**\n"
|
|
|
|
|
f"Il comando è stato ignorato.\n"
|
|
|
|
|
f"Una segnalazione di errore è stata automaticamente mandata a Steffo.\n\n"
|
|
|
|
|
f"Dettagli dell'errore:\n"
|
|
|
|
|
f"```python\n"
|
|
|
|
|
f"{repr(ei[1])}\n"
|
|
|
|
|
f"```")
|
|
|
|
|
except Exception:
|
|
|
|
|
pass
|
|
|
|
|
ei = sys.exc_info()
|
|
|
|
|
sentry.captureException(exc_info=ei)
|
|
|
|
|
else:
|
|
|
|
|
return result
|
|
|
|
|
return new_func
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def requires_cv(func):
|
|
|
|
|
"Decorator. Ensures the voice client is connected before running the command."
|
|
|
|
|
async def new_func(channel: discord.Channel, author: discord.User, params: typing.List[str], *args, **kwargs):
|
|
|
|
|
global voice_client
|
|
|
|
|
if voice_client is None or not voice_client.is_connected():
|
|
|
|
|
await client.send_message(channel,
|
|
|
|
|
"⚠️ Non sono connesso alla cv!\n"
|
|
|
|
|
"Fammi entrare scrivendo `!cv` mentre sei in chat vocale.")
|
|
|
|
|
return
|
|
|
|
|
return await func(channel=channel, author=author, params=params, *args, **kwargs)
|
|
|
|
|
return new_func
|
|
|
|
|
|
|
|
|
|
|
2018-05-26 08:50:54 +00:00
|
|
|
|
def requires_rygdb(func, optional=False):
|
2018-05-25 17:58:30 +00:00
|
|
|
|
async def new_func(channel: discord.Channel, author: discord.Member, params: typing.List[str], *args, **kwargs):
|
|
|
|
|
session = await loop.run_in_executor(executor, db.Session)
|
|
|
|
|
dbuser = await loop.run_in_executor(executor,
|
|
|
|
|
session.query(db.Discord)
|
|
|
|
|
.filter_by(discord_id=author.id)
|
|
|
|
|
.join(db.Royal)
|
|
|
|
|
.first)
|
2018-05-26 08:50:54 +00:00
|
|
|
|
if not optional and dbuser is None:
|
|
|
|
|
await client.send_message(channel,
|
|
|
|
|
"⚠️ Devi essere registrato su Royalnet per poter utilizzare questo comando.")
|
|
|
|
|
return
|
2018-05-25 17:58:30 +00:00
|
|
|
|
await loop.run_in_executor(executor, session.close)
|
|
|
|
|
return await func(channel=channel, author=author, params=params, dbuser=dbuser, *args, **kwargs)
|
|
|
|
|
return new_func
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@command
|
2018-05-26 08:50:54 +00:00
|
|
|
|
async def cmd_ping(channel: discord.Channel, author: discord.Member, params: typing.List[str]):
|
2018-05-25 17:58:30 +00:00
|
|
|
|
await client.send_message(channel, f"Pong!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@command
|
|
|
|
|
async def cmd_cv(channel: discord.Channel, author: discord.Member, params: typing.List[str]):
|
|
|
|
|
await client.send_typing(channel)
|
|
|
|
|
if author.voice.voice_channel is None:
|
|
|
|
|
await client.send_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(author.voice.voice_channel)
|
|
|
|
|
else:
|
|
|
|
|
voice_client = await client.join_voice_channel(author.voice.voice_channel)
|
|
|
|
|
await client.send_message(channel, f"✅ Mi sono connesso in <#{author.voice.voice_channel.id}>.")
|
|
|
|
|
|
|
|
|
|
|
2018-05-26 08:50:54 +00:00
|
|
|
|
@command
|
|
|
|
|
@requires_cv
|
|
|
|
|
async def cmd_play(channel: discord.Channel, author: discord.Member, params: typing.List[str]):
|
|
|
|
|
if len(params) < 2:
|
|
|
|
|
await client.send_message(channel, "⚠ Non hai specificato una canzone da riprodurre!\n"
|
|
|
|
|
"Sintassi: `!play <url|ricercayoutube|nomefile>`")
|
|
|
|
|
return
|
|
|
|
|
# Parse the parameter as URL
|
|
|
|
|
url = re.match(r"(?:https?://|ytsearch[0-9]*:).*", params[1].strip("<>"))
|
|
|
|
|
if url.group(0) is not None:
|
|
|
|
|
# This is a url
|
|
|
|
|
return
|
|
|
|
|
# Parse the parameter as file
|
|
|
|
|
file_path = os.path.join(os.path.join(os.path.curdir, "opusfiles"), params[1])
|
|
|
|
|
if os.path.exists(file_path):
|
|
|
|
|
# This is a file
|
|
|
|
|
return
|
|
|
|
|
# Search the parameter on youtube
|
|
|
|
|
search = params[1]
|
|
|
|
|
# This is a search
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
2017-11-05 21:50:37 +00:00
|
|
|
|
async def update_music_queue():
|
2017-11-06 15:54:36 +00:00
|
|
|
|
await client.wait_until_ready()
|
2018-02-25 18:50:57 +00:00
|
|
|
|
global voice_client
|
2017-11-20 09:49:58 +00:00
|
|
|
|
global voice_player
|
2018-02-25 18:50:57 +00:00
|
|
|
|
global voice_queue
|
2017-11-06 15:54:36 +00:00
|
|
|
|
while True:
|
2018-04-15 11:43:24 +00:00
|
|
|
|
try:
|
|
|
|
|
if voice_client is None:
|
|
|
|
|
await asyncio.sleep(5)
|
2018-04-09 20:55:48 +00:00
|
|
|
|
continue
|
2018-04-15 11:43:24 +00:00
|
|
|
|
if voice_player is not None and not voice_player.is_done():
|
|
|
|
|
await asyncio.sleep(1)
|
2018-02-25 19:47:12 +00:00
|
|
|
|
continue
|
2018-04-15 11:43:24 +00:00
|
|
|
|
if len(voice_queue) == 0:
|
|
|
|
|
await client.change_presence()
|
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
|
continue
|
|
|
|
|
video = voice_queue.pop(0)
|
|
|
|
|
if video.ytdl_url:
|
|
|
|
|
await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
|
2018-05-25 17:58:30 +00:00
|
|
|
|
f"⬇️ E' iniziato il download di {str(video)}.")
|
2018-04-15 11:43:24 +00:00
|
|
|
|
try:
|
|
|
|
|
async with async_timeout.timeout(30):
|
|
|
|
|
await video.download()
|
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
|
await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
|
|
|
|
|
f"⚠️ Il download della canzone ha richiesto più di 30 secondi ed è stato "
|
|
|
|
|
f"annullato. ")
|
|
|
|
|
continue
|
|
|
|
|
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 "
|
|
|
|
|
f"(`{config['YouTube']['max_duration']}` secondi).")
|
|
|
|
|
continue
|
|
|
|
|
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"
|
|
|
|
|
f"```\n"
|
|
|
|
|
f"{e}\n"
|
|
|
|
|
f"```")
|
|
|
|
|
continue
|
|
|
|
|
voice_player = voice_client.create_ffmpeg_player(f"opusfiles/{video.filename}.opus")
|
|
|
|
|
voice_player.start()
|
|
|
|
|
await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
|
|
|
|
|
f"▶ Ora in riproduzione in <#{voice_client.channel.id}>:\n"
|
|
|
|
|
f"`{video.filename}`")
|
|
|
|
|
await client.change_presence(game=discord.Game(name=video.filename, type=2))
|
|
|
|
|
await video.add_to_db()
|
|
|
|
|
except Exception:
|
|
|
|
|
ei = sys.exc_info()
|
|
|
|
|
try:
|
2018-02-26 09:48:17 +00:00
|
|
|
|
await client.send_message(client.get_channel(config["Discord"]["main_channel"]),
|
2018-04-15 11:43:24 +00:00
|
|
|
|
f"☢️ **ERRORE CRITICO NELL'AGGIORNAMENTO DELLA CODA DI VIDEO**\n"
|
|
|
|
|
f"Il bot si è disconnesso dalla chat vocale, e ha svuotato la coda.\n"
|
|
|
|
|
f"Una segnalazione di errore è stata automaticamente mandata a Steffo.\n\n"
|
|
|
|
|
f"Dettagli dell'errore:\n"
|
|
|
|
|
f"```python\n"
|
|
|
|
|
f"{repr(ei[1])}\n"
|
2018-02-26 09:48:17 +00:00
|
|
|
|
f"```")
|
2018-04-15 11:43:24 +00:00
|
|
|
|
if voice_player is not None:
|
|
|
|
|
await voice_player.stop()
|
|
|
|
|
voice_player = None
|
|
|
|
|
await voice_client.disconnect()
|
|
|
|
|
voice_client = None
|
|
|
|
|
voice_queue = []
|
|
|
|
|
except Exception as e:
|
|
|
|
|
print("ERRORE CRITICO PIU' CRITICO:\n" + repr(e) + "\n\n" + repr(sys.exc_info()))
|
|
|
|
|
sentry.captureException(exc_info=ei)
|
2017-11-06 15:54:36 +00:00
|
|
|
|
|
2017-11-05 21:50:37 +00:00
|
|
|
|
|
2018-01-15 12:42:40 +00:00
|
|
|
|
def process(users_connection=None):
|
2017-10-30 12:45:38 +00:00
|
|
|
|
print("Discordbot starting...")
|
2018-01-15 12:42:40 +00:00
|
|
|
|
if users_connection is not None:
|
|
|
|
|
asyncio.ensure_future(update_users_pipe(users_connection))
|
|
|
|
|
asyncio.ensure_future(update_music_queue())
|
2017-11-09 19:34:18 +00:00
|
|
|
|
client.on_error = on_error
|
2018-04-09 20:55:48 +00:00
|
|
|
|
client.run(config["Discord"]["bot_token"])
|
2018-01-15 12:42:40 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2018-01-25 14:30:07 +00:00
|
|
|
|
process()
|