Search code examples
pythonbotstelegramtelegram-bottelethon

Telethon: How to get the latest message id?


I have this code

from telethon.sync import TelegramClient, events


api_id = 
api_hash = ''
bot_token = ''

client = TelegramClient('session', api_id, api_hash).start(bot_token=bot_token)

@client.on(events.NewMessage)
async def newMessageListener(event):
    chat_id = event.chat_id
    message_id = event.message.id
    print(f"Received new message with id {message_id} in chat {chat_id}")

client.run_until_disconnected()

My problem is that when i add post with multiple images/videos im getting print with id of each media, but i need only id from first image/video and i dont know how i can do that. Can someone help me?

EDIT

I found a solution but I don't know if it is correct and will cause problems later

@client.on(events.NewMessage)
async def newMessageListener(event):
    if event.grouped_id:
        return
    
    message_id = event.message.id
    print(f"Received new message {message_id}}")

@client.on(events.Album)
async def newMessageListener(event):
    message_id = event.messages[0].id
    print(f"Received new message with id {message_id}")

Solution

  • @client.on(events.NewMessage)
    async def newMessageListener(event):
        if event.grouped_id:
            return
        
        message_id = event.message.id
        print(f"Received new message {message_id}}")
    
    @client.on(events.Album)
    async def newMessageListener(event):
        message_id = event.messages[0].id
        print(f"Received new message with id {message_id}")