Answer the question
In order to leave comments, you need to log in
How to make a telegram bot wait for a response from the user?
Hello, there was such a problem. I decided to write a simple telegram bot that sends weather updates to the user base. The problem is next! The user enters the command /weather and the bot asks the user if he wants to subscribe to the weather newsletter (yes/no). If the user answers yes, then the bot should ask for the user's city. At this moment, the bot should start waiting for a message from the user, and for any message it should make a request to the site with the weather and check the correctness of the entered city. It should do this until the user clicks cancel or until the correct city is entered.
Answer the question
In order to leave comments, you need to log in
You need to store a value for a specific user, which you will check for a new message from the user. For example: After the user is prompted to write his city, you can write in some storage \ cache - an object with the key chat_id and value. Further, with each new user message, we first check whether he entered the "/cancel"\"Cancel" command, if so, then we clean the object with the given chat_id. If not, then in the next check we try to get the value from the storage / cache. Found? write further code. Not found? check what command the user has entered.
You can get messages either through long poll (request /getUpdates of the bot) or through a webhook. The second option for simple bots without much load is redundant. So the script can be organized as a cycle: we execute the request, see if there are any new messages there - we process it.
If you use the popular telebot library, then you don’t even need to write a loop - just a “new message” event handler.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question