Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- import sqlite3
- import json
- import time
- import re
- import random
- FOLLOW_UNFOLLOW_INTERVAL = 86400 * 3
- QUERY_HASH = 'x'
- USERNAME = 'x'
- PASSWORD = 'x'
- FOLLOW_ITERATIONS = 50
- FOLLOW_PER_HOUR = 160 # 160 is the maximum for Instagram API
- class Instagram:
- 'Used for communicating with Instagram'
- 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'
- # API Endpoints
- INSTAGRAM_URL = 'https://www.instagram.com/'
- LOGIN_ENDPOINT = 'accounts/login/ajax/'
- FOLLOW_ENDPOINT = 'web/friendships/{id}/follow/'
- UNFOLLOW_ENDPOINT = 'web/friendships/{id}/unfollow/'
- GRAPHQL_API = 'graphql/query/'
- def __init__(self):
- self.session = requests.Session()
- r = self.session.get(self.INSTAGRAM_URL)
- self.csrf_token = r.cookies['csrftoken']
- def set_headers(self):
- 'Sets the necessary headers for Instagram requests'
- self.session.headers.update({
- 'Host': 'www.instagram.com',
- 'Origin': 'https://www.instagram.com',
- 'Referer': 'https://www.instagram.com/',
- 'User-Agent': self.USER_AGENT,
- 'X-Instagram-AJAX': '1',
- 'X-Requested-With': 'XMLHttpRequest',
- 'X-CSRFToken': self.csrf_token,
- })
- def login(self, username, password):
- 'Logs into Instagram'
- self.set_headers()
- login_data = {'username': username, 'password': password}
- login = self.session.post(self.INSTAGRAM_URL + self.LOGIN_ENDPOINT, data=login_data,
- allow_redirects=True)
- if not login.json()['authenticated']:
- raise ValueError("Username and/or password provided failed to authenticate")
- self.csrf_token = login.cookies['csrftoken']
- def get_suggested_people(self, request_count=0, seen=[], excludes=[], *, query_hash):
- '''Gets suggested people from the Explore tab
- Keyword Arguments:
- request_count -- the amount of times to fetch users (10 at a time) (0 for infinite)
- query_hash -- a query hash for the graphql api
- '''
- self.set_headers()
- variables = {"fetch_media_count": 0,
- "fetch_suggested_count": 20,
- "ignore_cache": False,
- "filter_followed_friends": True,
- "seen_ids": [],
- "include_reel": True}
- counter = 1
- while request_count == 0 or counter <= request_count:
- while True:
- try:
- response = self.session.get(self.INSTAGRAM_URL + self.GRAPHQL_API,
- params={'query_hash': query_hash,
- 'variables': json.dumps(variables)})
- people = response.json()
- suggested = people['data']['user']['edge_suggested_users']['edges']
- except KeyError:
- print('You are being rate limited, pausing for 20 minutes')
- time.sleep(1200)
- except json.JSONDecodeError as e:
- print('JSON Failed to decode with error:', e)
- time.sleep(5)
- else:
- for person in suggested:
- if any(re.findall(r, person['node']['user']['username']) for r in excludes):
- variables['seen_ids'].append(person['node']['user']['id'])
- continue
- elif person['node']['user']['id'] in seen:
- continue
- elif person['node']['user']['is_verified']:
- continue
- yield person['node']['user']
- break
- counter += 1
- variables['seen_ids'].extend([person['node']['user']['id'] for person in suggested])
- def follow(self, id):
- 'Follows a user based on their ID'
- self.set_headers()
- r = self.session.post(self.INSTAGRAM_URL + self.FOLLOW_ENDPOINT.format(id=id))
- return r
- def unfollow(self, id):
- 'Unfollows a user based on their ID'
- self.set_headers()
- r = self.session.post(self.INSTAGRAM_URL + self.UNFOLLOW_ENDPOINT.format(id=id))
- return r
- db = sqlite3.connect('instagram.db')
- c = db.cursor()
- c.execute('CREATE TABLE IF NOT EXISTS users (user_id INTEGER, unfollow_time REAL)')
- db.commit()
- # IG FOLLOW/UNFOLLOW
- ig = Instagram()
- def follow_person(person):
- ig.follow(person['id'])
- c.execute('INSERT INTO users VALUES (?, ?)',
- (person['id'], time.time() + FOLLOW_UNFOLLOW_INTERVAL))
- print('Connecting to instagram with the user ' + USERNAME)
- try:
- ig.login(USERNAME, PASSWORD)
- except Exception as e:
- print('Error while logging in', e)
- exit()
- else:
- print('Sucessfully logged in')
- # FOLLOW NEW USERS
- # print('========== FOLLOWING PROCESS ==========')
- #
- # c.execute('SELECT user_id FROM users')
- # seen_ids = [x[0] for x in c.fetchall()]
- #
- # people = ig.get_suggested_people(FOLLOW_ITERATIONS, seen=seen_ids,
- # query_hash=QUERY_HASH, excludes=[r'v2$'])
- # expected_time = ((FOLLOW_ITERATIONS*10 * 17.5) // 60) + FOLLOW_ITERATIONS
- # print('Please allow up to {} minutes to complete the following process'.format(expected_time))
- # print('Up to {} new users will be followed'.format(FOLLOW_ITERATIONS*10))
- #
- # for n, person in enumerate(people):
- # follow_person(person)
- # print('> Following {}'.format(person['username']))
- # db.commit()
- # time.sleep(random.randint(5, 30)) # To prevent rate limiting
- # UNFOLLOW EXPIRED USERS
- print('========= UNFOLLOWING PROCESS =========')
- c.execute('SELECT user_id FROM users WHERE unfollow_time > ?',
- (time.time(),))
- user_ids = c.fetchall()
- expected_time = len(user_ids) * 7.5
- total = len(user_ids)
- for n, user_id in enumerate(user_ids):
- print('Unfollowing {}/{} people, approx {} minutes remaining'
- .format(n+1, total, (expected_time - 27.5*n)//60))
- unfollow = ig.unfollow(user_id[0])
- if unfollow.status_code != 200:
- print('Something went wrong, retrying in 30 seconds')
- time.sleep(30)
- c.execute('UPDATE users SET unfollow_time = 9999999999 WHERE user_id = ?',
- (user_id[0],))
- db.commit()
- time.sleep(random.randint(25, 30)) # To prevent rate limiting
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement