Skip to content

Instantly share code, notes, and snippets.

@asarra
Last active March 8, 2025 13:04
Show Gist options
  • Save asarra/14065b34bf87b4378868de23117aed35 to your computer and use it in GitHub Desktop.
Save asarra/14065b34bf87b4378868de23117aed35 to your computer and use it in GitHub Desktop.
My Instagram library
import requests
import json
from datetime import datetime
import os
import hashlib
import hmac
import time
class Instagram():
def __init__(self, logger, username, password, use_cookie=True):
self.logger = logger
self.username = username
self.password = password
self.proxy = {}
self.path = os.getcwd()
self.base_url = "https://www.instagram.com/"
if use_cookie is False or os.path.exists(self.path+f'//cookie_{self.username}.bot') is False:
self.csrf = requests.get(self.base_url, headers={"User-Agent": "", "Cookie": 'ig_cb=2'}).cookies['csrftoken']
# see if I can login
payload = {
'username': self.username,
'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{int(datetime.now().timestamp())}:{self.password}',
'queryParams': {},
'optIntoOneTap': 'false'
}
login_response = requests.post(f'{self.base_url}accounts/login/ajax/', data=payload,
headers={"User-Agent": "", "X-CSRFToken": self.csrf, "Cookie": 'ig_cb=2'})
json_data = json.loads(login_response.text)
cookie_jar = login_response.cookies.get_dict()
try:
if json_data["authenticated"]:
pass
else:
self.logger.info("Instagram: [✗] Login Failed!", login_response.text)
return
except KeyError:
try:
if json_data["two_factor_required"]:
# self.ig_nrcb = cookie_jar['ig_nrcb'] # this one is never being used in fiddler
self.ig_did = cookie_jar['ig_did']
self.mid = cookie_jar['mid']
otp = input('[!] Two Factor Auth. Detected! Enter Code Here: ')
twofactor_url = f'{self.base_url}accounts/login/ajax/two_factor/'
twofactor_payload = {
'username': self.username,
'verificationCode': otp,
'identifier': json_data["two_factor_info"]["two_factor_identifier"],
'queryParams': {}
}
twofactor_header = {
"content-type": "application/x-www-form-urlencoded",
"cookie": 'ig_did='+self.ig_did+'; csrftoken='+self.csrf+'; mid='+self.mid,
"user-agent": "",
"x-csrftoken": self.csrf,
}
login_response = requests.post(twofactor_url, data=twofactor_payload, headers=twofactor_header, proxies=self.proxy)
elif json_data["message"] == "checkpoint_required":
self.logger.info("Instagram: Login failed. Checkpoint required. Skipping...")
except KeyError:
pass
self.sessionid = login_response.headers['Set-Cookie'].split('sessionid=')[1].split(';')[0]
self.userId = login_response.headers['Set-Cookie'].split('ds_user_id=')[1].split(';')[0]
self.cookie = "sessionid=" + self.sessionid + "; csrftoken=" + self.csrf + ";" + 'ds_user_id=' + self.userId + ";"
with open(self.path+f'//cookie_{self.username}.bot', 'w+', encoding='utf-8') as create_cookie:
create_cookie.write(self.cookie)
self.session = requests.session()
self.session.cookies.set_cookie(requests.cookies.create_cookie(name='sessionid', secure=True, value=self.sessionid))
self.logger.info("Instagram: Successfuly created cookie file")
elif os.path.exists(self.path+f'//cookie_{self.username}.bot'):
try:
with open(self.path+f'//cookie_{self.username}.bot', 'r', encoding='utf-8') as read_cookie:
self.cookie = read_cookie.read()
self.session = requests.session()
self.sessionid = self.cookie.split('=')[1].split(';')[0]
self.csrf = self.cookie.split('=')[2].split(';')[0] # replaced replace() with split()
self.uid = self.cookie.split('=')[3].split(';')[0] # we need it for video
self.session.cookies.set_cookie(requests.cookies.create_cookie(name='sessionid', secure=True, value=self.sessionid))
# see if sessionid is still valid
response = json.loads(self.session.get(f"{self.base_url}rupload_igphoto").content)
if hasattr(response, "message") and (response["message"] == "login_required" or response["status"] == "fail"):
os.remove(self.path+f'//cookie_{self.username}.bot')
self.logger.info("Instagram: [-] Deleted Corupted Cookie File! Try Again!")
return
except Exception:
os.remove(self.path+f'//cookie_{self.username}.bot')
self.logger.info("Instagram: Deleted cookie file. Try again!")
def upload_photo(self, image_path, caption=''):
try:
micro_time = int(datetime.now().timestamp())
headers = {
"content-type": "image/jpg",
"X-Entity-Name": f"fb_uploader_{micro_time}",
"Offset": "0",
"x-entity-length": "1",
"X-Instagram-Rupload-Params": f'{{"media_type": 1, "upload_id": {micro_time}, "upload_media_height": 1080, "upload_media_width": 1080}}',
"x-csrftoken": self.csrf,
"cookie": self.cookie
}
json_data = json.loads(requests.post(f'{self.base_url}rupload_igphoto/fb_uploader_{micro_time}',
data=open(image_path, "rb"), headers=headers, proxies=self.proxy).text)
if json_data["status"] == "ok":
url = f"{self.base_url}create/configure/"
payload = 'upload_id=' + json_data['upload_id'] + '&caption=' + caption
headers = {'content-type': 'application/x-www-form-urlencoded', 'x-csrftoken': self.csrf, 'cookie': self.cookie}
if json.loads(requests.request("POST", url, headers=headers, data=payload.encode('utf-8'), proxies=self.proxy).text)["status"] == "ok":
return True
else:
return False
except Exception as e:
self.logger.info(f"Instagram: Error: {e}")
return False
def upload_video(self, video_path, image_path, caption=''):
try:
# Upload video
upload_id = str(int(time.time() * 1000))
final = upload_id + '_0_' + str(hash("aaaaa"))
url = f'{self.base_url}rupload_igvideo/{final}'
headers = {
"content-type": "video/mp4",
'X-Entity-Name': final,
'X-Instagram-Rupload-Params': json.dumps({"upload_id": upload_id, "media_type": "2"}),
"Offset": "0", # do we need this
'X-Entity-Length': str(os.path.getsize(video_path)),
"x-csrftoken": self.csrf,
"cookie": self.cookie
}
if json.loads(requests.post(url, data=open(video_path, "rb"), headers=headers, proxies=self.proxy).text)["status"] == "ok":
# Configure the thumbnail part
url = f'{self.base_url}rupload_igphoto/{final}'
headers['X-Instagram-Rupload-Params'] = json.dumps({"media_type": "2", "upload_id": upload_id})
if "jpg" in image_path:
headers['X-Entity-Type'] = 'image/jpeg'
elif "png" in image_path:
headers['X-Entity-Type'] = 'image/png'
headers['X-Entity-Length'] = str(os.path.getsize(image_path))
if json.loads(requests.post(url, data=open(image_path, "rb"), headers=headers).text)["status"] == "ok":
# Confirm video upload
url = f"{self.base_url}create/configure/?video=1"
datapostvid = {
"_csrftoken": self.csrf,
"_uid": self.uid,
"caption": caption,
"upload_id": upload_id,
'audio_muted': False,
}
headers = {'content-type': 'application/x-www-form-urlencoded', 'x-csrftoken': self.csrf, 'cookie': self.cookie}
data = json.dumps(datapostvid).encode('utf-8')
_hash = hmac.new("".encode("utf-8"), data, hashlib.sha256).hexdigest()
signature = 'signed_body=' + _hash + '.' + data
if json.loads(requests.post(url, headers=headers, data=signature, proxies=self.proxy).text)["status"] == "ok":
# Video upload was successful
return True
else:
return False
except Exception as e:
self.logger.info(f"Instagram: Error: {e}")
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment