discord bot next song python
#this may not be the most optimal way to do it.
#initializiation. this where I placed my variables.
def __init__(self, client):
self.client = client
self.queue = []
self.position= 0
#have a playback function.
async def start_playback(self,ctx):
while (len(self.queue)) > self.position:#will continue looping until the queue is exhausted.
await asyncio.sleep(5)#lessens the lag imo
if not ctx.voice_client.is_playing():
self.position+=1
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_delay_max 5', 'options': '-vn'}
source = self.queue[self.position]
source1= await discord.FFmpegOpusAudio.from_probe(source,**FFMPEG_OPTIONS)
ctx.voice_client.play(source1)
if (len(self.queue)) < self.position:#once queue is empty it clears the list and resets it
self.queue.clear()
self.position=0
# the play command
@commands.command()
async def play(self,ctx, *,query: t.Optional[str]):
voice_channel= ctx.author.voice.channel
embed = discord.Embed()
if ctx.voice_client is None:
await voice_channel.connect()
#FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
IsString=False
query = query.strip("<>")
if not re.match(URL_REGEX, query):
query1 = f" {query}"
query = f"ytsearch:{query}"
IsString=True
await ctx.send(f"Searching for{query1}....")
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
if IsString==True:
info = ydl.extract_info(query, download=False, ie_key='YoutubeSearch')
info1 = info['entries'][0]['webpage_url']
info2= ydl.extract_info(info1, download=False)
embed.description = f"Found \"[{info2.get('title', None)}]({info1})\" "
await ctx.send(embed=embed)
url2 = info2['formats'][0]['url']
else:
info = ydl.extract_info(query, download=False)
url2= info['formats'][0]['url']
embed.description = f"Found \"[{info.get('title', None)}]({query})\" "
await ctx.send(embed=embed)
source= url2
await self.add_song(ctx, source)
if not ctx.voice_client.is_playing(): #if nothing is playing it will start the playback function
self.position-=1
await self.start_playback(ctx)