Is there a way to make my discord bot disconnect from the voice channel after finishing playing a song?

Eeyeo picture Eeyeo · May 16, 2020 · Viewed 7.3k times · Source

I was wondering if there was a way to make my discord bot leave the voice channel after playing the audio of a youtube video. I tried using sleep(duration of the video), but for getting and downloading the video to play, I used pafy, which gives me the duration of the video, but in the 00:00:00 format, which counts as a string, not an interger. I changed the code to diconnect at the after=lamda e: await vc.disconnect, but it gives me an error saying 'await' outside async function. My code for playing the music is below:

channel = message.author.voice.channel
vc = await channel.connect()
url = contents
url = url.strip("play ")
video = pafy.new(url)
await message.channel.send("Now playing **%s**" % video.title)

audio = video.getbestaudio()
audio.download()
duration = video.duration
player = vc.play(discord.FFmpegPCMAudio('%s.webm' % video.title), after=lambda e: await vc.disconnect)

Answer

DaveStSomeWhere picture DaveStSomeWhere · May 16, 2020

Here's a way to disconnect after the song completes (removing the after=).

Add after vc.play()

    while vc.is_playing():
        await sleep(1)
    await vc.disconnect()