Skip to content

Commit fbf86c1

Browse files
committed
Add API method for get direct messages
1 parent c333876 commit fbf86c1

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

InstagramAPI/InstagramAPI.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,13 @@ def getv2Inbox(self):
460460
inbox = self.SendRequest('direct_v2/inbox/?')
461461
return inbox
462462

463+
def getv2Threads(self, thread, cursor=None):
464+
endpoint = 'direct_v2/threads/{0}'.format(thread)
465+
if cursor is not None:
466+
endpoint += '?cursor={0}'.format(cursor)
467+
inbox = self.SendRequest(endpoint)
468+
return inbox
469+
463470
def getUserTags(self, usernameId):
464471
tags = self.SendRequest('usertags/'+ str(usernameId) +'/feed/?rank_token='+ str(self.rank_token) +'&ranked_content=true&')
465472
return tags

examples/thread_download.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import json
2+
3+
from InstagramAPI import InstagramAPI
4+
5+
6+
class DownloadThread():
7+
def __init__(self, client, thread_id):
8+
self.client = client
9+
10+
self.thread = thread_id
11+
self.newest_cursor = None
12+
self.oldest_cursor = None
13+
self.users = {}
14+
self.conversation = []
15+
16+
def init_owner(self):
17+
if not self.client.getProfileData():
18+
print("Failed!\n")
19+
20+
user = self.client.LastJson.get('user')
21+
self._add_user(user)
22+
23+
def _request(self):
24+
return self.client.getv2Threads(thread_id, self.oldest_cursor)
25+
26+
def _download(self):
27+
if self.oldest_cursor is not None:
28+
self._request()
29+
self._save()
30+
31+
def _save(self):
32+
data = self.client.LastJson.get('thread')
33+
self.conversation = data['items'][::-1] + self.conversation
34+
self.oldest_cursor = data.get('oldest_cursor')
35+
self.newest_cursor = data.get('newest_cursor')
36+
self._download()
37+
38+
def add_users(self, users):
39+
for user in users:
40+
self._add_user(user)
41+
42+
def _add_user(self, user):
43+
self.users[user['pk']] = {'full_name': user['pk'], 'username': user['username']}
44+
45+
def download(self):
46+
if not self._request():
47+
print("Failed!\n")
48+
49+
data = self.client.LastJson.get('thread')
50+
self.add_users(data['users'])
51+
self._save()
52+
53+
def save(self):
54+
dump = json.dumps(self.conversation)
55+
with open('back.txt', 'w') as f:
56+
f.write(dump)
57+
58+
59+
if __name__ == "__main__":
60+
user, pwd = '', '' # your credentials
61+
thread_id = '' # id thread for download
62+
63+
InstagramAPI = InstagramAPI(user, pwd)
64+
InstagramAPI.login()
65+
66+
inst = DownloadThead(InstagramAPI, thread_id)
67+
inst.download()
68+
inst.save()

0 commit comments

Comments
 (0)