niming_igapi/backend/ig/IG.py
2025-04-26 22:36:57 +00:00

115 lines
No EOL
3.1 KiB
Python

import os
import logging
from typing import List
from instagrapi import Client
from backend.utils import ld_picturemaker
from config.config import DEBUG, ACCOUNT_USERNAME, ACCOUNT_PASSWORD
from utils.err import easyExceptionHandler
#from utils.const import DEVICE
# logging
iglog = logging.getLogger("backend.ig")
iglog.setLevel(level=logging.DEBUG)
cl:Client = Client()
def login() -> int:
# session
session_file = "./config/session.json"
session = None
if os.path.exists(session_file):
session = cl.load_settings(session_file)
cl.delay_range = [2, 5]
#cl.set_device(DEVICE)
sessionSuccess = True
# login with sessionid
if session:
iglog.info("Trying logging in with session...")
try:
cl.set_settings(session)
cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD)
cl.get_timeline_feed()
except:
sessionSuccess = False
else:
sessionSuccess = False
# login with username and password
if not sessionSuccess:
iglog.info("Trying logging in with username and password")
try:
old_session = cl.get_settings()
cl.set_settings({})
cl.set_uuids(old_session["uuids"])
cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD)
cl.get_timeline_feed()
except:
iglog.error("Cannot log in")
return 0
# save session
cl.dump_settings(session_file)
# return
username = cl.account_info().dict()["username"]
iglog.info("Logged as %s"%username)
return 1
def account_info() -> dict | None:
iglog.info("Fetching account info")
try:
info = cl.account_info().dict()
return info
except Exception as e:
easyExceptionHandler(e)
return None
def media_info(code:str) -> dict | None:
try:
pk = cl.media_pk_from_code(code)
info = cl.media_info(pk).dict()
return info
except Exception as e:
easyExceptionHandler(e)
return None
def upload_media(context:str, paths:List[str]) -> dict | None:
try:
if len(paths) == 0:
return None
elif len(paths) == 1:
content = ld_picturemaker.picture_maker.gentext(context)
media = cl.photo_upload(path=paths[0], caption=content).dict()
else:
content = ld_picturemaker.picture_maker.gentext(context)
media = cl.album_upload(paths=paths, caption=content).dict()
return media
except Exception as e:
easyExceptionHandler(e)
return None
def delete_media(code:str) -> int:
try:
media_pk = str(cl.media_pk_from_code(code))
media_id = cl.media_id(media_pk)
cl.media_delete(media_id)
return 0
except Exception as e:
easyExceptionHandler(e)
return 1
def init():
if not DEBUG and not login():
iglog.critical("login failed")
raise Exception("Failed to login to Instagram")