使用 telethon 在特定 ID 后获取电报频道消息

Get telegram channel messages after an specific id with telethon

我想在 ID(例如 1245)之后获取特定频道的帖子。我写这段代码:

# After connection to session in cli variable
last_post = cli(
                GetHistoryRequest(
                    peer=entity,
                    limit=100,
                    offset_date=None,
                    add_offset=0,
                    hash=0
                )
            )

但这给了我第 100 条最后一条消息。即使将 max_id 参数传递给 GetHistoryRequest,我也会将消息从较早的消息传递给较旧的消息。我怎样才能收到相反顺序的消息?

您必须先阅读文档,然后再提出您的问题。 您可以简单地使用 iter_messages 参数来完成,如下所示:

next_post = cli.iter_messages(
                entity,
                limit=5,
                min_id=your_post_id,
                reverse=True
            )

使用 reverse 参数,您可以获得相反顺序的帖子。

这是一个使用 bot 的示例(对于客户端版本的代码大部分相同)

    bot = TelegramClient('bot', API_ID, API_HASH).start(bot_token=BOT_TOKEN)
    result = await bot(functions.messages.GetMessagesRequest(id=[message_id]))
    message = result.messages[0]
    print(message.text)

获得 chat/full 聊天

    @bot.on(events.NewMessage)
    async def any_message_arrived_handler(event):
        chat = await event.get_chat()
        full_chat = await bot(functions.messages.GetFullChatRequest(
            chat_id=chat.id
        ))

最好看的地方是the documentation。只需在页面中搜索 messages,您就会找到您需要的内容以及包含的示例。