[Python] How to make Telebot respond "I don't understand" when user sends unknown text?

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    I’m making a Telegram bot using Python and the telebot (pyTelegramBotAPI) library. I created a basic telegram bot for practice, and I want bot to say “Sorry, I don’t understand” when a user sends a message I haven’t defined.

    But right now, when the user types something random, the bot just replies with "Hello, user!" (my start message), even though it shouldn’t.

    How can I make the bot respond only with the start message on /start, and reply with "I don't understand" for all other unknown texts?

    What I’ve tried:

    • I added an else block at the bottom of my message handler to catch unknown messages.
    • I tried printing message.text to debug it, but still got the /start response.
    • I thought maybe /start is being triggered accidentally, but I only call it once in the code.

    import telebot
    import webbrowser
    from telebot import types

    bot = telebot.TeleBot('my_token')

    @bot.message_handler(commands=['start'])
    def welcome(message):
    bot.send_message(message.chat.id, f'<em>Hello, {message.from_user.first_name}</em>!', parse_mode='HTML')
    markup = types.ReplyKeyboardMarkup()
    btn1 = types.KeyboardButton('Open website')
    btn2 = types.KeyboardButton('Delete')
    btn3 = types.KeyboardButton('Change')
    markup.add(btn1)
    markup.row(btn2, btn3)
    bot.send_message(message.chat.id, "Choose the option:", reply_markup=markup)

    @bot.message_handler()
    def answers(message):
    if message.text == 'Open website':
    bot.send_message(message.chat.id, 'The website is open')
    elif message.text == 'Delete':
    bot.send_message(message.chat.id, 'The message is deleted')
    elif message.text == 'Change':
    bot.send_message(message.chat.id, 'The message is changed')
    elif message.text.lower() == 'id':
    bot.reply_to(message, f'ID: {message.from_user.id}')
    elif message.text == '/site':
    webbrowser.open('https://stackoverflow.com/')
    elif message.text == '/help':
    bot.send_message(message.chat.id, 'How can I help you?')
    elif message.text.lower() == 'bye':
    bot.send_message(message.chat.id, f'<em>Bye, {message.from_user.first_name}</em>!', parse_mode='HTML')
    elif message.text.lower() == 'hello' or 'hi':
    bot.send_message(message.chat.id, f'<em>Hello, {message.from_user.first_name}</em>!', parse_mode='HTML')


    bot.polling(non_stop=True)

    Continue reading...

Compartilhe esta Página