1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-27 13:34:28 +00:00

Change play messages

This commit is contained in:
Steffo 2020-01-13 14:51:06 +01:00
parent 92290f791e
commit ce14ed5652
3 changed files with 55 additions and 31 deletions

View file

@ -4,6 +4,7 @@ import discord
from typing import *
from royalnet.commands import *
from royalnet.utils import *
from royalnet.backpack.tables import User, Discord
class PlayCommand(Command):
@ -16,7 +17,7 @@ class PlayCommand(Command):
syntax = "{url}"
async def get_url(self, args: CommandArgs):
return args.joined()
return args.joined(require_at_least=1)
async def run(self, args: CommandArgs, data: CommandData) -> None:
# if not (url.startswith("http://") or url.startswith("https://")):
@ -33,30 +34,21 @@ class PlayCommand(Command):
guild_id: Optional[int] = guild.id
else:
guild_id = None
response: Dict[str, Any] = await self.interface.call_herald_event("discord", "discord_play",
url=await self.get_url(args),
guild_id=guild_id)
too_long: List[Dict[str, Any]] = response["too_long"]
if len(too_long) > 0:
await data.reply(f"{len(too_long)} file non {'è' if len(too_long) == 1 else 'sono'}"
f" stat{'o' if len(too_long) == 1 else 'i'} scaricat{'o' if len(too_long) == 1 else 'i'}"
f" perchè durava{'' if len(too_long) == 1 else 'no'}"
f" più di [c]{self.config['Play']['max_song_duration']}[/c] secondi.")
user: User = await data.get_author()
user_str = None
added: List[Dict[str, Any]] = response["added"]
if len(added) > 0:
reply = f"▶️ Aggiunt{'o' if len(added) == 1 else 'i'} {len(added)} file alla coda:\n"
if self.interface.name == "discord":
await data.reply(reply)
for item in added:
embed = pickle.loads(base64.b64decode(bytes(item["stringified_base64_pickled_discord_embed"],
encoding="ascii")))
# noinspection PyUnboundLocalVariable
await message.channel.send(embed=embed)
if user is not None:
try:
user_discord: Discord = user.discord[0]
except (AttributeError, IndexError):
user_str = str(user)
else:
reply += numberemojiformat([a["title"] for a in added])
await data.reply(reply)
user_str = str(f"<@{user_discord.discord_id}>")
if len(added) + len(too_long) == 0:
raise ExternalError("Nessun video trovato.")
self.loop.create_task(self.interface.call_herald_event("discord", "discord_play",
url=await self.get_url(args),
guild_id=guild_id,
user=user_str))
# await data.reply("✅ Richiesta di riproduzione inviata!")

View file

@ -6,6 +6,7 @@ from typing import *
from royalnet.commands import *
from royalnet.serf.discord import *
from royalnet.bard import *
from royalnet.backpack.tables.users import User
from ..utils import RoyalQueue
@ -15,18 +16,22 @@ class DiscordPlayEvent(Event):
async def run(self,
url: str,
guild_id: Optional[int] = None,
user: Optional[str] = None,
**kwargs) -> dict:
if not isinstance(self.serf, DiscordSerf):
raise UnsupportedError()
serf: DiscordSerf = self.serf
client: discord.Client = self.serf.client
# TODO: fix this in Royalnet sometime
candidate_players: List[VoicePlayer] = []
for player in self.serf.voice_players:
for player in serf.voice_players:
player: VoicePlayer
if not player.voice_client.is_connected():
continue
if guild_id is not None:
guild = self.serf.client.get_guild(guild_id)
guild = client.get_guild(guild_id)
if guild != player.voice_client.guild:
continue
candidate_players.append(player)
@ -37,7 +42,7 @@ class DiscordPlayEvent(Event):
elif len(candidate_players) == 1:
voice_player = candidate_players[0]
else:
raise InvalidInputError("Non so in che Server riprodurre questo file...\n"
raise CommandError("Non so in che Server riprodurre questo file...\n"
"Invia il comando su Discord, per favore!")
ytds = await YtdlDiscord.from_url(url)
@ -55,6 +60,30 @@ class DiscordPlayEvent(Event):
await voice_player.start()
else:
raise CommandError(f"Non so come aggiungere musica a [c]{voice_player.playing.__class__.__qualname__}[/c]!")
main_channel: discord.TextChannel = client.get_channel(self.config["Discord"]["main_channel_id"])
if len(added) > 0:
if user:
await main_channel.send(escape(f"▶️ {user} ha aggiunto {len(added)} file alla coda:"))
else:
await main_channel.send(escape(f"▶️ Aggiunt{'o' if len(added) == 1 else 'i'} {len(added)} file alla"
f" coda:"))
for ytd in added:
await main_channel.send(embed=ytd.embed())
if len(too_long) > 0:
if user:
await main_channel.send(escape(
f"{len(too_long)} file non {'è' if len(too_long) == 1 else 'sono'}"
f" stat{'o' if len(too_long) == 1 else 'i'} scaricat{'o' if len(too_long) == 1 else 'i'}"
f" perchè durava{'' if len(too_long) == 1 else 'no'}"
f" più di [c]{self.config['Play']['max_song_duration']}[/c] secondi."
))
if len(added) + len(too_long) == 0:
raise
return {
"added": [{
"title": ytd.info.title,

View file

@ -2,7 +2,6 @@ from typing import *
from starlette.requests import Request
from starlette.responses import *
from royalnet.constellation import *
from royalnet.utils import *
import logging
@ -14,12 +13,16 @@ class ApiDiscordPlayStar(PageStar):
async def page(self, request: Request) -> JSONResponse:
url = request.query_params.get("url", "")
user = request.query_params.get("user")
try:
guild_id: Optional[int] = int(request.query_params.get("guild_id", None))
except (ValueError, TypeError):
guild_id = None
log.info(f"Received request to play {url} on guild_id {guild_id} via web")
response = await self.interface.call_herald_event("discord", "discord_play", url=url, guild_id=guild_id)
response = await self.interface.call_herald_event("discord", "discord_play",
url=url,
guild_id=guild_id,
user=user)
return JSONResponse(response, headers={
"Access-Control-Allow-Origin": self.interface.config['Funkwhale']['instance_url'],
"Access-Control-Allow-Origin": "*",
})