1
votes

Today I started creating my own music bot for discord with discord.py. I'm using the command extensions for a simpler structure.

So far I've created commands for joining and leaving the voice channel (Removed safety checks):

@bot.command()
async def join(ctx):
  v_channel = ctx.message.author.voice.channel
  await v_channel.connect()

@bot.command()
async def leave(ctx):
  player = ctx.message.guild.voice_client
  await player.disconnect()

Now I want to implement a feature, so that if the "audience" (Non-bot members) left the voice channel, the bot leaves too. The bot must not leave if the user who "summoned" the bot leaves but other members are still in the voice channel.

I thought about using something like this:

@bot.event
async def on_voice_state_update():
    If len(ctx.channel.members) == 1 and ctx.channel.members[0].bot:
       ctx.channel.disconnect()

But im not sure how to put it all together and how to get the channel context. I would prefer to check on exactly the music bot voice client as there are multiple bots on the server. on_voice_state_update() seems to be global and the only context you get is that User X left one of the channels somewhere on the server.

Do you have an elegant idea?

1

1 Answers

0
votes

I would do something like so:

@bot.event
async def on_voice_state_update(member, prev, cur):
    if bot.user in prev.channel.members and len([m for m in prev.channel.members if not m.bot]) == 0:
        channel = discord.utils.get(bot.voice_clients, channel=prev.channel)
        await channel.disconnect()

References: