import os import json import uuid from pathlib import Path from instagrapi import Client from dotenv import dotenv_values # Load IG accounts from env (expects a JSON list string) INSTAGRAM_ACCOUNTS = json.loads(os.getenv("INSTAGRAM_ACCOUNTS", "[]")) # Path for storing session files SESSION_DIR = os.path.join(os.getcwd(), "instagram_sessions") os.makedirs(SESSION_DIR, exist_ok=True) def get_logged_in_client() -> Client: for account in INSTAGRAM_ACCOUNTS: username = account["username"] password = account["password"] 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: settings = json.load(f) client.load_settings(settings) client.login(username, password) print(f"โœ… Reused session: {username}") else: client.login(username, password) with open(session_path, "w") as f: json.dump(client.get_settings(), f) print(f"โœ… Fresh login: {username}") 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.")