This repository was archived by the owner on May 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInstagram.py
More file actions
180 lines (158 loc) · 6.31 KB
/
Instagram.py
File metadata and controls
180 lines (158 loc) · 6.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import time
import json
import queue
import threading
from InstagramAPI import InstagramAPI
import logging
class Instagram(InstagramAPI):
USER_AGENT = 'Instagram 10.34.0 Android (18/4.3; 320dpi; 720x1280; Xiaomi; HM 1SW; armani; qcom; en_US)'
def __init__(self, user, passwd, message_queue=queue.Queue(), debug_flag=threading.Event(), *args):
super(Instagram, self).__init__(user, passwd, *args)
self.log = logging.getLogger("client")
self.login()
self.message_queue = message_queue
self.response_queue = queue.Queue()
self.debug_flag = debug_flag
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 get_pending_inbox(self):
pending_inbox = self.SendRequest("direct_v2/pending_inbox/")
return pending_inbox
def approve_pending_threads(self, threads):
self.uuid = self.generateUUID(True)
data = {
"_csrftoken": self.token,
"_uuid": self.uuid,
}
if not isinstance(threads, list) or not isinstance(threads, tuple):
threads = [str(threads)]
if len(threads) > 1:
data["thread_ids"] = threads
succ = self.SendRequest("direct_v2/threads/approve_multiple/", self.generateSignature(json.dumps(data)))
else:
succ = self.SendRequest("direct_v2/threads/{}/approve/".format(threads[0]), self.generateSignature(json.dumps(data)))
return succ
def mark_as_seen(self, thread, item):
self.uuid = self.generateUUID(True)
data = json.dumps({
'_uuid': self.uuid,
'_csrftoken': self.token,
'action': 'mark_seen',
'thread_id': thread,
'item_id': item,
'use_unified_inbox': 'true',
})
request = self.SendRequest("direct_v2/threads/{}/items/{}/seen/".format(thread, item),
self.generateSignature(data))
return request
def listen(self):
self.log.info("Instagram has started listening...")
while True:
self.get_new_inbox()
self.get_new_pending()
time.sleep(0.5)
def get_new_inbox(self):
if not self.getv2Inbox():
return
self.process_inbox()
def get_new_pending(self):
if not self.get_pending_inbox():
return
self.process_inbox()
def process_inbox(self):
threads = self.LastJson.get("inbox", {}).get("threads")
messages = self.get_new_messages(threads)
if not messages:
return
else:
self.log.info("New message(s) received:" + str(messages))
self.push_to_queue(messages)
time.sleep(0.5)
while not self.response_queue.empty():
response, author = self.response_queue.get()
self.log.info("Message: {}, Author: {}".format(response, author))
if response is not None and self.debug_flag.is_set():
self.uuid = self.generateUUID(True)
self.direct_message(response, author)
def get_new_messages(self, threads):
for thread in threads:
if not thread.get("read_state"):
continue
time.sleep(0.3)
thread_id = thread.get("thread_id")
if not self.getv2Threads(thread_id):
continue
thread_details = self.LastJson.get("thread")
time.sleep(0.3)
if thread_details.get("pending"):
self.approve_pending_threads(thread_id)
last_seen_id = thread_details \
.get("last_seen_at", {}) \
.get(str(self.username_id), {}) \
.get("item_id")
self.log.info(last_seen_id)
self.log.info(self.username_id)
new_messages = []
for item in thread_details.get("items"):
if item.get("item_id") == last_seen_id:
break
new_messages.append((item.get("text"), item.get("user_id"), "IG"))
last_item_id = thread.get("last_permanent_item", {}).get("item_id")
self.mark_as_seen(thread_id, last_item_id)
new_messages.reverse()
return new_messages
def push_to_queue(self, messages):
for msg in messages:
self.message_queue.put(msg)