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 typing import *
from royalnet.commands import * from royalnet.commands import *
from royalnet.utils import * from royalnet.utils import *
from royalnet.backpack.tables import User, Discord
class PlayCommand(Command): class PlayCommand(Command):
@ -16,7 +17,7 @@ class PlayCommand(Command):
syntax = "{url}" syntax = "{url}"
async def get_url(self, args: CommandArgs): 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: async def run(self, args: CommandArgs, data: CommandData) -> None:
# if not (url.startswith("http://") or url.startswith("https://")): # if not (url.startswith("http://") or url.startswith("https://")):
@ -33,30 +34,21 @@ class PlayCommand(Command):
guild_id: Optional[int] = guild.id guild_id: Optional[int] = guild.id
else: else:
guild_id = None 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"] user: User = await data.get_author()
if len(too_long) > 0: user_str = None
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.")
added: List[Dict[str, Any]] = response["added"] if user is not None:
if len(added) > 0: try:
reply = f"▶️ Aggiunt{'o' if len(added) == 1 else 'i'} {len(added)} file alla coda:\n" user_discord: Discord = user.discord[0]
if self.interface.name == "discord": except (AttributeError, IndexError):
await data.reply(reply) user_str = str(user)
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)
else: else:
reply += numberemojiformat([a["title"] for a in added]) user_str = str(f"<@{user_discord.discord_id}>")
await data.reply(reply)
if len(added) + len(too_long) == 0: self.loop.create_task(self.interface.call_herald_event("discord", "discord_play",
raise ExternalError("Nessun video trovato.") 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.commands import *
from royalnet.serf.discord import * from royalnet.serf.discord import *
from royalnet.bard import * from royalnet.bard import *
from royalnet.backpack.tables.users import User
from ..utils import RoyalQueue from ..utils import RoyalQueue
@ -15,18 +16,22 @@ class DiscordPlayEvent(Event):
async def run(self, async def run(self,
url: str, url: str,
guild_id: Optional[int] = None, guild_id: Optional[int] = None,
user: Optional[str] = None,
**kwargs) -> dict: **kwargs) -> dict:
if not isinstance(self.serf, DiscordSerf): if not isinstance(self.serf, DiscordSerf):
raise UnsupportedError() raise UnsupportedError()
serf: DiscordSerf = self.serf
client: discord.Client = self.serf.client
# TODO: fix this in Royalnet sometime # TODO: fix this in Royalnet sometime
candidate_players: List[VoicePlayer] = [] candidate_players: List[VoicePlayer] = []
for player in self.serf.voice_players: for player in serf.voice_players:
player: VoicePlayer player: VoicePlayer
if not player.voice_client.is_connected(): if not player.voice_client.is_connected():
continue continue
if guild_id is not None: 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: if guild != player.voice_client.guild:
continue continue
candidate_players.append(player) candidate_players.append(player)
@ -37,8 +42,8 @@ class DiscordPlayEvent(Event):
elif len(candidate_players) == 1: elif len(candidate_players) == 1:
voice_player = candidate_players[0] voice_player = candidate_players[0]
else: 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!") "Invia il comando su Discord, per favore!")
ytds = await YtdlDiscord.from_url(url) ytds = await YtdlDiscord.from_url(url)
added: List[YtdlDiscord] = [] added: List[YtdlDiscord] = []
@ -55,6 +60,30 @@ class DiscordPlayEvent(Event):
await voice_player.start() await voice_player.start()
else: else:
raise CommandError(f"Non so come aggiungere musica a [c]{voice_player.playing.__class__.__qualname__}[/c]!") 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 { return {
"added": [{ "added": [{
"title": ytd.info.title, "title": ytd.info.title,

View file

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