Skip to main content
 首页 » 编程设计

python之Telegram 机器人等待用户回复

2024年10月01日6rubylouvre

下面的代码适用于 Telegram Bot,它基本上需要一个人的用户名 和密码 并验证它以提供他的平均支出。

我们看到的问题是机器人等待用户发送他的用户名和密码 10 秒 要么浪费时间(或)没有提供足够的时间。我如何编程让机器人等待用户消息然后执行下一行(等待触发器)

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) 

请您参考如下方法:

你应该使用 ForceReply标记您的请求并检查来自用户的回复 - 当回复在收到的 Message 的 reply_to_message 字段中包含 Username 时那么你应该发送密码等请求。


示例(伪代码):

// 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 
{ 
    ... 
} 

顺便说一句,在纯文本聊天中询问用户名/密码等私有(private)数据是非常不安全的,也是非常糟糕的做法。