I'm working on a Telegram bot and I've run into a problem. When I try to update a message that hasn't changed, I get this error:
BadRequest: Message is not modified
I want to make it show a custom message instead of the default error. I tried writing a function like this:
def handle_error(bot, update, error):
try:
raise error
except BadRequest:
print('No changes to message')
But it's not working as I hoped. Does anyone know how to catch this specific error and display a custom message? I'm pretty new to error handling in Python, so any help would be great. Thanks!
I’ve faced this exact issue with Telegram bots before. The trick is to catch the specific BadRequest exception and check its message. Here’s what worked for me:
from telegram.error import BadRequest
def edit_message(bot, chat_id, message_id, new_text):
try:
bot.edit_message_text(chat_id=chat_id, message_id=message_id, text=new_text)
except BadRequest as e:
if str(e) == 'Message is not modified':
print('No changes needed for this message')
else:
# Handle other BadRequest errors
print(f'Unexpected error: {e}')
This way, you’re only catching the specific ‘Message is not modified’ error and handling it separately. For all other BadRequest errors, you can log them or handle them differently. Hope this helps you out!
I’ve encountered this issue in my Telegram bot projects too. One approach that’s worked well for me is using a custom exception handler. Here’s a snippet that might help:
from telegram.error import BadRequest
def custom_error_handler(update, context):
if isinstance(context.error, BadRequest):
if str(context.error) == ‘Message is not modified’:
context.bot.send_message(chat_id=update.effective_chat.id, text=‘No changes were needed.’)
else:
context.bot.send_message(chat_id=update.effective_chat.id, text=‘An error occurred. Please try again.’)
else:
# Handle other types of errors
print(f’Error: {context.error}')
Then, add this handler to your dispatcher:
dispatcher.add_error_handler(custom_error_handler)
This way, you can catch the specific ‘Message is not modified’ error and respond appropriately, while still handling other potential errors.
hey laura, i’ve dealt with this before. try wrapping ur code in a try-except block like this:
try:
bot.edit_message_text(…)
except telegram.error.BadRequest as e:
if ‘Message is not modified’ in str(e):
print(‘no changes needed’)
else:
raise e
this should catch that specific error n let u handle it. good luck!