如何使用 telethon、python 只接收来自电报频道的新消息

问题描述 投票:0回答:2

我是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())

我只想要该频道上的最新消息。建议我需要修改的代码才能做到这一点。

python telegram telethon
2个回答
1
投票

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

要检索的消息数。

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

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

0
投票

如果“最新”是指新消息到达时,请查看文档,更具体地说是NewMessage,那里有一个很好的例子。 您可以根据许多参数(例如通道 ID,甚至消息模式)在 NewMessage 上定义多个事件处理程序。 例如,对于您的情况,您想从单个渠道获取新消息,它可能是

client.on(events.NewMessage(chats=myChannelIDList))
async def my_event_handler(event):
    print(event.message)

这将打印到达 myChannelIDList 中定义的实体的新消息。

根据文档,chats 参数可以有“一个或多个实体(用户名/同伴/等),最好是 ID”。 stackoverflow 中有几个关于如何获取此 ID 的问答,这个可能对您有用,因为您使用的是 Python,更具体地说是包含此代码的示例:

#To get the channel_id,group_id,user_id
for chat in client.get_dialogs():
    print('name:{0} ids:{1} is_user:{2} is_channel{3} is_group:{4}'.format(chat.name,chat.id,chat.is_user,chat.is_channel,chat.is_group))

这将打印 Telegram 帐户的所有“对话框”的 ID。如果您是频道的一部分,它就会在那里。

问候!

© www.soinside.com 2019 - 2024. All rights reserved.