from __future__ import annotations import hashlib import time class EchoCache: def __init__(self, ttl_ms: int = 10_000): self._cache: dict[str, float] = {} self._ttl = ttl_ms def remember(self, chat_guid: str, text: str) -> None: key = self._build_key(chat_guid, text) self._cache[key] = time.monotonic() def is_echo(self, chat_guid: str, text: str) -> bool: key = self._build_key(chat_guid, text) ts = self._cache.get(key) if ts and (time.monotonic() - ts) * 1000 < self._ttl: return True return False def cleanup(self) -> None: now = time.monotonic() expired = [ k for k, ts in self._cache.items() if (now - ts) * 1000 >= self._ttl ] for k in expired: del self._cache[k] def clear(self) -> None: self._cache.clear() @staticmethod def _build_key(chat_guid: str, text: str) -> str: raw = f"{chat_guid}:{text}" return hashlib.sha256(raw.encode()).hexdigest()[:16]