├── LICENSE
├── README.md
├── myigbot.py
├── usage.py
└── utils.py
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Pramurta Sinha (b31ngd3v)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MyIGBot 
2 |
3 | MyIGBot is a Instagram Private API to like, follow, comment, view & intaract with stories, upload post & stories, get all information about a user/posts and get posts based on locations/hashtags.
4 |
5 | - Easy to use
6 | - More Powerful Now
7 | - 2FA Login Support
8 |
9 | ## New Features!
10 |
11 | - Get information of a user/post.
12 | - Get posts based on hashtag/location.
13 | - It also supports proxy now.
14 | - Added 35+ features on this update.
15 |
16 | You can also:
17 | - Send Story Views
18 | - Like, Unlike, Comment in a Post
19 | - Follow, Unfollow User
20 | - Upload Post and Stories
21 | - Intaract with Stories
22 | - Cookie Storing Feature
23 |
24 | ### Tech
25 |
26 | MyIGBot uses a number of open source projects to work properly:
27 |
28 | * [Python](https://www.python.org/) - Python is an interpreted, high-level and general-purpose programming language
29 | * [Requests](https://requests.readthedocs.io/en/master/) - to make HTTP requests simpler
30 | * [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) - is a Python package for parsing HTML and XML documents.
31 |
32 | And of course MyIGBot itself is open source with a [public repository](https://github.com/b31ngD3v/MyIGBot)
33 | on GitHub.
34 |
35 | ### Installation
36 |
37 | Place **myigbot.py and utils.py** in the same folder where your project is. **(recommended)**
38 |
39 | **or,**
40 |
41 | Install MyIGBot from PyPi **(out of date)**
42 |
43 | ```sh
44 | $ pip install myigbot
45 | ```
46 | ### Usage
47 |
48 | Here is how to use MyIGBot (you can also check usage.py)
49 |
50 | ###### Login Process (if your account has 2 Factor Auth. The bot will ask you the code.)
51 |
52 | ```sh
53 | from myigbot import MyIGBot
54 |
55 | bot = MyIGBot('USERNAME', 'PASSWORD')
56 | ```
57 | ###### Like post
58 |
59 | ```sh
60 | response = bot.like('https://www.instagram.com/p/CH5qV6-so6Y/')
61 | print(response) # if the response code is 200 that means ok
62 | ```
63 | ###### Unlike post
64 |
65 | ```sh
66 | response = bot.unlike('https://www.instagram.com/p/CH5qV6-so6Y/')
67 | print(response) # if the response code is 200 that means ok
68 | ```
69 | ###### Like Recent post
70 |
71 | ```sh
72 | response = bot.like_recent('instagram')
73 | print(response) # if the response code is 200 that means ok
74 | ```
75 | ###### Comment on post
76 |
77 | ```sh
78 | response = bot.comment('https://www.instagram.com/p/CH5qV6-so6Y/', comment_text='Nice Post!')
79 | print(response) # if the response code is 200 that means ok
80 | ```
81 | ###### Comment on recent post
82 |
83 | ```sh
84 | response = bot.comment_recent('instagram', comment_text='Nice Post!')
85 | print(response) # if the response code is 200 that means ok
86 | ```
87 | ###### Follow user
88 |
89 | ```sh
90 | response = bot.follow('instagram')
91 | print(response) # if the response code is 200 that means ok
92 | ```
93 | ###### Unfollow user
94 |
95 | ```sh
96 | response = bot.unfollow('instagram')
97 | print(response) # if the response code is 200 that means ok
98 | ```
99 | ###### Send story view
100 |
101 | ```sh
102 | response = bot.story_view('b31ngdev')
103 | print(response) # if the response code is 200 that means ok
104 | ```
105 | ###### Upload post
106 |
107 | ```sh
108 | response = bot.upload_post('image.png', caption='Image 1')
109 | print(response) # if the response code is 200 that means ok
110 | ```
111 | ###### Upload Story
112 |
113 | ```sh
114 | response = bot.upload_story('image2.png')
115 | print(response) # if the response code is 200 that means ok
116 | ```
117 | ###### Find posts with hashtags
118 |
119 | ```sh
120 | response = bot.hashtag_posts('programmershumor', limit=50)
121 | print(response) # by default the limit is setted to 20, this is a optional parameter
122 | ```
123 | ###### Find posts with location
124 |
125 | ```sh
126 | response = bot.location_posts('https://www.instagram.com/explore/locations/6889842/paris-france/', limit=20)
127 | print(response) # by default the limit is setted to 20, this is a optional parameter
128 | ```
129 | ###### User post count
130 |
131 | ```sh
132 | response = bot.user_posts_count('instagram')
133 | print(response)
134 | ```
135 | ###### User follower count
136 |
137 | ```sh
138 | response = bot.user_followers_count('instagram')
139 | print(response)
140 | ```
141 | ###### User follow count
142 |
143 | ```sh
144 | response = bot.user_follow_count('instagram')
145 | print(response)
146 | ```
147 | ###### Post like count
148 |
149 | ```sh
150 | response = bot.like_count('https://www.instagram.com/p/CH5qV6-so6Y/')
151 | print(response)
152 | ```
153 | ###### Post comment count
154 |
155 | ```sh
156 | response = bot.comment_count('https://www.instagram.com/p/CH5qV6-so6Y/')
157 | print(response)
158 | ```
159 | ###### Get every post's link of a user
160 |
161 | ```sh
162 | response = bot.user_posts('instagram', limit=50)
163 | print(response) # by default the limit is setted to 50, this is a optional parameter
164 | ```
165 | ###### List of username who followed the user
166 |
167 | ```sh
168 | response = bot.user_followers('instagram', limit=50)
169 | print(response) # by default the limit is setted to 50, this is a optional parameter
170 | ```
171 | ###### List of username whom the user follows
172 |
173 | ```sh
174 | response = bot.user_follows('instagram', limit=50)
175 | print(response) # by default the limit is setted to 50, this is a optional parameter
176 | ```
177 | ###### List of username who liked a post
178 |
179 | ```sh
180 | response = bot.post_likers('https://www.instagram.com/p/CH5qV6-so6Y/', limit=50)
181 | print(response) # by default the limit is setted to 50, this is a optional parameter
182 | ```
183 | ###### List of username who commented a post
184 |
185 | ```sh
186 | response = bot.post_commenters('https://www.instagram.com/p/CH5qV6-so6Y/', limit=50)
187 | print(response) # by default the limit is setted to 50, this is a optional parameter
188 | ```
189 | ###### Feed posts of logged in user
190 |
191 | ```sh
192 | response = bot.feed_posts()
193 | print(response)
194 | ```
195 | ###### Username of the post owner
196 |
197 | ```sh
198 | response = bot.post_owner('https://www.instagram.com/p/CH5qV6-so6Y/')
199 | print(response)
200 | ```
201 | ###### Get caption of a post
202 |
203 | ```sh
204 | response = bot.post_caption('https://www.instagram.com/p/CH5qV6-so6Y/')
205 | print(response)
206 | ```
207 | ###### Get location of a post
208 |
209 | ```sh
210 | response = bot.post_location('https://www.instagram.com/p/CH5qV6-so6Y/')
211 | print(response)
212 | ```
213 | ###### Get hashtags used in the post
214 |
215 | ```sh
216 | response = bot.post_hashtags('https://www.instagram.com/p/CH5qV6-so6Y/')
217 | print(response)
218 | ```
219 | ###### Get usernames who are tagged in a post
220 |
221 | ```sh
222 | response = bot.post_tagged_user('https://www.instagram.com/p/B2fZRgBA2wj/')
223 | print(response)
224 | ```
225 | ###### Get HD quality Profile Picture download link
226 |
227 | ```sh
228 | response = bot.user_dp('instagram')
229 | print(response)
230 | ```
231 | ###### Get bio of a user
232 |
233 | ```sh
234 | response = bot.user_bio('instagram')
235 | print(response)
236 | ```
237 | ###### Find the account is private or not
238 |
239 | ```sh
240 | response = bot.private_user('instagram')
241 | print(response)
242 | ```
243 | ###### Find the account is verified or not
244 |
245 | ```sh
246 | response = bot.verified_user('instagram')
247 | print(response)
248 | ```
249 | ###### Get external url of a username
250 |
251 | ```sh
252 | response = bot.user_external_url('instagram')
253 | print(response)
254 | ```
255 | ###### Find the user follows you or not
256 |
257 | ```sh
258 | response = bot.follows_me('instagram')
259 | print(response)
260 | ```
261 | ###### Find you follow the user or not
262 |
263 | ```sh
264 | response = bot.followed_by_me('instagram')
265 | print(response)
266 | ```
267 | ###### Get video views count
268 |
269 | ```sh
270 | response = bot.video_views_count('https://www.instagram.com/p/B2XPNNvgApx/')
271 | print(response)
272 | ```
273 | ###### Get post type (video or picture)
274 |
275 | ```sh
276 | response = bot.post_type('https://www.instagram.com/p/CH5qV6-so6Y/')
277 | print(response)
278 | ```
279 | ###### Get exact time when the post was posted
280 |
281 | ```sh
282 | response = bot.post_time('https://www.instagram.com/p/CH5qV6-so6Y/')
283 | print(response)
284 | ```
285 | ### Proxy
286 | Here is how to add proxy
287 |
288 | #### Method For Authenticated Proxies
289 | ```sh
290 | from myigbot import MyIGBot
291 |
292 | proxies = {
293 | 'http': 'user:pass@host:port',
294 | 'https': 'user:pass@host:port'
295 | }
296 | bot = MyIGBot('USERNAME', 'PASSWORD', proxy=proxies)
297 | ```
298 |
299 | #### Method For Non-Authenticated Proxies
300 | ```sh
301 | from myigbot import MyIGBot
302 |
303 | proxies = {
304 | 'http': 'host:port',
305 | 'https': 'host:port',
306 | }
307 | bot = MyIGBot('USERNAME', 'PASSWORD', proxy=proxies)
308 | ```
309 |
310 | License
311 | ----
312 |
313 |
314 |
315 |
316 |
317 |
318 |
319 | **Free Software, Hell Yeah!**
320 |
--------------------------------------------------------------------------------
/myigbot.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import os
3 | from datetime import datetime
4 | import json
5 | from bs4 import BeautifulSoup as bs
6 | import time
7 | import random
8 | import string
9 | from typing import List
10 | from utils import get_media_duration
11 |
12 |
13 | class bcolors:
14 | HEADER = '\033[95m'
15 | OKBLUE = '\033[94m'
16 | OKCYAN = '\033[96m'
17 | OKGREEN = '\033[92m'
18 | WARNING = '\033[93m'
19 | FAIL = '\033[91m'
20 | ENDC = '\033[0m'
21 | BOLD = '\033[1m'
22 | UNDERLINE = '\033[4m'
23 |
24 |
25 | class MyIGBot:
26 | def __init__(self, username, password, use_cookie=True, proxy=None):
27 | self.username = username
28 | self.password = password
29 | self.use_cookie = use_cookie
30 | self.proxy = proxy
31 |
32 | self.path = os.getcwd()
33 |
34 | if use_cookie == False or os.path.exists(self.path + f'//cookie_{self.username}.bot') == False:
35 | link = 'https://www.instagram.com/'
36 | login_url = 'https://www.instagram.com/accounts/login/ajax/'
37 |
38 | time_now = int(datetime.now().timestamp())
39 | response = requests.get(link, proxies=self.proxy)
40 | try:
41 | csrf = response.cookies['csrftoken']
42 | except:
43 | letters = string.ascii_lowercase
44 | csrf = ''.join(random.choice(letters) for i in range(8))
45 |
46 | payload = {
47 | 'username': self.username,
48 | 'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{time_now}:{self.password}',
49 | 'queryParams': {},
50 | 'optIntoOneTap': 'false'
51 | }
52 |
53 | login_header = {
54 | "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
55 | "X-Requested-With": "XMLHttpRequest",
56 | "Referer": "https://www.instagram.com/accounts/login/",
57 | "x-csrftoken": csrf
58 | }
59 |
60 | login_response = requests.post(login_url, data=payload, headers=login_header, proxies=self.proxy)
61 | json_data = json.loads(login_response.text)
62 |
63 | cookies = login_response.cookies
64 | cookie_jar = cookies.get_dict()
65 | try:
66 | self.csrf_token = cookie_jar['csrftoken']
67 | except:
68 | self.csrf_token = csrf
69 |
70 | try:
71 | if json_data["authenticated"]:
72 | pass
73 | else:
74 | print(bcolors.FAIL + "[✗] Login Failed!" + bcolors.ENDC, login_response.text)
75 | quit()
76 | except KeyError:
77 | try:
78 | if json_data["two_factor_required"]:
79 | self.ig_nrcb = cookie_jar['ig_nrcb']
80 | self.ig_did = cookie_jar['ig_did']
81 | self.mid = cookie_jar['mid']
82 |
83 | otp = input(bcolors.OKBLUE + '[!] Two Factor Auth. Detected! Enter Code Here: ' + bcolors.ENDC)
84 | twofactor_url = 'https://www.instagram.com/accounts/login/ajax/two_factor/'
85 | twofactor_payload = {
86 | 'username': self.username,
87 | 'verificationCode': otp,
88 | 'identifier': json_data["two_factor_info"]["two_factor_identifier"],
89 | 'queryParams': {}
90 | }
91 |
92 | twofactor_header = {
93 | "accept": "*/*",
94 | "accept-encoding": "gzip, deflate, br",
95 | "accept-language": "en-US,en;q=0.9",
96 | "content-type": "application/x-www-form-urlencoded",
97 | "cookie": 'ig_did=' + self.ig_did + '; ig_nrcb=' + self.ig_nrcb + '; csrftoken=' + self.csrf_token + '; mid=' + self.mid,
98 | "origin": "https://www.instagram.com",
99 | "referer": "https://www.instagram.com/accounts/login/two_factor?next=%2F",
100 | "sec-fetch-dest": "empty",
101 | "sec-fetch-mode": "cors",
102 | "sec-fetch-site": "same-origin",
103 | "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
104 | "x-csrftoken": self.csrf_token,
105 | "x-ig-app-id": "936619743392459",
106 | "x-ig-www-claim": "0",
107 | "x-instagram-ajax": "00c4537694a4",
108 | "x-requested-with": "XMLHttpRequest"
109 | }
110 |
111 | login_response = requests.post(twofactor_url, data=twofactor_payload, headers=twofactor_header,
112 | proxies=self.proxy)
113 | try:
114 | if login_response.headers['Set-Cookie'] != 0:
115 | pass
116 | except:
117 | try:
118 | if json_data["message"] == "checkpoint_required":
119 | self.ig_nrcb = cookie_jar['ig_nrcb']
120 | self.ig_did = cookie_jar['ig_did']
121 | self.mid = cookie_jar['mid']
122 | url = 'https://www.instagram.com' + json_data['checkpoint_url']
123 | header = {
124 | "accept": "*/*",
125 | "accept-encoding": "gzip, deflate, br",
126 | "accept-language": "en-US,en;q=0.9",
127 | "content-type": "application/x-www-form-urlencoded",
128 | "cookie": 'ig_did=' + self.ig_did + '; ig_nrcb=' + self.ig_nrcb + '; csrftoken=' + self.csrf_token + '; mid=' + self.mid,
129 | "origin": "https://www.instagram.com",
130 | "referer": 'https://instagram.com' + json_data['checkpoint_url'],
131 | "sec-fetch-dest": "empty",
132 | "sec-fetch-mode": "cors",
133 | "sec-fetch-site": "same-origin",
134 | "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
135 | "x-csrftoken": self.csrf_token,
136 | "x-ig-app-id": "936619743392459",
137 | "x-ig-www-claim": "0",
138 | "x-instagram-ajax": "e8e20d8ba618",
139 | "x-requested-with": "XMLHttpRequest"
140 | }
141 | code = input(bcolors.OKBLUE + json.loads(
142 | requests.post(url, headers=header, data={'choice': '1'}).text,
143 | proxies=self.proxy)['extraData']['content'][1]['text'] + ' > ' + bcolors.ENDC)
144 | if json.loads(requests.post(url, headers=header, data={'security_code': code}).text,
145 | proxies=self.proxy)['type'] == 'CHALLENGE_REDIRECTION':
146 | login_response = requests.post(login_url, data=payload, headers=login_header,
147 | proxies=self.proxy)
148 | else:
149 | print(bcolors.FAIL + '[✗] Login Failed!' + bcolors.ENDC)
150 | quit()
151 | except:
152 | print(bcolors.FAIL + '[✗] Login Failed!' + bcolors.ENDC)
153 | quit()
154 |
155 | except KeyError:
156 | try:
157 | if json_data["message"] == "checkpoint_required":
158 | self.ig_nrcb = cookie_jar['ig_nrcb']
159 | self.ig_did = cookie_jar['ig_did']
160 | self.mid = cookie_jar['mid']
161 | url = 'https://www.instagram.com' + json_data['checkpoint_url']
162 | header = {
163 | "accept": "*/*",
164 | "accept-encoding": "gzip, deflate, br",
165 | "accept-language": "en-US,en;q=0.9",
166 | "content-type": "application/x-www-form-urlencoded",
167 | "cookie": 'ig_did=' + self.ig_did + '; ig_nrcb=' + self.ig_nrcb + '; csrftoken=' + self.csrf_token + '; mid=' + self.mid,
168 | "origin": "https://www.instagram.com",
169 | "referer": 'https://instagram.com' + json_data['checkpoint_url'],
170 | "sec-fetch-dest": "empty",
171 | "sec-fetch-mode": "cors",
172 | "sec-fetch-site": "same-origin",
173 | "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
174 | "x-csrftoken": self.csrf_token,
175 | "x-ig-app-id": "936619743392459",
176 | "x-ig-www-claim": "0",
177 | "x-instagram-ajax": "e8e20d8ba618",
178 | "x-requested-with": "XMLHttpRequest"
179 | }
180 | code = input(bcolors.OKBLUE +
181 | json.loads(requests.post(url, headers=header, data={'choice': '1'}).text,
182 | proxies=self.proxy)['extraData']['content'][1][
183 | 'text'] + ' > ' + bcolors.ENDC)
184 | if json.loads(requests.post(url, headers=header, data={'security_code': code}).text,
185 | proxies=self.proxy)['type'] == 'CHALLENGE_REDIRECTION':
186 | login_response = requests.post(login_url, data=payload, headers=login_header,
187 | proxies=self.proxy)
188 | else:
189 | print(bcolors.FAIL + '[✗] Login Failed!' + bcolors.ENDC)
190 | quit()
191 | except:
192 | print(bcolors.FAIL + '[✗] Login Failed!' + bcolors.ENDC)
193 | quit()
194 |
195 | self.sessionid = login_response.headers['Set-Cookie'].split('sessionid=')[1].split(';')[0]
196 | self.userId = login_response.headers['Set-Cookie'].split('ds_user_id=')[1].split(';')[0]
197 | self.cookie = "sessionid=" + self.sessionid + "; csrftoken=" + self.csrf_token + "; ds_user_id=" + self.userId + ";"
198 | create_cookie = open(self.path + f'//cookie_{self.username}.bot', 'w+', encoding='utf-8')
199 | create_cookie.write(self.cookie)
200 | create_cookie.close()
201 | self.session = requests.session()
202 | cookie_obj = requests.cookies.create_cookie(
203 | name='sessionid', secure=True, value=self.sessionid)
204 | self.session.cookies.set_cookie(cookie_obj)
205 |
206 | elif os.path.exists(self.path + f'//cookie_{self.username}.bot'):
207 | try:
208 | read_cookie = open(self.path + f'//cookie_{self.username}.bot', 'r', encoding='utf-8')
209 | self.cookie = read_cookie.read()
210 | read_cookie.close()
211 | homelink = 'https://www.instagram.com/op/'
212 | self.session = requests.session()
213 | self.sessionid = self.cookie.split('=')[1].split(';')[0]
214 | self.csrf_token = self.cookie.split('=')[2].split(';')[0]
215 | cookie_obj = requests.cookies.create_cookie(
216 | name='sessionid', secure=True, value=self.sessionid)
217 | self.session.cookies.set_cookie(cookie_obj)
218 | login_response = self.session.get(homelink, proxies=self.proxy)
219 | time.sleep(1)
220 | soup = bs(login_response.text, 'html.parser')
221 | soup.find("strong", {"class": "-cx-PRIVATE-NavBar__username -cx-PRIVATE-NavBar__username__"}).get_text()
222 | except AttributeError:
223 | print(bcolors.FAIL + "[✗] Login Failed! Cookie file is corupted!" + bcolors.ENDC)
224 | os.remove(self.path + f'//cookie_{self.username}.bot')
225 | print(bcolors.WARNING + "[-] Deleted Corupted Cookie File! Try Again!" + bcolors.ENDC)
226 | quit()
227 |
228 | def already_liked(self, post_link):
229 | if post_link.find('/tv/') != -1:
230 | post_link = post_link.replace('/tv/', '/p/')
231 | try:
232 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
233 | except:
234 | pass
235 | resp = self.session.get(post_link, proxies=self.proxy)
236 | time.sleep(1)
237 | soup = bs(resp.text, 'html.parser')
238 | scripts = soup.find_all('script')
239 | data_script = str(scripts[15])
240 | time.sleep(1)
241 | try:
242 | shortcode = post_link.split('/p/')[1].replace('/', '')
243 | data_script = data_script.replace(
244 | f'''", '')
250 | data_json = json.loads(data_object)
251 | liked = data_json["graphql"]["shortcode_media"]["viewer_has_liked"]
252 |
253 | return bool(liked)
254 |
255 | def like(self, post_link):
256 | if post_link.find('/tv/') != -1:
257 | post_link = post_link.replace('/tv/', '/p/')
258 | try:
259 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
260 | except:
261 | pass
262 | try:
263 | if self.already_liked(post_link) == False:
264 | resp = self.session.get(post_link, proxies=self.proxy)
265 | time.sleep(1)
266 | soup = bs(resp.text, 'html.parser')
267 | scripts = soup.find_all('script')
268 | data_script = str(scripts[15])
269 | time.sleep(1)
270 | try:
271 | shortcode = post_link.split('/p/')[1].replace('/', '')
272 | data_script = data_script.replace(
273 | f'''", '')
279 | data_json = json.loads(data_object)
280 | id_post = data_json["graphql"]["shortcode_media"]["id"]
281 |
282 | url_post = f"https://www.instagram.com/web/likes/{id_post}/like/"
283 |
284 | headers = {
285 | "accept": "*/*",
286 | "accept-encoding": "gzip, deflate, br",
287 | "accept-language": "en-US,en;q=0.9",
288 | "content-length": "0",
289 | "content-type": "application/x-www-form-urlencoded",
290 | "cookie": self.cookie,
291 | "origin": "https://www.instagram.com",
292 | "referer": post_link,
293 | "sec-fetch-dest": "empty",
294 | "sec-fetch-mode": "cors",
295 | "sec-fetch-site": "same-origin",
296 | "user-agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
297 | "x-csrftoken": self.csrf_token,
298 | "x-ig-app-id": "936619743392459",
299 | "x-ig-www-claim": "hmac.AR3dC7naiVtTKkwrEY0hwTO9zj4kLxfvf4Srvp3wFyoZFqSx",
300 | "x-instagram-ajax": "d3d3aea32e75",
301 | "x-requested-with": "XMLHttpRequest"
302 | }
303 | response = requests.request("POST", url_post, headers=headers, proxies=self.proxy)
304 |
305 | if response.status_code != 200:
306 | return response.status_code
307 | else:
308 | return 208
309 | except:
310 | return 403
311 |
312 | return 200
313 |
314 | def unlike(self, post_link):
315 | if post_link.find('/tv/') != -1:
316 | post_link = post_link.replace('/tv/', '/p/')
317 | try:
318 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
319 | except:
320 | pass
321 | try:
322 | if self.already_liked(post_link) == True:
323 | resp = self.session.get(post_link, proxies=self.proxy)
324 | time.sleep(1)
325 | soup = bs(resp.text, 'html.parser')
326 | scripts = soup.find_all('script')
327 | data_script = str(scripts[15])
328 | time.sleep(1)
329 | try:
330 | shortcode = post_link.split('/p/')[1].replace('/', '')
331 | data_script = data_script.replace(
332 | f'''", '')
338 | data_json = json.loads(data_object)
339 | id_post = data_json["graphql"]["shortcode_media"]["id"]
340 |
341 | url_post = f"https://www.instagram.com/web/likes/{id_post}/unlike/"
342 |
343 | headers = {
344 | "accept": "*/*",
345 | "accept-encoding": "gzip, deflate, br",
346 | "accept-language": "en-US,en;q=0.9",
347 | "content-length": "0",
348 | "content-type": "application/x-www-form-urlencoded",
349 | "cookie": self.cookie,
350 | "origin": "https://www.instagram.com",
351 | "referer": post_link,
352 | "sec-fetch-dest": "empty",
353 | "sec-fetch-mode": "cors",
354 | "sec-fetch-site": "same-origin",
355 | "user-agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
356 | "x-csrftoken": self.csrf_token,
357 | "x-ig-app-id": "936619743392459",
358 | "x-ig-www-claim": "hmac.AR3dC7naiVtTKkwrEY0hwTO9zj4kLxfvf4Srvp3wFyoZFqSx",
359 | "x-instagram-ajax": "d3d3aea32e75",
360 | "x-requested-with": "XMLHttpRequest"
361 | }
362 | response = requests.request("POST", url_post, headers=headers, proxies=self.proxy)
363 |
364 | if response.status_code != 200:
365 | return response.status_code
366 | else:
367 | return 208
368 |
369 | except:
370 | return 403
371 |
372 | return 200
373 |
374 | def like_recent(self, username):
375 | resp = self.session.get('https://www.instagram.com/' + username + '/', proxies=self.proxy)
376 | time.sleep(1)
377 | soup = bs(resp.text, 'html.parser')
378 | scripts = soup.find_all('script')
379 | try:
380 | data_script = str(scripts[4])
381 | time.sleep(1)
382 | data_script = data_script.replace(
383 | '''", '')
385 | data_json = json.loads(data_object)
386 | except:
387 | data_script = str(scripts[3])
388 | time.sleep(1)
389 | data_script = data_script.replace(
390 | '''", '')
392 | data_json = json.loads(data_object)
393 | try:
394 | shortcode = \
395 | data_json["entry_data"]["ProfilePage"][0]["graphql"]['user']["edge_owner_to_timeline_media"]["edges"][
396 | 0][
397 | "node"]["shortcode"]
398 | return self.like('https://www.instagram.com/p/' + shortcode + '/')
399 | except IndexError:
400 | return 404
401 | except KeyError:
402 | return 404
403 |
404 | def comment(self, post_link, comment_text):
405 | if post_link.find('/tv/') != -1:
406 | post_link = post_link.replace('/tv/', '/p/')
407 | try:
408 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
409 | except:
410 | pass
411 | try:
412 | resp = self.session.get(post_link, proxies=self.proxy)
413 | time.sleep(1)
414 | soup = bs(resp.text, 'html.parser')
415 | scripts = soup.find_all('script')
416 | data_script = str(scripts[15])
417 | time.sleep(1)
418 | try:
419 | shortcode = post_link.split('/p/')[1].replace('/', '')
420 | data_script = data_script.replace(
421 | f'''", '')
427 | data_json = json.loads(data_object)
428 | id_post = data_json["graphql"]["shortcode_media"]["id"]
429 |
430 | url_post = f"https://www.instagram.com/web/comments/{id_post}/add/"
431 |
432 | headers = {
433 | "accept": "*/*",
434 | "accept-encoding": "gzip, deflate, br",
435 | "accept-language": "en-US,en;q=0.9",
436 | "content-length": "39",
437 | "content-type": "application/x-www-form-urlencoded",
438 | "cookie": self.cookie,
439 | "origin": "https://www.instagram.com",
440 | "referer": post_link,
441 | "sec-fetch-dest": "empty",
442 | "sec-fetch-mode": "cors",
443 | "sec-fetch-site": "same-origin",
444 | "user-agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
445 | "x-csrftoken": self.csrf_token,
446 | "x-ig-app-id": "936619743392459",
447 | "x-ig-www-claim": "hmac.AR3dC7naiVtTKkwrEY0hwTO9zj4kLxfvf4Srvp3wFyoZFvZV",
448 | "x-instagram-ajax": "d3d3aea32e75",
449 | "x-requested-with": "XMLHttpRequest"
450 | }
451 |
452 | response = requests.request("POST", url_post, headers=headers,
453 | data=f"comment_text={comment_text}&replied_to_comment_id=".encode('utf-8'),
454 | proxies=self.proxy)
455 |
456 | if response.status_code != 200:
457 | return response.status_code
458 | except:
459 | return 403
460 |
461 | return 200
462 |
463 | def comment_recent(self, username, comment_text):
464 | resp = self.session.get('https://www.instagram.com/' + username + '/', proxies=self.proxy)
465 | time.sleep(1)
466 | soup = bs(resp.text, 'html.parser')
467 | scripts = soup.find_all('script')
468 | try:
469 | data_script = str(scripts[4])
470 | time.sleep(1)
471 | data_script = data_script.replace(
472 | '''", '')
474 | data_json = json.loads(data_object)
475 | except:
476 | data_script = str(scripts[3])
477 | time.sleep(1)
478 | data_script = data_script.replace(
479 | '''", '')
481 | data_json = json.loads(data_object)
482 | try:
483 | shortcode = \
484 | data_json["entry_data"]["ProfilePage"][0]["graphql"]['user']["edge_owner_to_timeline_media"]["edges"][
485 | 0][
486 | "node"]["shortcode"]
487 | return self.comment('https://www.instagram.com/p/' + shortcode + '/', comment_text)
488 | except IndexError:
489 | return 404
490 | except KeyError:
491 | return 404
492 |
493 | def already_followed(self, username):
494 | resp = self.session.get('https://www.instagram.com/' + username + '/', proxies=self.proxy)
495 | time.sleep(1)
496 | soup = bs(resp.text, 'html.parser')
497 | scripts = soup.find_all('script')
498 | try:
499 | data_script = str(scripts[4])
500 | time.sleep(1)
501 | data_script = data_script.replace(
502 | '''", '')
504 | data_json = json.loads(data_object)
505 | except:
506 | data_script = str(scripts[3])
507 | time.sleep(1)
508 | data_script = data_script.replace(
509 | '''", '')
511 | data_json = json.loads(data_object)
512 | followed = data_json["entry_data"]["ProfilePage"][0]["graphql"]['user']['followed_by_viewer']
513 | return bool(followed)
514 |
515 | def follow(self, username):
516 | try:
517 | if self.already_followed(username) == False:
518 | resp = self.session.get('https://www.instagram.com/' + username + '/', proxies=self.proxy)
519 | time.sleep(1)
520 | soup = bs(resp.text, 'html.parser')
521 | scripts = soup.find_all('script')
522 | try:
523 | data_script = str(scripts[4])
524 | time.sleep(1)
525 | data_script = data_script.replace(
526 | '''", '')
528 | data_json = json.loads(data_object)
529 | except:
530 | data_script = str(scripts[3])
531 | time.sleep(1)
532 | data_script = data_script.replace(
533 | '''", '')
535 | data_json = json.loads(data_object)
536 | id_page = data_json["entry_data"]["ProfilePage"][0]["graphql"]['user']['id']
537 |
538 | url_page = f"https://www.instagram.com/web/friendships/{id_page}/follow/"
539 |
540 | headers = {
541 | 'accept': '*/*',
542 | 'accept-encoding': 'gzip, deflate, br',
543 | 'accept-language': 'en-US,en;q=0.9',
544 | 'content-length': '0',
545 | 'content-type': 'application/x-www-form-urlencoded',
546 | 'cookie': self.cookie,
547 | "origin": "https://www.instagram.com",
548 | "referer": f"https://www.instagram.com/{username}/",
549 | "sec-fetch-dest": "empty",
550 | "sec-fetch-mode": "cors",
551 | "sec-fetch-site": "same-origin",
552 | "user-agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
553 | "x-csrftoken": self.csrf_token,
554 | "x-ig-app-id": "936619743392459",
555 | "x-ig-www-claim": "hmac.AR3dC7naiVtTKkwrEY0hwTO9zj4kLxfvf4Srvp3wFyoZFvZV",
556 | "x-instagram-ajax": "d3d3aea32e75",
557 | "x-requested-with": "XMLHttpRequest"
558 | }
559 |
560 | response = requests.request("POST", url_page, headers=headers, proxies=self.proxy)
561 | if response.status_code == 200:
562 | return 200
563 | else:
564 | return response.status_code
565 | else:
566 | return 208
567 |
568 | except KeyError:
569 | return 404
570 |
571 | def unfollow(self, username):
572 | try:
573 | if self.already_followed(username) == True:
574 | resp = self.session.get('https://www.instagram.com/' + username + '/', proxies=self.proxy)
575 | time.sleep(1)
576 | soup = bs(resp.text, 'html.parser')
577 | scripts = soup.find_all('script')
578 | try:
579 | data_script = str(scripts[4])
580 | time.sleep(1)
581 | data_script = data_script.replace(
582 | '''", '')
584 | data_json = json.loads(data_object)
585 | except:
586 | data_script = str(scripts[3])
587 | time.sleep(1)
588 | data_script = data_script.replace(
589 | '''", '')
591 | data_json = json.loads(data_object)
592 | id_page = data_json["entry_data"]["ProfilePage"][0]["graphql"]['user']['id']
593 |
594 | url_page = f"https://www.instagram.com/web/friendships/{id_page}/unfollow/"
595 |
596 | headers = {
597 | 'accept': '*/*',
598 | 'accept-encoding': 'gzip, deflate, br',
599 | 'accept-language': 'en-US,en;q=0.9',
600 | 'content-length': '0',
601 | 'content-type': 'application/x-www-form-urlencoded',
602 | 'cookie': self.cookie,
603 | "origin": "https://www.instagram.com",
604 | "referer": f"https://www.instagram.com/{username}/",
605 | "sec-fetch-dest": "empty",
606 | "sec-fetch-mode": "cors",
607 | "sec-fetch-site": "same-origin",
608 | "user-agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
609 | "x-csrftoken": self.csrf_token,
610 | "x-ig-app-id": "936619743392459",
611 | "x-ig-www-claim": "hmac.AR3dC7naiVtTKkwrEY0hwTO9zj4kLxfvf4Srvp3wFyoZFvZV",
612 | "x-instagram-ajax": "d3d3aea32e75",
613 | "x-requested-with": "XMLHttpRequest"
614 | }
615 |
616 | response = requests.request("POST", url_page, headers=headers, proxies=self.proxy)
617 | if response.status_code == 200:
618 | return 200
619 | else:
620 | return response.status_code
621 | else:
622 | return 208
623 | except KeyError:
624 | return 404
625 |
626 | def story_view(self, username):
627 | try:
628 | resp = self.session.get('https://www.instagram.com/' + username + '/', proxies=self.proxy)
629 | time.sleep(1)
630 | soup = bs(resp.text, 'html.parser')
631 | scripts = soup.find_all('script')
632 | try:
633 | data_script = str(scripts[4])
634 | time.sleep(1)
635 | data_script = data_script.replace(
636 | '''", '')
638 | data_json = json.loads(data_object)
639 | except:
640 | try:
641 | data_script = str(scripts[3])
642 | time.sleep(1)
643 | data_script = data_script.replace(
644 | '''", '')
646 | data_json = json.loads(data_object)
647 | except:
648 | return 404
649 | page_id = data_json["entry_data"]["ProfilePage"][0]["graphql"]['user']['id']
650 | surl = f'https://www.instagram.com/graphql/query/?query_hash=c9c56db64beb4c9dea2d17740d0259d9&variables=%7B%22reel_ids%22%3A%5B%22{page_id}%22%5D%2C%22tag_names%22%3A%5B%5D%2C%22location_ids%22%3A%5B%5D%2C%22highlight_reel_ids%22%3A%5B%5D%2C%22precomposed_overlay%22%3Afalse%2C%22show_story_viewer_list%22%3Atrue%2C%22story_viewer_fetch_count%22%3A50%2C%22story_viewer_cursor%22%3A%22%22%2C%22stories_video_dash_manifest%22%3Afalse%7D'
651 | resp = self.session.get(surl, proxies=self.proxy)
652 | time.sleep(1)
653 | soup = bs(resp.text, 'html.parser')
654 | data_json = json.loads(str(soup))
655 | story_count = len(data_json["data"]["reels_media"][0]["items"])
656 |
657 | for i in range(0, story_count):
658 | id_story = data_json["data"]["reels_media"][0]["items"][i]['id']
659 | taken_at_timestamp = data_json["data"]["reels_media"][0]["items"][i]['taken_at_timestamp']
660 | stories_page = f"https://www.instagram.com/stories/reel/seen"
661 |
662 | headers = {
663 | 'accept': '*/*',
664 | 'accept-encoding': 'gzip, deflate, br',
665 | 'accept-language': 'en-US,en;q=0.9',
666 | 'content-length': '127',
667 | 'content-type': 'application/x-www-form-urlencoded',
668 | 'cookie': self.cookie,
669 | "origin": "https://www.instagram.com",
670 | "referer": f"https://www.instagram.com/stories/{username}/{id_story}/",
671 | "sec-fetch-dest": "empty",
672 | "sec-fetch-mode": "cors",
673 | "sec-fetch-site": "same-origin",
674 | "user-agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
675 | "x-csrftoken": self.csrf_token,
676 | "x-ig-app-id": "936619743392459",
677 | "x-ig-www-claim": "hmac.AR3dC7naiVtTKkwrEY0hwTO9zj4kLxfvf4Srvp3wFyoZFvZV",
678 | "x-instagram-ajax": "d3d3aea32e75",
679 | "x-requested-with": "XMLHttpRequest"
680 | }
681 |
682 | data = {
683 | 'reelMediaId': id_story,
684 | 'reelMediaOwnerId': page_id,
685 | 'reelId': page_id,
686 | 'reelMediaTakenAt': taken_at_timestamp,
687 | 'viewSeenAt': taken_at_timestamp
688 | }
689 |
690 | requests.request("POST", stories_page, headers=headers, data=data, proxies=self.proxy)
691 |
692 | except IndexError:
693 | return 404
694 |
695 | except KeyError:
696 | return 404
697 |
698 | return 200
699 |
700 | def pre_upload_image(self, image_path: str, id=None, media_type=1, upload_media_height=1080, upload_media_width=1080):
701 | micro_time = id or int(datetime.now().timestamp())
702 |
703 | headers = {
704 | "content-type": "image / jpg",
705 | "content-length": "1",
706 | "X-Entity-Name": f"fb_uploader_{micro_time}",
707 | "Offset": "0",
708 | "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
709 | "x-entity-length": "1",
710 | "X-Instagram-Rupload-Params": f'{{"media_type": {media_type}, "upload_id": {micro_time}, "upload_media_height": {upload_media_height}, "upload_media_width": {upload_media_width}}}',
711 | "x-csrftoken": self.csrf_token,
712 | "x-ig-app-id": "1217981644879628",
713 | "cookie": self.cookie
714 | }
715 |
716 | upload_response = requests.post(f'https://www.instagram.com/rupload_igphoto/fb_uploader_{micro_time}',
717 | data=open(image_path, "rb"), headers=headers, proxies=self.proxy)
718 |
719 | return json.loads(upload_response.text)
720 |
721 | def upload_post(self, image_path, caption=''):
722 | json_data = self.pre_upload_image(image_path)
723 | upload_id = json_data['upload_id']
724 |
725 | if json_data["status"] == "ok":
726 | url = "https://www.instagram.com/create/configure/"
727 |
728 | payload = 'upload_id=' + upload_id + '&caption=' + caption + '&usertags=&custom_accessibility_caption=&retry_timeout='
729 | payload = payload.encode('utf-8')
730 | headers = {
731 | 'authority': 'www.instagram.com',
732 | 'x-ig-www-claim': 'hmac.AR2-43UfYbG2ZZLxh-BQ8N0rqGa-hESkcmxat2RqMAXejXE3',
733 | 'x-instagram-ajax': 'adb961e446b7-hot',
734 | 'content-type': 'application/x-www-form-urlencoded',
735 | 'accept': '*/*',
736 | 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
737 | 'x-requested-with': 'XMLHttpRequest',
738 | 'x-csrftoken': self.csrf_token,
739 | 'x-ig-app-id': '1217981644879628',
740 | 'origin': 'https://www.instagram.com',
741 | 'sec-fetch-site': 'same-origin',
742 | 'sec-fetch-mode': 'cors',
743 | 'sec-fetch-dest': 'empty',
744 | 'referer': 'https://www.instagram.com/create/details/',
745 | 'accept-language': 'en-US,en;q=0.9,fa-IR;q=0.8,fa;q=0.7',
746 | 'cookie': self.cookie
747 | }
748 |
749 | response = requests.request("POST", url, headers=headers, data=payload, proxies=self.proxy)
750 | json_data = json.loads(response.text)
751 |
752 | if json_data["status"] == "ok":
753 | return {"code": 200, "id": json_data['media']['code']}
754 |
755 | else:
756 | return {"code": 400}
757 |
758 | def upload_posts(self, image_paths: List[str], caption=''):
759 | upload_ids = []
760 |
761 | for path in image_paths:
762 | id = int(datetime.now().timestamp())
763 | json_data = self.pre_upload_image(path, id=id)
764 |
765 | if 'upload_id' not in json_data:
766 | raise Exception("Error during image thumbnail upload")
767 |
768 | upload_ids.append({"upload_id": json_data['upload_id']})
769 |
770 | url = "https://i.instagram.com/api/v1/media/configure_sidecar/"
771 | payload = {
772 | "caption": caption,
773 | "children_metadata": upload_ids,
774 | "client_sidecar_id": str(int(datetime.now().timestamp())),
775 | "disable_comments": 0,
776 | }
777 | headers = {
778 | 'authority': 'i.instagram.com',
779 | 'x-ig-www-claim': 'hmac.AR2-43UfYbG2ZZLxh-BQ8N0rqGa-hESkcmxat2RqMAXejXE3',
780 | 'x-instagram-ajax': 'adb961e446b7-hot',
781 | 'accept': '*/*',
782 | 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
783 | 'x-csrftoken': self.csrf_token,
784 | 'x-ig-app-id': '1217981644879628',
785 | 'origin': 'https://www.instagram.com',
786 | 'sec-fetch-site': 'same-origin',
787 | 'sec-fetch-mode': 'cors',
788 | 'sec-fetch-dest': 'empty',
789 | 'referer': 'https://www.instagram.com/',
790 | 'accept-encoding': 'gzip, deflate, br',
791 | 'accept-language': 'en-US,en;q=0.9,fa-IR;q=0.8,fa;q=0.7',
792 | 'cookie': self.cookie
793 | }
794 |
795 | response = requests.request("POST", url, headers=headers, data=json.dumps(payload), proxies=self.proxy)
796 | json_data = json.loads(response.text)
797 |
798 | if json_data["status"] == "ok":
799 | return {"code": 200, "id": json_data['media']['code']}
800 |
801 | return {"code": 400}
802 |
803 |
804 | def pre_upload_video(self, video_path: str, video_params, id=None):
805 | micro_time = id or int(datetime.now().timestamp())
806 |
807 | headers = {
808 | # "content-type": "video / mp4",
809 | "content-length": "1",
810 | "X-Entity-Name": f"fb_uploader_{micro_time}",
811 | "Offset": "0",
812 | "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
813 | "x-entity-length": "1",
814 | "X-Instagram-Rupload-Params": json.dumps(video_params),
815 | # f'{{"media_type": 1, "upload_id": {micro_time}, "upload_media_height": 1080, "upload_media_width": 1080}}',
816 | "x-csrftoken": self.csrf_token,
817 | "x-ig-app-id": "1217981644879628",
818 | "cookie": self.cookie
819 |
820 | }
821 |
822 | upload_response = requests.post(f'https://www.instagram.com/rupload_igvideo/fb_uploader_{micro_time}',
823 | data=open(video_path, "rb"), headers=headers, proxies=self.proxy)
824 | return json.loads(upload_response.text)
825 |
826 |
827 | def upload_video_post(self, video_path: str, thumbnail_path: str, caption: str = '', params=None):
828 | micro_time = int(datetime.now().timestamp())
829 |
830 | media_duration = get_media_duration(video_path)
831 |
832 | video_params = params or {
833 | "client-passthrough": "1",
834 | "is_igtv_video": True,
835 | "is_sidecar": "0",
836 | "is_unified_video": "1",
837 | "media_type": 2,
838 | "for_album": False,
839 | "video_format": "",
840 | "upload_id": micro_time,
841 | "upload_media_duration_ms": media_duration * 1000,
842 | "upload_media_height": 720,
843 | "upload_media_width": 1280,
844 | "video_transform": None,
845 | "video_edit_params": {
846 | "crop_height": 720,
847 | "crop_width": 720,
848 | "crop_x1": 280,
849 | "crop_y1": 0,
850 | "mute": False,
851 | "trim_end": media_duration,
852 | "trim_start": 0
853 | }
854 | }
855 |
856 | json_data = self.pre_upload_video(video_path, video_params, id=micro_time)
857 |
858 | if 'media_id' not in json_data:
859 | raise Exception("Error during video upload")
860 |
861 | time.sleep(30)
862 | json_data = self.pre_upload_image(thumbnail_path, id=micro_time, media_type=2)
863 |
864 | if 'upload_id' not in json_data:
865 | raise Exception("Error during image thumbnail upload")
866 |
867 | upload_id = json_data['upload_id']
868 | time.sleep(30)
869 |
870 | if json_data["status"] == "ok":
871 | url = "https://www.instagram.com/igtv/configure_to_igtv/"
872 |
873 | payload = 'upload_id=' + upload_id + '&caption=' + caption + '&source_type=library&upcoming_event=&usertags=&custom_accessibility_caption=&retry_timeout=&disable_comments=0&like_and_view_counts_disabled=0&igtv_ads_toggled_on=&igtv_share_preview_to_feed=1&is_unified_video=1&video_subtitles_enabled=0'
874 | payload = payload.encode('utf-8')
875 | headers = {
876 | 'authority': 'www.instagram.com',
877 | 'x-ig-www-claim': 'hmac.AR2-43UfYbG2ZZLxh-BQ8N0rqGa-hESkcmxat2RqMAXejXE3',
878 | 'x-instagram-ajax': 'adb961e446b7-hot',
879 | 'content-type': 'application/x-www-form-urlencoded',
880 | 'accept': '*/*',
881 | 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
882 | 'x-requested-with': 'XMLHttpRequest',
883 | 'x-csrftoken': self.csrf_token,
884 | 'x-ig-app-id': '1217981644879628',
885 | 'origin': 'https://www.instagram.com',
886 | 'sec-fetch-site': 'same-origin',
887 | 'sec-fetch-mode': 'cors',
888 | 'sec-fetch-dest': 'empty',
889 | 'referer': 'https://www.instagram.com/',
890 | 'accept-language': 'en-US,en;q=0.9,fa-IR;q=0.8,fa;q=0.7',
891 | 'cookie': self.cookie
892 | }
893 |
894 | response = requests.request("POST", url, headers=headers, data=payload, proxies=self.proxy)
895 | json_data = json.loads(response.text)
896 |
897 | if json_data["status"] == "ok":
898 | return {"code": 200, "id": json_data['media']['code']}
899 |
900 | else:
901 | return {"code": 400}
902 |
903 |
904 | def upload_story(self, image_path):
905 | micro_time = int(datetime.now().timestamp())
906 |
907 | headers = {
908 | "content-type": "image / jpg",
909 | "content-length": "1",
910 | "X-Entity-Name": f"fb_uploader_{micro_time}",
911 | "Offset": "0",
912 | "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
913 | "x-entity-length": "1",
914 | "X-Instagram-Rupload-Params": f'{{"media_type": 1, "upload_id": {micro_time}, "upload_media_height": 1080, "upload_media_width": 1080}}',
915 | "x-csrftoken": self.csrf_token,
916 | "x-ig-app-id": "1217981644879628",
917 | "cookie": self.cookie
918 | }
919 |
920 | upload_response = requests.post(f'https://www.instagram.com/rupload_igphoto/fb_uploader_{micro_time}',
921 | data=open(image_path, "rb"), headers=headers, proxies=self.proxy)
922 |
923 | json_data = json.loads(upload_response.text)
924 | upload_id = json_data['upload_id']
925 |
926 | if json_data["status"] == "ok":
927 | url = "https://www.instagram.com/create/configure_to_story/"
928 |
929 | payload = 'upload_id=' + upload_id + '&caption=&usertags=&custom_accessibility_caption=&retry_timeout='
930 | headers = {
931 | 'authority': 'www.instagram.com',
932 | 'x-ig-www-claim': 'hmac.AR2-43UfYbG2ZZLxh-BQ8N0rqGa-hESkcmxat2RqMAXejXE3',
933 | 'x-instagram-ajax': 'adb961e446b7-hot',
934 | 'content-type': 'application/x-www-form-urlencoded',
935 | 'accept': '*/*',
936 | 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
937 | 'x-requested-with': 'XMLHttpRequest',
938 | 'x-csrftoken': self.csrf_token,
939 | 'x-ig-app-id': '1217981644879628',
940 | 'origin': 'https://www.instagram.com',
941 | 'sec-fetch-site': 'same-origin',
942 | 'sec-fetch-mode': 'cors',
943 | 'sec-fetch-dest': 'empty',
944 | 'referer': 'https://www.instagram.com/create/details/',
945 | 'accept-language': 'en-US,en;q=0.9,fa-IR;q=0.8,fa;q=0.7',
946 | 'cookie': self.cookie
947 | }
948 |
949 | response = requests.request("POST", url, headers=headers, data=payload, proxies=self.proxy)
950 | json_data = json.loads(response.text)
951 |
952 | if json_data["status"] == "ok":
953 | return 200
954 |
955 | else:
956 | return 400
957 |
958 |
959 | def hashtag_posts(self, hashtag, limit=20):
960 | headers = self._get_headers()
961 |
962 | response = self.session.get(
963 | f'https://www.instagram.com/graphql/query/?query_hash=9b498c08113f1e09617a1703c22b2f32&variables=%7B%22tag_name%22%3A%22{hashtag}%22%2C%22first%22%3A{limit}%7D',
964 | headers=headers, proxies=self.proxy).text
965 | post_count = len(json.loads(response)['data']['hashtag']['edge_hashtag_to_media']['edges'])
966 |
967 | if limit > post_count:
968 | limit = post_count
969 |
970 | links = []
971 | for i in range(0, limit):
972 | links.append('https://instagram.com/p/' +
973 | json.loads(response)['data']['hashtag']['edge_hashtag_to_media']['edges'][i]['node'][
974 | 'shortcode'])
975 |
976 | return links
977 |
978 |
979 | def location_posts(self, location_url, limit=20):
980 | id_location = location_url.split('/locations/')[1].split('/')[0]
981 | headers = self._get_headers()
982 |
983 | response = self.session.get(
984 | f'https://www.instagram.com/graphql/query/?query_hash=36bd0f2bf5911908de389b8ceaa3be6d&variables=%7B%22id%22%3A%22{id_location}%22%2C%22first%22%3A{limit}%7D',
985 | headers=headers, proxies=self.proxy).text
986 | post_count = len(json.loads(response)['data']['location']['edge_location_to_media']['edges'])
987 |
988 | if limit > post_count:
989 | limit = post_count
990 |
991 | links = []
992 | for i in range(0, limit):
993 | links.append('https://instagram.com/p/' +
994 | json.loads(response)['data']['location']['edge_location_to_media']['edges'][i]['node'][
995 | 'shortcode'])
996 |
997 | return links
998 |
999 |
1000 | def user_posts_count(self, username):
1001 | headers = self._get_headers()
1002 |
1003 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1004 | proxies=self.proxy).text
1005 | post_count = json.loads(response)['graphql']['user']['edge_owner_to_timeline_media']['count']
1006 |
1007 | return post_count
1008 |
1009 |
1010 | def user_followers_count(self, username):
1011 | headers = self._get_headers()
1012 |
1013 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1014 | proxies=self.proxy).text
1015 | followers_count = json.loads(response)['graphql']['user']['edge_followed_by']['count']
1016 |
1017 | return followers_count
1018 |
1019 |
1020 | def user_follow_count(self, username):
1021 | headers = self._get_headers()
1022 |
1023 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1024 | proxies=self.proxy).text
1025 | follow_count = json.loads(response)['graphql']['user']['edge_follow']['count']
1026 |
1027 | return follow_count
1028 |
1029 |
1030 | def like_count(self, post_link):
1031 | if post_link.find('/tv/') != -1:
1032 | post_link = post_link.replace('/tv/', '/p/')
1033 | try:
1034 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1035 | except:
1036 | pass
1037 | headers = self._get_headers()
1038 |
1039 | if post_link[-1] == '/':
1040 | post_link = post_link[:-1]
1041 |
1042 | response = self.session.get(f'{post_link}/?__a=1', headers=headers, proxies=self.proxy).text
1043 | like_count = json.loads(response)['graphql']['shortcode_media']['edge_media_preview_like']['count']
1044 |
1045 | return like_count
1046 |
1047 |
1048 | def comment_count(self, post_link):
1049 | if post_link.find('/tv/') != -1:
1050 | post_link = post_link.replace('/tv/', '/p/')
1051 | try:
1052 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1053 | except:
1054 | pass
1055 | headers = self._get_headers()
1056 |
1057 | if post_link[-1] == '/':
1058 | post_link = post_link[:-1]
1059 |
1060 | response = self.session.get(f'{post_link}/?__a=1', headers=headers, proxies=self.proxy).text
1061 | comment_count = json.loads(response)['graphql']['shortcode_media']['edge_media_preview_comment']['count']
1062 |
1063 | return comment_count
1064 |
1065 |
1066 | def user_posts(self, username, limit=50):
1067 | posts_have = self.user_posts_count(username)
1068 |
1069 | if posts_have < limit:
1070 | limit = posts_have
1071 |
1072 | limit_k = limit
1073 | headers = self._get_headers()
1074 |
1075 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1076 | proxies=self.proxy).text
1077 | user_id = json.loads(response)['graphql']['user']['id']
1078 |
1079 | links = []
1080 |
1081 | response = self.session.get(
1082 | f'https://www.instagram.com/graphql/query/?query_hash=003056d32c2554def87228bc3fd9668a&variables=%7B%22id%22%3A%22{user_id}%22%2C%22first%22%3A{limit}%7D',
1083 | headers=headers, proxies=self.proxy).text
1084 | post_count = len(json.loads(response)['data']['user']['edge_owner_to_timeline_media']['edges'])
1085 |
1086 | if limit > post_count:
1087 | limit = post_count
1088 |
1089 | for i in range(0, limit):
1090 | links.append('https://instagram.com/p/' +
1091 | json.loads(response)['data']['user']['edge_owner_to_timeline_media']['edges'][i]['node'][
1092 | 'shortcode'])
1093 |
1094 | if limit_k > 50:
1095 | limit = limit_k - 50
1096 | limit_k = limit
1097 | while limit_k > 0:
1098 | try:
1099 | after = json.loads(response)['data']['user']['edge_owner_to_timeline_media']['page_info'][
1100 | 'end_cursor']
1101 | response = self.session.get(
1102 | f'https://www.instagram.com/graphql/query/?query_hash=003056d32c2554def87228bc3fd9668a&variables=%7B%22id%22%3A%22{user_id}%22%2C%22first%22%3A50%2C%22after%22%3A%22{after.replace("==", "")}%3D%3D%22%7D',
1103 | headers=headers, proxies=self.proxy).text
1104 | post_count = len(json.loads(response)['data']['user']['edge_owner_to_timeline_media']['edges'])
1105 |
1106 | if limit > post_count:
1107 | limit = post_count
1108 |
1109 | limit_k -= limit
1110 | for i in range(0, limit):
1111 | links.append('https://instagram.com/p/' +
1112 | json.loads(response)['data']['user']['edge_owner_to_timeline_media']['edges'][i][
1113 | 'node']['shortcode'])
1114 | limit = limit_k
1115 | except:
1116 | break
1117 | return links
1118 |
1119 |
1120 | def user_follows(self, username, limit=49):
1121 | followed = self.user_follow_count(username)
1122 |
1123 | if followed < limit:
1124 | limit = followed
1125 |
1126 | limit_k = limit
1127 | headers = self._get_headers()
1128 |
1129 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1130 | proxies=self.proxy).text
1131 | user_id = json.loads(response)['graphql']['user']['id']
1132 |
1133 | usernames = []
1134 |
1135 | response = self.session.get(
1136 | f'https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=%7B%22id%22%3A%22{user_id}%22%2C%22first%22%3A{limit}%7D',
1137 | headers=headers, proxies=self.proxy).text
1138 | follow_count = len(json.loads(response)['data']['user']['edge_follow']['edges'])
1139 |
1140 | if limit > follow_count:
1141 | limit = follow_count
1142 |
1143 | for i in range(0, limit):
1144 | usernames.append(json.loads(response)['data']['user']['edge_follow']['edges'][i]['node']['username'])
1145 |
1146 | if limit_k > 49:
1147 | limit = limit_k - 49
1148 | limit_k = limit
1149 | while limit_k > 0:
1150 | try:
1151 | after = json.loads(response)['data']['user']['edge_follow']['page_info']['end_cursor']
1152 | response = self.session.get(
1153 | f'https://www.instagram.com/graphql/query/?query_hash=d04b0a864b4b54837c0d870b0e77e076&variables=%7B%22id%22%3A%22{user_id}%22%2C%22first%22%3A50%2C%22after%22%3A%22{after.replace("==", "")}%3D%3D%22%7D',
1154 | headers=headers, proxies=self.proxy).text
1155 | follow_count = len(json.loads(response)['data']['user']['edge_follow']['edges'])
1156 |
1157 | if limit > follow_count:
1158 | limit = follow_count
1159 |
1160 | limit_k -= limit
1161 | for i in range(0, limit):
1162 | usernames.append(
1163 | json.loads(response)['data']['user']['edge_follow']['edges'][i]['node']['username'])
1164 | limit = limit_k
1165 | except:
1166 | break
1167 | return usernames
1168 |
1169 |
1170 | def user_followers(self, username, limit=49):
1171 | follower = self.user_followers_count(username)
1172 |
1173 | if follower < limit:
1174 | limit = follower
1175 |
1176 | limit_k = limit
1177 | headers = self._get_headers()
1178 |
1179 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1180 | proxies=self.proxy).text
1181 | user_id = json.loads(response)['graphql']['user']['id']
1182 |
1183 | usernames = []
1184 |
1185 | response = self.session.get(
1186 | f'https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=%7B%22id%22%3A%22{user_id}%22%2C%22first%22%3A{limit}%7D',
1187 | headers=headers, proxies=self.proxy).text
1188 | follower_count = len(json.loads(response)['data']['user']['edge_followed_by']['edges'])
1189 |
1190 | if limit > follower_count:
1191 | limit = follower_count
1192 |
1193 | for i in range(0, limit):
1194 | usernames.append(json.loads(response)['data']['user']['edge_followed_by']['edges'][i]['node']['username'])
1195 |
1196 | if limit_k > 49:
1197 | limit = limit_k - 49
1198 | limit_k = limit
1199 | while limit_k > 0:
1200 | try:
1201 | after = json.loads(response)['data']['user']['edge_followed_by']['page_info']['end_cursor']
1202 | response = self.session.get(
1203 | f'https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=%7B%22id%22%3A%22{user_id}%22%2C%22first%22%3A50%2C%22after%22%3A%22{after.replace("==", "")}%3D%3D%22%7D',
1204 | headers=headers, proxies=self.proxy).text
1205 | follower_count = len(json.loads(response)['data']['user']['edge_followed_by']['edges'])
1206 |
1207 | if limit > follower_count:
1208 | limit = follower_count
1209 |
1210 | limit_k -= limit
1211 | for i in range(0, limit):
1212 | usernames.append(
1213 | json.loads(response)['data']['user']['edge_followed_by']['edges'][i]['node']['username'])
1214 | limit = limit_k
1215 | except:
1216 | break
1217 | return usernames
1218 |
1219 |
1220 | def post_likers(self, post_link, limit=50):
1221 | if post_link.find('/tv/') != -1:
1222 | post_link = post_link.replace('/tv/', '/p/')
1223 | try:
1224 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1225 | except:
1226 | pass
1227 | likers = self.like_count(post_link)
1228 |
1229 | if likers < limit:
1230 | limit = likers
1231 |
1232 | limit_k = limit
1233 | headers = self._get_headers()
1234 |
1235 | shortcode = post_link.split('/p/')[1].replace('/', '')
1236 | usernames = []
1237 |
1238 | response = self.session.get(
1239 | f'https://www.instagram.com/graphql/query/?query_hash=d5d763b1e2acf209d62d22d184488e57&variables=%7B%22shortcode%22%3A%22{shortcode}%22%2C%22first%22%3A{limit}%7D',
1240 | headers=headers, proxies=self.proxy).text
1241 | like_count = len(json.loads(response)['data']['shortcode_media']['edge_liked_by']['edges'])
1242 |
1243 | if limit > like_count:
1244 | limit = like_count
1245 |
1246 | for i in range(0, limit):
1247 | usernames.append(
1248 | json.loads(response)['data']['shortcode_media']['edge_liked_by']['edges'][i]['node']['username'])
1249 |
1250 | if limit_k > 50:
1251 | limit = limit_k - 50
1252 | limit_k = limit
1253 | while limit_k > 0:
1254 | try:
1255 | after = json.loads(response)['data']['shortcode_media']['edge_liked_by']['page_info']['end_cursor']
1256 | response = self.session.get(
1257 | f'https://www.instagram.com/graphql/query/?query_hash=d5d763b1e2acf209d62d22d184488e57&variables=%7B%22shortcode%22%3A%22{shortcode}%22%2C%22first%22%3A50%2C%22after%22%3A%22{after.replace("==", "")}%3D%3D%22%7D',
1258 | headers=headers, proxies=self.proxy).text
1259 | like_count = len(json.loads(response)['data']['shortcode_media']['edge_liked_by']['edges'])
1260 |
1261 | if limit > like_count:
1262 | limit = like_count
1263 |
1264 | limit_k -= limit
1265 | for i in range(0, limit):
1266 | usernames.append(
1267 | json.loads(response)['data']['shortcode_media']['edge_liked_by']['edges'][i]['node'][
1268 | 'username'])
1269 | limit = limit_k
1270 | except:
1271 | break
1272 | return usernames
1273 |
1274 |
1275 | def post_commenters(self, post_link, limit=50):
1276 | if post_link.find('/tv/') != -1:
1277 | post_link = post_link.replace('/tv/', '/p/')
1278 | try:
1279 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1280 | except:
1281 | pass
1282 | commenters = self.comment_count(post_link)
1283 |
1284 | if commenters < limit:
1285 | limit = commenters
1286 |
1287 | limit_k = limit
1288 | headers = self._get_headers()
1289 |
1290 | shortcode = post_link.split('/p/')[1].replace('/', '')
1291 |
1292 | usernames = []
1293 |
1294 | response = self.session.get(
1295 | f'https://www.instagram.com/graphql/query/?query_hash=bc3296d1ce80a24b1b6e40b1e72903f5&variables=%7B%22shortcode%22%3A%22{shortcode}%22%2C%22first%22%3A{limit}%7D',
1296 | headers=headers, proxies=self.proxy).text
1297 | comment_count = len(json.loads(response)['data']['shortcode_media']['edge_media_to_parent_comment']['edges'])
1298 |
1299 | if limit > comment_count:
1300 | limit = comment_count
1301 |
1302 | for i in range(0, limit):
1303 | usernames.append(
1304 | json.loads(response)['data']['shortcode_media']['edge_media_to_parent_comment']['edges'][i]['node'][
1305 | 'owner']['username'])
1306 |
1307 | if limit_k > 50:
1308 | limit = limit_k - 50
1309 | limit_k = limit
1310 | while limit_k > 0:
1311 | try:
1312 | response = self.session.get(
1313 | 'https://www.instagram.com/graphql/query/?query_hash=bc3296d1ce80a24b1b6e40b1e72903f5&variables={%22shortcode%22:%22' + shortcode + '%22,%22first%22:50,%22after%22:' + json.dumps(
1314 | json.loads(response)['data']['shortcode_media']['edge_media_to_parent_comment'][
1315 | 'page_info']['end_cursor']) + '}', headers=headers, proxies=self.proxy).text
1316 | comment_count = len(
1317 | json.loads(response)['data']['shortcode_media']['edge_media_to_parent_comment']['edges'])
1318 |
1319 | if limit > comment_count:
1320 | limit = comment_count
1321 |
1322 | limit_k -= limit
1323 | for i in range(0, limit):
1324 | usernames.append(
1325 | json.loads(response)['data']['shortcode_media']['edge_media_to_parent_comment']['edges'][i][
1326 | 'node']['owner']['username'])
1327 | limit = limit_k
1328 | except:
1329 | break
1330 | return usernames
1331 |
1332 |
1333 | def feed_posts(self):
1334 | headers = self._get_headers()
1335 | response = self.session.get(
1336 | 'https://www.instagram.com/graphql/query/?query_hash=c699b185975935ae2a457f24075de8c7', headers=headers,
1337 | proxies=self.proxy).text
1338 |
1339 | post_count = len(json.loads(response)['data']['user']['edge_web_feed_timeline']['edges'])
1340 | feed_posts = []
1341 | for i in range(0, post_count):
1342 | feed_posts.append('https://instagram.com/p/' +
1343 | json.loads(response)['data']['user']['edge_web_feed_timeline']['edges'][i]['node'][
1344 | 'shortcode'])
1345 |
1346 | return feed_posts
1347 |
1348 |
1349 | def post_owner(self, post_link):
1350 | if post_link.find('/tv/') != -1:
1351 | post_link = post_link.replace('/tv/', '/p/')
1352 | try:
1353 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1354 | except:
1355 | pass
1356 | headers = self._get_headers()
1357 |
1358 | if post_link[-1] == '/':
1359 | post_link = post_link[:-1]
1360 |
1361 | response = self.session.get(f'{post_link}/?__a=1', headers=headers, proxies=self.proxy).text
1362 | owner = json.loads(response)['graphql']['shortcode_media']['owner']['username']
1363 |
1364 | return owner
1365 |
1366 |
1367 | def post_caption(self, post_link):
1368 | if post_link.find('/tv/') != -1:
1369 | post_link = post_link.replace('/tv/', '/p/')
1370 | try:
1371 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1372 | except:
1373 | pass
1374 | headers = self._get_headers()
1375 |
1376 | if post_link[-1] == '/':
1377 | post_link = post_link[:-1]
1378 |
1379 | response = self.session.get(f'{post_link}/?__a=1', headers=headers, proxies=self.proxy).text
1380 | caption = json.loads(response)['graphql']['shortcode_media']['edge_media_to_caption']['edges'][0]['node'][
1381 | 'text']
1382 |
1383 | return caption
1384 |
1385 |
1386 | def post_location(self, post_link):
1387 | if post_link.find('/tv/') != -1:
1388 | post_link = post_link.replace('/tv/', '/p/')
1389 | try:
1390 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1391 | except:
1392 | pass
1393 | headers = self._get_headers()
1394 |
1395 | if post_link[-1] == '/':
1396 | post_link = post_link[:-1]
1397 |
1398 | response = self.session.get(f'{post_link}/?__a=1', headers=headers, proxies=self.proxy).text
1399 | location = {"id": json.loads(response)['graphql']['shortcode_media']['location']['id'],
1400 | "name": json.loads(response)['graphql']['shortcode_media']['location']['name']}
1401 |
1402 | return location
1403 |
1404 |
1405 | def post_hashtags(self, post_link):
1406 | if post_link.find('/tv/') != -1:
1407 | post_link = post_link.replace('/tv/', '/p/')
1408 | try:
1409 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1410 | except:
1411 | pass
1412 | hashtag_filter = self.post_caption(post_link).replace('\n', ' ').split()
1413 | hashtags = []
1414 | for hashtag in hashtag_filter:
1415 | if hashtag.startswith('#'):
1416 | hashtags.append(hashtag)
1417 |
1418 | return hashtags
1419 |
1420 |
1421 | def post_tagged_user(self, post_link):
1422 | if post_link.find('/tv/') != -1:
1423 | post_link = post_link.replace('/tv/', '/p/')
1424 | try:
1425 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1426 | except:
1427 | pass
1428 | headers = self._get_headers()
1429 |
1430 | if post_link[-1] == '/':
1431 | post_link = post_link[:-1]
1432 |
1433 | tagged_users = []
1434 | try:
1435 | response = self.session.get(f'{post_link}/?__a=1', headers=headers, proxies=self.proxy).text
1436 | tag_count = len(
1437 | json.loads(response)['graphql']['shortcode_media']['edge_sidecar_to_children']['edges'][0]['node'][
1438 | 'edge_media_to_tagged_user']['edges'])
1439 |
1440 | for i in range(0, tag_count):
1441 | tagged_users.append(
1442 | json.loads(response)['graphql']['shortcode_media']['edge_sidecar_to_children']['edges'][0]['node'][
1443 | 'edge_media_to_tagged_user']['edges'][i]['node']['user']['username'])
1444 | except:
1445 | try:
1446 | response = self.session.get(f'{post_link}/?__a=1', headers=headers, proxies=self.proxy).text
1447 | tag_count = len(
1448 | json.loads(response)['graphql']['shortcode_media']['edge_media_to_tagged_user']['edges'])
1449 |
1450 | for i in range(0, tag_count):
1451 | tagged_users.append(
1452 | json.loads(response)['graphql']['shortcode_media']['edge_media_to_tagged_user']['edges'][i][
1453 | 'node']['user']['username'])
1454 | except:
1455 | pass
1456 |
1457 | return tagged_users
1458 |
1459 |
1460 | def post_time(self, post_link):
1461 | if post_link.find('/tv/') != -1:
1462 | post_link = post_link.replace('/tv/', '/p/')
1463 | try:
1464 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1465 | except:
1466 | pass
1467 | headers = self._get_headers()
1468 |
1469 | if post_link[-1] == '/':
1470 | post_link = post_link[:-1]
1471 |
1472 | response = self.session.get(f'{post_link}/?__a=1', headers=headers, proxies=self.proxy).text
1473 | time = {"timestamp": json.loads(response)['graphql']['shortcode_media']['taken_at_timestamp'], "datetime": str(
1474 | datetime.fromtimestamp(json.loads(response)['graphql']['shortcode_media']['taken_at_timestamp']))}
1475 |
1476 | return time
1477 |
1478 |
1479 | def post_type(self, post_link):
1480 | if post_link.find('/tv/') != -1:
1481 | post_link = post_link.replace('/tv/', '/p/')
1482 | try:
1483 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1484 | except:
1485 | pass
1486 | headers = self._get_headers()
1487 |
1488 | if post_link[-1] == '/':
1489 | post_link = post_link[:-1]
1490 |
1491 | response = self.session.get(f'{post_link}/?__a=1', headers=headers, proxies=self.proxy).text
1492 | if bool(json.loads(response)['graphql']['shortcode_media']['is_video']):
1493 | post_type = 'video'
1494 | else:
1495 | post_type = 'picture'
1496 |
1497 | return post_type
1498 |
1499 |
1500 | def video_views_count(self, post_link):
1501 | if post_link.find('/tv/') != -1:
1502 | post_link = post_link.replace('/tv/', '/p/')
1503 | try:
1504 | post_link = post_link.replace(post_link.split('/p/')[1].split('/')[1], '')
1505 | except:
1506 | pass
1507 | if self.post_type(post_link) == 'video':
1508 | headers = self._get_headers()
1509 |
1510 | if post_link[-1] == '/':
1511 | post_link = post_link[:-1]
1512 |
1513 | response = self.session.get(f'{post_link}/?__a=1', headers=headers, proxies=self.proxy).text
1514 | view_count = json.loads(response)['graphql']['shortcode_media']['video_view_count']
1515 |
1516 | return view_count
1517 |
1518 |
1519 | def followed_by_me(self, username):
1520 | headers = self._get_headers()
1521 |
1522 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1523 | proxies=self.proxy).text
1524 | followed_by_viewer = bool(json.loads(response)['graphql']['user']['followed_by_viewer'])
1525 |
1526 | return followed_by_viewer
1527 |
1528 |
1529 | def follows_me(self, username):
1530 | headers = self._get_headers()
1531 |
1532 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1533 | proxies=self.proxy).text
1534 | follows_viewer = bool(json.loads(response)['graphql']['user']['follows_viewer'])
1535 |
1536 | return follows_viewer
1537 |
1538 |
1539 | def user_external_url(self, username):
1540 | headers = self._get_headers()
1541 |
1542 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1543 | proxies=self.proxy).text
1544 | url = json.loads(response)['graphql']['user']['external_url']
1545 |
1546 | return url
1547 |
1548 |
1549 | def verified_user(self, username):
1550 | headers = self._get_headers()
1551 |
1552 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1553 | proxies=self.proxy).text
1554 | is_verified = bool(json.loads(response)['graphql']['user']['is_verified'])
1555 |
1556 | return is_verified
1557 |
1558 |
1559 | def private_user(self, username):
1560 | headers = self._get_headers()
1561 |
1562 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1563 | proxies=self.proxy).text
1564 | is_private = bool(json.loads(response)['graphql']['user']['is_private'])
1565 |
1566 | return is_private
1567 |
1568 |
1569 | def user_bio(self, username):
1570 | headers = self._get_headers()
1571 |
1572 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1573 | proxies=self.proxy).text
1574 | bio = json.loads(response)['graphql']['user']['biography']
1575 |
1576 | return bio
1577 |
1578 |
1579 | def user_dp(self, username):
1580 | headers = self._get_headers()
1581 |
1582 | response = self.session.get(f'https://www.instagram.com/{username}/?__a=1', headers=headers,
1583 | proxies=self.proxy).text
1584 | dp_url = json.loads(response)['graphql']['user']['profile_pic_url_hd']
1585 |
1586 | return dp_url
1587 |
1588 |
1589 | def _get_headers(self, options=None):
1590 | if options is None:
1591 | options = dict()
1592 |
1593 | headers = {
1594 | "accept": "*/*",
1595 | "accept-encoding": "gzip, deflate, br",
1596 | "accept-language": "en-US,en;q=0.9",
1597 | "content-length": "0",
1598 | "content-type": "application/x-www-form-urlencoded",
1599 | "cookie": self.cookie,
1600 | "sec-fetch-dest": "empty",
1601 | "sec-fetch-mode": "cors",
1602 | "sec-fetch-site": "same-origin",
1603 | "user-agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
1604 | "x-csrftoken": self.csrf_token,
1605 | "x-ig-app-id": "936619743392459",
1606 | "x-ig-www-claim": "hmac.AR3dC7naiVtTKkwrEY0hwTO9zj4kLxfvf4Srvp3wFyoZFqSx",
1607 | "x-instagram-ajax": "d3d3aea32e75",
1608 | "x-requested-with": "XMLHttpRequest"
1609 | }
1610 |
1611 | for key, value in options.items():
1612 | headers[key] = value
1613 |
1614 | return headers
1615 |
--------------------------------------------------------------------------------
/usage.py:
--------------------------------------------------------------------------------
1 | from myigbot import MyIGBot
2 |
3 | bot=MyIGBot('pup.shot', 'qwertypad098')
4 |
5 | response = bot.like('https://www.instagram.com/p/CH5qV6-so6Y/')
6 | print(response) # if the response code is 200 that means ok
7 |
8 | response = bot.unlike('https://www.instagram.com/p/CH5qV6-so6Y/')
9 | print(response) # if the response code is 200 that means ok
10 |
11 | response = bot.like_recent('instagram')
12 | print(response) # if the response code is 200 that means ok
13 |
14 | response = bot.comment('https://www.instagram.com/p/CH5qV6-so6Y/', comment_text='Nice Post!')
15 | print(response) # if the response code is 200 that means ok
16 |
17 | response = bot.comment_recent('instagram', comment_text='Nice Post!')
18 | print(response) # if the response code is 200 that means ok
19 |
20 | response = bot.follow('instagram')
21 | print(response) # if the response code is 200 that means ok
22 |
23 | response = bot.unfollow('instagram')
24 | print(response) # if the response code is 200 that means ok
25 |
26 | response = bot.story_view('b31ngdev')
27 | print(response) # if the response code is 200 that means ok
28 |
29 | response = bot.upload_post('image.png', caption='Image 1')
30 | print(response) # if the response code is 200 that means ok
31 |
32 | response = bot.upload_story('image2.png')
33 | print(response) # if the response code is 200 that means ok
34 |
35 | response = bot.hashtag_posts('programmershumor', limit=50)
36 | print(response) # by default the limit is setted to 20, this is a optional parameter
37 |
38 | response = bot.location_posts('https://www.instagram.com/explore/locations/6889842/paris-france/', limit=20)
39 | print(response) # by default the limit is setted to 20, this is a optional parameter
40 |
41 | response = bot.user_posts_count('instagram')
42 | print(response)
43 |
44 | response = bot.user_followers_count('instagram')
45 | print(response)
46 |
47 | response = bot.user_follow_count('instagram')
48 | print(response)
49 |
50 | response = bot.like_count('https://www.instagram.com/p/CH5qV6-so6Y/')
51 | print(response)
52 |
53 | response = bot.comment_count('https://www.instagram.com/p/CH5qV6-so6Y/')
54 | print(response)
55 |
56 | response = bot.user_posts('instagram', limit=50)
57 | print(response) # by default the limit is setted to 50, this is a optional parameter
58 |
59 | response = bot.user_followers('instagram', limit=50)
60 | print(response) # by default the limit is setted to 50, this is a optional parameter
61 |
62 | response = bot.user_follows('instagram', limit=50)
63 | print(response) # by default the limit is setted to 50, this is a optional parameter
64 |
65 | response = bot.post_likers('https://www.instagram.com/p/CH5qV6-so6Y/', limit=50)
66 | print(response) # by default the limit is setted to 50, this is a optional parameter
67 |
68 | response = bot.post_commenters('https://www.instagram.com/p/CH5qV6-so6Y/', limit=50)
69 | print(response) # by default the limit is setted to 50, this is a optional parameter
70 |
71 | response = bot.feed_posts()
72 | print(response)
73 |
74 | response = bot.post_owner('https://www.instagram.com/p/CH5qV6-so6Y/')
75 | print(response)
76 |
77 | response = bot.post_caption('https://www.instagram.com/p/CH5qV6-so6Y/')
78 | print(response)
79 |
80 | response = bot.post_location('https://www.instagram.com/p/CH5qV6-so6Y/')
81 | print(response)
82 |
83 | response = bot.post_hashtags('https://www.instagram.com/p/CH5qV6-so6Y/')
84 | print(response)
85 |
86 | response = bot.post_tagged_user('https://www.instagram.com/p/B2fZRgBA2wj/')
87 | print(response)
88 |
89 | response = bot.user_dp('instagram')
90 | print(response)
91 |
92 | response = bot.user_bio('instagram')
93 | print(response)
94 |
95 | response = bot.private_user('instagram')
96 | print(response)
97 |
98 | response = bot.verified_user('instagram')
99 | print(response)
100 |
101 | response = bot.user_external_url('instagram')
102 | print(response)
103 |
104 | response = bot.follows_me('instagram')
105 | print(response)
106 |
107 | response = bot.followed_by_me('instagram')
108 | print(response)
109 |
110 | response = bot.video_views_count('https://www.instagram.com/p/B2XPNNvgApx/')
111 | print(response)
112 |
113 | response = bot.post_type('https://www.instagram.com/p/CH5qV6-so6Y/')
114 | print(response)
115 |
116 | response = bot.post_time('https://www.instagram.com/p/CH5qV6-so6Y/')
117 | print(response)
118 |
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import cv2
2 |
3 |
4 | def get_media_duration(media_path: str) -> float:
5 | video = cv2.VideoCapture(media_path)
6 |
7 | duration = video.get(cv2.CAP_PROP_FRAME_COUNT) / video.get(cv2.CAP_PROP_FPS)
8 |
9 | return duration
10 |
--------------------------------------------------------------------------------