微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Twilio的Python WhatsApp API不适用于基于响应的条件流语句

如何解决Twilio的Python WhatsApp API不适用于基于响应的条件流语句

我正在尝试使用Python进行Twilio的WhatsApp API,但条件流程不起作用。当收到答复“您要打印什么?”后输入“办公室”一词时,没有得到预期的答复“正在营业...”。我需要有关此的一些帮助。

from twilio.rest import Client
from flask import Flask,request,redirect
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)
@app.route("/",methods=['GET','POST'])
def wa_print():
    """Respond to incoming messages with a simple text message."""
    question = request.values.get('Body')
    print(question)
    # Start our TwiML response
    resp = MessagingResponse()
    if (question == 'print'):
        resp.message('What would you like to print?')
        doc = request.values.get('Body')

        if (doc == 'office'):
            resp.message('opening...')

    return str(resp)


if __name__ == "__main__":
    app.run()

解决方法

这里是Twilio开发人员的传播者。

每次用户向您的WhatsApp号发送消息时,您都会向Webhook端点收到新请求。新的响应将在Body参数中包含用户的新消息。

在示例代码中,您始终使用一个响应,因此变量questiondoc相同。

def wa_print():
    """Respond to incoming messages with a simple text message."""
    question = request.values.get('Body')
    print(question)
    # Start our TwiML response
    resp = MessagingResponse()
    if (question == 'print'):
        resp.message('What would you like to print?')
        doc = request.values.get('Body')

        if (doc == 'office'):
            resp.message('Opening...')

    return str(resp)

您可以像这样嵌套条件,而不是嵌套条件:

def wa_print():
    """Respond to incoming messages with a simple text message."""
    question = request.values.get('Body')
    print(question)
    # Start our TwiML response
    resp = MessagingResponse()
    if (question == 'print'):
        resp.message('What would you like to print?')

    elif (question == 'office'):
        resp.message('Opening...')

    return str(resp)

使用上面的代码,如果有人向您发送“打印”消息,您的应用程序将响应“您要打印什么?”。并且如果他们提示“办公室”,则应用程序将以“正在打开...”作为响应。

如果您想进一步控制对话,可以将状态存储在HTTP cookie中。我建议查看creating SMS conversation in Python上的这篇文章,以更深入地了解这一点。

让我知道这是否有帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。