I am new to python and its framework and i am having this trouble in accessing the latest messages from a telegram channel.
I want to get the latest message from the channel and process them using my code. with some searching in stackoverflow i found a solution for getting the messages of a channel. yet that code dumps all the messages from that telegram channel.
The code to get channel messages.
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())
I only want the recent messages on that channel. suggest me the code i need to modify to do so.
2
Answers
The documentation for
client.iter_messages
shows that this method has alimit
parameter:Your code simply needs to make use of this parameter:
If by "the latest" you mean the new messages as they arrive, look at the docs, and more specifically NewMessage, there is a good example there.
You can define several event handlers on NewMessage according to many parameters, like channel IDs, and even message pattern.
For your case, for instance, where you want to get new messages from a single channel, it could be
This will print the new messages arriving to the entities defined in myChannelIDList.
According to the docs, the chats parameter can have "one or more entities (username/peer/etc.), preferably IDs." There are several Q/A in stackoverflow about how to get this IDs, this one might be useful for you since you are with Python, more specifically the example with this code:
This will print IDs of all the "dialogs" of the Telegram account. If you are part of a channel it will be there.
Regards!