Slack bot不会在while循环中暂停而是在true语句时重新启动

时间:2017-05-24 21:27:00

标签: python python-3.x slack-api slack

我正在研究机器人的松懈。我的问题是,我希望当一个人用某些文本(@bot日志)ping机器人它要求一个电子邮件地址,然后重复电子邮件并要求确认。

这一切都有效,我的麻烦开始了。当您回复确认信息时,它会重复您刚刚说的内容,并且不会继续说“获取您的用户名”。

if command.startswith(LOG):
    slack_client.rtm_send_message(channel, "Please input your username:")
    while True:
        for slack_message in slack_client.rtm_read():

            message = slack_message.get("text")
            user = slack_message.get("user")
            if not message or not user:
                continue
            slack_client.rtm_send_message(channel, "You Wrote :  " + message +  "\n is that your correct email?")
    else:
        print("That didnt work")
            #break  ##ask for confirmation, maybe the text in this line can reference in a different way
            #while True:
        respond = slack_message.get("text")
        while respond is 'yes' or 'Yes':##would this to true already, push in regex
                continue
        slack_client.rtm_send_message(channel, "Got it, your username is :" + message)#possibly grabbing newest text and not variable of message
                #if respond != 'yes' or 'Yes':#push from regex above
                    #slack_client.rtm_send_message(channel, "sorry!")                   
        time.sleep(.1)

1 个答案:

答案 0 :(得分:0)

while True在循环中被无限期执行;你必须使用breakreturn以某种方式退出它。但breakreturn都会在else之后忽略您的while,因此您必须显着重构您的代码。像这样:

while True:
    for slack_message in slack_client.rtm_read():
        message = slack_message.get("text")
        user = slack_message.get("user")
        if not message or not user:
            continue
        slack_client.rtm_send_message(…)
        break
# and no else here
print(…)

我认为你根本不需要while True。让我用这种方式重写代码:

while True:
    command = ??? # slack_client.rtm_read() perhaps?
    if command.startswith(LOG):
        slack_client.rtm_send_message(channel, "Please input your username:")
        for slack_message in slack_client.rtm_read():
            message = slack_message.get("text")
            user = slack_message.get("user")
            if not message or not user:
                continue
            slack_client.rtm_send_message(channel, "You Wrote :  " + message +  "\n is that your correct email?")

        while True:
            respond = slack_message.get("text")
            if respond is 'yes' or 'Yes':##would this to true already, push in regex
                continue
            break
        slack_client.rtm_send_message(channel, "Got it, your username is :" + message)#possibly grabbing newest text and not variable of message