-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmessyger.py
executable file
·224 lines (185 loc) · 7.17 KB
/
messyger.py
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import argparse
import collections
import datetime
import json
import random
import re
import esprima
import requests
## Get the email and password
parser = argparse.ArgumentParser("messyger")
parser.add_argument("-u", "--email", required=True)
parser.add_argument("-p", "--password", required=True)
parser.add_argument("-m", "--message")
parser.add_argument("-r", "--recipient", type=int)
args = parser.parse_args()
## Parse the HTML response
html_resp = requests.get("https://www.messenger.com")
html_resp.raise_for_status()
html_page = html_resp.text
initial_request_id = re.search(
r'name="initial_request_id" value="([^"]+)"', html_page
).group(1)
lsd = re.search(r'name="lsd" value="([^"]+)"', html_page).group(1)
datr = re.search(r'"_js_datr","([^"]+)"', html_page).group(1)
## Make the login request
login = requests.post(
"https://www.messenger.com/login/password/",
cookies={"datr": datr},
data={
"lsd": lsd,
"initial_request_id": initial_request_id,
"email": args.email,
"pass": args.password,
},
allow_redirects=False,
)
assert login.status_code == 302
## Extract the inbox query parameters
inbox_html_resp = requests.get("https://www.messenger.com", cookies=login.cookies)
inbox_html_resp.raise_for_status()
inbox_html_page = inbox_html_resp.text
dtsg = re.search(r'"DTSGInitialData",\[\],\{"token":"([^"]+)"', inbox_html_page).group(
1
)
device_id = re.search(r'"deviceId":"([^"]+)"', inbox_html_page).group(1)
schema_version = re.search(r'"schemaVersion":"([0-9]+)"', inbox_html_page).group(1)
script_urls = re.findall(r'"([^"]+rsrc\.php/[^"]+\.js[^"]+)"', inbox_html_page)
scripts = []
for url in script_urls:
resp = requests.get(url)
resp.raise_for_status()
scripts.append(resp.text)
for script in scripts:
if "LSPlatformGraphQLLightspeedRequestQuery" not in script:
continue
doc_id = re.search(
r'id:"([0-9]+)",metadata:\{\},name:"LSPlatformGraphQLLightspeedRequestQuery"',
script,
).group(1)
break
if not args.message:
inbox_resp = requests.post(
"https://www.messenger.com/api/graphql/",
cookies=login.cookies,
data={
"fb_dtsg": dtsg,
"doc_id": doc_id,
"variables": json.dumps(
{
"deviceId": device_id,
"requestId": 0,
"requestPayload": json.dumps(
{
"database": 1,
"version": schema_version,
"sync_params": json.dumps({}),
}
),
"requestType": 1,
}
),
},
)
inbox_resp.raise_for_status()
## Parse the inbox data response
inbox_json = inbox_resp.json()
inbox_js = inbox_json["data"]["viewer"]["lightspeed_web_request"]["payload"]
ast = esprima.parseScript(inbox_js)
def is_lightspeed_call(node):
return (
node.type == "CallExpression"
and node.callee.type == "MemberExpression"
and node.callee.object.type == "Identifier"
and node.callee.object.name == "LS"
and node.callee.property.type == "Identifier"
and node.callee.property.name == "sp"
)
def parse_argument(node):
if node.type == "Literal":
return node.value
if node.type == "ArrayExpression":
assert len(node.elements) == 2
high_bits, low_bits = map(parse_argument, node.elements)
return (high_bits << 32) + low_bits
if node.type == "UnaryExpression" and node.prefix and node.operator == "-":
return -parse_argument(node.argument)
fn_calls = collections.defaultdict(list)
def handle_node(node, meta):
if not is_lightspeed_call(node):
return
args = [parse_argument(arg) for arg in node.arguments]
(fn_name, *fn_args) = args
fn_calls[fn_name].append(fn_args)
esprima.parseScript(inbox_js, delegate=handle_node)
conversations = collections.defaultdict(dict)
for args in fn_calls["deleteThenInsertThread"]:
last_sent_ts, last_read_ts, last_msg, *rest = args
user_id, last_msg_author = [
arg for arg in rest if isinstance(arg, int) and arg > 1e14
]
conversations[user_id]["unread"] = last_sent_ts != last_read_ts
conversations[user_id]["last_message"] = last_msg
conversations[user_id]["last_message_author"] = last_msg_author
for args in fn_calls["verifyContactRowExists"]:
user_id, _, _, name, *rest = args
conversations[user_id]["name"] = name
print(json.dumps(conversations, indent=2))
else:
## Replicate the send-message request
timestamp = int(datetime.datetime.now().timestamp() * 1000)
epoch = timestamp << 22
otid = epoch + random.randrange(2 ** 22)
send_message_resp = requests.post(
"https://www.messenger.com/api/graphql/",
cookies=login.cookies,
data={
"fb_dtsg": dtsg,
"doc_id": doc_id,
"variables": json.dumps(
{
"deviceId": device_id,
"requestId": 0,
"requestPayload": json.dumps(
{
"version_id": str(schema_version),
"tasks": [
{
"label": "46",
"payload": json.dumps(
{
"thread_id": args.recipient,
"otid": "6870463702739115830",
"source": 0,
"send_type": 1,
"text": args.message,
"initiating_source": 1,
}
),
"queue_name": str(args.recipient),
"task_id": 0,
"failure_count": None,
},
{
"label": "21",
"payload": json.dumps(
{
"thread_id": args.recipient,
"last_read_watermark_ts": timestamp,
"sync_group": 1,
}
),
"queue_name": str(args.recipient),
"task_id": 1,
"failure_count": None,
},
],
"epoch_id": 6870463702858032000,
}
),
"requestType": 3,
}
),
},
)
print(send_message_resp.text)