How Can I Make a discord.py Bot Leave While Using a Command Tree

Question:

I have spent over an hour on this. I am using command trees so that my commands will show up as slash commands. I already have a command to join a voice chat, however I cannot figure out how to leave. Here is my code (I know that voice_client does not go with interaction):

@tree.command(name= "leave", description = "leaves the vc", guild = server)
async def leave(interaction = discord.Interaction):
    if (interaction.voice_client): # If the bot is in a voice channel 
        await interaction.guild.voice_client.disconnect() # Leave the channel
        await interaction.send('Bot left')
    else: # But if it isn't
        await interaction.send("not in vc")

Many thanks!

I have tried passing it through client, interaction, etc and nothing has worked.

Asked By: Woodenlalaloo

||

Answers:

In your code, you are trying to use the interaction object to interact with the voice client, but that object does not have a voice_client attribute. Instead, you should use the guild attribute of the interaction object to get the guild (server) that the command was used in, and then use the voice_client attribute of that guild to disconnect from the voice channel.

Your code shoule be like this:

@tree.command(name= "leave", description = "leaves the vc", guild = server)
async def leave(interaction = discord.Interaction):
    guild = interaction.guild # Get the guild that the command was used in
    voice_client = guild.voice_client # Get the voice client for that guild

    if voice_client: # If the bot is in a voice channel 
        await voice_client.disconnect() # Leave the channel
        await interaction.send('Bot left')
    else: # But if it isn't
        await interaction.send("not in vc")

Now the function will get the guild that the command was used in, and check if it has an active voice client. If so, it will disconnect from the voice channel and send a message to confirm it. If the bot is not in a voice channel, it will send a message indicating that.

Hope that solves the problem.

Answered By: Nova
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.