Jil Jung Juk
Jil Jung Juk

Reputation: 700

Telegram bot to wait for user reply

The code below is for a Telegram Bot which basically takes a person username and password and verifies it to provide his average expenditures.

The problem as we see is the bot waits for the user to send his username and password for 10 sec either waste of time (or) not sufficient time was given. How could I program such that the bot waits for user message and then executes the next lines ( wait till the trigger )

def highest(intent,chatid,text):
    seq=["What is your Username ?","Password?"]
    send_message(seq[0],chatid)
    time.sleep(6)
    name,chatid = reply_function()
    print name
    send_message(seq[1],chatid)
    time.sleep(6)
    pw,chatid = reply_function()
    print pw
    try:
        flag = obj.validate(name,pw)
        if flag=="Verified":
            for i in obj.avg_transactions():
                send_message(i,chatid)
        else:
            send_message("try again",chatid)
            highest(intent,chatid,text)
     except:
        send_message("try again",chatid)
        highest(intent,chatid,text)

Upvotes: 2

Views: 13749

Answers (2)

Thehackitect
Thehackitect

Reputation: 75

You can use the conversation Handler to solve this problem. All you need to do is to create a function that asks the question, return the state of the the next function and grab the reply from the new function in. Update.message.text

Upvotes: -2

anatol
anatol

Reputation: 1770

You should use ForceReply markup with your requests and check replies from user - when reply contains Username in reply_to_message field of the received Message then you should send a request for password etc.


Example (pseudocode):

// Asking user for username/password
Bot.SendChatAction(update.Message.Chat.Id, ChatAction.Typing);
Bot.SendTextMessage(update.Message.Chat.Id, "Type your username, please");

// Checking incoming messages for replies
if (update.Message.ReplyToMessage.Text.Contains("your username"))
{
    if (!IsValidUsername(update.Message.ReplyToMessage.Text)) return;
    SaveUsernameToDb(update.Message.Chat.Id, update.Message.ReplyToMessage.Text);
    Bot.SendChatAction(update.Message.Chat.Id, ChatAction.Typing);
    Bot.SendTextMessage(update.Message.Chat.Id, "Username has been successfully saved!");
}
else
{
    ...
}

By the way, asking for private data such as username/password in plain-text-chat is quiet unsafe and very bad practice.

Upvotes: 3

Related Questions