Get last message/s from Telegram channel with Python

14.6k views Asked by At

I'm using the python-telegram-bot library to write a bot in Python that sends URLs into a channel where the bot is administrator.

Now, I would like to have the bot reading, let's say, the last 5 messages (I don't really care about the number as I just need to read the message on the chat) and store them into a list in the code for further elaborations.

I already have my bot working with:

bot = telegram.Bot(token='mytoken')
bot.sendMessage(chat_id='@mychatid', text=entry.link)

But I can't find a bot.getLastMessage or bot.getMessage kind of class into the python-telegram-bot library.

In case there's already no written class that does that, how can I implement it via the Telegram API as I'm a bit of a beginner when it comes to API implementation?

Thanks.

2

There are 2 answers

1
Tibebes. M On BEST ANSWER

That's not possible in Bots unfortunately.
Here you can find all available methods (that python-telegram-bot invokes behind the scenes) and there's no such method available to fetch messages on demand.

The closest you can get through the api is getChat (which would return the pinned_message in that chat).

What you can do in this case is, store the messages the bot sends as well as the message updates the bot receives (by setting up a handler) in some storage (database) and fetch from there later on.

0
Mahozad On

Have you tried the other type of Telegram API: Telegram [client] API and TDLib?

Using telethon library makes it easy to read channels history (see telethon docs).

For this, we need an api_id and an api_hash. So, do the following:

  1. Log in to your Telegram core
  2. Open the API development tools area
  3. Fill out the simple form there
  4. Now you can receive your api_id and api_hash

See Telegram's help documentation about how to get your API credentials.

Here is an example code that gets the last 5 messages of targetChannelId:

from telethon import TelegramClient


API_ID = 123456     # See above for how to get it
API_HASH = '123abc' # See above for how to get it
client = TelegramClient('my-client', API_ID, API_HASH)


async def main():
    async for message in client.iter_messages('targetChannelId', limit=5):
        print(message.id, message.text)


with client:
    client.loop.run_until_complete(main())

The first time you run this code it asks your phone number or bot token. Enter your phone number in the format +9912345... where 99 is your country code and the rest is your phone number. It then may send a login code to your Telegram app; enter it in the console.

Note: Only users (phone numbers) can see channel history messages; bots cannot (at least in telethon). Bots can only listen for channel updates only if they are one of its administrators.

The client.iter_messages() accepts other parameters like min_id which can be used to get messages only after a specific message (for example, we can save the last message id that we have processed and next time pass that id as min_id so only messages after that message are returned).