Kas
Kas

Reputation: 89

python telegram bot ForceReply callback

I'm currently developing a telegram bot with python-telegram-bot. I want to be able to get the message, that was replied to ForceReply. The expected flow is this:

  1. User sends /start command
  2. Bot sends a message with some information. The message is linked with ForceReply
  3. User replies to the message
  4. Handle and operate the message.

How could I achieve the expected result? Thanks

initial_message = "Hi... Please reply to this message to proceed to the next step..."

def start (update: Update, context: CallbackContext):
    chat_id = update.message.chat_id
    print(update.message.from_user.username)
    context.bot.send_message(chat_id=chat_id, text=initial_message, reply_markup=ForceReply())

Upvotes: 1

Views: 1058

Answers (1)

Rafael Colombo
Rafael Colombo

Reputation: 435

To be able to handle the ForceReply() you must implement a ConversationHandler. Once the user reply to ForceReply, with the ConversationHandler, you'll be able to deal with his/her reply. That's how it's done:

END = ConversationHandler.END
NEXTSTEP = range (1)

initial_message = "Hi... Please reply to this message to proceed to the next step..."
def start (update, context):
    chat_id = update.message.chat_id
    print(update.message.from_user.username)
    context.bot.send_message(chat_id=chat_id,
                             text=initial_message,
                             reply_markup=ForceReply())

    return NEXTSTEP

def nextstep (update, context):

    chat_id = update.message.chat_id
    ##user reply will be assigned to replied variable below
    replied = update.message.text
    print(replied)

    return END

def main():
    ##handler start
    start_handler = ConversationHandler(
        entry_points = [CommandHandler('start', start)],
        states = {
            NEXTSTEP: [MessageHandler(Filters.text & ~Filters.command, nextstep)]},
        fallbacks = [CommandHandler('cancel', callback = functions.cancel)])
    dp.add_handler(start_handler)

Upvotes: 1

Related Questions