"""Thin, defensive wrapper around pypresence.Presence. Discord Rich Presence talks to the local Discord client over a named pipe - it's simply not there if Discord isn't running, the user hasn't enabled it, or the client id is wrong. Every call here is wrapped so a missing/closed pipe just flips `connected` back to False instead of raising into the caller - the UI polls `connected` and retries on a timer. """ from __future__ import annotations import time from typing import Optional try: from pypresence import Presence from pypresence.exceptions import PyPresenceException except ImportError: # pragma: no cover - handled by requirements.txt Presence = None PyPresenceException = Exception class DiscordRPC: def __init__(self) -> None: self._presence: Optional["Presence"] = None self._client_id: Optional[str] = None self.connected = False self.start_ts: Optional[int] = None def connect(self, client_id: str) -> bool: if Presence is None: return False if self.connected and self._client_id == client_id: return True self.disconnect() if not client_id or not client_id.isdigit(): return False try: self._presence = Presence(client_id) self._presence.connect() except Exception: self._presence = None self.connected = False return False self._client_id = client_id self.connected = True self.start_ts = int(time.time()) return True def disconnect(self) -> None: if self._presence is not None: try: self._presence.close() except Exception: pass self._presence = None self.connected = False def update(self, details: str, state: str, large_image: Optional[str] = None) -> bool: if not self.connected or self._presence is None: return False try: kwargs = {"details": details, "state": state, "start": self.start_ts} if large_image: kwargs["large_image"] = large_image self._presence.update(**kwargs) return True except Exception: self.connected = False self._presence = None return False