I have an issue with my telegram bot. I wrote a bot in which the user needs to make a choice with an Inline Keyboard. If he selects 'Cerca un prodotto' the bot should wait for user input and print it. But if I start the bot then it prints the text 'FU' in update.message.reply_text('HELLO FU', reply_markup=reply_markup_main) row instead of printing user input. This is my code:
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.ext import CommandHandler, CallbackQueryHandler, CallbackContext
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
from telegram import Update
import telegram
def start(update, context):
kb_main = [
[InlineKeyboardButton("Cerca le migliori offerte", callback_data='trovaofferte')],
[InlineKeyboardButton("Cerca un prodotto", callback_data='cercaprod')]
]
reply_markup_main = InlineKeyboardMarkup(kb_main)
update.message.reply_text('HELLO FU', reply_markup=reply_markup_main)
def kb(update: Update, _: CallbackContext) -> None:
query = update.callback_query
query.answer()
#===> IF USER CHOICE IS 'cercaprod' THEN BOT SHOULD WAIT FOR USER INPUT<====
if query.data == 'cercaprod':
print(query.message.text)
def main():
update= Updater('1655760090:AAFKyOR-i7wLW1zIAH9-air0EtqIDQJrCwk', use_context=True)
disp=update.dispatcher
disp.add_handler(CommandHandler("start", start))
disp.add_handler(MessageHandler(Filters.text & ~Filters.command, kb))
update.dispatcher.add_handler(CallbackQueryHandler(kb))
update.start_polling()
update.idle()
if __name__=='__main__':
main()
A have a few remarks:
kb in both a MessageHandler and a CallbackQueryHandler, but call update.callback_query.answer(). However, if the update is a message (in the MessageHandler case, update.callback_query will be None and you'll get an exception.Now to the actual problem:
When the button is pressed, the only update you get is the CallbackQuery and query.message is the message that the button is attached to - in your case the message with text HELLO FU. If you want the user to enter some text after pressing the button, that will come in a new update. So you'd have to use a MessageHandler to catch that. I guess that's what you tried by setting up a MessageHandler with kb as callback, but as mentioned above that will only raise an error, which you currently won't see because you have no logging set up and no error handler.
For this kind of setup, I strongly recommend to use ConversationHandler, which is perfect for setups where multiple user inputs are needed. There's also a neat example here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With