3
votes

I need to know how to make a discord bot disconnect from a voice channel. Currently this is the code i have to join a voice channel

@client.command(pass_context=True)
async def joinvoice(ctx):
    #"""Joins your voice channel"""
    author = ctx.message.author
    voice_channel = author.voice_channel
    await client.join_voice_channel(voice_channel)

I need the code to disconnect from a voice channel

1

1 Answers

6
votes

You'll need the voice client object which is returned from await client.join_voice_channel(voice_channel). This object has a method disconnect() which allows you to do just that. The client also has an attribute voice_clients which returns an iterable of all the connected voice clients as can be seen at the docs. With that in mind, we can add a command called leavevoice (or whatever you want to call it).

@client.command(pass_context=True)
async def joinvoice(ctx):
    #"""Joins your voice channel"""
    author = ctx.message.author
    voice_channel = author.voice_channel
    vc = await client.join_voice_channel(voice_channel)

@client.command(pass_context = True)
async def leavevoice(ctx):
    for x in client.voice_clients:
        if(x.server == ctx.message.server):
            return await x.disconnect()

    return await client.say("I am not connected to any voice channel on this server!")

Here in the leavevoice command, we looped over all the voice clients the bot is connected to in order to find the voice channel for that server. Once found, disconnects. If none, then the bot isn't connected to a voice channel in that server.