Telegram bot to wait for user reply

久未见 提交于 2019-12-08 01:44:55

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/44639923/telegram-bot-to-wait-for-user-reply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!