Search code examples
pythontelegramtelegram-botpython-telegram-bot

Python Telebot API. Why my bot react on every message?


I would like my bot to react to a specific message sent by a user. But bot reacts to every message.

@bot.message_handler(content_types=['text'])
def send_rand_photo(message):
  keyboard = types.InlineKeyboardMarkup()
  if message.text =='photo' or 'new car':
  msg=bot.send_message(message.chat.id, "Ну как тебе?", reply_markup=keyboard)

    like_button= types.InlineKeyboardButton(text=emojize("Like :heart:", use_aliases=True), callback_data='like')
    keyboard.add(like_button)

    dislike_button =types.InlineKeyboardButton (text=emojize("Dislike :broken_heart:", use_aliases=True), callback_data='dislike')
    keyboard.add(dislike_button)

    all_photo_in_directory=os.listdir(PATH)
    random_photo=random.choice (all_photo_in_directory)
    img=open (PATH + '/' +random_photo, 'rb')
    bot.send_chat_action(message.from_user.id,'upload_photo')
    bot.send_photo(message.from_user.id,img, reply_markup=keyboard)
    img.close()

In this code, when a user enters a word 'photo', bot sent him a pick. But I enter a random word and it still sends me a pick. What is wrong with my code?


Solution

  • The problem is this line here: if message.text =='photo' or 'new car':. You are essentially asking this everytime:

    >>> False or True
    True
    
    >>> message = 'random'
    >>> message =='photo' or 'new car'
    'new car'
    

    You should either be asking if message.text == 'photo' or message.text == 'new_car' or you could shorten it slightly like this if message.text in ('photo', 'new_car'):

    Example:

    >>> message = 'random'
    >>> if message in ('photo', 'new_car'):
    ...     print('yes!')
    ... 
    >>> message = 'photo'
    >>> if message in ('photo', 'new_car'):
    ...     print('yes!')
    ... 
    yes!