Search code examples
pythonbotstelegrampython-telegram-bot

How do I wait for user reply? (Telegram bot with python-telegram-bot)


How do I have the bot wait for a reply to save it? My goal is to save the name in the database, which I have already accomplished. For example,

User: /name
Bot: What do you want to name this dog?
User: dog
Bot: Dog saved as dog.
def name(update, context):
    update.message.reply_text("What do you want to name this dog?")

to save reply to database.

I know that if I were to use return(update.message.text), it would return /name, instead of dog, as that is the most recent message when the user types /name.

Help would be appreciated!


Solution

  • You can use ConversationHandler to implement it.

    Here is a working sample code:

    from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
                              ConversationHandler)
    
    TOKEN = " ... "
    
    NAME, DOG_SAVE = range(2)
    
    def start(update, context):
        update.message.reply_text(
            'send /name to activate save a dog name'
        )
        return NAME
    
    def name(update, context):
        update.message.reply_text('What do you want to name this dog?')
    
        return DOG_SAVE
    
    def dog_save(update, context):
        name = update.message.text
        update.message.reply_text(f'Dog saved as {name}')
    
        return ConversationHandler.END
    
    def main():
        updater = Updater(TOKEN, use_context=True)
    
        dp = updater.dispatcher
    
        conv_handler = ConversationHandler(
            entry_points=[CommandHandler('start', start)],
            fallbacks=[],
    
            states={
                NAME: [CommandHandler('name', name)],
                DOG_SAVE: [MessageHandler(Filters.text, dog_save)],
            },
        )
    
        dp.add_handler(conv_handler)
    
        updater.start_polling()
        updater.idle()
    
    
    if __name__ == '__main__':
        main()
    

    You can find additional example here

    Sample output: enter image description here