How to get Instagram session id?

Question:

I am making a bot and I want the program to automatically get a session id if the old session id expires. This is the code I am currently using:

from instagrapi import Client
import os

cl = Client()

session_id = "<<SESSION ID GOES HERE>>"

print("Trying Login")
cl.login_by_sessionid(session_id)
print("Login Success")

thread = cl.direct_threads(0)[0]

command = 'python -u args.py --uuid '+ str(thread.messages[0].user_id) + ' --session_id ' + session_id
os.system(command)
# args.py takes in the uuid and session_id and executes other functions

I am using the instagrapi module.
Is there anyway I can get the sessionid using any method?

Asked By: Sohan Reddy

||

Answers:

I found a code that works.

import re
import requests

from datetime import datetime

link = 'https://www.instagram.com/accounts/login/'
login_url = 'https://www.instagram.com/accounts/login/ajax/'

time = int(datetime.now().timestamp())

payload = {
    'username': '###INSERT USERNAME###',
    'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{time}:###INSERT PASSWORD###',
    'queryParams': {},
    'optIntoOneTap': 'false'
}

with requests.Session() as s:
    r = s.get(link)
    csrf = re.findall(r"csrf_token":"(.*?)"",r.text)[0]
    r = s.post(login_url,data=payload,headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest",
        "Referer": "https://www.instagram.com/accounts/login/",
        "x-csrftoken":csrf
    })
    print(r.status_code)
    print(r.url)
    print(r.text)

    print(s.cookies.values()[6])
Answered By: Sohan Reddy
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.