FastApi-ISS/utils/instagram_client.py
2025-08-07 01:36:42 +03:30

54 lines
1.7 KiB
Python

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.")