首页 > 解决方案 > 如何使用 Telethon,python 仅接收来自电报频道的新消息

问题描述

我是 python 及其框架的新手,我在从电报频道访问最新消息时遇到了麻烦。

我想从频道获取最新消息并使用我的代码处理它们。通过在stackoverflow中进行一些搜索,我找到了获取频道消息的解决方案。但是该代码会转储该电报频道中的所有消息。

获取频道消息的代码。

    from telethon import TelegramClient, events, sync
# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = 123456
api_hash = 'abcdefghijklmnopqrstuvwxyz123456789'

client = TelegramClient('anon', api_id, api_hash)

async def main():
    # You can print the message history of any chat:
    async for message in client.iter_messages('SampleChannel'):
        print(message.sender.username, message.text)
        print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')

with client:
    client.loop.run_until_complete(main())

我只想要该频道上的最新消息。建议我需要修改的代码。

标签: pythontelegramtelethon

解决方案


的文档client.iter_messages显示此方法有一个limit参数:

要检索的消息数。

您的代码只需要使用此参数:

async def main():
    limit = 10
    async for message in client.iter_messages('SampleChannel', limit):
        print(message.sender.username, message.text)

推荐阅读