Search code examples
pythondjangopython-telegram-bot

python telegram bot to get next question I need to type anything


I'm working with Django and Python Telegram Bot, the problem that I have is that when the conversation starts and I get to my 3rd question and answer, I need to type anything again in order to get the next question

enter image description here

As you can see in the picture if I dont type 'OK' I do not get the next question.

This is my code

GET_CLIENTE, GET_TELEFONO, SET_MENU, SET_TELEFONO, SET_CLIENTE, SET_NOMBRE, SET_EMAIL, GET_EMAIL, RESPUESTAS = range(
    9)


def cliente(update: Update, _: CallbackContext):
    nombre = Cliente.objects.filter(id=1)[0]
    nombre = str(nombre)
    update.message.reply_markdown_v2(
        nombre, reply_markup=ForceReply(selective=True),
    )


def set_nombre(bot, update):
    message = 'Dame el nombre completo de la persona'
    pass


def start(update: Update, _: CallbackContext) -> None:
    """Send a message when the command /start is issued."""

    keyboard = [['Clientes', 'Reporte']]

    message = 'Selecciona la Opción deseada'

    reply_markup = ReplyKeyboardMarkup(keyboard,
                                       one_time_keyboard=True,
                                       resize_keyboard=True)
    update.message.reply_text(message, reply_markup=reply_markup)

    return SET_MENU


def set_menu(update: Update, _: CallbackContext) -> None:
    """
    Set option selected from menu.
    """
    keyboard = [['Alta', 'Actualizar']]

    message = 'Qué vamos a hacer'

    reply_markup = ReplyKeyboardMarkup(keyboard,
                                       one_time_keyboard=True,
                                       resize_keyboard=True)
    update.message.reply_text(message, reply_markup=reply_markup)

    return SET_CLIENTE


def set_cliente(update: Update, _: CallbackContext) -> None:
    message = 'Dame el nombre completo de la persona'
    update.message.reply_text(message)
    return GET_CLIENTE


def get_nombre(update: Update, context: CallbackContext) -> None:
    nombre = update.message.text
    context.user_data['nombre'] = nombre
    respuesta = f'El nombre es: {nombre}'
    update.message.reply_text(respuesta)
    return SET_EMAIL


def set_email(update: Update, _: CallbackContext) -> None:
    message = 'Dame el email'
    update.message.reply_text(message)
    return GET_EMAIL


def get_email(update: Update, context: CallbackContext) -> None:
    email = update.message.text
    context.user_data['email'] = email
    respuesta = f'El email es: {email}'
    update.message.reply_text(respuesta)
    return SET_TELEFONO


def set_telefono(update: Update, _: CallbackContext) -> None:
    message = 'Dame el telefono'
    update.message.reply_text(message)
    return GET_TELEFONO


def get_telefono(update: Update, context: CallbackContext) -> None:
    telefono = update.message.text
    context.user_data['telefono'] = telefono
    respuesta = f'El teléfono es: {telefono}'
    update.message.reply_text(respuesta)
    return RESPUESTAS


def respuestas(update: Update, context: CallbackContext) -> None:
    user_data = context.user_data
    respuestas = list(user_data.values())

    update.message.reply_text(
        f'Los datos son los siguientes: Nombre: {(respuestas[0])} Email: {(respuestas[1])} Teléfono: {(respuestas[2])}')


def cancel(update: Update, _: CallbackContext) -> None:
    """
    User cancelation function.
    Cancel conersation by user.
    """
    user = update.message.from_user
    logger.info("User {} canceled the conversation.".format(user.first_name))
    update.message.reply_text('bye',
                              reply_markup=ReplyKeyboardRemove())

    return ConversationHandler.END


def error(bot, update, error):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, error)


class Command(BaseCommand):
    help = 'test'

    def handle(self, *args, **options):

        updater = Updater(settings.TOKEN)
        dispatcher = updater.dispatcher

        conv_handler = ConversationHandler(
            entry_points=[CommandHandler('start', start)],
            states={

                SET_MENU: [MessageHandler(Filters.regex('^(Clientes|Reporte)$'), set_menu)],
                SET_CLIENTE: [MessageHandler(Filters.regex('^(Alta|Actualizar)$'), set_cliente)],
                GET_CLIENTE: [MessageHandler(Filters.text, get_nombre)],
                SET_EMAIL: [MessageHandler(Filters.text, set_email)],
                GET_EMAIL: [MessageHandler(Filters.text, get_email)],
                SET_TELEFONO: [MessageHandler(Filters.text, set_telefono)],
                GET_TELEFONO: [MessageHandler(Filters.text, get_telefono)],
                RESPUESTAS: [MessageHandler(Filters.text, respuestas)],


            },
            fallbacks=[CommandHandler('cancel', cancel)],

        )
        dispatcher.add_handler(conv_handler)
        dispatcher.add_error_handler(error)

        updater.start_polling()
        updater.idle()

Solution

  • Just ask the user for the email from within the get_nombre callback. In ConversationHandler, each handler should in general parse the users input and tell the user what to do next.


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