Discord bot won't exit voice channel despite using disconnect() method

I’m having trouble with my Discord bot. It’s supposed to leave the voice channel when I use a command, but it’s not working right. Here’s what I’ve got:

@bot.command()
async def exit_voice(ctx):
    if ctx.voice_client:
        await ctx.voice_client.disconnect()
        await ctx.send('Left the voice channel')
    else:
        await ctx.send('Not in a voice channel')

The bot sends the message ‘Left the voice channel’ when I use the command. But it doesn’t actually leave. It just stays there. I’m not sure what I’m doing wrong. Any ideas on how to fix this?

hm, that’s weird. have u tried using voice_client.stop() before disconnect()? sometimes the bot gets stuck if it’s still playing audio. also, double-check ur bot’s permissions in the server settings. it might not have the right perms to disconnect itself

Have you checked if there are any active tasks or coroutines running in the background? Sometimes, these can prevent the bot from properly disconnecting. You might want to try adding a short delay before disconnecting:

import asyncio

@bot.command()
async def exit_voice(ctx):
    if ctx.voice_client:
        ctx.voice_client.stop()
        await asyncio.sleep(1)
        await ctx.voice_client.disconnect()
        await ctx.send('Left the voice channel')
    else:
        await ctx.send('Not in a voice channel')

This gives the bot a moment to finish any ongoing processes. Also, ensure your bot’s code isn’t reconnecting automatically elsewhere. If the issue persists, you might want to check your bot’s event logs for any errors during the disconnect process.

I encountered a similar issue with my Discord bot a while back. What worked for me was forcing the bot to stop any ongoing activities before disconnecting. Try modifying your code like this:

@bot.command()
async def exit_voice(ctx):
    if ctx.voice_client:
        ctx.voice_client.stop()
        await ctx.voice_client.disconnect(force=True)
        await ctx.send('Left the voice channel')
    else:
        await ctx.send('Not in a voice channel')

The stop() method halts any audio playback, and using force=True with disconnect() ensures the bot leaves even if there are lingering connections. Also, make sure your bot has the ‘Move Members’ permission in your server settings. This solved the problem for me, so it might work for you too.