Python Telebot API。为什么我的机器人会对每条消

时间:2018-02-25 14:31:38

标签: python telegram telegram-bot python-telegram-bot

我希望我的机器人能够对用户发送的特定消息做出反应。 但是机器人会对每条消息做出反应。

@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()

在此代码中,当用户输入单词“photo”时,bot会向他发送一个选择。但我输入一个随机的单词,它仍然给我一个选择。我的代码出了什么问题?

1 个答案:

答案 0 :(得分:3)

问题是这一行:if message.text =='photo' or 'new car':。你基本上每次都会这样问:

>>> False or True
True

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

你应该问if message.text == 'photo' or message.text == 'new_car'或者你可以稍微缩短它if message.text in ('photo', 'new_car'):

示例:

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