0
votes

I'm looking for code that let's my bot disconnect when it is alone in a voice channel, even when it is playing music. I tried different pieces of code but they don't work. This is what I have but I get an error whenever it detects an event. (its in a cog) and I want to use another command called _leave in a class called music(Music._leave)

@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
    if before.channel and len(before.channel.members) == 1:
        voice = get(bot.voice_clients, guild=member.guild)
        if voice is None:
            return
        else:
            #use _leave command

_leave code:

@commands.command(name='leave', aliases=['l'])
async def _leave(self, ctx: commands.Context):

    if not ctx.voice_state.voice:
        embedVar = discord.Embed(title="",
                                 description='Not connected to any voice channel.',
                                 color=0x000000)
        return await ctx.send(embed=embedVar)

    await ctx.voice_state.stop()
    del self.voice_states[ctx.guild.id]
1
Welcome to SO. If you are "not that good at it" can I suggest you learn some basic Python until you feel confident enough to try it.Mike Poole

1 Answers

0
votes

Guild.voice_client can be None if the bot it's not connected to a voice channel, you can check for it with a simple if statement

@client.event
async def on_voice_state_update(member, before, after):
    voice_state = member.guild.voice_client
    if voice_state is None:
        # Exiting if the bot it's not connected to a voice channel
        return 

    if len(voice_state.channel.members) == 1:
        await voice_state.disconnect()

Also make sure to enable intents.voice_states

Reference: