如何使用 TELETHON 按日期获取消息?

how to get messages by date using TELETHON?

如何使用 TELETHON

获取今天发布的消息

我正在使用下面的代码

date_of_post = datetime.datetime(2019, 12, 24)

with TelegramClient(name, api_id, api_hash) as client:
    for message in client.iter_messages(chat , offset_date = date_of_post):
        print(message.sender_id, ':', message.text)

offset_date 用于获取该日期 之前的消息。所以你应该使用后一天:

async def get_messages_at_date(chat, date):
    result = []
    tomorrow = date + datetime.timedelta(days=1)
    async for msg in client.iter_messages(chat, offset_date=date):
        if msg.date < date:
            return result
        result.append(msg)

@Lonami 提出的观点是有效的 - offset_date 用于获取该日期 之前的消息。但是,docs 描述了另一个名为 reverse 的参数,您可以将其提供给 iter_messages :

reverse (bool, optional): If set to True, the messages will be returned in reverse order (from oldest to newest, instead of the default newest to oldest). This also means that the meaning of offset_id and offset_date parameters is reversed, although they will still be exclusive.

所以,如果你这样使用它:


对于 client.iter_messages(聊天,<b>reverse = True</b>,offset_date = date_of_post)中的消息:
   打印(message.sender_id, ':', message.text)

它应该会如您所愿。