"""内存限流器,防止刷屏触发 KOOK 的 429(文档警告过:多次超速可能封 bot)。""" import time import random class RateLimiter: """带自动清理的内存限流器,防止内存泄漏""" def __init__(self, cleanup_interval: int = 300): self._last_times: dict = {} self._last_cleanup = time.time() self._cleanup_interval = cleanup_interval def _cleanup_expired(self, now: float, cooldown: float): if now - self._last_cleanup < self._cleanup_interval: return self._last_cleanup = now for cmd in list(self._last_times.keys()): expired = [ uid for uid, ts in self._last_times[cmd].items() if now - ts > cooldown * 10 ] for uid in expired: del self._last_times[cmd][uid] if not self._last_times[cmd]: del self._last_times[cmd] def check_limit(self, user_id: str, command_name: str, cooldown: float): """返回 (是否被限流, 剩余秒数)""" now = time.time() if random.random() < 0.01: self._cleanup_expired(now, cooldown) bucket = self._last_times.setdefault(command_name, {}) elapsed = now - bucket.get(user_id, 0) if elapsed < cooldown: return True, round(cooldown - elapsed, 1) bucket[user_id] = now return False, 0 rate_limiter = RateLimiter()