diff --git a/examples/fetch.py b/examples/fetch.py index 5db97b8..cbcef40 100644 --- a/examples/fetch.py +++ b/examples/fetch.py @@ -1,5 +1,6 @@ # -*- coding: UTF-8 -*- +from itertools import islice from fbchat import Client from fbchat.models import * @@ -62,3 +63,9 @@ print("thread's type: {}".format(thread.type)) # Here should be an example of `getUnread` + + +# Print image url for 20 last images from thread. +images = client.fetchThreadImages("") +for image in islice(image, 20): + print(image.large_preview_url) diff --git a/fbchat/_client.py b/fbchat/_client.py index 63e6334..f19fe2e 100644 --- a/fbchat/_client.py +++ b/fbchat/_client.py @@ -981,6 +981,42 @@ class Client(object): """ return self._buddylist.get(str(user_id)) + def fetchThreadImages(self, thread_id=None): + """ + Creates generator object for fetching images posted in thread. + :param thread_id: ID of the thread + :return: :class:`ImageAttachment` or :class:`VideoAttachment`. + :rtype: iterable + """ + thread_id, thread_type = self._getThread(thread_id, None) + data = {"id": thread_id, "first": 48} + thread_id = str(thread_id) + j = self.graphql_request(_graphql.from_query_id("515216185516880", data)) + while True: + try: + i = j[thread_id]["message_shared_media"]["edges"][0] + except IndexError: + if j[thread_id]["message_shared_media"]["page_info"].get( + "has_next_page" + ): + data["after"] = j[thread_id]["message_shared_media"][ + "page_info" + ].get("end_cursor") + j = self.graphql_request( + _graphql.from_query_id("515216185516880", data) + ) + continue + else: + break + + if i["node"].get("__typename") == "MessageImage": + yield ImageAttachment._from_list(i) + elif i["node"].get("__typename") == "MessageVideo": + yield VideoAttachment._from_list(i) + else: + yield Attachment(uid=i["node"].get("legacy_attachment_id")) + del j[thread_id]["message_shared_media"]["edges"][0] + """ END FETCH METHODS """ diff --git a/fbchat/_file.py b/fbchat/_file.py index 45cd282..13bd9db 100644 --- a/fbchat/_file.py +++ b/fbchat/_file.py @@ -155,6 +155,18 @@ class ImageAttachment(Attachment): uid=data.get("legacy_attachment_id"), ) + @classmethod + def _from_list(cls, data): + data = data["node"] + return cls( + width=data["original_dimensions"].get("x"), + height=data["original_dimensions"].get("y"), + thumbnail_url=data["image"].get("uri"), + large_preview=data["image2"], + preview=data["image1"], + uid=data["legacy_attachment_id"], + ) + @attr.s(cmp=False, init=False) class VideoAttachment(Attachment): @@ -252,6 +264,18 @@ class VideoAttachment(Attachment): uid=data["target"].get("video_id"), ) + @classmethod + def _from_list(cls, data): + data = data["node"] + return cls( + width=data["original_dimensions"].get("x"), + height=data["original_dimensions"].get("y"), + small_image=data["image"], + medium_image=data["image1"], + large_image=data["image2"], + uid=data["legacy_attachment_id"], + ) + def graphql_to_attachment(data): _type = data["__typename"]