-
-
Notifications
You must be signed in to change notification settings - Fork 51
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 (Sourcery refactored) #21
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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,26 +70,39 @@ 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) | ||
traceback.print_exception(type(error), error, error.__traceback__, 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) | ||
|
||
|
||
@commands.Cog.listener() | ||
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) | ||
Comment on lines
-75
to
+105
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
||
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 | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,7 +8,7 @@ | |
|
||
from discord.ext import commands | ||
|
||
from youtubesearchpython import PlaylistsSearch | ||
from youtubesearchpython.extras import Playlist | ||
|
||
from Tools.Utils import Utils | ||
|
||
|
@@ -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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ):
|
||
|
||
|
||
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 | ||
Comment on lines
-76
to
+77
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
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 | ||
Comment on lines
-120
to
+114
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
|
||
|
||
async def searchSoundcloud(self, ctx, args): | ||
|
@@ -165,21 +157,27 @@ def check(message): | |
messageContent = int(message.content) | ||
if ((messageContent >= 0) and (messageContent <= 5)): | ||
return message.content | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
try: | ||
msg = await self.bot.wait_for('message', timeout=15.0, check=check) | ||
if int(msg.content) == 0: | ||
await ctx.send(f"{ctx.author.mention} Search exit!") | ||
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 | ||
|
||
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 +189,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 +264,7 @@ async def play(self, ctx, *args): | |
|
||
tracks = args | ||
|
||
await addTrack(self, ctx, tracks) | ||
await addTrack(self, ctx, self.playlistLimit, tracks) | ||
|
||
|
||
def setup(bot): | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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) | ||
|
||
Comment on lines
-24
to
+33
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
|
||
# 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,15 +41,15 @@ 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) | ||
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)) |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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,76 @@ 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("*", "\\*") | ||
|
||
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" | ||
|
||
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) | ||
trackDuration = await Utils().durationFormat(track.duration) | ||
trackTitle = track.title.replace("*", "\\*") | ||
|
||
if len(tracks) == 1: | ||
if queueSizeAndDuration := DBQueue( | ||
self.bot.dbConnection | ||
).queueSizeAndDuration(ctx.guild.id): | ||
Comment on lines
-68
to
+70
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Function
This removes the following comments ( why? ):
|
||
queueDuration = int(queueSizeAndDuration[0]) | ||
queueDuration = await Utils().durationFormat(queueDuration) | ||
queueSize = queueSizeAndDuration[1] | ||
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) | ||
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) | ||
queueSize = 0 | ||
queueDuration = "00:00" | ||
|
||
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) | ||
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: | ||
DBServer(self.bot.dbConnection).clearMusicParameters(ctx.guild.id, False, False) | ||
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) | ||
|
||
if queueSizeAndDuration := DBQueue( | ||
self.bot.dbConnection | ||
).queueSizeAndDuration(ctx.guild.id): | ||
queueSize = queueSizeAndDuration[1] | ||
else: | ||
queueSize = 0 | ||
|
||
if (queueLengthToAdd> 1): | ||
total=discord.Embed(title=f"{queueLengthToAdd} added, {queueSize} in queue") | ||
else: | ||
total = discord.Embed(title="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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Function
EventsCog.on_command_error
refactored with the following changes:use-fstring-for-concatenation
)remove-redundant-fstring
)use-fstring-for-formatting
)