Skip to content

Commit 0198ccc

Browse files
authored
Merge pull request #322 from raphasousa/master
Add function to send direct message
2 parents 38c1330 + 9caf59d commit 0198ccc

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

InstagramAPI/InstagramAPI.py

+57-1
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,63 @@ def configureTimelineAlbum(self, media, albumInternalMetadata, captionText='', l
384384
except:
385385
pass
386386
return False
387-
387+
388+
def direct_message(self, text, recipients):
389+
if type(recipients) != type([]):
390+
recipients = [str(recipients)]
391+
recipient_users = '"",""'.join(str(r) for r in recipients)
392+
endpoint = 'direct_v2/threads/broadcast/text/'
393+
boundary = self.uuid
394+
bodies = [
395+
{
396+
'type' : 'form-data',
397+
'name' : 'recipient_users',
398+
'data' : '[["{}"]]'.format(recipient_users),
399+
},
400+
{
401+
'type' : 'form-data',
402+
'name' : 'client_context',
403+
'data' : self.uuid,
404+
},
405+
{
406+
'type' : 'form-data',
407+
'name' : 'thread',
408+
'data' : '["0"]',
409+
},
410+
{
411+
'type' : 'form-data',
412+
'name' : 'text',
413+
'data' : text or '',
414+
},
415+
]
416+
data = self.buildBody(bodies,boundary)
417+
self.s.headers.update (
418+
{
419+
'User-Agent' : self.USER_AGENT,
420+
'Proxy-Connection' : 'keep-alive',
421+
'Connection': 'keep-alive',
422+
'Accept': '*/*',
423+
'Content-Type': 'multipart/form-data; boundary={}'.format(boundary),
424+
'Accept-Language': 'en-en',
425+
}
426+
)
427+
#self.SendRequest(endpoint,post=data) #overwrites 'Content-type' header and boundary is missed
428+
response = self.s.post(self.API_URL + endpoint, data=data)
429+
430+
if response.status_code == 200:
431+
self.LastResponse = response
432+
self.LastJson = json.loads(response.text)
433+
return True
434+
else:
435+
print ("Request return " + str(response.status_code) + " error!")
436+
# for debugging
437+
try:
438+
self.LastResponse = response
439+
self.LastJson = json.loads(response.text)
440+
except:
441+
pass
442+
return False
443+
388444
def direct_share(self, media_id, recipients, text=None):
389445
if not isinstance(position, list):
390446
recipients = [str(recipients)]

0 commit comments

Comments
 (0)