FastApi-ISS/utils/instagram_client.py
2025-08-07 00:53:03 +03:30

44 lines
1.5 KiB
Python

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