diff --git a/instagram_monitor.py b/instagram_monitor.py index 83d1983..e89ffc6 100644 --- a/instagram_monitor.py +++ b/instagram_monitor.py @@ -52,8 +52,13 @@ class InstagramMonitor: if session_path.exists(): try: self.loader.load_session_from_file(config.instagram_username, str(session_path)) - logger.info(f"Session loaded from {session_path}") - return True + # Verify session belongs to the right account + if self._verify_session(): + logger.info(f"Session loaded from {session_path}") + return True + else: + logger.warning(f"Session from {session_path} belongs to wrong account, skipping") + self._reset_session() except Exception as e: logger.warning(f"Session file {session_path} invalid: {e}") @@ -134,6 +139,20 @@ class InstagramMonitor: # Verify session works instaloader.Profile.from_username(self.loader.context, config.instagram_username) + def _verify_session(self) -> bool: + """Check if loaded session belongs to the expected account.""" + try: + profile = instaloader.Profile.from_username(self.loader.context, config.instagram_username) + return True + except instaloader.exceptions.ProfileNotExistsException: + return False + except Exception: + return False + + def _reset_session(self) -> None: + """Clear session cookies to start fresh.""" + self.loader.context._session.cookies.clear() + def _load_cookies_from_json(self, path: Path) -> None: with open(path) as f: cookies = json.load(f)