Iterate Over More Than 10 Chats
eth opened this issue · 5 comments
Hey, I'm unable to iterate over my chats, when I run this code it'll print 10 chats, and then when I just call sk.chats.recent() normally I only get 10 as well. Is there a better way to do this or to iterate through all chats? Ideally I would like to pull every group chat I'm in.
Account type
Live
Conversation details
Group, desktop & mobile
Steps to reproduce
>>> while True: ... for id in sk.chats.recent(): ... print(id) ... else: # No more chats returned. ... break
Result or traceback
Just looping over it in a for-loop seems to do the trick!
You've already posted chat iteration code wrapped with a while
loop that achieves this.
The while
loop (also provided on https://skpy.t.allofti.me/guides/chats.html#iterating-chats) is actually equivalent to its nested for
:
while True:
for id in sk.chats.recent():
print(id)
else:
break # executes in any case
From Python docs (https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops):
a loop’s
else
clause runs when nobreak
occurs
Inside the body of the for
loop, no break
occurs.
To get all chats, the following code can be used:
def get_id2chat(sk):
id2chat = {}
while id2chat_recent := sk.chats.recent():
id2chat.update(id2chat_recent)
return id2chat
Ah, this is indeed a doc bug (fixed here).
To get all chats, the following code can be used
As noted in the updated example, you can also just populate the cache and use sk.chats
directly, which can be iterated over to work with each chat, or used like a dict
for key lookups, rather than building a second mapping.