2
0
mirror of https://github.com/pyrogram/pyrogram synced 2025-08-23 18:37:26 +00:00

Revamp get_chat_history related methods

This commit is contained in:
Dan 2022-04-24 11:56:07 +02:00
parent 5f2dcf70ed
commit bf8a334e32
5 changed files with 51 additions and 33 deletions

View File

@ -171,10 +171,9 @@ def pyrogram_api():
delete_messages delete_messages
get_messages get_messages
get_media_group get_media_group
get_history get_chat_history
get_history_count get_chat_history_count
read_history read_chat_history
iter_history
send_poll send_poll
vote_poll vote_poll
stop_poll stop_poll

View File

@ -29,13 +29,13 @@ from .edit_message_media import EditMessageMedia
from .edit_message_reply_markup import EditMessageReplyMarkup from .edit_message_reply_markup import EditMessageReplyMarkup
from .edit_message_text import EditMessageText from .edit_message_text import EditMessageText
from .forward_messages import ForwardMessages from .forward_messages import ForwardMessages
from .get_chat_history import GetChatHistory
from .get_chat_history_count import GetChatHistoryCount
from .get_discussion_message import GetDiscussionMessage from .get_discussion_message import GetDiscussionMessage
from .get_history import GetHistory from .get_history import GetHistory
from .get_history_count import GetHistoryCount
from .get_media_group import GetMediaGroup from .get_media_group import GetMediaGroup
from .get_messages import GetMessages from .get_messages import GetMessages
from .iter_history import IterHistory from .read_chat_history import ReadChatHistory
from .read_history import ReadHistory
from .retract_vote import RetractVote from .retract_vote import RetractVote
from .search_global import SearchGlobal from .search_global import SearchGlobal
from .search_global_count import SearchGlobalCount from .search_global_count import SearchGlobalCount
@ -92,10 +92,10 @@ class Messages(
StopPoll, StopPoll,
RetractVote, RetractVote,
DownloadMedia, DownloadMedia,
IterHistory, GetChatHistory,
SendCachedMedia, SendCachedMedia,
GetHistoryCount, GetChatHistoryCount,
ReadHistory, ReadChatHistory,
EditInlineText, EditInlineText,
EditInlineCaption, EditInlineCaption,
EditInlineMedia, EditInlineMedia,

View File

@ -20,24 +20,47 @@ from datetime import datetime
from typing import Union, Optional, AsyncGenerator from typing import Union, Optional, AsyncGenerator
import pyrogram import pyrogram
from pyrogram import types from pyrogram import types, raw, utils
class IterHistory: async def get_chunk(
async def iter_history( *,
client: "pyrogram.Client",
chat_id: Union[int, str],
limit: int = 0,
offset: int = 0,
from_message_id: int = 0,
from_date: datetime = datetime.fromtimestamp(0)
):
messages = await client.invoke(
raw.functions.messages.GetHistory(
peer=await client.resolve_peer(chat_id),
offset_id=from_message_id,
offset_date=utils.datetime_to_timestamp(from_date),
add_offset=offset,
limit=limit,
max_id=0,
min_id=0,
hash=0
),
sleep_threshold=60
)
return await utils.parse_messages(client, messages, replies=0)
class GetChatHistory:
async def get_chat_history(
self: "pyrogram.Client", self: "pyrogram.Client",
chat_id: Union[int, str], chat_id: Union[int, str],
limit: int = 0, limit: int = 0,
offset: int = 0, offset: int = 0,
offset_id: int = 0, offset_id: int = 0,
offset_date: datetime = datetime.fromtimestamp(0), offset_date: datetime = datetime.fromtimestamp(0)
reverse: bool = False
) -> Optional[AsyncGenerator["types.Message", None]]: ) -> Optional[AsyncGenerator["types.Message", None]]:
"""Iterate through a chat history sequentially. """Get messages from a chat history.
This convenience method does the same as repeatedly calling :meth:`~pyrogram.Client.get_history` in a loop, thus saving The messages are returned in reverse chronological order.
you from the hassle of setting up boilerplate code. It is useful for getting the whole chat history with a
single call.
Parameters: Parameters:
chat_id (``int`` | ``str``): chat_id (``int`` | ``str``):
@ -59,37 +82,33 @@ class IterHistory:
offset_date (:py:obj:`~datetime.datetime`, *optional*): offset_date (:py:obj:`~datetime.datetime`, *optional*):
Pass a date as offset to retrieve only older messages starting from that date. Pass a date as offset to retrieve only older messages starting from that date.
reverse (``bool``, *optional*):
Pass True to retrieve the messages in reversed order (from older to most recent).
Returns: Returns:
``Generator``: A generator yielding :obj:`~pyrogram.types.Message` objects. ``Generator``: A generator yielding :obj:`~pyrogram.types.Message` objects.
Example: Example:
.. code-block:: python .. code-block:: python
for message in app.iter_history("pyrogram"): for message in app.get_chat_history(chat_id):
print(message.text) print(message.text)
""" """
offset_id = offset_id or (1 if reverse else 0)
current = 0 current = 0
total = limit or (1 << 31) - 1 total = limit or (1 << 31) - 1
limit = min(100, total) limit = min(100, total)
while True: while True:
messages = await self.get_history( messages = await get_chunk(
client=self,
chat_id=chat_id, chat_id=chat_id,
limit=limit, limit=limit,
offset=offset, offset=offset,
offset_id=offset_id, from_message_id=offset_id,
offset_date=offset_date, from_date=offset_date
reverse=reverse
) )
if not messages: if not messages:
return return
offset_id = messages[-1].id + (1 if reverse else 0) offset_id = messages[-1].id
for message in messages: for message in messages:
yield message yield message

View File

@ -25,8 +25,8 @@ from pyrogram import raw
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class GetHistoryCount: class GetChatHistoryCount:
async def get_history_count( async def get_chat_history_count(
self: "pyrogram.Client", self: "pyrogram.Client",
chat_id: Union[int, str] chat_id: Union[int, str]
) -> int: ) -> int:

View File

@ -22,8 +22,8 @@ import pyrogram
from pyrogram import raw from pyrogram import raw
class ReadHistory: class ReadChatHistory:
async def read_history( async def read_chat_history(
self: "pyrogram.Client", self: "pyrogram.Client",
chat_id: Union[int, str], chat_id: Union[int, str],
max_id: int = 0 max_id: int = 0