Twilio's Python WhatsApp API doesn't work with conditional flow statements based on responses

Viewed 134

I'm experimenting with Twilio's WhatsApp API with Python but the conditional flow doesn't work. When I enter the word 'office' after getting the response 'What would you like to print?', I don't get the expected response 'Opening...'. I'd require some help regarding this.

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()
1 Answers

Twilio developer evangelist here.

Each time a user sends your WhatsApp number a message you will get a new request to your webhook endpoint. The new response will have the user's new message in the Body parameter.

In your example code you are always working with one response, so the variables question and doc are the same.

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)

Instead of nesting your conditionals, you could flatten them like this:

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)

With the above code, if someone messages "print" your application will respond "What would you like to print?" and if they message "office" the application will respond with "Opening...".

If you want to get more into controlling the conversation you can store state in HTTP cookies. I recommend checking this article on creating SMS conversation in Python to learn about that in more depth.

Let me know if this helps at all.

Related