Search code examples
python-3.xtwiliowhatsapptwilio-api

nested if else in Twilio


I'm making an automated whatsapp reply bot using Twilio and python, however I am facing problems and am unable to used nested if else in it

from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

@app.route('/mybot', methods = ['POST'])

def mybot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()
    responded = False

    print(incoming_msg)
    if incoming_msg == "list of doctors":
        msg.body("We have Dr. Phil with us today")
        responded = True

    if "book appointment" in str.lower(incoming_msg) or "see a doctor" in str.lower(incoming_msg):
            msg.body("Which department would you like to visit?\nPress :-\n1 - General Surgery\n2 - Internal Medicine\n3 - Gynaecology\n4 - Obstetrics\n5 - Ophthalmology\n6 - Orthopaedics\n7 - Dermatology Venereology & Leprology\n8 - ENT\n9 - Paediatric")
            if (incoming_msg == "1" or "general surgery" in incoming_msg): # This statement gets ignored
                msg.body("General Surgery")
            responded = True

where if (incoming_msg == "1" or "general surgery" in incoming_msg): is the problem statement.

Is there any way to work this out?


Solution

  • In this case you can't nest them. Each answer by a user is a new SMS/WhatsApp message and will call the mybot() function/webhook again, hence in the second call you won't have book appointment or see a doctor in the incoming_msg but just a number or the name of the department.

    Try it like this:

    def mybot():
        incoming_msg = request.values.get('Body', '').lower()
        resp = MessagingResponse()
        msg = resp.message()
        responded = False
    
        if incoming_msg == "list of doctors":
            msg.body("We have Dr. Phil with us today")
            responded = True
    
        if "book appointment" in str.lower(incoming_msg) or "see a doctor" in str.lower(incoming_msg):
            msg.body("Which department would you like to visit?\nPress :-\n1 - General Surgery\n2 - Internal Medicine\n3 - Gynaecology\n4 - Obstetrics\n5 - Ophthalmology\n6 - Orthopaedics\n7 - Dermatology Venereology & Leprology\n8 - ENT\n9 - Paediatric")
            responded = True
    
        if incoming_msg == "1" or "general surgery" in incoming_msg:
            msg.body("General Surgery")
            responded = True
    
        [...]
    

    As long as all of your options/inputs are distinct this will work.