From 5fa1d8619176af0931b89f0d34536e528ee38ff8 Mon Sep 17 00:00:00 2001 From: 2FWAH <36737818+2FWAH@users.noreply.github.com> Date: Fri, 21 Sep 2018 19:12:46 +0200 Subject: [PATCH] Add before, after and limit parameters to fetchThreads --- fbchat/client.py | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/fbchat/client.py b/fbchat/client.py index 66f02a4..95bd4e6 100644 --- a/fbchat/client.py +++ b/fbchat/client.py @@ -487,11 +487,15 @@ class Client(object): })) return j - def fetchThreads(self, thread_location, after=None, limit=None): + def fetchThreads(self, thread_location, before=None, after=None, limit=None): """ Get all threads in thread_location. + Threads will be sorted from newest to oldest. :param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER + :param before: Fetch only thread before this epoch (in ms) (default all threads) + :param after: Fetch only thread after this epoch (in ms) (default all threads) + :param limit: The max. amount of threads to fetch (default all threads) :return: :class:`models.Thread` objects :rtype: list :raises: FBchatException if request failed @@ -500,15 +504,40 @@ class Client(object): threads += self.fetchThreadList(thread_location=thread_location) if not threads: return [] + while True: - lastThreadTimestamp = threads[-1].last_message_timestamp - candidates = self.fetchThreadList(before=lastThreadTimestamp, thread_location=thread_location) # return at max 20 threads before lastThreadTimestamp (included) + # break if limit is exceeded + if limit and len(threads) >= limit: + break + + last_thread_timestamp = threads[-1].last_message_timestamp + # 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: + else: # End of threads break - return threads # from newest to oldest - + + # 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 list(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): """ Get all users involved in threads.