Skip to content

Commit

Permalink
Enhance playing feature
Browse files Browse the repository at this point in the history
  • Loading branch information
TheophileDiot committed Jun 23, 2022
1 parent 99ab9f6 commit b9089db
Show file tree
Hide file tree
Showing 2 changed files with 153 additions and 79 deletions.
103 changes: 44 additions & 59 deletions cogs/dj/play.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,40 +375,28 @@ async def play_slash_command(

async def add_song_to_queue(
self,
source: Union[Context, GuildCommandInteraction],
source: GuildCommandInteraction,
track: dict,
player,
query: str,
audio_file: Attachment = None,
sleeping: float = 0.0,
multiple: bool = False,
) -> Optional[dict]:
yt_infos = None
try:
if self.yt_rx.match(track["info"]["uri"]) and sleeping == 0.0:
if self.yt_rx.match(track["info"]["uri"]) and multiple is False:
yt_infos = self.ytdl.extract_info(track["info"]["uri"], download=False)
except Exception as e:
if not f"{e}".endswith("This video may be inappropriate for some users."):
if isinstance(source, Context):
return await source.channel.send(
f"⚠️ - An error occurred while retrieving the video information ({track['info']['uri']}), please try again in a few moments!",
delete_after=20,
)
else:
return await source.followup.send(
f"⚠️ - {source.author.mention} - An error occurred while retrieving the video information ({track['info']['uri']}), please try again in a few moments!",
ephemeral=True,
)
return await source.followup.send(
f"⚠️ - {source.author.mention} - An error occurred while retrieving the video information ({track['info']['uri']}), please try again in a few moments!",
ephemeral=True,
)
else:
if isinstance(source, Context):
return await source.channel.send(
f"⚠️ - This video is not suitable for some users ({track['info']['uri']})! (I can't play some age restricted videos)",
delete_after=20,
)
else:
return await source.followup.send(
f"⚠️ - {source.author.mention} - This video is not suitable for some users ({track['info']['uri']})! (I can't play some age restricted videos)",
ephemeral=True,
)
return await source.followup.send(
f"⚠️ - {source.author.mention} - This video is not suitable for some users ({track['info']['uri']})! (I can't play some age restricted videos)",
ephemeral=True,
)

# You can attach additional information to audiotracks through kwargs, however this involves
# constructing the AudioTrack class yourself.
Expand Down Expand Up @@ -453,8 +441,6 @@ async def add_song_to_queue(
}
)

await sleep(sleeping)

return yt_infos

async def add_spotify_song_to_queue(
Expand All @@ -463,7 +449,7 @@ async def add_spotify_song_to_queue(
track: dict,
player,
query: str = "ytsearch",
sleeping: float = 0.0,
multiple: bool = False,
) -> Optional[dict]:
try:
results = await player.node.get_tracks(
Expand All @@ -479,9 +465,32 @@ async def add_spotify_song_to_queue(

track = results["tracks"][0]
return await self.add_song_to_queue(
source, track, player, query, sleeping=sleeping
source, track, player, query, multiple=multiple
)

async def add_songs_to_queue(
self,
source: Union[Context, GuildCommandInteraction],
tracks: List[dict],
player,
query: str = "ytsearch",
_type: str = "regular",
):
for track in tracks:
if player.is_playing:
# Add all of the tracks from the playlist to the queue.
if _type == "regular":
await self.add_song_to_queue(
source, track, player, query, multiple=True
)
else:
await self.add_spotify_song_to_queue(
source, track, player, multiple=True
)

if not player.is_playing:
self.bot.playlists[source.guild.id] = []

async def handle_play(
self,
source: Union[Context, GuildCommandInteraction],
Expand Down Expand Up @@ -604,15 +613,6 @@ async def handle_play(
ephemeral=True,
)

# if audio_file:
# if not isinstance(source, Context):
# message = await source.channel.send(
# f"💿 - `{audio_file.filename}` - 💿", file=await audio_file.to_file()
# )
# query = message.attachments[0].url
# else:
# query = audio_file.url

if not isinstance(query, list):
try:
results = await player.node.get_tracks(query)
Expand Down Expand Up @@ -675,24 +675,16 @@ async def handle_play(
# LOAD_FAILED - most likely, the video encountered an exception during loading.
if results["loadType"] == "PLAYLIST_LOADED":
tracks = results["tracks"]
max_length_reached = False

if len(tracks) > 40:
tracks = tracks[:40]

yt_infos = await self.add_song_to_queue(
source, tracks.pop(0), player, query
)

for track in tracks:
# Add all of the tracks from the playlist to the queue.
self.bot.loop.create_task(
self.add_song_to_queue(
source, track, player, query, sleeping=2.0
)
)
self.bot.loop.create_task(
self.add_songs_to_queue(source, tracks, player)
)

content = f"🎶 - **Adding the playlist to the server playlist{' (the playlist was cropped because the max length for playlist queries is 40 songs)' if max_length_reached else ''}:** - 🎶"
content = f"🎶 - **Adding the playlist to the server playlist:** - 🎶"
else:
track = results["tracks"][0]

Expand All @@ -709,18 +701,11 @@ async def handle_play(
source, query.pop(0), player
)

max_length_reached = False

if len(query) > 40:
query = query[:40]

for track in query:
# Add all of the tracks from the playlist to the queue.
self.bot.loop.create_task(
self.add_spotify_song_to_queue(source, track, player, sleeping=2.0)
)
self.bot.loop.create_task(
self.add_songs_to_queue(source, query, player, _type="spotify")
)

content = f"🎶 - **Adding the spotify playlist to the server playlist{' (the playlist was cropped because the max length for playlist queries is 40 songs)' if max_length_reached else ''}:** - 🎶"
content = f"🎶 - **Adding the spotify playlist to the server playlist:** - 🎶"

# We don't want to call .play() if the player is playing as that will effectively skip
# the current track.
Expand Down
129 changes: 109 additions & 20 deletions cogs/dj/playlist.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
from typing import Union
from copy import deepcopy
from typing import List, Union

from disnake import Colour, Embed, GuildCommandInteraction
from disnake import (
ButtonStyle,
Colour,
Embed,
GuildCommandInteraction,
MessageInteraction,
)
from disnake.ext.commands import (
bot_has_permissions,
BucketType,
Expand All @@ -11,10 +18,76 @@
max_concurrency,
slash_command,
)
from disnake.ui import button, Button, View

from data import Utils


class Playlist(View):
def __init__(self, embeds: List[Embed]):
super().__init__(timeout=None)
self.embeds = embeds
self.embed_count = 0

self.first_page.disabled = True
self.prev_page.disabled = True

# Sets the footer of the embeds with their respective page numbers.
for i, embed in enumerate(self.embeds):
embed.set_footer(text=f"Page {i + 1} of {len(self.embeds)}")

@button(emoji="⏪", style=ButtonStyle.blurple)
async def first_page(self, button: Button, interaction: MessageInteraction):
self.embed_count = 0
embed = self.embeds[self.embed_count]
embed.set_footer(text=f"Page 1 of {len(self.embeds)}")

self.first_page.disabled = True
self.prev_page.disabled = True
self.next_page.disabled = False
self.last_page.disabled = False
await interaction.response.edit_message(embed=embed, view=self)

@button(emoji="◀", style=ButtonStyle.secondary)
async def prev_page(self, button: button, interaction: MessageInteraction):
self.embed_count -= 1
embed = self.embeds[self.embed_count]

self.next_page.disabled = False
self.last_page.disabled = False
if self.embed_count == 0:
self.first_page.disabled = True
self.prev_page.disabled = True
await interaction.response.edit_message(embed=embed, view=self)

@button(emoji="❌", style=ButtonStyle.red)
async def remove(self, button: button, interaction: MessageInteraction):
await interaction.response.edit_message(view=None)

@button(emoji="▶", style=ButtonStyle.secondary)
async def next_page(self, button: button, interaction: MessageInteraction):
self.embed_count += 1
embed = self.embeds[self.embed_count]

self.first_page.disabled = False
self.prev_page.disabled = False
if self.embed_count == len(self.embeds) - 1:
self.next_page.disabled = True
self.last_page.disabled = True
await interaction.response.edit_message(embed=embed, view=self)

@button(emoji="⏩", style=ButtonStyle.blurple)
async def last_page(self, button: button, interaction: MessageInteraction):
self.embed_count = len(self.embeds) - 1
embed = self.embeds[self.embed_count]

self.first_page.disabled = False
self.prev_page.disabled = False
self.next_page.disabled = True
self.last_page.disabled = True
await interaction.response.edit_message(embed=embed, view=self)


class Dj(Cog, name="dj.playlist"):
def __init__(self, bot):
self.bot = bot
Expand Down Expand Up @@ -71,6 +144,23 @@ async def handle_playlist(
source: Union[Context, GuildCommandInteraction],
position: int = None,
):
if not self.bot.playlists.get(source.guild.id):
if isinstance(source, Context):
return await source.reply(
f"⚠️ - {source.author.mention} - There is no playlist in this server.",
delete_after=20,
)
else:
return await source.followup.send(
f"⚠️ - {source.author.mention} - There is no playlist in this server.",
ephemeral=True,
)

if not isinstance(source, Context):
await source.response.defer()

print(self.bot.playlists.get(source.guild.id))

em = Embed(colour=Colour(0xFF0000)) # YTB color

if position is not None:
Expand Down Expand Up @@ -149,28 +239,27 @@ async def handle_playlist(
if self.bot.playlists[source.guild.id][0].get("thumbnail"):
em.set_thumbnail(url=self.bot.playlists[source.guild.id][0]["thumbnail"])

x = 0
default_em = deepcopy(em)
playlist = deepcopy(self.bot.playlists[source.guild.id])

nl = "\n"
while x < len(self.bot.playlists[source.guild.id]) and x <= 24:
if x == 24:
em.add_field(
name="**Too many sounds to display them all**",
value="...",
inline=False,
)
else:
em.add_field(
name=f"**{x + 1}:** {self.bot.playlists[source.guild.id][x]['title']}"
+ (" - *currently playing*" if x == 0 else ""),
value=f"**Type:** {self.bot.playlists[source.guild.id][x]['type']}{nl}**Author:** {self.bot.playlists[source.guild.id][x]['author']}{nl}**Duration:** {self.bot.playlists[source.guild.id][x]['duration']}{nl}**URL:** {self.bot.playlists[source.guild.id][x]['url']}",
inline=True,
)
x += 1
embeds = []
for x in range(len(playlist)):
if x != 0 and x % 25 == 0:
embeds.append(em.copy())
em = default_em.copy()

em.add_field(
name=f"**{x + 1}:** {playlist[x]['title']}"
+ (" - *currently playing*" if x == 0 else ""),
value=f"**Type:** {playlist[x]['type']}{nl}**Author:** {playlist[x]['author']}{nl}**Duration:** {playlist[x]['duration']}{nl}**URL:** {playlist[x]['url']}",
inline=True,
)

if isinstance(source, Context):
await source.send(embed=em)
await source.send(embed=embeds[0], view=Playlist(embeds))
else:
await source.response.send_message(embed=em)
await source.response.send_message(embed=embeds[0], view=Playlist(embeds))


def setup(bot):
Expand Down

0 comments on commit b9089db

Please sign in to comment.