client.py
This commit is contained in:
parent
62743cdb62
commit
3b3e9823ae
@ -1,38 +1,47 @@
|
||||
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)
|
||||
|
||||
# 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"]
|
||||
session_path = os.path.join(SESSION_DIR, f"{username}.json")
|
||||
|
||||
# ✅ 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:
|
||||
settings = json.load(f)
|
||||
client.load_settings(settings)
|
||||
client.login(username, password)
|
||||
print(f"✅ Reused session: {username}")
|
||||
else:
|
||||
client.login(username, password)
|
||||
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"✅ Fresh login: {username}")
|
||||
|
||||
print(f"✅ Logged in and cached: {username}")
|
||||
client_cache[username] = client
|
||||
return client
|
||||
|
||||
except Exception as e:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user