I’m working on a Telegram bot and keep running into this annoying issue. When I try to edit a message that hasn’t actually changed, the bot throws this exception:
telegram.error.BadRequest: Message is not modified
Instead of letting this error crash my bot or show the default error message, I want to catch it and display my own custom message. I’ve been trying to create an error handler function but can’t get it working properly:
def handle_telegram_errors(bot_instance, update_obj, exception):
try:
raise exception
except BadRequest:
# custom handling for bad requests
print('Message content unchanged')
The function runs but doesn’t seem to catch the specific error I’m targeting. What’s the right way to handle this particular exception type in a Telegram bot?
Had this exact problem for months. Your error handler isn’t preventing the exception - it’s just catching it after it happens. I fixed it by checking before editing. Store a hash of the message content and compare it with new content before calling edit_message_text. If they’re the same, skip the edit and return a custom response. No more BadRequest exceptions and you’re not wasting API calls to Telegram.
The global error handler approach works, but you’ve got to configure it right with the dispatcher. I’ve hit similar issues before - checking the exception message directly beats trying to catch the generic BadRequest type every time.
Try this instead:
def handle_telegram_errors(bot_instance, update_obj, exception):
if "not modified" in str(exception):
# handle the unchanged message case
return
# let other exceptions bubble up
Register it with dispatcher.add_error_handler(handle_telegram_errors). The trick is matching against the actual error text instead of just the exception type. BadRequest covers way too many different scenarios - not just unmodified messages.