Skip to content

Commit d4b8ef6

Browse files
committed
New Feature: Direct Share
1 parent 6ecef53 commit d4b8ef6

3 files changed

Lines changed: 90 additions & 9 deletions

File tree

InstagramAPI.py

Lines changed: 83 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
import copy
1313
import math
1414
import sys
15+
from datetime import datetime
16+
import calendar
17+
import os
1518

1619
#The urllib library was split into other modules from Python 2 to Python 3
1720
if sys.version_info.major == 3:
@@ -207,8 +210,65 @@ def uploadVideo(self, video, thumbnail, caption = None, upload_id = None):
207210
return False
208211

209212
def direct_share(self, media_id, recipients, text = None):
210-
# TODO Instagram.php 420-490
211-
return False
213+
if type(recipients) != type([]):
214+
recipients = [str(recipients)]
215+
recipient_users = '"",""'.join(str(r) for r in recipients)
216+
endpoint = 'direct_v2/threads/broadcast/media_share/?media_type=photo'
217+
boundary = self.uuid
218+
bodies = [
219+
{
220+
'type' : 'form-data',
221+
'name' : 'media_id',
222+
'data' : media_id,
223+
},
224+
{
225+
'type' : 'form-data',
226+
'name' : 'recipient_users',
227+
'data' : '[["{}"]]'.format(recipient_users),
228+
},
229+
{
230+
'type' : 'form-data',
231+
'name' : 'client_context',
232+
'data' : self.uuid,
233+
},
234+
{
235+
'type' : 'form-data',
236+
'name' : 'thread_ids',
237+
'data' : '["0"]',
238+
},
239+
{
240+
'type' : 'form-data',
241+
'name' : 'text',
242+
'data' : text or '',
243+
},
244+
]
245+
data = self.buildBody(bodies,boundary)
246+
self.s.headers.update (
247+
{
248+
'User-Agent' : self.USER_AGENT,
249+
'Proxy-Connection' : 'keep-alive',
250+
'Connection': 'keep-alive',
251+
'Accept': '*/*',
252+
'Content-Type': 'multipart/form-data; boundary={}'.format(boundary),
253+
'Accept-Language': 'en-en',
254+
}
255+
)
256+
#self.SendRequest(endpoint,post=data) #overwrites 'Content-type' header and boundary is missed
257+
response = self.s.post(self.API_URL + endpoint, data=data)
258+
259+
if response.status_code == 200:
260+
self.LastResponse = response
261+
self.LastJson = json.loads(response.text)
262+
return True
263+
else:
264+
print ("Request return " + str(response.status_code) + " error!")
265+
# for debugging
266+
try:
267+
self.LastResponse = response
268+
self.LastJson = json.loads(response.text)
269+
except:
270+
pass
271+
return False
212272

213273
def configureVideo(self, upload_id, video, thumbnail, caption = ''):
214274
clip = VideoFileClip(video)
@@ -592,23 +652,37 @@ def generateUUID(self, type):
592652
return generated_uuid
593653
else:
594654
return generated_uuid.replace('-', '')
595-
596-
def buildBody(bodies, boundary):
597-
# TODO Instagram.php 1620-1645
598-
return False
599-
655+
656+
def generateUploadId():
657+
return str(calendar.timegm(datetime.utcnow().utctimetuple()))
658+
659+
def buildBody(self,bodies, boundary):
660+
body = u''
661+
for b in bodies:
662+
body += u'--{boundary}\r\n'.format(boundary=boundary)
663+
body += u'Content-Disposition: {b_type}; name="{b_name}"'.format(b_type = b['type'], b_name = b['name'])
664+
_filename = b.get('filename',None)
665+
_headers = b.get('headers',None)
666+
if _filename:
667+
_filename, ext = os.path.splitext(_filename)
668+
_body += u'; filename="pending_media_{uid}.{ext}"'.format(uid = self.generateUploadId(), ext = ext)
669+
if _headers and type(_headers) == type([]):
670+
for h in _headers:
671+
_body += u'\r\n{header}'.format(header = h)
672+
body += u'\r\n\r\n{data}\r\n'.format(data = b['data'])
673+
body += u'--{boundary}--'.format(boundary = boundary)
674+
return body;
675+
600676
def SendRequest(self, endpoint, post = None, login = False):
601677
if (not self.isLoggedIn and not login):
602678
raise Exception("Not logged in!\n")
603679
return;
604-
605680
self.s.headers.update ({'Connection' : 'close',
606681
'Accept' : '*/*',
607682
'Content-type' : 'application/x-www-form-urlencoded; charset=UTF-8',
608683
'Cookie2' : '$Version=1',
609684
'Accept-Language' : 'en-US',
610685
'User-Agent' : self.USER_AGENT})
611-
612686
if (post != None): # POST
613687
response = self.s.post(self.API_URL + endpoint, data=post) # , verify=False
614688
else: # GET

examples/direct_share.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from InstagramAPI import InstagramAPI
2+
user,pwd = '', '' #your credentials
3+
InstagramAPI = InstagramAPI(user,pwd)
4+
InstagramAPI.login() # login
5+
mediaId='1469246128528859784_1520706701' #a media_id
6+
recipients = [] #array of user_ids. They can be strings or ints
7+
InstagramAPI.direct_share(mediaId, recipients,text='aquest es es darrer')
File renamed without changes.

0 commit comments

Comments
 (0)