I recommend you not to try handel multiple tasks in one single function , follow this steps instead :
1 : firstly , you should make a conversation handler , where user enters the conversation using a command and then step by step communicates with the bot . this is quite useful in tasks like users registering (enter name ? [Behrad] | thanks , enter age ? [21] | thanks , enter phone number ? [+98993...]) etc .
2 : when you fully wrote that conversation handler , you should simply add it to bot !
this is exactly what I mean (in the registering example):
imagine user enters "/register" command ...
# ---------- defining states ---------
ONE , TWO = range(2)
# ---------- functions ---------
def register(update: Update, context: CallbackContext):
chat_id = update.message.chat_id
bot.send_message(chat_id , text = "hello , you are registering ! please enter your name | type 'cancel' anytime to cancel process")
return ONE
def got_name(update: Update, context: CallbackContext):
chat_id = update.message.chat_id
name = update.message.text # now we got the name
context.user_data["name"] = name # to use it later (in next func)
bot.send_message(chat_id , text = f"thanks {name} ! please enter your phone number")
return TWO
def got_phone_number(update: Update, context: CallbackContext):
chat_id = update.message.chat_id
phone_number = update.message.text # now we got the phone number
name = context.user_data["name"] # we had the name , remember ?!
bot.send_message(chat_id , text = f"completed ! your name is {name} and your phone number is {phone_number}")
return ConversationHandler.END
def cancel(update: Update, context: CallbackContext):
chat_id = update.message.chat_id
bot.send_message(chat_id , text = "process canceled !")
return ConversationHandler.END
# ---------- conversation handler ---------
CH = ConversationHandler (entry_points = [CommandHandler("register", register)],
states = {ONE : [MessageHandler(Filters.text , got_name)],
TWO : [MessageHandler(Filters.text , got_phone_number]
},
fallbacks = [MessageHandler(Filters.regex('cancel'), cancel)],
allow-reentry = True)
# -------- add handler ---------
updater.dispatcher.add_handler(CH)
in the end , remember it's way better to write any function to do 1 task , not more !
I hope it helps you , have a nice day .