Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up adding tracks from playlist #20

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cogs/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ async def on_command_error(self, ctx, error):
embed.set_footer(text=f"Server : {ctx.guild.name} - {ctx.guild.id} | Author : {ctx.author} - {ctx.author.id}")
await channel.send(embed=embed)

print("\n\n⚠️⚠️⚠️ " + datetime.datetime.now().strftime("%x at %X") + " Ignoring exception in command {}\n:".format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
print("\n\n⚠️⚠️⚠️ " + datetime.datetime.now().strftime("%x at %X") + " Ignoring exception in command {}\n:".format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)


@commands.Cog.listener()
Expand Down
8 changes: 4 additions & 4 deletions Cogs/play.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from discord.ext import commands

from youtubesearchpython import PlaylistsSearch
from youtubesearchpython.extras import Playlist

from Tools.Utils import Utils

Expand Down Expand Up @@ -179,7 +179,8 @@ def check(message):
async def searchPlaylist(self, ctx, args):
"""Get YouTube links from a playlist link."""
await ctx.send("<:YouTubeLogo:798492404587954176> Searching...", delete_after=10)
videoCount = int(PlaylistsSearch(args, limit = 1).result()["result"][0]["videoCount"])
#videoCount = int(PlaylistsSearch(args, limit = 1).result()["result"][0]["videoCount"])
videoCount = int(Playlist.getInfo(args)["videoCount"])
if videoCount == 0:
await noResultFound(self, ctx)
return None
Expand All @@ -191,7 +192,6 @@ async def searchPlaylist(self, ctx, args):
tracks = await self.bot.wavelink.get_tracks(args)
return tracks.tracks


async def playlistTooLarge(self, ctx):
"""Send an embed with the error : playlist is too big."""
embed=discord.Embed(title="Search results :", description=f"{self.bot.emojiList.false} The playlist is too big! (max : {self.playlistLimit} tracks)", color=discord.Colour.random())
Expand Down Expand Up @@ -267,7 +267,7 @@ async def play(self, ctx, *args):

tracks = args

await addTrack(self, ctx, tracks)
await addTrack(self, ctx, self.playlistLimit, tracks)


def setup(bot):
Expand Down
6 changes: 3 additions & 3 deletions Cogs/skip.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ async def skip(self, ctx):
if not ratio > 50:
return await ctx.send(f"{ctx.author.mention} Waiting for other voice users! ({usersCount}/{ceil(len(ctx.author.voice.channel.voice_states)/2)})")

player = self.bot.wavelink.get_player(ctx.guild.id)
await player.seek(player.current.duration)

# Clean the dict
DBSkip(self.bot.dbConnection).clear(ctx.guild.id)
await ctx.send(f"{ctx.author.mention} Current music skipped!")

player = self.bot.wavelink.get_player(ctx.guild.id)
await player.seek(player.current.duration)

def setup(bot):
bot.add_cog(CogSkip(bot))
111 changes: 63 additions & 48 deletions Tools/addTrack.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
from DataBase.Server import DBServer


async def addTrack(self, ctx, tracks):

async def addTrack(self, ctx, playlistLimit, tracks):
if not await Check().userInVoiceChannel(ctx, self.bot): return

# If there is only one track
Expand All @@ -30,9 +29,11 @@ async def addTrack(self, ctx, tracks):
await ctx.send(f"{ctx.author.mention} Connected in **`{channel.name}`**!")

playlistMessage = None
embeds = []
index = None
queueLengthToAdd = len(tracks)

for track in tracks:

tempLink = track
if isinstance(track, str):
# Convert the link in a track
Expand All @@ -43,55 +44,69 @@ async def addTrack(self, ctx, tracks):

requester = f"{ctx.author.name}#{ctx.author.discriminator}"
# Add the requester
if player.is_playing:
queueSize = DBQueue(self.bot.dbConnection).countQueueItems(ctx.guild.id)
if queueSize >= 50:
return await ctx.channel.send(f"{self.bot.emojiList.false} {ctx.author.mention} You are over the queue limit! The limit of the queue is 50 songs.")
index = DBQueue(self.bot.dbConnection).getFutureIndex(ctx.guild.id)
if index is not None:
index += 1
# Add to the queue
queueSize = DBQueue(self.bot.dbConnection).countQueueItems(ctx.guild.id)
if playlistLimit != 0 and queueSize >= playlistLimit:
await ctx.channel.send(f"{self.bot.emojiList.false} {ctx.author.mention} You are over the queue limit! The limit of the queue is {playlistLimit} songs.")
break
index = DBQueue(self.bot.dbConnection).getFutureIndex(ctx.guild.id)

if index is None:
index = 0

index += 1
# Add to the queue
if not player.is_playing:
DBServer(self.bot.dbConnection).clearMusicParameters(ctx.guild.id, False, False)
await playTrack(self, ctx, player, track, requester)
else:
DBQueue(self.bot.dbConnection).add(ctx.guild.id, False, requester, ctx.channel.id, track.uri, track.title, track.duration, index)

trackDuration = await Utils().durationFormat(track.duration)
trackTitle = track.title.replace("*", "\\*")
trackDuration = await Utils().durationFormat(track.duration)
trackTitle = track.title.replace("*", "\\*")

if len(tracks) == 1:
if len(tracks) == 1:
# Queue size and duration
queueSizeAndDuration = DBQueue(self.bot.dbConnection).queueSizeAndDuration(ctx.guild.id)
if queueSizeAndDuration:
queueDuration = int(queueSizeAndDuration[0])
queueDuration = await Utils().durationFormat(queueDuration)
queueSize = queueSizeAndDuration[1]
else:
queueSize = 0
queueDuration = "00:00"

# Queue size and duration
queueSizeAndDuration = DBQueue(self.bot.dbConnection).queueSizeAndDuration(ctx.guild.id)
if queueSizeAndDuration:
queueDuration = int(queueSizeAndDuration[0])
queueDuration = await Utils().durationFormat(queueDuration)
queueSize = queueSizeAndDuration[1]
else:
queueSize = 0
queueDuration = "00:00"

embed=discord.Embed(title="Song added in the queue", description=f"New song added : **[{trackTitle}]({track.uri})** ({trackDuration})", color=discord.Colour.random())
embed.add_field(name="Place in the queue : ", value=f"`{queueSize}`", inline=True)
embed.add_field(name="Estimated time before playing :", value=f"`{queueDuration}`", inline=True)
embed.set_thumbnail(url=track.thumb)
await ctx.channel.send(embed=embed)
playlistMessage=discord.Embed(title="Song added in the queue", description=f"New song added : **[{trackTitle}]({track.uri})** ({trackDuration})", color=discord.Colour.random())
playlistMessage.add_field(name="Place in the queue : ", value=f"`{queueSize}`", inline=True)
playlistMessage.add_field(name="Estimated time before playing :", value=f"`{queueDuration}`", inline=True)
playlistMessage.set_thumbnail(url=track.thumb)
else:
# If it's a playlist => Update the same message to do not spam the channel
if playlistMessage is None:
playlistMessage = discord.Embed(title="Song added in the queue", description=f"- **[{trackTitle}]({track.uri})** ({trackDuration})", color=discord.Colour.random())
playlistMessage.set_thumbnail(url=track.thumb)
else:
# If it's a playlist => Update the same message to do not spam the channel
if playlistMessage is None:
embed=discord.Embed(title="Song added in the queue", description=f"- **[{trackTitle}]({track.uri})** ({trackDuration})", color=discord.Colour.random())
embed.set_thumbnail(url=track.thumb)
playlistMessage = await ctx.channel.send(embed=embed)
if len(playlistMessage.description + f"\n- **[{trackTitle}]({track.uri})** ({trackDuration})") > 4096:
embeds.append(playlistMessage)
playlistMessage = discord.Embed(title="Song added in the queue", description=f"- **[{trackTitle}]({track.uri})** ({trackDuration})", color=discord.Colour.random())
playlistMessage.set_thumbnail(url=track.thumb)
else:
# Update the message
embedEdited = discord.Embed(title="Songs added in the queue", description= playlistMessage.embeds[0].description + f"\n- **[{trackTitle}]({track.uri})** ({trackDuration})", color=discord.Colour.random())
playlistMessage.embeds[0].description = embedEdited.description
if len(playlistMessage.embeds[0].description) > 1800:
embed=discord.Embed(title="Song added in the queue", description=f"- **[{trackTitle}]({track.uri})** ({trackDuration})", color=discord.Colour.random())
embed.set_thumbnail(url=track.thumb)
playlistMessage = await ctx.channel.send(embed=embed)
else:
await playlistMessage.edit(embed=embedEdited)
else:
DBServer(self.bot.dbConnection).clearMusicParameters(ctx.guild.id, False, False)
playlistMessage = discord.Embed(title="Songs added in the queue", description=playlistMessage.description + f"\n- **[{trackTitle}]({track.uri})** ({trackDuration})", color=discord.Colour.random())

embeds.append(playlistMessage)

queueSizeAndDuration = DBQueue(self.bot.dbConnection).queueSizeAndDuration(ctx.guild.id)
if queueSizeAndDuration:
queueSize = queueSizeAndDuration[1]
else:
queueSize = 0

if (queueLengthToAdd> 1):
total=discord.Embed(title=f"{queueLengthToAdd} added, {queueSize} in queue")
else:
total=discord.Embed(title=f"No Songs added to the queue")

await ctx.channel.send(embed=total)

for embedMessage in embeds:
await ctx.channel.send(embed=embedMessage)

DBQueue(self.bot.dbConnection).add(ctx.guild.id, True, requester, ctx.channel.id, track.uri, track.title, track.duration, 1) # Add to the DB
# Play the track
await playTrack(self, ctx, player, track, requester)