-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_client.py
3875 lines (3283 loc) · 130 KB
/
_client.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
import requests
import urllib
from uuid import uuid1
from random import choice
from bs4 import BeautifulSoup as bs
from mimetypes import guess_type
from collections import OrderedDict
from ._util import *
from .models import *
from . import _graphql
from ._state import State
from ._mqtt import Mqtt
import time
import json
try:
from urllib.parse import urlparse, parse_qs
except ImportError:
from urlparse import urlparse, parse_qs
ACONTEXT = {
"action_history": [
{"surface": "messenger_chat_tab", "mechanism": "messenger_composer"}
]
}
class Client(object):
"""A client for the Facebook Chat (Messenger).
This is the main class of ``fbchat``, which contains all the methods you use to
interact with Facebook. You can extend this class, and overwrite the ``on`` methods,
to provide custom event handling (mainly useful while listening).
"""
listening = False
"""Whether the client is listening.
Used when creating an external event loop to determine when to stop listening.
"""
@property
def ssl_verify(self):
"""Verify SSL certificate.
Set to False to allow debugging with a proxy.
"""
# TODO: Deprecate this
return self._state._session.verify
@ssl_verify.setter
def ssl_verify(self, value):
self._state._session.verify = value
@property
def uid(self):
"""The ID of the client.
Can be used as ``thread_id``. See :ref:`intro_threads` for more info.
"""
return self._uid
def __init__(
self,
email,
password,
user_agent=None,
max_tries=5,
session_cookies=None,
logging_level=logging.INFO,
):
"""Initialize and log in the client.
Args:
email: Facebook ``email``, ``id`` or ``phone number``
password: Facebook account password
user_agent: Custom user agent to use when sending requests. If `None`, user agent will be chosen from a premade list
max_tries (int): Maximum number of times to try logging in
session_cookies (dict): Cookies from a previous session (Will default to login if these are invalid)
logging_level (int): Configures the `logging level <https://docs.python.org/3/library/logging.html#logging-levels>`_. Defaults to ``logging.INFO``
Raises:
FBchatException: On failed login
"""
self._default_thread_id = None
self._default_thread_type = None
self._markAlive = True
self._buddylist = dict()
self._mqtt = None
handler.setLevel(logging_level)
# If session cookies aren't set, not properly loaded or gives us an invalid session, then do the login
if (
not session_cookies
or not self.setSession(session_cookies, user_agent=user_agent)
or not self.isLoggedIn()
):
self.login(email, password, max_tries, user_agent=user_agent)
"""
INTERNAL REQUEST METHODS
"""
def _get(self, url, params):
return self._state._get(url, params)
def _post(self, url, params, files=None):
return self._state._post(url, params, files=files)
def _payload_post(self, url, data, files=None):
return self._state._payload_post(url, data, files=files)
def graphql_requests(self, *queries):
"""Execute GraphQL queries.
Args:
queries (dict): Zero or more dictionaries
Returns:
tuple: A tuple containing JSON GraphQL queries
Raises:
FBchatException: If request failed
"""
return tuple(self._state._graphql_requests(*queries))
def graphql_request(self, query):
"""Shorthand for ``graphql_requests(query)[0]``.
Raises:
FBchatException: If request failed
"""
return self.graphql_requests(query)[0]
"""
END INTERNAL REQUEST METHODS
"""
"""
LOGIN METHODS
"""
def isLoggedIn(self):
"""Send a request to Facebook to check the login status.
Returns:
bool: True if the client is still logged in
"""
return self._state.is_logged_in()
def getSession(self):
"""Retrieve session cookies.
Returns:
dict: A dictionary containing session cookies
"""
return self._state.get_cookies()
def setSession(self, session_cookies, user_agent=None):
"""Load session cookies.
Args:
session_cookies (dict): A dictionary containing session cookies
Returns:
bool: False if ``session_cookies`` does not contain proper cookies
"""
try:
# Load cookies into current session
self._state = State.from_cookies(session_cookies, user_agent=user_agent)
self._uid = self._state.user_id
except Exception as e:
log.exception("Failed loading session")
return False
return True
def login(self, email, password, max_tries=5, user_agent=None):
"""Login the user, using ``email`` and ``password``.
If the user is already logged in, this will do a re-login.
Args:
email: Facebook ``email`` or ``id`` or ``phone number``
password: Facebook account password
max_tries (int): Maximum number of times to try logging in
Raises:
FBchatException: On failed login
"""
self.onLoggingIn(email=email)
if max_tries < 1:
raise FBchatUserError("Cannot login: max_tries should be at least one")
if not (email and password):
raise FBchatUserError("Email and password not set")
for i in range(1, max_tries + 1):
try:
self._state = State.login(
email,
password,
on_2fa_callback=self.on2FACode,
user_agent=user_agent,
)
self._uid = self._state.user_id
except Exception:
if i >= max_tries:
raise
log.exception("Attempt #{} failed, retrying".format(i))
time.sleep(1)
else:
self.onLoggedIn(email=email)
break
def logout(self):
"""Safely log out the client.
Returns:
bool: True if the action was successful
"""
if self._state.logout():
self._state = None
self._uid = None
return True
return False
"""
END LOGIN METHODS
"""
"""
DEFAULT THREAD METHODS
"""
def _getThread(self, given_thread_id=None, given_thread_type=None):
"""Check if thread ID is given and if default is set, and return correct values.
Returns:
tuple: Thread ID and thread type
Raises:
ValueError: If thread ID is not given and there is no default
"""
if given_thread_id is None:
if self._default_thread_id is not None:
return self._default_thread_id, self._default_thread_type
else:
raise ValueError("Thread ID is not set")
else:
return given_thread_id, given_thread_type
def setDefaultThread(self, thread_id, thread_type):
"""Set default thread to send messages to.
Args:
thread_id: User/Group ID to default to. See :ref:`intro_threads`
thread_type (ThreadType): See :ref:`intro_threads`
"""
self._default_thread_id = thread_id
self._default_thread_type = thread_type
def resetDefaultThread(self):
"""Reset default thread."""
self.setDefaultThread(None, None)
"""
END DEFAULT THREAD METHODS
"""
"""
FETCH METHODS
"""
def _forcedFetch(self, thread_id, mid):
params = {"thread_and_message_id": {"thread_id": thread_id, "message_id": mid}}
(j,) = self.graphql_requests(_graphql.from_doc_id("1768656253222505", params))
return j
def fetchThreads(self, thread_location, before=None, after=None, limit=None):
"""Fetch all threads in ``thread_location``.
Threads will be sorted from newest to oldest.
Args:
thread_location (ThreadLocation): INBOX, PENDING, ARCHIVED or OTHER
before: Fetch only thread before this epoch (in ms) (default all threads)
after: Fetch only thread after this epoch (in ms) (default all threads)
limit: The max. amount of threads to fetch (default all threads)
Returns:
list: :class:`Thread` objects
Raises:
FBchatException: If request failed
"""
threads = []
last_thread_timestamp = None
while True:
# break if limit is exceeded
if limit and len(threads) >= limit:
break
# fetchThreadList returns at max 20 threads before last_thread_timestamp (included)
candidates = self.fetchThreadList(
before=last_thread_timestamp, thread_location=thread_location
)
if len(candidates) > 1:
threads += candidates[1:]
else: # End of threads
break
last_thread_timestamp = threads[-1].last_message_timestamp
# FB returns a sorted list of threads
if (before is not None and int(last_thread_timestamp) > before) or (
after is not None and int(last_thread_timestamp) < after
):
break
# Return only threads between before and after (if set)
if before is not None or after is not None:
for t in threads:
last_message_timestamp = int(t.last_message_timestamp)
if (before is not None and last_message_timestamp > before) or (
after is not None and last_message_timestamp < after
):
threads.remove(t)
if limit and len(threads) > limit:
return threads[:limit]
return threads
def fetchAllUsersFromThreads(self, threads):
"""Fetch all users involved in given threads.
Args:
threads: Thread: List of threads to check for users
Returns:
list: :class:`User` objects
Raises:
FBchatException: If request failed
"""
users = []
users_to_fetch = [] # It's more efficient to fetch all users in one request
for thread in threads:
if thread.type == ThreadType.USER:
if thread.uid not in [user.uid for user in users]:
users.append(thread)
elif thread.type == ThreadType.GROUP:
for user_id in thread.participants:
if (
user_id not in [user.uid for user in users]
and user_id not in users_to_fetch
):
users_to_fetch.append(user_id)
for user_id, user in self.fetchUserInfo(*users_to_fetch).items():
users.append(user)
return users
def fetchAllUsers(self):
"""Fetch all users the client is currently chatting with.
Returns:
list: :class:`User` objects
Raises:
FBchatException: If request failed
"""
data = {"viewer": self._uid}
j = self._payload_post("/chat/user_info_all", data)
users = []
for data in j.values():
if data["type"] in ["user", "friend"]:
if data["id"] in ["0", 0]:
# Skip invalid users
continue
users.append(User._from_all_fetch(data))
return users
def searchForUsers(self, name, limit=10):
"""Find and get users by their name.
Args:
name: Name of the user
limit: The max. amount of users to fetch
Returns:
list: :class:`User` objects, ordered by relevance
Raises:
FBchatException: If request failed
"""
params = {"search": name, "limit": limit}
(j,) = self.graphql_requests(_graphql.from_query(_graphql.SEARCH_USER, params))
return [User._from_graphql(node) for node in j[name]["users"]["nodes"]]
def searchForPages(self, name, limit=10):
"""Find and get pages by their name.
Args:
name: Name of the page
Returns:
list: :class:`Page` objects, ordered by relevance
Raises:
FBchatException: If request failed
"""
params = {"search": name, "limit": limit}
(j,) = self.graphql_requests(_graphql.from_query(_graphql.SEARCH_PAGE, params))
return [Page._from_graphql(node) for node in j[name]["pages"]["nodes"]]
def searchForGroups(self, name, limit=10):
"""Find and get group threads by their name.
Args:
name: Name of the group thread
limit: The max. amount of groups to fetch
Returns:
list: :class:`Group` objects, ordered by relevance
Raises:
FBchatException: If request failed
"""
params = {"search": name, "limit": limit}
(j,) = self.graphql_requests(_graphql.from_query(_graphql.SEARCH_GROUP, params))
return [Group._from_graphql(node) for node in j["viewer"]["groups"]["nodes"]]
def searchForThreads(self, name, limit=10):
"""Find and get threads by their name.
Args:
name: Name of the thread
limit: The max. amount of groups to fetch
Returns:
list: :class:`User`, :class:`Group` and :class:`Page` objects, ordered by relevance
Raises:
FBchatException: If request failed
"""
params = {"search": name, "limit": limit}
(j,) = self.graphql_requests(
_graphql.from_query(_graphql.SEARCH_THREAD, params)
)
rtn = []
for node in j[name]["threads"]["nodes"]:
if node["__typename"] == "User":
rtn.append(User._from_graphql(node))
elif node["__typename"] == "MessageThread":
# MessageThread => Group thread
rtn.append(Group._from_graphql(node))
elif node["__typename"] == "Page":
rtn.append(Page._from_graphql(node))
elif node["__typename"] == "Group":
# We don't handle Facebook "Groups"
pass
else:
log.warning(
"Unknown type {} in {}".format(repr(node["__typename"]), node)
)
return rtn
def searchForMessageIDs(self, query, offset=0, limit=5, thread_id=None):
"""Find and get message IDs by query.
Args:
query: Text to search for
offset (int): Number of messages to skip
limit (int): Max. number of messages to retrieve
thread_id: User/Group ID to search in. See :ref:`intro_threads`
Returns:
typing.Iterable: Found Message IDs
Raises:
FBchatException: If request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {
"query": query,
"snippetOffset": offset,
"snippetLimit": limit,
"identifier": "thread_fbid",
"thread_fbid": thread_id,
}
j = self._payload_post("/ajax/mercury/search_snippets.php?dpr=1", data)
result = j["search_snippets"][query]
snippets = result[thread_id]["snippets"] if result.get(thread_id) else []
for snippet in snippets:
yield snippet["message_id"]
def searchForMessages(self, query, offset=0, limit=5, thread_id=None):
"""Find and get `Message` objects by query.
Warning:
This method sends request for every found message ID.
Args:
query: Text to search for
offset (int): Number of messages to skip
limit (int): Max. number of messages to retrieve
thread_id: User/Group ID to search in. See :ref:`intro_threads`
Returns:
typing.Iterable: Found :class:`Message` objects
Raises:
FBchatException: If request failed
"""
message_ids = self.searchForMessageIDs(
query, offset=offset, limit=limit, thread_id=thread_id
)
for mid in message_ids:
yield self.fetchMessageInfo(mid, thread_id)
def search(self, query, fetch_messages=False, thread_limit=5, message_limit=5):
"""Search for messages in all threads.
Args:
query: Text to search for
fetch_messages: Whether to fetch :class:`Message` objects or IDs only
thread_limit (int): Max. number of threads to retrieve
message_limit (int): Max. number of messages to retrieve
Returns:
typing.Dict[str, typing.Iterable]: Dictionary with thread IDs as keys and iterables to get messages as values
Raises:
FBchatException: If request failed
"""
data = {"query": query, "snippetLimit": thread_limit}
j = self._payload_post("/ajax/mercury/search_snippets.php?dpr=1", data)
result = j["search_snippets"][query]
if not result:
return {}
if fetch_messages:
search_method = self.searchForMessages
else:
search_method = self.searchForMessageIDs
return {
thread_id: search_method(query, limit=message_limit, thread_id=thread_id)
for thread_id in result
}
def _fetchInfo(self, *ids):
data = {"ids[{}]".format(i): _id for i, _id in enumerate(ids)}
j = self._payload_post("/chat/user_info/", data)
if j.get("profiles") is None:
raise FBchatException("No users/pages returned: {}".format(j))
entries = {}
for _id in j["profiles"]:
k = j["profiles"][_id]
if k["type"] in ["user", "friend"]:
entries[_id] = {
"id": _id,
"type": ThreadType.USER,
"url": k.get("uri"),
"first_name": k.get("firstName"),
"is_viewer_friend": k.get("is_friend"),
"gender": k.get("gender"),
"profile_picture": {"uri": k.get("thumbSrc")},
"name": k.get("name"),
}
elif k["type"] == "page":
entries[_id] = {
"id": _id,
"type": ThreadType.PAGE,
"url": k.get("uri"),
"profile_picture": {"uri": k.get("thumbSrc")},
"name": k.get("name"),
}
else:
raise FBchatException(
"{} had an unknown thread type: {}".format(_id, k)
)
log.debug(entries)
return entries
def fetchUserInfo(self, *user_ids):
"""Fetch users' info from IDs, unordered.
Warning:
Sends two requests, to fetch all available info!
Args:
user_ids: One or more user ID(s) to query
Returns:
dict: :class:`User` objects, labeled by their ID
Raises:
FBchatException: If request failed
"""
threads = self.fetchThreadInfo(*user_ids)
users = {}
for id_, thread in threads.items():
if thread.type == ThreadType.USER:
users[id_] = thread
else:
raise FBchatUserError("Thread {} was not a user".format(thread))
return users
def fetchPageInfo(self, *page_ids):
"""Fetch pages' info from IDs, unordered.
Warning:
Sends two requests, to fetch all available info!
Args:
page_ids: One or more page ID(s) to query
Returns:
dict: :class:`Page` objects, labeled by their ID
Raises:
FBchatException: If request failed
"""
threads = self.fetchThreadInfo(*page_ids)
pages = {}
for id_, thread in threads.items():
if thread.type == ThreadType.PAGE:
pages[id_] = thread
else:
raise FBchatUserError("Thread {} was not a page".format(thread))
return pages
def fetchGroupInfo(self, *group_ids):
"""Fetch groups' info from IDs, unordered.
Args:
group_ids: One or more group ID(s) to query
Returns:
dict: :class:`Group` objects, labeled by their ID
Raises:
FBchatException: If request failed
"""
threads = self.fetchThreadInfo(*group_ids)
groups = {}
for id_, thread in threads.items():
if thread.type == ThreadType.GROUP:
groups[id_] = thread
else:
raise FBchatUserError("Thread {} was not a group".format(thread))
return groups
def fetchThreadInfo(self, *thread_ids):
"""Fetch threads' info from IDs, unordered.
Warning:
Sends two requests if users or pages are present, to fetch all available info!
Args:
thread_ids: One or more thread ID(s) to query
Returns:
dict: :class:`Thread` objects, labeled by their ID
Raises:
FBchatException: If request failed
"""
queries = []
for thread_id in thread_ids:
params = {
"id": thread_id,
"message_limit": 0,
"load_messages": False,
"load_read_receipts": False,
"before": None,
}
queries.append(_graphql.from_doc_id("2147762685294928", params))
j = self.graphql_requests(*queries)
for i, entry in enumerate(j):
if entry.get("message_thread") is None:
# If you don't have an existing thread with this person, attempt to retrieve user data anyways
j[i]["message_thread"] = {
"thread_key": {"other_user_id": thread_ids[i]},
"thread_type": "ONE_TO_ONE",
}
pages_and_user_ids = [
k["message_thread"]["thread_key"]["other_user_id"]
for k in j
if k["message_thread"].get("thread_type") == "ONE_TO_ONE"
]
pages_and_users = {}
if len(pages_and_user_ids) != 0:
pages_and_users = self._fetchInfo(*pages_and_user_ids)
rtn = {}
for i, entry in enumerate(j):
entry = entry["message_thread"]
if entry.get("thread_type") == "GROUP":
_id = entry["thread_key"]["thread_fbid"]
rtn[_id] = Group._from_graphql(entry)
elif entry.get("thread_type") == "ONE_TO_ONE":
_id = entry["thread_key"]["other_user_id"]
if pages_and_users.get(_id) is None:
raise FBchatException("Could not fetch thread {}".format(_id))
entry.update(pages_and_users[_id])
if entry["type"] == ThreadType.USER:
rtn[_id] = User._from_graphql(entry)
else:
rtn[_id] = Page._from_graphql(entry)
else:
raise FBchatException(
"{} had an unknown thread type: {}".format(thread_ids[i], entry)
)
return rtn
def fetchThreadMessages(self, thread_id=None, limit=20, before=None):
"""Fetch messages in a thread, ordered by most recent.
Args:
thread_id: User/Group ID to get messages from. See :ref:`intro_threads`
limit (int): Max. number of messages to retrieve
before (int): A timestamp, indicating from which point to retrieve messages
Returns:
list: :class:`Message` objects
Raises:
FBchatException: If request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
params = {
"id": thread_id,
"message_limit": limit,
"load_messages": True,
"load_read_receipts": True,
"before": before,
}
(j,) = self.graphql_requests(_graphql.from_doc_id("1860982147341344", params))
if j.get("message_thread") is None:
raise FBchatException("Could not fetch thread {}: {}".format(thread_id, j))
messages = [
Message._from_graphql(message)
for message in j["message_thread"]["messages"]["nodes"]
]
messages.reverse()
read_receipts = j["message_thread"]["read_receipts"]["nodes"]
for message in messages:
for receipt in read_receipts:
if int(receipt["watermark"]) >= int(message.timestamp):
message.read_by.append(receipt["actor"]["id"])
return messages
def fetchThreadList(
self, offset=None, limit=20, thread_location=ThreadLocation.INBOX, before=None
):
"""Fetch the client's thread list.
Args:
offset: Deprecated. Do not use!
limit (int): Max. number of threads to retrieve. Capped at 20
thread_location (ThreadLocation): INBOX, PENDING, ARCHIVED or OTHER
before (int): A timestamp (in milliseconds), indicating from which point to retrieve threads
Returns:
list: :class:`Thread` objects
Raises:
FBchatException: If request failed
"""
if offset is not None:
log.warning(
"Using `offset` in `fetchThreadList` is no longer supported, "
"since Facebook migrated to the use of GraphQL in this request. "
"Use `before` instead."
)
if limit > 20 or limit < 1:
raise FBchatUserError("`limit` should be between 1 and 20")
if thread_location in ThreadLocation:
loc_str = thread_location.value
else:
raise FBchatUserError('"thread_location" must be a value of ThreadLocation')
params = {
"limit": limit,
"tags": [loc_str],
"before": before,
"includeDeliveryReceipts": True,
"includeSeqID": False,
}
(j,) = self.graphql_requests(_graphql.from_doc_id("1349387578499440", params))
rtn = []
for node in j["viewer"]["message_threads"]["nodes"]:
_type = node.get("thread_type")
if _type == "GROUP":
rtn.append(Group._from_graphql(node))
elif _type == "ONE_TO_ONE":
rtn.append(User._from_thread_fetch(node))
else:
raise FBchatException(
"Unknown thread type: {}, with data: {}".format(_type, node)
)
return rtn
def fetchUnread(self):
"""Fetch unread threads.
Returns:
list: List of unread thread ids
Raises:
FBchatException: If request failed
"""
form = {
"folders[0]": "inbox",
"client": "mercury",
"last_action_timestamp": now() - 60 * 1000
# 'last_action_timestamp': 0
}
j = self._payload_post("/ajax/mercury/unread_threads.php", form)
result = j["unread_thread_fbids"][0]
return result["thread_fbids"] + result["other_user_fbids"]
def fetchUnseen(self):
"""Fetch unseen / new threads.
Returns:
list: List of unseen thread ids
Raises:
FBchatException: If request failed
"""
j = self._payload_post("/mercury/unseen_thread_ids/", {})
result = j["unseen_thread_fbids"][0]
return result["thread_fbids"] + result["other_user_fbids"]
def fetchImageUrl(self, image_id):
"""Fetch URL to download the original image from an image attachment ID.
Args:
image_id (str): The image you want to fetch
Returns:
str: An URL where you can download the original image
Raises:
FBchatException: If request failed
"""
image_id = str(image_id)
data = {"photo_id": str(image_id)}
j = self._post("/mercury/attachments/photo/", data)
url = get_jsmods_require(j, 3)
if url is None:
raise FBchatException("Could not fetch image URL from: {}".format(j))
return url
def fetchMessageInfo(self, mid, thread_id=None):
"""Fetch `Message` object from the given message id.
Args:
mid: Message ID to fetch from
thread_id: User/Group ID to get message info from. See :ref:`intro_threads`
Returns:
Message: :class:`Message` object
Raises:
FBchatException: If request failed
"""
thread_id, thread_type = self._getThread(thread_id, None)
message_info = self._forcedFetch(thread_id, mid).get("message")
return Message._from_graphql(message_info)
def fetchPollOptions(self, poll_id):
"""Fetch list of `PollOption` objects from the poll id.
Args:
poll_id: Poll ID to fetch from
Returns:
list
Raises:
FBchatException: If request failed
"""
data = {"question_id": poll_id}
j = self._payload_post("/ajax/mercury/get_poll_options", data)
return [PollOption._from_graphql(m) for m in j]
def fetchPlanInfo(self, plan_id):
"""Fetch `Plan` object from the plan id.
Args:
plan_id: Plan ID to fetch from
Returns:
Plan: :class:`Plan` object
Raises:
FBchatException: If request failed
"""
data = {"event_reminder_id": plan_id}
j = self._payload_post("/ajax/eventreminder", data)
return Plan._from_fetch(j)
def _getPrivateData(self):
(j,) = self.graphql_requests(_graphql.from_doc_id("1868889766468115", {}))
return j["viewer"]
def getPhoneNumbers(self):
"""Fetch list of user's phone numbers.
Returns:
list: List of phone numbers
"""
data = self._getPrivateData()
return [
j["phone_number"]["universal_number"] for j in data["user"]["all_phones"]
]
def getEmails(self):
"""Fetch list of user's emails.
Returns:
list: List of emails
"""
data = self._getPrivateData()
return [j["display_email"] for j in data["all_emails"]]
def getUserActiveStatus(self, user_id):
"""Fetch friend active status as an `ActiveStatus` object.
Return ``None`` if status isn't known.
Warning:
Only works when listening.
Args:
user_id: ID of the user
Returns:
ActiveStatus: Given user active status
"""
return self._buddylist.get(str(user_id))
def fetchThreadImages(self, thread_id=None):
"""Fetch images posted in thread.
Args:
thread_id: ID of the thread
Returns:
typing.Iterable: :class:`ImageAttachment` or :class:`VideoAttachment`
"""
thread_id, thread_type = self._getThread(thread_id, None)
data = {"id": thread_id, "first": 48}
thread_id = str(thread_id)
(j,) = self.graphql_requests(_graphql.from_query_id("515216185516880", data))
while True:
try: