'Discord.py disconnect from voice channel

So I was making a bot in discord.py which joins a voice channel and disconnects from it after a delay of 3 seconds, just to test how to make it disconnect. I have done much research but couldn't find it. The bot successfully connects but isn't able to disconnect. Here is the code-

if message.content == "-p":
        channel = message.author.voice.channel
        await channel.connect()
        time.sleep(3)
        await channel.disconnect()

And here is the error I get-

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\arnha\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\arnha\Desktop\Music bot\bot.py", line 44, in on_message
    await channel.disconnect()
AttributeError: 'VoiceChannel' object has no attribute 'disconnect'

Kindly help me with the same.



Solution 1:[1]

It is pretty unintuitive. You have to use disconnect() on the voice_client that is an attribute of a guild. Like this:

channel = message.author.voice.channel
await channel.connect()
time.sleep(3)
voice_client = message.guild.voice_client
await voice_client.disconnect()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TheFungusAmongUs