From a46ddc9b2130b72e60bbc7cec2f6e0e5b5356329 Mon Sep 17 00:00:00 2001 From: Spencer Grimes Date: Sun, 18 Jan 2026 18:27:01 -0600 Subject: [PATCH] Added Disconnect --- bot.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/bot.py b/bot.py index 22f6795..f71fa9e 100644 --- a/bot.py +++ b/bot.py @@ -1,6 +1,7 @@ import numba_config import asyncio import io +import time from typing import Any import discord @@ -13,6 +14,10 @@ from config import Config from voice_manager import VoiceManager +# Inactivity timeout in seconds (10 minutes) +INACTIVITY_TIMEOUT = 10 * 60 + + class TTSBot(commands.Bot): """Discord bot that reads messages aloud using Pocket TTS.""" @@ -24,6 +29,7 @@ class TTSBot(commands.Bot): self.voice_manager = VoiceManager(Config.VOICES_DIR, Config.DEFAULT_VOICE) self.message_queue: asyncio.Queue[tuple[discord.Message, str]] = asyncio.Queue() + self.last_activity: float = 0.0 self._setup_slash_commands() @@ -201,6 +207,7 @@ class TTSBot(commands.Bot): await asyncio.to_thread(self.voice_manager.get_voice_state, default) self.loop.create_task(self.process_queue()) + self.loop.create_task(self.check_inactivity()) # Sync slash commands print("Syncing slash commands...") @@ -295,6 +302,7 @@ class TTSBot(commands.Bot): self.loop.call_soon_threadsafe(play_complete.set) voice_client.play(audio_source, after=after_playing) + self.last_activity = time.time() print(f"Playing audio in {voice_channel.name}") await play_complete.wait() @@ -321,6 +329,23 @@ class TTSBot(commands.Bot): wav_buffer.seek(0) return wav_buffer.read() + async def check_inactivity(self) -> None: + """Periodically check for inactivity and disconnect from voice channels.""" + while True: + await asyncio.sleep(60) # Check every minute + + if self.last_activity == 0.0: + continue + + elapsed = time.time() - self.last_activity + if elapsed >= INACTIVITY_TIMEOUT: + # Disconnect from all voice channels + for guild in self.guilds: + if guild.voice_client is not None: + print(f"Disconnecting from {guild.name} due to inactivity") + await guild.voice_client.disconnect() + self.last_activity = 0.0 + async def ensure_voice_connection(self, channel: discord.VoiceChannel) -> discord.VoiceClient | None: """Ensure we're connected to the specified voice channel.""" guild = channel.guild @@ -333,6 +358,7 @@ class TTSBot(commands.Bot): try: voice_client = await channel.connect(timeout=10.0) + self.last_activity = time.time() return voice_client except Exception as e: print(f"Failed to connect to voice channel: {e}")