From 5e8be0e6efe94c7faae01e08b821f875d6394fae Mon Sep 17 00:00:00 2001 From: Dan <14043624+delivrance@users.noreply.github.com> Date: Tue, 9 Oct 2018 14:48:43 +0200 Subject: [PATCH] Make use of the "with" context manager --- examples/get_history.py | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/examples/get_history.py b/examples/get_history.py index 0466fc96..7289e0f2 100644 --- a/examples/get_history.py +++ b/examples/get_history.py @@ -28,25 +28,22 @@ target = "me" # "me" refers to your own chat (Saved Messages) messages = [] # List that will contain all the messages of the target chat offset_id = 0 # ID of the last message of the chunk -app.start() +with app: + while True: + try: + m = app.get_history(target, offset_id=offset_id) + except FloodWait as e: # For very large chats the method call can raise a FloodWait + print("waiting {}".format(e.x)) + time.sleep(e.x) # Sleep X seconds before continuing + continue -while True: - try: - m = app.get_history(target, offset_id=offset_id) - except FloodWait as e: # For very large chats the method call can raise a FloodWait - print("waiting {}".format(e.x)) - time.sleep(e.x) # Sleep X seconds before continuing - continue + if not m.messages: + break - if not m.messages: - break + messages += m.messages + offset_id = m.messages[-1].message_id - messages += m.messages - offset_id = m.messages[-1].message_id - - print("Messages: {}".format(len(messages))) - -app.stop() + print("Messages: {}".format(len(messages))) # Now the "messages" list contains all the messages sorted by date in # descending order (from the most recent to the oldest one)