Audio bot unable to exit voice chat: 'NoneType' error with disconnect method

I’m making a music bot for my server. It joins voice channels fine, but when I try to make it leave, I get this error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'disconnect'

Here’s my code for joining and leaving:

@bot.command()
async def enter(ctx):
    user_vc = ctx.author.voice.channel
    await user_vc.connect()
    print('Bot entered voice chat')

@bot.command()
async def exit(ctx):
    guild = ctx.guild
    bot_vc = bot.voice_client_in(guild)
    await bot_vc.disconnect()
    print('Bot exited voice chat')

I’m using discord, commands, and random modules. Any ideas why it can’t leave?

I’ve encountered this issue before when working on my own Discord bot. The problem lies in how you’re retrieving the voice client. Instead of using bot.voice_client_in(guild), try accessing it directly through the context.

Here’s what worked for me:

@bot.command()
async def exit(ctx):
if ctx.voice_client:
await ctx.voice_client.disconnect()
await ctx.send(‘Successfully disconnected from voice channel’)
else:
await ctx.send(‘I’m not currently in a voice channel’)

This approach is more reliable because it uses the context to check and access the voice client. It also provides feedback to users, which is always helpful.

Remember to handle potential errors, like when the bot loses connection unexpectedly. You might want to add a try-except block to catch and log any exceptions that occur during the disconnect process.

The issue likely stems from attempting to disconnect when the bot isn’t in a voice channel. To resolve this, modify your exit command to first verify the bot’s voice state. Here’s a more robust approach:

@bot.command()
async def exit(ctx):
if ctx.voice_client:
await ctx.voice_client.disconnect()
print(‘Bot exited voice chat’)
else:
await ctx.send(‘Not currently in a voice channel’)

This checks if the bot is connected to a voice channel in the current context before attempting to disconnect. It also provides feedback to the user if the bot isn’t in a channel, which can help with debugging and user experience.

hey there! sounds like ur bot_vc is None when trying to disconnect.
maybe check if the bot is in a voice channel before calling disconnect.
try adding a check:

if bot_vc:
await bot_vc.disconnect()
else:
await ctx.send(‘Not in a voice channel’)

that might fix it. good luck!