Memory Leak in Cooldown System #2

Open
opened 2026-02-02 15:09:34 -05:00 by jared · 0 comments
Owner

ask_cooldowns = {} # Line 558
Issue: Dictionary grows indefinitely, never removes old entries.

Fix:

from collections import defaultdict
from datetime import datetime, timedelta

class CooldownManager:
def init(self, minutes: int):
self.cooldowns = {}
self.duration = timedelta(minutes=minutes)

def check(self, user_id: int) -> tuple[bool, float]:
    """Returns (can_use, remaining_time)"""
    current_time = datetime.now()
    if user_id in self.cooldowns:
        time_diff = current_time - self.cooldowns[user_id]
        if time_diff < self.duration:
            remaining = self.duration.total_seconds() - time_diff.total_seconds()
            return False, remaining / 60
    return True, 0

def update(self, user_id: int):
    self.cooldowns[user_id] = datetime.now()
    # Cleanup old entries (>24 hours)
    cutoff = datetime.now() - timedelta(hours=24)
    self.cooldowns = {k: v for k, v in self.cooldowns.items() if v > cutoff}

Usage:

ask_cooldown_manager = CooldownManager(COOLDOWN_MINUTES)

ask_cooldowns = {} # Line 558 Issue: Dictionary grows indefinitely, never removes old entries. Fix: from collections import defaultdict from datetime import datetime, timedelta class CooldownManager: def __init__(self, minutes: int): self.cooldowns = {} self.duration = timedelta(minutes=minutes) def check(self, user_id: int) -> tuple[bool, float]: """Returns (can_use, remaining_time)""" current_time = datetime.now() if user_id in self.cooldowns: time_diff = current_time - self.cooldowns[user_id] if time_diff < self.duration: remaining = self.duration.total_seconds() - time_diff.total_seconds() return False, remaining / 60 return True, 0 def update(self, user_id: int): self.cooldowns[user_id] = datetime.now() # Cleanup old entries (>24 hours) cutoff = datetime.now() - timedelta(hours=24) self.cooldowns = {k: v for k, v in self.cooldowns.items() if v > cutoff} # Usage: ask_cooldown_manager = CooldownManager(COOLDOWN_MINUTES)
Sign in to join this conversation.
No Label
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: LotusGuild/discordBot#2