1616# You should have received a copy of the GNU Lesser General Public License
1717# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
1818
19- import logging
20- from typing import Union , Optional , AsyncGenerator
19+ from typing import Union , AsyncGenerator , Optional
2120
2221import pyrogram
23- from pyrogram import raw
24- from pyrogram import types
25- from pyrogram import utils
26-
27- log = logging .getLogger (__name__ )
22+ from pyrogram import types , raw , utils
2823
2924
3025class GetForumTopics :
@@ -43,26 +38,66 @@ async def get_forum_topics(
4338
4439 limit (``int``, *optional*):
4540 Limits the number of topics to be retrieved.
41+ By default, no limit is applied and all topics are returned.
4642
4743 Returns:
48- ``Generator``: On success, a generator yielding :obj:`~pyrogram.types.ForumTopic` objects is returned .
44+ ``Generator``: A generator yielding :obj:`~pyrogram.types.ForumTopic` objects.
4945
5046 Example:
5147 .. code-block:: python
5248
53- # get all forum topics
49+ # Iterate through all topics
5450 async for topic in app.get_forum_topics(chat_id):
5551 print(topic)
56-
57- Raises:
58- ValueError: In case of invalid arguments.
5952 """
53+ current = 0
54+ total = limit or (1 << 31 ) - 1
55+ limit = min (100 , total )
56+
57+ offset_date = 0
58+ offset_id = 0
59+ offset_topic = 0
60+
61+ while True :
62+ r = await self .invoke (
63+ raw .functions .channels .GetForumTopics (
64+ channel = await self .resolve_peer (chat_id ),
65+ offset_date = offset_date ,
66+ offset_id = offset_id ,
67+ offset_topic = offset_topic ,
68+ limit = limit
69+ )
70+ )
71+
72+ users = {i .id : i for i in r .users }
73+ chats = {i .id : i for i in r .chats }
74+
75+ messages = {}
76+
77+ for message in r .messages :
78+ if isinstance (message , raw .types .MessageEmpty ):
79+ continue
80+
81+ messages [message .id ] = await types .Message ._parse (self , message , users , chats )
82+
83+ topics = []
84+
85+ for topic in r .topics :
86+ topics .append (types .ForumTopic ._parse (self , topic , messages , users , chats ))
87+
88+ if not topics :
89+ return
90+
91+ last = topics [- 1 ]
6092
61- peer = await self .resolve_peer (chat_id )
93+ offset_id = last .top_message .id
94+ offset_date = utils .datetime_to_timestamp (last .top_message .date )
95+ offset_topic = last .id
6296
63- rpc = raw .functions .channels .GetForumTopics (channel = peer , offset_date = 0 , offset_id = 0 , offset_topic = 0 , limit = limit )
97+ for topic in topics :
98+ yield topic
6499
65- r = await self . invoke ( rpc , sleep_threshold = - 1 )
100+ current += 1
66101
67- for _topic in r . topics :
68- yield types . ForumTopic . _parse ( _topic )
102+ if current >= total :
103+ return
0 commit comments