Advertisement
Guest User

Untitled

a guest
Sep 30th, 2018
570
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.56 KB | None | 0 0
  1. import requests
  2. import sqlite3
  3. import json
  4. import time
  5. import re
  6. import random
  7.  
  8. FOLLOW_UNFOLLOW_INTERVAL = 86400 * 3
  9. QUERY_HASH = 'x'
  10. USERNAME = 'x'
  11. PASSWORD = 'x'
  12. FOLLOW_ITERATIONS = 50
  13. FOLLOW_PER_HOUR = 160 # 160 is the maximum for Instagram API
  14.  
  15.  
  16. class Instagram:
  17. 'Used for communicating with Instagram'
  18.  
  19. USER_AGENT = 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'
  20.  
  21. # API Endpoints
  22. INSTAGRAM_URL = 'https://www.instagram.com/'
  23. LOGIN_ENDPOINT = 'accounts/login/ajax/'
  24. FOLLOW_ENDPOINT = 'web/friendships/{id}/follow/'
  25. UNFOLLOW_ENDPOINT = 'web/friendships/{id}/unfollow/'
  26. GRAPHQL_API = 'graphql/query/'
  27.  
  28. def __init__(self):
  29. self.session = requests.Session()
  30. r = self.session.get(self.INSTAGRAM_URL)
  31. self.csrf_token = r.cookies['csrftoken']
  32.  
  33. def set_headers(self):
  34. 'Sets the necessary headers for Instagram requests'
  35.  
  36. self.session.headers.update({
  37. 'Host': 'www.instagram.com',
  38. 'Origin': 'https://www.instagram.com',
  39. 'Referer': 'https://www.instagram.com/',
  40. 'User-Agent': self.USER_AGENT,
  41. 'X-Instagram-AJAX': '1',
  42. 'X-Requested-With': 'XMLHttpRequest',
  43. 'X-CSRFToken': self.csrf_token,
  44. })
  45.  
  46. def login(self, username, password):
  47. 'Logs into Instagram'
  48.  
  49. self.set_headers()
  50.  
  51. login_data = {'username': username, 'password': password}
  52. login = self.session.post(self.INSTAGRAM_URL + self.LOGIN_ENDPOINT, data=login_data,
  53. allow_redirects=True)
  54.  
  55. if not login.json()['authenticated']:
  56. raise ValueError("Username and/or password provided failed to authenticate")
  57.  
  58. self.csrf_token = login.cookies['csrftoken']
  59.  
  60. def get_suggested_people(self, request_count=0, seen=[], excludes=[], *, query_hash):
  61. '''Gets suggested people from the Explore tab
  62.  
  63. Keyword Arguments:
  64. request_count -- the amount of times to fetch users (10 at a time) (0 for infinite)
  65. query_hash -- a query hash for the graphql api
  66. '''
  67.  
  68. self.set_headers()
  69. variables = {"fetch_media_count": 0,
  70. "fetch_suggested_count": 20,
  71. "ignore_cache": False,
  72. "filter_followed_friends": True,
  73. "seen_ids": [],
  74. "include_reel": True}
  75.  
  76. counter = 1
  77. while request_count == 0 or counter <= request_count:
  78. while True:
  79. try:
  80. response = self.session.get(self.INSTAGRAM_URL + self.GRAPHQL_API,
  81. params={'query_hash': query_hash,
  82. 'variables': json.dumps(variables)})
  83. people = response.json()
  84. suggested = people['data']['user']['edge_suggested_users']['edges']
  85. except KeyError:
  86. print('You are being rate limited, pausing for 20 minutes')
  87. time.sleep(1200)
  88. except json.JSONDecodeError as e:
  89. print('JSON Failed to decode with error:', e)
  90. time.sleep(5)
  91. else:
  92. for person in suggested:
  93. if any(re.findall(r, person['node']['user']['username']) for r in excludes):
  94. variables['seen_ids'].append(person['node']['user']['id'])
  95. continue
  96. elif person['node']['user']['id'] in seen:
  97. continue
  98. elif person['node']['user']['is_verified']:
  99. continue
  100. yield person['node']['user']
  101. break
  102.  
  103. counter += 1
  104. variables['seen_ids'].extend([person['node']['user']['id'] for person in suggested])
  105.  
  106. def follow(self, id):
  107. 'Follows a user based on their ID'
  108. self.set_headers()
  109. r = self.session.post(self.INSTAGRAM_URL + self.FOLLOW_ENDPOINT.format(id=id))
  110. return r
  111.  
  112. def unfollow(self, id):
  113. 'Unfollows a user based on their ID'
  114. self.set_headers()
  115. r = self.session.post(self.INSTAGRAM_URL + self.UNFOLLOW_ENDPOINT.format(id=id))
  116. return r
  117.  
  118.  
  119. db = sqlite3.connect('instagram.db')
  120. c = db.cursor()
  121. c.execute('CREATE TABLE IF NOT EXISTS users (user_id INTEGER, unfollow_time REAL)')
  122. db.commit()
  123.  
  124. # IG FOLLOW/UNFOLLOW
  125.  
  126. ig = Instagram()
  127.  
  128.  
  129. def follow_person(person):
  130. ig.follow(person['id'])
  131. c.execute('INSERT INTO users VALUES (?, ?)',
  132. (person['id'], time.time() + FOLLOW_UNFOLLOW_INTERVAL))
  133.  
  134.  
  135. print('Connecting to instagram with the user ' + USERNAME)
  136. try:
  137. ig.login(USERNAME, PASSWORD)
  138. except Exception as e:
  139. print('Error while logging in', e)
  140. exit()
  141. else:
  142. print('Sucessfully logged in')
  143.  
  144. # FOLLOW NEW USERS
  145. # print('========== FOLLOWING PROCESS ==========')
  146. #
  147. # c.execute('SELECT user_id FROM users')
  148. # seen_ids = [x[0] for x in c.fetchall()]
  149. #
  150. # people = ig.get_suggested_people(FOLLOW_ITERATIONS, seen=seen_ids,
  151. # query_hash=QUERY_HASH, excludes=[r'v2$'])
  152. # expected_time = ((FOLLOW_ITERATIONS*10 * 17.5) // 60) + FOLLOW_ITERATIONS
  153. # print('Please allow up to {} minutes to complete the following process'.format(expected_time))
  154. # print('Up to {} new users will be followed'.format(FOLLOW_ITERATIONS*10))
  155. #
  156. # for n, person in enumerate(people):
  157. # follow_person(person)
  158. # print('> Following {}'.format(person['username']))
  159. # db.commit()
  160. # time.sleep(random.randint(5, 30)) # To prevent rate limiting
  161.  
  162.  
  163. # UNFOLLOW EXPIRED USERS
  164. print('========= UNFOLLOWING PROCESS =========')
  165.  
  166. c.execute('SELECT user_id FROM users WHERE unfollow_time > ?',
  167. (time.time(),))
  168.  
  169. user_ids = c.fetchall()
  170.  
  171. expected_time = len(user_ids) * 7.5
  172. total = len(user_ids)
  173.  
  174. for n, user_id in enumerate(user_ids):
  175. print('Unfollowing {}/{} people, approx {} minutes remaining'
  176. .format(n+1, total, (expected_time - 27.5*n)//60))
  177. unfollow = ig.unfollow(user_id[0])
  178. if unfollow.status_code != 200:
  179. print('Something went wrong, retrying in 30 seconds')
  180. time.sleep(30)
  181. c.execute('UPDATE users SET unfollow_time = 9999999999 WHERE user_id = ?',
  182. (user_id[0],))
  183. db.commit()
  184. time.sleep(random.randint(25, 30)) # To prevent rate limiting
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement