Search code examples
pythontelegramtelethon

Read last messages using Telethon


I'm trying to retrieve last messages (and also latest messages) from a specific channel I'm subscribed to.

I tried the following code:

from telethon import TelegramClient, events, sync

# Remember to use your own values from my.telegram.org!
api_id = 'xxx'
api_hash = 'xxx'
client = TelegramClient('xxx', api_id, api_hash)

@client.on(events.NewMessage(chats='Channel 123'))
async def my_event_handler(event):
    print(event.raw_text)

client.start()
client.run_until_disconnected()

For some reason, it's not working as it says "Channel 123" not detected.

What's the proper way to get messages from a specific channel (that I don't own but am subbed to)?


Solution

  • You need to add the channel_id in this line

    @client.on(events.NewMessage(chats='channel_id'))

    Sometimes, you can use the alias of the channel, but for private channels you can see the channel id opening telegram in the web browser and selected the chat, in the search box where appear the url, in the final of this appear the id like this example:

    https://web.telegram.org/k/#-1515693207
    

    This is the id -1515693207

    Another method is to use get_entity function to obtain the id, and pass it to the function you want to get the messages.

    channel_entity = await client.get_entity(PeerChannel(client.message.to_id.channel_id))
    

    Hope this help you.