获取输入用户Python Telegram Bot

时间:2020-08-08 16:26:07

标签: python-telegram-bot

在询问以下问题后,我试图从用户那里读取一本书的名称:您要寻找什么书?如何将用户的响应保存在变量中以便在算法中使用?

def bookinfo(bot, update):
    chat_id = update.message.chat_id
    bot.send_message(chat_id=chat_id, text='What book are you looking for??')
    dp.add_handler(MessageHandler(Filters.text))
    BOOK_NAME = update.message.text
    BOOK_NAME = str.lower(BOOK)
    answer = 'You have wrote me ' + BOOK_NAME
    bot.send_message(answer)
    
updater = Updater('TOKEN')
dp = updater.dispatcher
    
dp.add_handler(CommandHandler('bookinfo', bookinfo))

updater.start_polling()
updater.idle()

问了问题,但是机器人并没有通过发送带有书名的消息来回应...预先表示感谢!

1 个答案:

答案 0 :(得分:0)

首先,总是从更新中获取chat_id,如下所示:

chat_id = update.effective_user.id

以及send_message方法也需要一个chat_id来发送,您有两种选择来回答此更新:

  • 甚至不需要向处理程序中添加处理程序
bot.send_message(chat_id, message)
update.message.reply_text(message)
def bookinfo(bot, update):
    update.message.reply_text(text='What book are you looking for??')
    

def get_bookinfo(bot, update):
    book_name = update.message.text
    book_name = str.lower(book_name)
    # TODO: do what you want with book name

    answer = f'You have wrote me {book_name}'  
    update.message.reply_text(answer)
    

updater = Updater('TOKEN')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bookinfo', bookinfo))
dp.add_handler(MessageHandler(Filters.text, get_bookinfo))
updater.start_polling()
updater.idle()