Telegram Bot API getUpdates method includes deleted messages

I’m developing a bot for Telegram and I’ve encountered a challenge with the getUpdates function. My bot has been granted admin privileges in a channel and I need to retrieve the latest message that hasn’t been removed.

When I use the bot token and set offset: -1 along with limit: 1, I expect to receive just the newest message. Unfortunately, the API still provides messages that have been deleted from the channel.

Here’s a snippet of my code:

import requests

def fetch_newest_message():
    bot_token = "YOUR_BOT_TOKEN"
    api_url = f"https://api.telegram.org/bot{bot_token}/getUpdates"
    
    params = {
        "offset": -1,
        "limit": 1
    }
    
    response = requests.get(api_url, params=params)
    return response.json()

newest_update = fetch_newest_message()
print(newest_update)

Is there a way to configure the API to ignore deleted messages and just provide the current ones? What’s a good method to deal with this issue?

Indeed, this behavior is inherent to Telegram’s API. Deleted messages remain in the update history, leading to confusion when trying to retrieve the latest messages. To manage this, I recommend maintaining a local list of valid message IDs and incorporating a verification step. By calling getMessage with the relevant chat_id and message_id for each update, you can effectively filter out those that produce a ‘message not found’ error, confirming their deletion. Additionally, monitoring the edit_date field may provide clues, but this isn’t always dependable due to the nature of message deletions.

Yes, this is a limitation of Telegram’s API. The getUpdates method retrieves all updates, including those for messages that have been deleted. Essentially, when a message is removed, the update for that message remains in the update list, which is why you’re still seeing it.

A practical approach is to implement message validation within your bot. Upon receiving an update, you can attempt to interact with the message (like forwarding it) to check for any “message not found” errors, indicating that the message has been deleted. Alternatively, consider using webhooks instead of polling; they might provide faster notification of deletions, but you’ll still need to filter out the removed messages manually.

unfortunately, there’s no direct way to filter deleted msgs from getUpdates. I store message IDs in a database and mark them as deleted when needed. you could try channels.getMessages from the raw API, but it’s more complex than the bot API.