Fettiger Burger
Fettiger Burger

Reputation: 31

How to play the next Song after first finished Discord Bot

I'm trying to create a Discord music Bot with discord.py, I'm new to Python. I don't know how to let the Bot automatically play the next song. I tried many different things. This is my current code for playing one song:

vc.play(discord.FFmpegPCMAudio(executable="C:/FFmpeg/bin/ffmpeg.exe", source=sound + ".mp3"))
await message.channel.send("Spiele nun " + str(sound) +"weiter")

With the above code I didn't get a problem.

Upvotes: 3

Views: 9124

Answers (1)

MrSpaar
MrSpaar

Reputation: 3994

You should use the after parameter of the FFmpegPCMAudio function. This parameter takes a callable as an argument and executes it when the current song is over.

  • First, you have to create a song queue variable :
song_queue = []
  • Then, you'll have to change your play() function :
source = sound + '.mp3'
soung_queue.append(source)
if not vc.is_playing():
    vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
    await ctx.send("Now playing...")
else:
    await ctx.send('Song queued')
  • Finally, you'll have to create a play_next() function :
import asyncio

def play_next(ctx, source):
    if len(self.song_queue) >= 1:
        del self.song_queue[0]
        vc = get(self.bot.voice_clients, guild=ctx.guild)
        vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
        asyncio.run_coroutine_threadsafe(ctx.send("No more songs in queue."), self.bot.loop)

You can name the play_next() function whatever you want.
If you want your bot to disconnect because it's been too long since it was playing sound, change the play_next() function to :

import asyncio

def play_next(ctx, source):
    vc = get(self.bot.voice_clients, guild=ctx.guild)
    if len(self.song_queue) >= 1:
        del self.song_queue[0]
        vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
    else:
        asyncio.sleep(90) #wait 1 minute and 30 seconds
        if not vc.is_playing():
            asyncio.run_coroutine_threadsafe(vc.disconnect(ctx), self.bot.loop)
            asyncio.run_coroutine_threadsafe(ctx.send("No more songs in queue."), self.bot.loop)
            

Upvotes: 7

Related Questions