skip to Main Content

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


  1. The documentation for client.iter_messages shows that this method has a limit parameter:

    Number of messages to be retrieved.

    Your code simply needs to make use of this parameter:

    async def main():
        limit = 10
        async for message in client.iter_messages('SampleChannel', limit):
            print(message.sender.username, message.text)
    
    Login or Signup to reply.
  2. 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

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

    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:

    #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))
    

    This will print IDs of all the "dialogs" of the Telegram account. If you are part of a channel it will be there.

    Regards!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search