├── README.md
├── instagram_class.py
├── like_timeline.py
├── main.py
└── story.py
/README.md:
--------------------------------------------------------------------------------
1 | # Instagram web API
2 |
3 | ## Features
4 | - Auto like timeline
5 | - Auto view story
6 |
7 | ## Instalation
8 | - `git clone https://github.com/corrykalam/InstagramAPI`
9 | - `pip3 install requests`
10 |
11 | ## RUN
12 | - `python3 story.py`
13 | - `python3 like_timeline.py`
14 |
--------------------------------------------------------------------------------
/instagram_class.py:
--------------------------------------------------------------------------------
1 | import requests, json, re, time
2 | from datetime import datetime
3 |
4 | class InstagramApi:
5 | """
6 | created with <3 by corrykalam
7 | """
8 | def __init__(self, username=None, password=None, session={}):
9 | self.username = username
10 | self.password = password
11 | self.loggedIn = False
12 | self.session = session
13 | self.headers = {}
14 | self.base_url = "https://www.instagram.com"
15 | self.generateHeaders()
16 | def generateHeaders(self):
17 | if self.session == {}:
18 | headers = {'user-agent': 'Mozilla/5.0 (Linux; Android 9; LM-G710 Build/PKQ1.181105.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.149 Mobile Safari/537.36'}
19 | else:
20 | headers = {'user-agent': 'Mozilla/5.0 (Linux; Android 9; LM-G710 Build/PKQ1.181105.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.149 Mobile Safari/537.36'}
21 | headers["x-csrftoken"] = self.session["csrftoken"]
22 | headers["cookie"] = 'csrftoken='+self.session['csrftoken']+'; sessionid='+self.session['sessionid']
23 | self.headers = headers
24 | def unixTime(self):
25 | x = str(time.time())
26 | timenow = x.split(".")[0]
27 | return timenow
28 | def getStr(self, string,start,end, index=1):
29 | try:
30 | str = string.split(start)
31 | str = str[index].split(end)
32 | return str[0]
33 | except:
34 | return False
35 | def logIn(self):
36 | web_fetch = self.base_url+"/accounts/login/"
37 | web_login_url = self.base_url+"/accounts/login/ajax/"
38 | fetch_cookies = requests.get(web_fetch).headers
39 | csrf = self.getStr(str(fetch_cookies), 'csrftoken=', ';')
40 | mid = self.getStr(str(fetch_cookies), 'mid=', ';')
41 | headers = {
42 | 'Host': 'www.instagram.com',
43 | 'x-csrftoken': csrf,
44 | 'user-agent': 'Mozilla/5.0 (Linux; Android 9; LM-G710 Build/PKQ1.181105.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.149 Mobile Safari/537.36',
45 | 'cookie': 'rur=FTW; mid='+mid+'; csrftoken='+csrf,
46 | }
47 | data = {
48 | 'username': self.username,
49 | 'enc_password': '#PWD_INSTAGRAM_BROWSER:0:{}:{}'.format(int(datetime.now().timestamp()), self.password)
50 | }
51 | fetch_login = requests.post(web_login_url, headers=headers, data=data)
52 | print(fetch_login.text)
53 | if '{"authenticated": false' in fetch_login.text:
54 | data_login = {
55 | 'action': 'login',
56 | 'status': 'error',
57 | 'username': self.username
58 | }
59 | elif '{"authenticated": true' in fetch_login.text:
60 | print("You login as %s"%(self.username))
61 | self.loggedIn = True
62 | data_login = {
63 | 'action': 'login',
64 | 'status': 'success',
65 | 'username': self.username,
66 | 'csrftoken': self.getStr(str(fetch_login.headers), 'csrftoken=', ';'),
67 | 'sessionid': self.getStr(str(fetch_login.headers), 'sessionid=', ';')
68 | }
69 | self.session = data_login
70 | self.headers["x-csrftoken"] = self.session["csrftoken"]
71 | self.headers["cookie"] = 'csrftoken='+self.session['csrftoken']+'; sessionid='+self.session['sessionid']
72 | else:
73 | data_login = fetch_login.text
74 | return data_login
75 | def getHome(self):
76 | timeline_id = []
77 | post = requests.get(self.base_url, headers=self.headers)
78 | data_output = self.getStr(post.text, "window.__additionalDataLoaded('feed',", ");")
79 | if data_output != False:
80 | json_timeline = json.loads(data_output)
81 | result = json_timeline["user"]["edge_web_feed_timeline"]
82 | for i in result["edges"]:
83 | if i["node"]["viewer_has_liked"] == False:
84 | timeline_id.append(i["node"]["id"])
85 | return timeline_id
86 | else:
87 | print("You not loggedIn!")
88 | return False
89 | def getStory(self):
90 | story_id = []
91 | query_hash = self.getQueryHash()
92 | url = 'https://www.instagram.com/graphql/query/?query_hash=%s&variables={"reel_ids":[],"tag_names":[],"location_ids":[],"highlight_reel_ids":[],"precomposed_overlay":false,"show_story_viewer_list":true,"story_viewer_fetch_count":50,"story_viewer_cursor":"","stories_video_dash_manifest":false}'%(query_hash)
93 | post = requests.get(url, headers=self.headers)
94 | json_parse = json.loads(post.text)
95 | result = json_parse["data"]["user"]["feed_reels_tray"]["edge_reels_tray_to_reel"]
96 | for i in result["edges"]:
97 | user_id = i["node"]["id"]
98 | username = i["node"]["user"]["username"]
99 | if i["node"]["items"] != None:
100 | for b in i["node"]["items"]:
101 | reelMediaId = b["id"]
102 | taken_at = b["taken_at_timestamp"]
103 | data_output = {
104 | 'reelid': reelMediaId,
105 | 'user_id': user_id,
106 | 'taken_at': str(taken_at),
107 | 'username': username
108 | }
109 | story_id.append(data_output)
110 | return story_id
111 | def seenStory(self, reelMediaId, user_id, taken_at):
112 | data = {
113 | 'reelMediaId': reelMediaId,
114 | 'reelMediaOwnerId': user_id,
115 | 'reelId': user_id,
116 | 'reelMediaTakenAt': taken_at,
117 | 'viewSeenAt': self.unixTime()
118 | }
119 | post = requests.post(self.base_url+"/stories/reel/seen", headers=self.headers, data=data)
120 | status = json.loads(post.text)
121 | if status["status"] == "ok":
122 | print("Success seen story_id %s"%(reelMediaId))
123 | return True
124 | elif "Please wait a few minutes before you try again." in post.text:
125 | print("Please wait a few minutes before you try again.")
126 | print("Failed seen story_id %s"%(reelMediaId))
127 | return False
128 | else:
129 | print(post.text)
130 | return False
131 | def follow(self, user_id):
132 | post = requests.post(self.base_url+"/web/friendships/%s/follow/"%(user_id), headers=self.headers)
133 | status = json.loads(post.text)
134 | if status["status"] == "ok":
135 | print("Success unfollow id %s"%(user_id))
136 | else:
137 | print("Failed unfollow id %s"%(user_id))
138 | def unfollow(self, user_id):
139 | post = requests.post(self.base_url+"/web/friendships/%s/unfollow/"%(user_id), headers=self.headers)
140 | status = json.loads(post.text)
141 | if status["status"] == "ok":
142 | print("Success unfollow id %s"%(user_id))
143 | else:
144 | print("Failed unfollow id %s"%(user_id))
145 | def likePost(self, id_post):
146 | post = requests.post(self.base_url+"/web/likes/%s/like/"%(id_post), headers=self.headers)
147 | status = json.loads(post.text)
148 | if status["status"] == "ok":
149 | print("Success like id %s"%(id_post))
150 | return True
151 | else:
152 | print("Failed like id %s"%(id_post))
153 | return False
154 | def unlikePost(self, id_post):
155 | post = requests.post(self.base_url+"/web/likes/%s/unlike/"%(id_post), headers=self.headers)
156 | status = json.loads(post.text)
157 | if status["status"] == "ok":
158 | print("Success unlike id %s"%(id_post))
159 | else:
160 | print("Failed unlike id %s"%(id_post))
161 | def findProfile(self, username):
162 | post = requests.get(self.base_url+"/%s/"%(username), headers=self.headers).text
163 | if "The link you followed may be broken, or the page may have been removed." in post:
164 | data_array = {
165 | 'status': 'error',
166 | 'details': 'user_not_found'
167 | }
168 | else:
169 | data_output = self.getStr(post, '')
170 | json_profile = json.loads(data_output)
171 | result = json_profile["entry_data"]["ProfilePage"][0]["graphql"]["user"]
172 | is_follow = result["followed_by_viewer"]
173 | is_private = result["is_private"]
174 | is_verified = result["is_verified"]
175 | is_follback = result["follows_viewer"]
176 | user_id = result["id"]
177 | followers = result["edge_followed_by"]["count"]
178 | following = result["edge_follow"]["count"]
179 | data_array= {
180 | 'status': 'success',
181 | 'user_id': user_id,
182 | 'username': username,
183 | 'is_follow': is_follow,
184 | 'is_private': is_private,
185 | 'is_verifed': is_verified,
186 | 'is_follback': is_follback,
187 | }
188 | return data_array
189 | def getQueryHash(self):
190 | post = requests.get(self.base_url, headers=self.headers)
191 | query_hash = self.getStr(post.text, '/graphql/query/?query_hash=', '&', 1)
192 | return query_hash
193 | def getStoryIds(self, session, limit=False):
194 | url = "https://www.instagram.com/"
195 | reel_id = []
196 | headers = {
197 | 'Host': 'www.instagram.com',
198 | 'x-csrftoken': session["csrftoken"],
199 | 'user-agent': 'Mozilla/5.0 (Linux; Android 9; LM-G710 Build/PKQ1.181105.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.149 Mobile Safari/537.36',
200 | 'cookie': 'csrftoken='+session['csrftoken']+'; sessionid='+session['sessionid']
201 | }
202 | post = requests.get(url, headers=headers)
203 | getting_link = self.getStr(post.text, '')
204 | fething_story = url+"graphql/"+ getting_link.replace("&", "&")
205 | fetch_story = requests.get(fething_story, headers=headers).text
206 | json_story = json.loads(fetch_story)
207 | result = json_story["data"]["user"]["feed_reels_tray"]["edge_reels_tray_to_reel"]["edges"]
208 | if limit == False:
209 | for items in result:
210 | try:
211 | reelid = items["node"]["id"]
212 | reel_id.append(reelid)
213 | except: pass
214 | output_fetch = json.dumps(reel_id)
215 | else:
216 | for i in range(int(limit)):
217 | try:
218 | reelid = result[i]["node"]["id"]
219 | reel_id.append(reelid)
220 | except: pass
221 | output_fetch = json.dumps(reel_id)
222 | return output_fetch
223 |
--------------------------------------------------------------------------------
/like_timeline.py:
--------------------------------------------------------------------------------
1 | from instagram_class import InstagramApi
2 | import time, random
3 | #loggin by token
4 | # token = {'action': 'login', 'status': 'success', 'username': 'corrykalam', 'csrftoken': 'asdasfwjelkfwfw', 'sessionid': 'xjkcdjksxkdlsldsd'}
5 | # get your token use function logIn()
6 | # leertsefani = InstagramApi(session=token)
7 |
8 |
9 | #login by user & password
10 | leertsefani = InstagramApi("USERNAME", "PASSWORD")
11 | leertsefani.logIn()
12 | while(True):
13 | try:
14 | timeline_id = leertsefani.getHome()
15 | for like in timeline_id:
16 | leertsefani.likePost(like)
17 | time.sleep(random.randint(4, 7))
18 | except Exception as E:
19 | print(E)
20 | print("Error!")
21 | print("Sleeping for 100 seconds")
22 | time.sleep(100)
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | from instagram_class import InstagramApi
2 | import time, random
3 | menu = """
4 | 1.) Auto like timeline
5 | 2.) Auto view story timeline
6 | 3.) Auto like & views timeline
7 | """
8 | print(menu)
9 | choice = int(input("Choice: "))
10 | username = input("Username: ")
11 | password = input("Password: ")
12 | delay = int(input("Delay (Seconds): "))
13 | user = InstagramApi(username, password)
14 | login = user.logIn()
15 | if login["status"] == "success":
16 | if choice == 1:
17 | while(True):
18 | try:
19 | timeline_id = user.getHome()
20 | for like in timeline_id:
21 | likee = user.likePost(like)
22 | if likee == False:
23 | user.logIn()
24 | time.sleep(random.randint(4, 7))
25 | except Exception as E:
26 | print(E)
27 | print("Error!")
28 | print("Sleeping for %s seconds"%(delay))
29 | time.sleep(delay)
30 | elif choice == 2:
31 | while(True):
32 | try:
33 | story_id = user.getStory()
34 | for story in story_id:
35 | print("Viewing story @%s"%(story["username"]))
36 | seen = user.seenStory(story["reelid"], story["user_id"], story["taken_at"])
37 | if seen == False:
38 | user.logIn()
39 | time.sleep(random.randint(4, 7))
40 | except:
41 | print("Error!")
42 | print("Sleeping for %s seconds"%(delay))
43 | time.sleep(delay)
44 | elif choice == 3:
45 | while(True):
46 | try:
47 | print("="*10 + " [STORY VIEWS] " + "="*10)
48 | story_id = user.getStory()
49 | for story in story_id:
50 | print("Viewing story @%s"%(story["username"]))
51 | seen = user.seenStory(story["reelid"], story["user_id"], story["taken_at"])
52 | if seen == False:
53 | user.logIn()
54 | time.sleep(random.randint(5, 10))
55 | print("Sleeping for %s seconds"%(delay))
56 | time.sleep(delay)
57 | #################################################
58 | print("="*10 + " [TIMELINE LIKE] " + "="*10)
59 | timeline_id = user.getHome()
60 | for like in timeline_id:
61 | likee = user.likePost(like)
62 | if likee == False:
63 | user.logIn()
64 | time.sleep(random.randint(5, 10))
65 | print("Sleeping for %s seconds"%(delay))
66 | time.sleep(delay)
67 | except:
68 | print("Error!")
69 | else:
70 | print("Error no option!")
71 | else:
72 | print(login)
73 |
--------------------------------------------------------------------------------
/story.py:
--------------------------------------------------------------------------------
1 | from instagram_class import InstagramApi
2 | import time, random
3 | #loggin by token
4 | # token = {'action': 'login', 'status': 'success', 'username': 'corrykalam', 'csrftoken': 'asdasfwjelkfwfw', 'sessionid': 'xjkcdjksxkdlsldsd'}
5 | # get your token use function logIn()
6 | # leertsefani = InstagramApi(session=token)
7 |
8 |
9 | #login by user & password
10 | leertsefani = InstagramApi("USERNAME", "PASSWORD")
11 | leertsefani.logIn()
12 | while(True):
13 | try:
14 | story_id = leertsefani.getStory()
15 | for story in story_id:
16 | print("Viewing story @%s"%(story["username"]))
17 | leertsefani.seenStory(story["reelid"], story["user_id"], story["taken_at"])
18 | time.sleep(random.randint(4, 7))
19 | except:
20 | print("Error!")
21 | print("Sleeping for 100 seconds")
22 | time.sleep(100)
--------------------------------------------------------------------------------