ruining a good night's sleep

This commit is contained in:
2025-11-18 01:48:36 +01:00
parent 12c69f4797
commit 1650f9343e

View File

@@ -9,7 +9,7 @@ class ListenerManager:
def __init__(self): def __init__(self):
# This dictionary will hold our running listener tasks. # This dictionary will hold our running listener tasks.
# The key will be the user_id and the value will be the asyncio.Task. # The key will be the user_id and the value will be the asyncio.Task.
self.active_listeners: Dict[int, asyncio.Task] = {} self.active_listeners: Dict[int, Dict] = {}
print("ListenerManager initialized.") print("ListenerManager initialized.")
async def start_listener_for_user(self, user, websocket_manager): async def start_listener_for_user(self, user, websocket_manager):
@@ -27,8 +27,10 @@ class ListenerManager:
print(f"Starting listener for user {user.id} ({user.username})...") print(f"Starting listener for user {user.id} ({user.username})...")
try:
tokens = security.decrypt_tokens(user.encrypted_tokens) tokens = security.decrypt_tokens(user.encrypted_tokens)
access_token = tokens['access_token'] access_token = tokens['access_token']
bot = TwitchBot( bot = TwitchBot(
access_token=access_token, access_token=access_token,
channel_name=user.username, channel_name=user.username,
@@ -37,10 +39,13 @@ class ListenerManager:
websocket_manager=websocket_manager, websocket_manager=websocket_manager,
db_user_id=user.id db_user_id=user.id
) )
# We now call our custom start() method in the TwitchBot class,
# which gives us direct control over the connection process.
task = asyncio.create_task(bot.start()) task = asyncio.create_task(bot.start())
self.active_listeners[user.id] = task # Store both the task and the bot instance for graceful shutdown
self.active_listeners[user.id] = {"task": task, "bot": bot}
except Exception as e:
# This will catch errors during bot instantiation (e.g., bad token)
print(f"ERROR: Failed to instantiate or start listener for user {user.id}: {e}")
async def stop_listener_for_user(self, user_id: int): async def stop_listener_for_user(self, user_id: int):
"""Stops a chat listener for a given user.""" """Stops a chat listener for a given user."""
@@ -49,7 +54,15 @@ class ListenerManager:
return return
print(f"Stopping listener for user {user_id}...") print(f"Stopping listener for user {user_id}...")
task = self.active_listeners.pop(user_id) listener_info = self.active_listeners.pop(user_id)
task = listener_info["task"]
bot = listener_info["bot"]
# Gracefully close the bot's connection
if bot and not bot.is_closed():
await bot.close()
# Cancel the asyncio task
task.cancel() task.cancel()
try: try:
await task await task