I’ve been trying to get my music bot to leave a voice channel it’s in if it’s been alone for more than 5 seconds but can’t seem to get it to work. I’d appreciate any pointers toward the correct implementation.
class MusicCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.voice_state_timers = {}
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
def start_inactivity_timer(self, guild, voice_state):
async def inactivity_timer():
await asyncio.sleep(5) # 5 seconds countdown
if guild.id in self.voice_state_timers and self.voice_state_timers[guild.id] == voice_state:
if len(voice_state.channel.members) == 1:
await self.disconnect_and_cleanup(voice_state)
interaction_channel_id = getattr(voice_state, 'interaction_channel_id', None)
if interaction_channel_id:
channel = self.bot.get_channel(interaction_channel_id)
if channel:
await self.send_inactivity_message(channel)
else:
logging.error("Cannot find the channel to send the inactivity message.")
else:
logging.error("Interaction channel ID not set on voice state.")
else:
del self.voice_state_timers[guild.id]
asyncio.create_task(inactivity_timer())
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
if member == self.bot.user: # Check if it's the bot whose voice state changed
if after.channel and len(after.channel.members) == 1: # Bot is alone in the channel
guild = member.guild
self.voice_state_timers[guild.id] = after # Store the voice state for the guild
self.start_inactivity_timer(guild, after)
elif before.channel and len(before.channel.members) == 1: # Bot was alone but not anymore
guild = member.guild
if guild.id in self.voice_state_timers:
del self.voice_state_timers[guild.id] # Reset the timer
The listener seems to never actually be listening to any voice state changes, despite having the necessary intents and the cog being loaded
New contributor
Noah is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.