skip to Main Content

I want to write a simple bot for registration, but I made a mistake and do not know how to fix it, please help me.
my problem is that no messages are sent from such functions: name_handler, age_handler.

from telegram import Update
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)

from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
                          ConversationHandler)

NAME, GENDER, AGE = 0, 0, 0
user_data = {}


def start_handler(update: Update, context):
    update.message.reply_text(
        "enter ur name",
        reply_markup=ReplyKeyboardRemove(),
    )
    return NAME


def name_handler(update: Update, context):
    user_data[NAME] = update.message.text

    update.message.reply_text("enter ur gender")

    return GENDER


def age_handler(update: Update, context):
    user_data[GENDER] = update.message.text
    update.message.reply_text("enter ur age")

    return AGE


def finish_handler(update: Update, context):
    user_data[AGE] = update.message.text

    update.message.reply_text(f"registered successfully, you are {user_data[NAME]}, {user_data[GENDER]}, "
                              f"{user_data[AGE]}")

    return ConversationHandler.END


def cancel_handler(update: Update, context):
    print("bye")


def main():
    updater = Updater(
        token="token",
        use_context=True,
    )

    dp = updater.dispatcher

    conv_handler = ConversationHandler(
        entry_points=[
            CommandHandler("start", start_handler),
        ],
        states={
            NAME: [MessageHandler(Filters.all, name_handler)],
            GENDER: [MessageHandler(Filters.all, age_handler)],
            AGE: [MessageHandler(Filters.all, finish_handler)]
        },
        fallbacks=[CommandHandler("cancel", cancel_handler)],
    )

    dp.add_handler(conv_handler)

    updater.start_polling()
    updater.idle()


main()

after "enter ur name" must be "enter ur gender" but telegram wrote "registered successfully"

2

Answers


  1. Because NAME, GENDER and AGE are all equal to 0, your conversation handler only has a single state, namely the last. To understand this, try running print({0:1, 0:2, 0:3}) in your python console. So to solve this, make sure that your states have unique values.


    Disclaimer: I’m currently the maintainer of python-telegram-bot.

    Login or Signup to reply.
  2. Try something like:

    NAME, GENDER, AGE = range(3)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search