From 2d41bf893c12e77515e82e1423591d8623f192cc Mon Sep 17 00:00:00 2001 From: nznaza Date: Tue, 3 Jan 2023 00:19:45 -0600 Subject: [PATCH 1/2] Changed Playlist addTrack embed messages to send them in one batch, speeding up adding tracks from a playlist, changed youtube playlist looup function to avoid searching a known playlist url --- Cogs/events.py | 4 +- Cogs/play.py | 8 ++-- Cogs/skip.py | 6 +-- Tools/addTrack.py | 111 ++++++++++++++++++++++++++-------------------- 4 files changed, 72 insertions(+), 57 deletions(-) diff --git a/Cogs/events.py b/Cogs/events.py index b1ce190..e9832bb 100644 --- a/Cogs/events.py +++ b/Cogs/events.py @@ -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() diff --git a/Cogs/play.py b/Cogs/play.py index 6332227..c4fc8c9 100644 --- a/Cogs/play.py +++ b/Cogs/play.py @@ -8,7 +8,7 @@ from discord.ext import commands -from youtubesearchpython import PlaylistsSearch +from youtubesearchpython.extras import Playlist from Tools.Utils import Utils @@ -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 @@ -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()) @@ -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): diff --git a/Cogs/skip.py b/Cogs/skip.py index e1a3648..84754c0 100644 --- a/Cogs/skip.py +++ b/Cogs/skip.py @@ -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)) \ No newline at end of file diff --git a/Tools/addTrack.py b/Tools/addTrack.py index 3e574a0..1f55314 100644 --- a/Tools/addTrack.py +++ b/Tools/addTrack.py @@ -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 @@ -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 @@ -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) \ No newline at end of file From d004af6810b4727fa49f725a7bc03304bea3c92b Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Tue, 3 Jan 2023 06:24:10 +0000 Subject: [PATCH 2/2] 'Refactored by Sourcery' --- Cogs/events.py | 55 +++++++++++++++++++++++++++++++++-------------- Cogs/play.py | 23 +++++++++----------- Cogs/skip.py | 10 ++++----- Tools/addTrack.py | 43 ++++++++++++++++++++---------------- 4 files changed, 79 insertions(+), 52 deletions(-) diff --git a/Cogs/events.py b/Cogs/events.py index e9832bb..9724601 100644 --- a/Cogs/events.py +++ b/Cogs/events.py @@ -29,11 +29,17 @@ async def on_command_error(self, ctx, error): heure = round(error.retry_after/3600) minute = round(error.retry_after/60) if jour > 0: - return await ctx.send(f'{ctx.author.mention} This command has a cooldown, be sure to wait for '+str(jour)+ "day(s)") + return await ctx.send( + f'{ctx.author.mention} This command has a cooldown, be sure to wait for {str(jour)}day(s)' + ) if heure > 0: - return await ctx.send(f'{ctx.author.mention} This command has a cooldown, be sure to wait for '+str(heure)+ " hour(s)") + return await ctx.send( + f'{ctx.author.mention} This command has a cooldown, be sure to wait for {str(heure)} hour(s)' + ) if minute > 0: - return await ctx.send(f'{ctx.author.mention} This command has a cooldown, be sure to wait for '+ str(minute)+" minute(s)") + return await ctx.send( + f'{ctx.author.mention} This command has a cooldown, be sure to wait for {str(minute)} minute(s)' + ) return await ctx.send(f'{ctx.author.mention} This command has a cooldown, be sure to wait for {error.retry_after:.2f} second(s)') if isinstance(error, BotMissingPermissions): missing = ", ".join(error.missing_perms) @@ -45,8 +51,12 @@ async def on_command_error(self, ctx, error): return await ctx.send(f"{ctx.author.mention} Required argument is missed!\nUse this model : `{self.bot.command_prefix}{ctx.command.name} {ctx.command.usage}`") if isinstance(error, ExpectedClosingQuoteError): return await ctx.send(f"{ctx.author.mention} Your request cannot only contain `{error.close_quote}`") - - embed = discord.Embed(title=f"__**COMMAND ERROR**__", description=f"[**GitHub**](https://github.com/Darkempire78/Music-Discord-Bot)\n\n**You may report this issue on the [GitHub repository](https://github.com/Darkempire78/Music-Discord-Bot)**\n```{error}```", color=discord.Colour.red()) + + embed = discord.Embed( + title="__**COMMAND ERROR**__", + description=f"[**GitHub**](https://github.com/Darkempire78/Music-Discord-Bot)\n\n**You may report this issue on the [GitHub repository](https://github.com/Darkempire78/Music-Discord-Bot)**\n```{error}```", + color=discord.Colour.red(), + ) embed.set_footer(text="Bot Created by Darkempire#8245") try: await ctx.channel.send(embed=embed) @@ -60,11 +70,22 @@ async def on_command_error(self, ctx, error): invite = await ctx.guild.channels[0].create_invite() except: invite = None - embed = discord.Embed(title=f"**ERROR :**", description=f"**Date :** " + datetime.datetime.now().strftime("%x at %X") + f"\n**Command name :** {ctx.command.name}\n**Server link :** <{invite}>\n\n```{error}```", color=discord.Colour.red()) + embed = discord.Embed( + title="**ERROR :**", + description="**Date :** " + + datetime.datetime.now().strftime("%x at %X") + + f"\n**Command name :** {ctx.command.name}\n**Server link :** <{invite}>\n\n```{error}```", + color=discord.Colour.red(), + ) 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) + print( + "\n\n⚠️⚠️⚠️ " + + datetime.datetime.now().strftime("%x at %X") + + f" Ignoring exception in command {ctx.command}\n:", + file=sys.stderr, + ) traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr) @@ -72,14 +93,16 @@ async def on_command_error(self, ctx, error): async def on_voice_state_update(self, member, before, after): # If the bot leave a voice channel - if (before.channel is not None) and (after.channel is None): - if member == self.bot.user: - - player = self.bot.wavelink.get_player(before.channel.guild.id) - if player.is_playing: - await player.destroy() - DBQueue(self.bot.dbConnection).clear(before.channel.guild.id) - DBServer(self.bot.dbConnection).clearMusicParameters(before.channel.guild.id, False, False) + if ( + (before.channel is not None) + and (after.channel is None) + and member == self.bot.user + ): + player = self.bot.wavelink.get_player(before.channel.guild.id) + if player.is_playing: + await player.destroy() + DBQueue(self.bot.dbConnection).clear(before.channel.guild.id) + DBServer(self.bot.dbConnection).clearMusicParameters(before.channel.guild.id, False, False) if (before.channel is not None) and (after.channel is not before.channel): if ( @@ -91,7 +114,7 @@ async def on_voice_state_update(self, member, before, after): if member != self.bot.user: player = self.bot.wavelink.get_player(before.channel.guild.id) await player.disconnect() - + DBServer(self.bot.dbConnection).clearMusicParameters(before.channel.guild.id, False, False) # If the bot join a voice channel diff --git a/Cogs/play.py b/Cogs/play.py index c4fc8c9..7fc7a12 100644 --- a/Cogs/play.py +++ b/Cogs/play.py @@ -60,9 +60,7 @@ async def searchSpotifyPlaylist(self, ctx, args): await ctx.send(f"{self.bot.emojiList.false} {ctx.author.mention} No song found to : `{title} - {artist}` !") else: trackLinks.append(track[0]) - if not trackLinks: # if len(trackLinks) == 0: - return None - return trackLinks + return trackLinks or None async def searchDeezer(self, ctx, args): @@ -73,14 +71,10 @@ async def searchDeezer(self, ctx, args): # Chack if it's a track if "track" in response._real_url.path: link = await searchDeezerTrack(self, ctx, session, response) - if link is None: - return None - return link + return None if link is None else link if "playlist" in response._real_url.path: links = await searchDeezerPlaylist(self, ctx, session, response) - if links is None: - return None - return links + return None if links is None else links await ctx.send(f"{self.bot.emojiList.false} {ctx.author.mention} The Deezer link is not a track!") return None @@ -117,9 +111,7 @@ async def searchDeezerPlaylist(self, ctx, session, response): await ctx.send(f"{self.bot.emojiList.false} {ctx.author.mention} No song found to : `{title} - {artist}` !") else: trackLinks.append(track[0]) - if not trackLinks: - return None - return trackLinks + return trackLinks or None async def searchSoundcloud(self, ctx, args): @@ -165,6 +157,7 @@ def check(message): messageContent = int(message.content) if ((messageContent >= 0) and (messageContent <= 5)): return message.content + try: msg = await self.bot.wait_for('message', timeout=15.0, check=check) if int(msg.content) == 0: @@ -172,7 +165,11 @@ def check(message): return None return tracks[int(msg.content) -1] except asyncio.TimeoutError: - embed = discord.Embed(title = f"**TIME IS OUT**", description = f"{self.bot.emojiList.false} {ctx.author.mention} You exceeded the response time (15s)", color = discord.Colour.red()) + embed = discord.Embed( + title="**TIME IS OUT**", + description=f"{self.bot.emojiList.false} {ctx.author.mention} You exceeded the response time (15s)", + color=discord.Colour.red(), + ) await ctx.channel.send(embed = embed) return None diff --git a/Cogs/skip.py b/Cogs/skip.py index 84754c0..689ad17 100644 --- a/Cogs/skip.py +++ b/Cogs/skip.py @@ -21,16 +21,16 @@ def __init__(self, bot): @commands.guild_only() @commands.cooldown(1, 2, commands.BucketType.member) async def skip(self, ctx): - - if not await Check().userInVoiceChannel(ctx, self.bot): return - if not await Check().botInVoiceChannel(ctx, self.bot): return + + if not await Check().userInVoiceChannel(ctx, self.bot): return + if not await Check().botInVoiceChannel(ctx, self.bot): return if not await Check().userAndBotInSameVoiceChannel(ctx, self.bot): return if not ctx.author.guild_permissions.administrator: users = DBSkip(self.bot.dbConnection).displayUsers(ctx.guild.id) usersCount = len(users) - + # If user had already skip if ctx.author.id in [ i[0] for i in users]: return await ctx.send(f"{ctx.author.mention} Waiting for other voice users! ({usersCount}/{ceil(len(ctx.author.voice.channel.voice_states)/2)})") @@ -41,7 +41,7 @@ async def skip(self, ctx): # Calcul the ratio ratio = usersCount/(len(ctx.author.voice.channel.voice_states) -1) *100 # It's a percentage - if not ratio > 50: + if 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) diff --git a/Tools/addTrack.py b/Tools/addTrack.py index 1f55314..5452191 100644 --- a/Tools/addTrack.py +++ b/Tools/addTrack.py @@ -65,9 +65,9 @@ async def addTrack(self, ctx, playlistLimit, tracks): trackTitle = track.title.replace("*", "\\*") if len(tracks) == 1: - # Queue size and duration - queueSizeAndDuration = DBQueue(self.bot.dbConnection).queueSizeAndDuration(ctx.guild.id) - if queueSizeAndDuration: + if queueSizeAndDuration := DBQueue( + self.bot.dbConnection + ).queueSizeAndDuration(ctx.guild.id): queueDuration = int(queueSizeAndDuration[0]) queueDuration = await Utils().durationFormat(queueDuration) queueSize = queueSizeAndDuration[1] @@ -79,23 +79,30 @@ async def addTrack(self, ctx, playlistLimit, tracks): 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) + elif 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) + elif ( + len( + f"{playlistMessage.description}\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: - # 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 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: - playlistMessage = discord.Embed(title="Songs added in the queue", description=playlistMessage.description + f"\n- **[{trackTitle}]({track.uri})** ({trackDuration})", color=discord.Colour.random()) - + playlistMessage = discord.Embed( + title="Songs added in the queue", + description=f"{playlistMessage.description}\n- **[{trackTitle}]({track.uri})** ({trackDuration})", + color=discord.Colour.random(), + ) + embeds.append(playlistMessage) - queueSizeAndDuration = DBQueue(self.bot.dbConnection).queueSizeAndDuration(ctx.guild.id) - if queueSizeAndDuration: + if queueSizeAndDuration := DBQueue( + self.bot.dbConnection + ).queueSizeAndDuration(ctx.guild.id): queueSize = queueSizeAndDuration[1] else: queueSize = 0 @@ -103,7 +110,7 @@ async def addTrack(self, ctx, playlistLimit, tracks): 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") + total = discord.Embed(title="No Songs added to the queue") await ctx.channel.send(embed=total)