import os import json from instagrapi import Client INSTAGRAM_ACCOUNTS = json.loads(os.getenv("INSTAGRAM_ACCOUNTS", "[]")) SESSION_DIR = os.path.join(os.getcwd(), "instagram_sessions") os.makedirs(SESSION_DIR, exist_ok=True) # Global cache of logged-in clients client_cache: dict[str, Client] = {} def get_logged_in_client() -> Client: global client_cache for account in INSTAGRAM_ACCOUNTS: username = account["username"] password = account["password"] # โœ… Return from memory if already logged in if username in client_cache: return client_cache[username] session_path = os.path.join(SESSION_DIR, f"{username}.json") client = Client() try: if os.path.exists(session_path): with open(session_path, "r") as f: session_data = json.load(f) if isinstance(session_data, dict): client.load_settings(session_data) else: raise ValueError("Invalid session format") client.login(username, password) # Save session if freshly logged in if not os.path.exists(session_path): with open(session_path, "w") as f: json.dump(client.get_settings(), f) print(f"โœ… Logged in and cached: {username}") client_cache[username] = client return client except Exception as e: print(f"โŒ Login failed for {username}: {e}") if os.path.exists(session_path): os.remove(session_path) print(f"๐Ÿงน Removed invalid session for {username}") raise Exception("โŒ All Instagram accounts failed login.")