Skip to content

Commit

Permalink
Merge branch 'master' of github.com:LevPasha/Instagram-API-python int…
Browse files Browse the repository at this point in the history
…o delete_media
  • Loading branch information
r17x committed Mar 25, 2018
2 parents 46f1ce8 + c17f33a commit 6f6db85
Show file tree
Hide file tree
Showing 8 changed files with 251 additions and 11 deletions.
105 changes: 103 additions & 2 deletions InstagramAPI/InstagramAPI.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def setProxy(self, proxy=None):

if proxy is not None:
print('Set proxy!')
proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy}
proxies = {'http': proxy, 'https': proxy}
self.s.proxies.update(proxies)

def login(self, force=False):
Expand Down Expand Up @@ -388,7 +388,63 @@ def configureTimelineAlbum(self, media, albumInternalMetadata, captionText='', l
except:
pass
return False


def direct_message(self, text, recipients):
if type(recipients) != type([]):
recipients = [str(recipients)]
recipient_users = '"",""'.join(str(r) for r in recipients)
endpoint = 'direct_v2/threads/broadcast/text/'
boundary = self.uuid
bodies = [
{
'type' : 'form-data',
'name' : 'recipient_users',
'data' : '[["{}"]]'.format(recipient_users),
},
{
'type' : 'form-data',
'name' : 'client_context',
'data' : self.uuid,
},
{
'type' : 'form-data',
'name' : 'thread',
'data' : '["0"]',
},
{
'type' : 'form-data',
'name' : 'text',
'data' : text or '',
},
]
data = self.buildBody(bodies,boundary)
self.s.headers.update (
{
'User-Agent' : self.USER_AGENT,
'Proxy-Connection' : 'keep-alive',
'Connection': 'keep-alive',
'Accept': '*/*',
'Content-Type': 'multipart/form-data; boundary={}'.format(boundary),
'Accept-Language': 'en-en',
}
)
#self.SendRequest(endpoint,post=data) #overwrites 'Content-type' header and boundary is missed
response = self.s.post(self.API_URL + endpoint, data=data)

if response.status_code == 200:
self.LastResponse = response
self.LastJson = json.loads(response.text)
return True
else:
print ("Request return " + str(response.status_code) + " error!")
# for debugging
try:
self.LastResponse = response
self.LastJson = json.loads(response.text)
except:
pass
return False

def direct_share(self, media_id, recipients, text=None):
if not isinstance(position, list):
recipients = [str(recipients)]
Expand Down Expand Up @@ -727,6 +783,20 @@ def unlike(self, mediaId):
'media_id': mediaId})
return self.SendRequest('media/' + str(mediaId) + '/unlike/', self.generateSignature(data))

def save(self, mediaId):
data = json.dumps({'_uuid': self.uuid,
'_uid': self.username_id,
'_csrftoken': self.token,
'media_id': mediaId})
return self.SendRequest('media/' + str(mediaId) + '/save/', self.generateSignature(data))

def unsave(self, mediaId):
data = json.dumps({'_uuid': self.uuid,
'_uid': self.username_id,
'_csrftoken': self.token,
'media_id': mediaId})
return self.SendRequest('media/' + str(mediaId) + '/unsave/', self.generateSignature(data))

def getMediaComments(self, mediaId, max_id=''):
return self.SendRequest('media/' + mediaId + '/comments/?max_id=' + max_id)

Expand Down Expand Up @@ -827,6 +897,37 @@ def generateUUID(self, type):
def generateUploadId(self):
return str(calendar.timegm(datetime.utcnow().utctimetuple()))

def createBroadcast(self, previewWidth=1080, previewHeight=1920, broadcastMessage=''):
data = json.dumps({'_uuid': self.uuid,
'_uid': self.username_id,
'preview_height': previewHeight,
'preview_width': previewWidth,
'broadcast_message': broadcastMessage,
'broadcast_type': 'RTMP',
'internal_only': 0,
'_csrftoken': self.token})
return self.SendRequest('live/create/', self.generateSignature(data))

def startBroadcast(self, broadcastId, sendNotification=False):
data = json.dumps({'_uuid': self.uuid,
'_uid': self.username_id,
'should_send_notifications': int(sendNotification),
'_csrftoken': self.token})
return self.SendRequest('live/' + str(broadcastId) + '/start', self.generateSignature(data))

def stopBroadcast(self, broadcastId):
data = json.dumps({'_uuid': self.uuid,
'_uid': self.username_id,
'_csrftoken': self.token})
return self.SendRequest('live/' + str(broadcastId) + '/end_broadcast/', self.generateSignature(data))

def addBroadcastToLive(self, broadcastId):
# broadcast has to be ended first!
data = json.dumps({'_uuid': self.uuid,
'_uid': self.username_id,
'_csrftoken': self.token})
return self.SendRequest('live/' + str(broadcastId) + '/add_to_post_live/', self.generateSignature(data))

def buildBody(self, bodies, boundary):
body = u''
for b in bodies:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ This is the Python port of https://github.com/mgp25/Instagram-API which is writt
It is still a work in progress to copy all of its API endpoints.

NOTE: To successfully parse for a long time you should verify your phone number in your Instagram account.
The new fake Instagram account with an unverifird phone number after ~ 1-24 hours could not do any requests. All requests will be redirected to the page instagram.com/challenge
The new fake Instagram account with an unverified phone number after ~ 1-24 hours could not do any requests. All requests will be redirected to the page https://instagram.com/challenge

### Installation Instructions

Expand Down
Empty file added examples/evaluation/__init__.py
Empty file.
30 changes: 30 additions & 0 deletions examples/evaluation/evaluate_user_followers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Use text editor to edit the script and type in valid Instagram username/password

from InstagramAPI import InstagramAPI
from examples.evaluation.evaluation_log import EvaluationLog
from examples.user_followers import getTotalFollowers


def evaluate_method(function, parameters, function_name=None):
evaluation_log = EvaluationLog()
evaluation_log.start_log(function_name)
response = function(*parameters)
evaluation_log.end_log(function_name)

print('response size:', len(response))
print('number of unique users:', len(set([user['username'] for user in response])))
print()


if __name__ == "__main__":
api = InstagramAPI("username", "password")
api.login()

# For a user with over 22k followers, use: user_id = '1461295173'
user_id = api.username_id

evaluate_method(api.getTotalFollowers, [user_id], 'api.getTotalFollowers')
evaluate_method(getTotalFollowers, [api, user_id], 'getTotalFollowers')
37 changes: 37 additions & 0 deletions examples/evaluation/evaluation_log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from time import time, process_time, strftime, localtime
from datetime import timedelta


def time_to_str(elapsed=None):
if elapsed is None:
return strftime("%Y-%m-%d %H:%M:%S", localtime())
else:
return str(timedelta(seconds=elapsed))


class EvaluationLog():

def start_log(self, s="Start Program"):
self.start = time()
self.cpu_start = process_time()
self.log(s)

def end_log(self, s="End Program"):
self.end = time()
self.cpu_end = process_time()
elapsed_time = self.end - self.start
cpu_time = self.cpu_end - self.cpu_start
self.log(s, time_to_str(elapsed_time), time_to_str(cpu_time))

@staticmethod
def log(s, elapsed_time=None, cpu_time=None):
line = "=" * 40
print(line)
print(time_to_str(), '-', s)

if elapsed_time:
print("Elapsed time:", elapsed_time)
if cpu_time:
print("CPU time:", cpu_time)

print(line)
44 changes: 44 additions & 0 deletions examples/live_broadcast.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Use text editor to edit the script and type in valid Instagram username/password

import subprocess

from InstagramAPI import InstagramAPI

USERNAME = ''
PASSWORD = ''
FILE_PATH = '/path/to/video/file'
PUBLISH_TO_LIVE_FEED = False
SEND_NOTIFICATIONS = False

api = InstagramAPI(USERNAME, PASSWORD, debug=False)
assert api.login()

# first you have to create a broadcast - you will receive a broadcast id and an upload url here
assert api.createBroadcast()
broadcast_id = api.LastJson['broadcast_id']
upload_url = api.LastJson['upload_url']

# we now start a boradcast - it will now appear in the live-feed of users
assert api.startBroadcast(broadcast_id, sendNotification=SEND_NOTIFICATIONS)

ffmpeg_cmd = "ffmpeg -rtbufsize 256M -re -i '{file}' -acodec libmp3lame -ar 44100 -b:a 128k -pix_fmt yuv420p -profile:v baseline -s 720x1280 -bufsize 6000k -vb 400k -maxrate 1500k -deinterlace -vcodec libx264 -preset veryfast -g 30 -r 30 -f flv '{stream_url}'".format(
file=FILE_PATH,
stream_url=upload_url.replace(':443', ':80', ).replace('rtmps://', 'rtmp://'),
)

print("Hit Ctrl+C to stop broadcast")
try:
subprocess.call(ffmpeg_cmd, shell=True)
except KeyboardInterrupt:
print('Stop Broadcasting')

assert api.stopBroadcast(broadcast_id)

print('Finished Broadcast')

if PUBLISH_TO_LIVE_FEED:
api.addBroadcastToLive(broadcast_id)
print('Added Broadcast to LiveFeed')
2 changes: 1 addition & 1 deletion examples/thread_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,6 @@ def save(self):
InstagramAPI = InstagramAPI("login", "password")
InstagramAPI.login()

inst = DownloadThead(InstagramAPI, thread_id)
inst = DownloadThread(InstagramAPI, thread_id)
inst.download()
inst.save()
42 changes: 35 additions & 7 deletions examples/user_followers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,38 @@

from InstagramAPI import InstagramAPI

api = InstagramAPI("login", "password")
api.login() # login
api.tagFeed("cat") # get media list by tag #cat
media_id = api.LastJson # last response JSON
api.like(media_id["ranked_items"][0]["pk"]) # like first media
api.getUserFollowers(media_id["ranked_items"][0]["user"]["pk"]) # get first media owner followers
print(api.LastJson)

def getTotalFollowers(api, user_id):
"""
Returns the list of followers of the user.
It should be equivalent of calling api.getTotalFollowers from InstagramAPI
"""

followers = []
next_max_id = True
while next_max_id:
# first iteration hack
if next_max_id is True:
next_max_id = ''

_ = api.getUserFollowers(user_id, maxid=next_max_id)
followers.extend(api.LastJson.get('users', []))
next_max_id = api.LastJson.get('next_max_id', '')
return followers


if __name__ == "__main__":
api = InstagramAPI("username", "password")
api.login()

# user_id = '1461295173'
user_id = api.username_id

# List of all followers
followers = getTotalFollowers(api, user_id)
print('Number of followers:', len(followers))

# Alternatively, use the code below
# (check evaluation.evaluate_user_followers for further details).
followers = api.getTotalFollowers(user_id)
print('Number of followers:', len(followers))

0 comments on commit 6f6db85

Please sign in to comment.