Skip to content

Auto-pause and idle disconnect for a Discord music bot

Handling on_voice_state_update in discord.py so a music bot pauses when the channel empties, resumes when someone returns, never resumes a song the user paused, and leaves after idling unless in 24/7 mode.

3 min read

A music bot that keeps playing to an empty voice channel wastes audio bandwidth and loses your place in the song. Melodius for Discord pauses when everyone leaves and picks up where it stopped when someone comes back.

Why pause instead of leave

People step out of voice briefly all the time: a reconnect, switching devices, a quick call elsewhere. Leaving would throw away the queue and position. Pausing keeps both, and costs nothing.

Reading voice state updates

on_voice_state_update fires for every voice change in every server, so the handler filters hard: ignore changes that do not involve the bot's channel, and treat the bot itself leaving as the end of the session. Then one question decides everything: is any non-bot member still in the channel?

python
if any(not m.bot for m in voice.channel.members):
    if player.fetch("auto_paused"):          # I paused for nobody: play on
        player.delete("auto_paused")
        await self._set_pause(player, False)
else:
    if player.current is not None and not player.paused:
        await self._set_pause(player, True)
        player.store("auto_paused", True)

Only resume what you paused

The auto_paused flag is the important part. If a listener paused the song themselves and then left, the bot should not start playing when someone joins later. The bot resumes only a pause it made, and posts a short notice either way so the channel knows what happened.

Leaving when idle

When nothing is playing, the bot schedules a leave task per server, kept in a dictionary so it can be cancelled the moment music starts or someone acts. When it fires, the bot disconnects and posts a notice that premium servers can keep it there with 24/7 mode. The task removes itself from the dictionary only if it is still the current task for that server, so a newer schedule is never deleted by an older one finishing.

Illustrated avatar of Kumar Manas

Written by Kumar Manas

Full-stack developer in India. I build Melodius and Krypton.

Related projectMelodius for Discord: discord music bot