Search code examples
pythonpython-telegram-bot

How can I receive messages from users in python-telegram-bot?


I'm using python-telegram-bot

def delete(update: Update, context: CallbackContext) -> None:
    """delete account from database"""
    num = random.randrange(111111,999999)
    update.message.reply_text("Something to write here\n\n****" + str(num) + "****")
    time.sleep(10)
    if int(update.message.text) == num: #here update.message.text == '/cancel' and not the message user
        flag = delete_db(update.effective_user.id)
        if flag:
            update.message.reply_text('OK')
    else:
        update.message.reply_text('Something goes wrong or time is out')

How can i force the update of the message? I think is there the problem...


Solution

  • I resolved it, on the advice of the telegram community, with a Conversational Handler with two function, one to start the operation and the second to confirm.

    In def main:

    dispatcher.add_handler(
            ConversationHandler(
                entry_points = [MessageHandler(Filters.regex('^Cancel$'), delete)],
                states = {
                    DELETE: [MessageHandler(Filters.text, random_number)],
                },
                fallbacks = [None], # here you can enter an /end function to break the process
                conversation_timeout = 30,
            ),
        )
    

    Start function 'delete':

    def delete(update: Update, context: CallbackContext):
        update.message.reply_text('some message')
        CallbackContext.chat_data = random.randrange(111111,999999)
        update.message.reply_text("some other message\n*" + str(CallbackContext.chat_data) + "*")
        return DELETE
    

    The function to keep the string message and compare to random number generated:

    def random_number(update: Update, context: CallbackContext):
        try:
            user_action = int(update.message.text)
            if user_action == CallbackContext.chat_data:
                #flag = delete_db(update.effective_user.id) # function to delete from database
                if flag:
                    update.message.reply_text('Okay done')
            else:
                update.message.reply_text('Wrong number')
        except:
            update.message.reply_text('failed')    
        return ConversationHandler.END