Handling unmodified message error in Telegram bot

I’m working on a Telegram bot and running into an issue. When I try to update a message that hasn’t changed, I get this error:

TelegramException: Message not modified

I want to catch this error and show a custom message instead. I tried this code:

def handle_error(bot, update, error):
    try:
        raise error
    except TelegramException as e:
        if 'Message not modified' in str(e):
            print('No changes to update')
        else:
            print(f'Unexpected error: {e}')

But it’s not working as expected. The bot still crashes when this error happens. How can I properly catch and handle this specific error? I want the bot to keep running and just print my custom message when a message isn’t modified. Any help would be great!

I encountered a similar scenario when working on a Telegram bot. In my experience, the solution was to catch the specific TelegramError rather than the broader TelegramException. I modified my code so that the try-except block wraps only the edit_message_text call. This approach allowed me to check if the error message contained ‘Message is not modified’ and then handle it accordingly, without interrupting the bot’s operation. Additionally, importing TelegramError from telegram.error ensures that the proper exception is caught. I found that using logging instead of print statements further enhanced error tracking in production.

hey mate, i had a similar issue. try using a try-except block directly where u update the message. something like:

try:
bot.edit_message_text(…)
except TelegramError as e:
if ‘Message not modified’ in str(e):
print(‘no changes’)
else:
raise

this should catch the error and prevent crashes. good luck!

I’ve encountered similar issues when dealing with Telegram bot errors. In my experience, handling the error requires catching the more specific BadRequest exception rather than a generic one. I imported BadRequest from telegram.error and wrapped only the bot.edit_message_text call in a try block. By checking if the error message equals “Message is not modified”, I was able to log an informative message and avoid crashing the bot. I also switched from print to proper logging to aid in production debugging.