1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00

Final touches

This commit is contained in:
Steffo 2019-12-03 19:00:52 +01:00
parent 332dea5206
commit d9d4857a16
7 changed files with 62 additions and 6 deletions

View file

@ -24,7 +24,7 @@ class QueueCommand(Command):
guild_id=guild_id) guild_id=guild_id)
queue_type = response["type"] queue_type = response["type"]
if queue_type == "PlayableYTDQueue": if queue_type == "RoyalQueue":
next_up = response["next_up"] next_up = response["next_up"]
now_playing = response["now_playing"] now_playing = response["now_playing"]
await data.reply(f" La coda contiene {len(next_up)} file.\n\n") await data.reply(f" La coda contiene {len(next_up)} file.\n\n")

View file

@ -1,4 +1,3 @@
import typing
import discord import discord
from royalnet.commands import * from royalnet.commands import *

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 ..utils import RoyalQueue
class DiscordPlayEvent(Event): class DiscordPlayEvent(Event):
@ -35,7 +36,7 @@ class DiscordPlayEvent(Event):
ytds = await YtdlDiscord.from_url(url) ytds = await YtdlDiscord.from_url(url)
added: List[YtdlDiscord] = [] added: List[YtdlDiscord] = []
too_long: List[YtdlDiscord] = [] too_long: List[YtdlDiscord] = []
if isinstance(voice_player.playing, PlayableYTDQueue): if isinstance(voice_player.playing, RoyalQueue):
for index, ytd in enumerate(ytds): for index, ytd in enumerate(ytds):
if ytd.info.duration >= datetime.timedelta(seconds=self.config["Play"]["max_song_duration"]): if ytd.info.duration >= datetime.timedelta(seconds=self.config["Play"]["max_song_duration"]):
too_long.append(ytd) too_long.append(ytd)

View file

@ -4,6 +4,7 @@ import base64
from typing import * from typing import *
from royalnet.commands import * from royalnet.commands import *
from royalnet.serf.discord import * from royalnet.serf.discord import *
from ..utils import RoyalQueue
class DiscordQueueEvent(Event): class DiscordQueueEvent(Event):
@ -29,7 +30,7 @@ class DiscordQueueEvent(Event):
if voice_player is None: if voice_player is None:
raise UserError("Il bot non è in nessun canale vocale.\n" raise UserError("Il bot non è in nessun canale vocale.\n"
"Evocalo prima con [c]summon[/c]!") "Evocalo prima con [c]summon[/c]!")
if isinstance(voice_player.playing, PlayableYTDQueue): if isinstance(voice_player.playing, RoyalQueue):
now_playing = voice_player.playing.now_playing now_playing = voice_player.playing.now_playing
return { return {
"type": f"{voice_player.playing.__class__.__qualname__}", "type": f"{voice_player.playing.__class__.__qualname__}",

View file

@ -2,6 +2,7 @@ from typing import *
from royalnet.commands import * from royalnet.commands import *
from royalnet.serf.discord import * from royalnet.serf.discord import *
from royalnet.serf.discord.errors import * from royalnet.serf.discord.errors import *
from ..utils import RoyalQueue
import discord import discord
@ -55,7 +56,7 @@ class DiscordSummonEvent(Event):
raise InvalidInputError("Non ho trovato nessun canale in cui connettermi.") raise InvalidInputError("Non ho trovato nessun canale in cui connettermi.")
# Create a new VoicePlayer # Create a new VoicePlayer
vp = VoicePlayer(loop=self.loop) vp = VoicePlayer(loop=self.loop)
vp.playing = await PlayableYTDQueue.create() vp.playing = await RoyalQueue.create()
# Connect to the channel # Connect to the channel
try: try:
await vp.connect(channel) await vp.connect(channel)

View file

@ -3,5 +3,14 @@ from .mminterfacedata import MMInterfaceData, MMInterfaceDataTelegram
from .leaguetier import LeagueTier from .leaguetier import LeagueTier
from .leaguerank import LeagueRank from .leaguerank import LeagueRank
from .leagueleague import LeagueLeague from .leagueleague import LeagueLeague
from .royalqueue import RoyalQueue
__all__ = ["MMChoice", "MMInterfaceData", "MMInterfaceDataTelegram", "LeagueTier", "LeagueRank", "LeagueLeague"] __all__ = [
"MMChoice",
"MMInterfaceData",
"MMInterfaceDataTelegram",
"LeagueTier",
"LeagueRank",
"LeagueLeague",
"RoyalQueue",
]

View file

@ -0,0 +1,45 @@
import logging
from typing import Optional, List, AsyncGenerator, Tuple, Any, Dict
from royalnet.bard import YtdlDiscord
from royalnet.serf.discord import Playable
import discord
log = logging.getLogger(__name__)
class RoyalQueue(Playable):
"""A queue of :class:`YtdlDiscord` to be played in sequence."""
def __init__(self, start_with: Optional[List[YtdlDiscord]] = None):
super().__init__()
self.contents: List[YtdlDiscord] = []
self.now_playing: Optional[YtdlDiscord] = None
if start_with is not None:
self.contents = [*self.contents, *start_with]
log.debug(f"Created new {self.__class__.__qualname__} containing: {self.contents}")
async def _generator(self) \
-> AsyncGenerator[Optional["discord.AudioSource"], Tuple[Tuple[Any, ...], Dict[str, Any]]]:
yield
while True:
log.debug(f"Dequeuing an item...")
try:
# Try to get the first YtdlDiscord of the queue
self.now_playing: YtdlDiscord = self.contents.pop(0)
except IndexError:
# If there isn't anything, yield None
log.debug(f"Nothing to dequeue, yielding None.")
yield None
continue
log.debug(f"Yielding FileAudioSource from: {self.now_playing}")
# Create a FileAudioSource from the YtdlDiscord
# If the file hasn't been fetched / downloaded / converted yet, it will do so before yielding
async with self.now_playing.spawn_audiosource() as fas:
# Yield the resulting AudioSource
yield fas
# Delete the YtdlDiscord file
log.debug(f"Deleting: {self.now_playing}")
await self.now_playing.delete_asap()
log.debug(f"Deleting: {self.now_playing.ytdl_file}")
await self.now_playing.ytdl_file.delete_asap()
log.debug(f"Deleted successfully!")