def webhook(): # endpoint for processing incoming messaging events data = request.get_json() log(data) # you may not want to log every incoming message in production, but it's good for testing if data["object"] == "page": for entry in data["entry"]: for messaging_event in entry["messaging"]: if messaging_event.get("postback"): # user clicked/tapped "postback" button in earlier message sender_id = messaging_event["sender"]["id"] # the facebook ID of the person sending you the message recipient_id = messaging_event["recipient"]["id"] message = messaging_event["postback"]["payload"] send_message(sender_id, message) elif messaging_event.get("message"): # someone sent us a message sender_id = messaging_event["sender"]["id"] # the facebook ID of the person sending you the message recipient_id = messaging_event["recipient"]["id"] # the recipient's ID, which should be your page's facebook ID # sort different types of messages message = messaging_event["message"] gender = 'male' age = 20 sid = None if message.get("text"): # get message message = message["text"] if message == "DoctorBot": init_buttom_template(sender_id) elif string.find(message,"headache") is not -1: sid = diagnose.searchSymptom("headache", sender_id) send_message(sender_id, "Give me a sec!") elif string.find(message,"fever") is not -1: sid= diagnose.searchSymptom("fever", sender_id) send_message(sender_id, "Give me a sec!") elif string.find(message,"knee") is not -1: sid = diagnose.searchSymptom("knee pain", sender_id) send_message(sender_id, "Give me a sec!") if symptom is not None: if string.find(message,str(diagnosis.question.items[0]["choices"][0]["label"])) is not -1: diagnosis = diagnose.improve_diagnosis(diagnosis,sender_id,symptom,str(diagnosis.question.items[0]["choices"][0]["id"])) elif string.find(message,str(diagnosis.question.items[0]["choices"][1]["label"])) is not -1: diagnosis = diagnose.improve_diagnosis(diagnosis,sender_id,symptom,str(diagnosis.question.items[0]["choices"][1]["id"])) else: diagnosis = diagnose.improve_diagnosis(diagnosis,sender_id,symptom,str(diagnosis.question.items[0]["choices"][2]["id"])) if diagnosis.conditions[0]["probability"] > 0.25: send_message(sender_id, "I suspect "+str(diagnosis.conditions[0]["name"])+" with a probability of "+str(diagnosis.conditions[0]["probability"])) send_message(sender_id, "Please send me your location so I can find a doctor near you") else: symptom = str(diagnosis.question.items[0]["id"]) response = str(diagnosis.question.text) for x in diagnosis.question.items[0]["choices"]: response = response + "\n - " + str(x["label"]) send_message(sender_id, response) global diagnosis, symptom if diagnosis is None and sid is not None: diagnosis = diagnose.init_diagnose(sid,age,gender,sender_id) symptom = str(diagnosis.question.items[0]["id"]) send_message(sender_id, str(diagnosis.question.text)) if message.get("text"): # get message message = message["text"] if symptom_mode: symptoms = 3 print symptoms # if symptom == None # symptom = apiai_symptom(message) # assuming user put symptom # elif elif alert_mode: pass else: if message == "Hi": init_buttom_template(sender_id) else: send_message(sender_id, "Say 'Hi' to the DoctorBot to get started!") elif message.get("attachments"): # get attachment attach = message["attachments"][0] # loop over attachments? if attach["type"] == "location": latitude = attach["payload"]["coordinates"]["lat"] longitude = attach["payload"]["coordinates"]["long"] clinic_type = "hospital" clinicsURL = "https://api.foursquare.com/v2/venues/search?ll="+str(latitude)+","+str(longitude)+"&radius=15000&query="+clinic_type+"&client_id=1TCDH3ZYXC3NYNCRVL1RL4WEGDP4CHZSLPMKGCBIHAYYVJWA&client_secret=VASKTPATQLSPXIFJZQ0EZ4GDH2QAZU1QGEEZ4YDCKYA11V2J&v=20160917" r = urllib.urlopen(clinicsURL) data = json.loads(r.read()) hospitals = [] latitudes = [] longitudes = [] venues = data["response"]["venues"] if len(venues) > 3: maxi = 3 else: maxi = len(venues) for x in range(0, maxi): hospitals.append(venues[x]["name"]) send_message(sender_id, "Option #"+str(x+1)+": "+venues[x]["name"]) latitudes.append(venues[x]["location"]["lat"]) longitudes.append(venues[x]["location"]["lng"]) message = "Location: " + str(latitude) + ", " + str(longitude) mapurl = "https://maps.googleapis.com/maps/api/staticmap?center="+str(latitude)+","+str(longitude)+"&markers=color:green%7C"+str(latitude)+","+str(longitude)+"&key=AIzaSyB1CFi3ImDxL21QTu7EN2e-RvP2LPAJgiY&size=800x800" for y in range(0,maxi): mapurl = mapurl +"&markers=color:red%7Clabel:H%7C"+str(latitudes[y])+","+str(longitudes[y]) send_message(sender_id, "And here they are on a map :)") #sendImage send_message(sender_id, mapurl) elif attach["type"] == "image": image_url = attach["payload"]["url"] message = "Image url: " + image_url send_message(sender_id, message) if messaging_event.get("delivery"): # delivery confirmation pass if messaging_event.get("optin"): # optin confirmation pass return "ok", 200
def webhook(): # endpoint for processing incoming messaging events data = request.get_json() log( "%%%% New Message %%%% " + str(data) ) # you may not want to log every incoming message in production, but it's good for testing global myUsers, myUser if "object" in data: if data["object"] == "page": for entry in data["entry"]: for messaging_event in entry["messaging"]: log("myUsers Lenght : " + str(len(myUsers))) if messaging_event.get("postback") or messaging_event.get( "message"): if user.CheckUser(messaging_event["sender"]["id"]): myUser = user.GetUser( messaging_event["sender"]["id"]) log("User Found : " + str(myUser.id)) else: myUser = user.CreateUser( messaging_event["sender"]["id"]) myUsers.append(myUser) log("User Created : " + str(myUser.id)) if messaging_event.get( "postback" ): # user clicked/tapped "postback" button in earlier message recipient_id = messaging_event["recipient"]["id"] log("recipient_id : " + recipient_id) title = messaging_event["postback"]["payload"].split( ":")[0] payload = messaging_event["postback"]["payload"].split( ":")[1] if title == 'SymptomChecker' or title == 'HealthAlerts': message = payload log("message : " + message) send_message(myUser.id, message) elif title == 'TonicDiscountsMain': message = payload log("message : " + message) send_message(myUser.id, message) send_message_quick_location(myUser.id) elif title == 'TonicDiscounts': message = payload log("message : " + message) send_message(myUser.id, message) elif messaging_event.get( "message"): # someone sent us a message recipient_id = messaging_event["recipient"][ "id"] # the recipient's ID, which should be your page's facebook ID # sort different types of messages message = messaging_event["message"] sid = None if message.get("text"): # get message message = message["text"] if message.upper() == "DOCTORBOT" or message.upper( ) == "HI" or message.upper() == "HELLO": myUser.symptom = 'empty' myUser.diagnosis = 'empty' myUser.question_count = 0 if psql.update_user( messaging_event["sender"]["id"], myUser) == 0: log("Error : User not found for update id. : " + str(messaging_event["sender"]["id"])) else: log("Success : User updated. id : " + str(messaging_event["sender"]["id"])) init_buttom_template(myUser) elif message.upper() == "DEV MYUSER": log("Dev Test myUsers Lenght : " + str(len(myUsers))) for i in range(len(myUsers)): log( str(i) + " - " + str(myUsers[i].first_name)) if user.CheckUser( messaging_event["sender"]["id"]): devTestUser = user.GetUser( messaging_event["sender"]["id"]) log("Dev Test User Found id : " + str(devTestUser.id)) log("Dev Test User Found symptom : " + str(devTestUser.symptom)) log("Dev Test User Found gender : " + str(devTestUser.gender)) log("Dev Test User Found diagnosis : " + str(devTestUser.diagnosis)) log("Dev Test User Found first_name : " + str(devTestUser.first_name)) log("Dev Test User Found last_name : " + str(devTestUser.last_name)) log("Dev Test User Found profile_pic : " + str(devTestUser.profile_pic)) else: log("Dev Test User Not Found id : " + str(messaging_event["sender"]["id"])) elif message.upper() == "DEV CREATE TABLE MLK": psql.create_tables() elif message.upper() == "DEV DROP TABLE MLK": psql.drop_tables() elif message.upper() == "DEV TEST SQLCONNECT MLK": psql.connect() elif myUser.symptom != 'empty' and myUser.diagnosis != 'empty': try: if string.find( message.upper(), str(myUser.diagnosis.question. items[0]["choices"][0] ["label"]).upper()) is not -1: myUser.diagnosis = diagnose.improve_diagnosis( myUser.diagnosis, myUser.id, myUser.symptom, str(myUser.diagnosis.question. items[0]["choices"][0]["id"])) elif string.find( message.upper(), str(myUser.diagnosis.question. items[0]["choices"][1] ["label"]).upper()) is not -1: myUser.diagnosis = diagnose.improve_diagnosis( myUser.diagnosis, myUser.id, myUser.symptom, str(myUser.diagnosis.question. items[0]["choices"][1]["id"])) elif string.find( message.upper(), str(myUser.diagnosis.question. items[0]["choices"][2] ["label"]).upper()) is not -1: myUser.diagnosis = diagnose.improve_diagnosis( myUser.diagnosis, myUser.id, myUser.symptom, str(myUser.diagnosis.question. items[0]["choices"][2]["id"])) else: send_message( myUser.id, "Sorry, I didn't get that. Please enter your answer again." ) if psql.update_user( messaging_event["sender"]["id"], myUser) == 0: log("Error : User not found for update. id : " + str(messaging_event["sender"] ["id"])) else: log("Success : User updated. id : " + str(messaging_event["sender"] ["id"])) if myUser.diagnosis.conditions[0][ "probability"] > 0.25 and myUser.question_count > 3: send_message( myUser.id, "I suspect " + str(myUser.diagnosis.conditions[0] ["name"]) + " with a probability of " + str(myUser.diagnosis.conditions[0] ["probability"])) send_message( myUser.id, "Please send me your location so I can find a doctor near you" ) send_message_quick_location(myUser.id) myUser.symptom = 'empty' myUser.diagnosis = 'empty' myUser.question_count = 0 if psql.update_user( messaging_event["sender"] ["id"], myUser) == 0: log("Error : User not found for update. id : " + str(messaging_event["sender"] ["id"])) else: log("Success : User updated. id : " + str(messaging_event["sender"] ["id"])) # log("myUsers Lenght : " + str(len(myUsers))) # log("Removing user : "******"myUsers Lenght : " + str(len(myUsers))) myUser = user.MyUser() else: myUser.symptom = str( myUser.diagnosis.question.items[0] ["id"]) response = str( myUser.diagnosis.question.text. encode('utf8')) if "image_url" in myUser.diagnosis.question.extras: send_message_image( myUser.id, myUser.diagnosis. question.extras["image_url"]) if str(myUser.diagnosis.question.type ) == "group_single" or str( myUser.diagnosis.question. type) == "group_multiple": response = response + "\n " + str( myUser.diagnosis.question. items[0]["name"].encode( 'utf8')) + "? " for x in myUser.diagnosis.question.items[ 0]["choices"]: response = response + "\n - " + str( x["label"]) myUser.question_count = myUser.question_count + 1 send_message(myUser.id, response) if psql.update_user( messaging_event["sender"] ["id"], myUser) == 0: log("Error : User not found for update. id : " + str(messaging_event["sender"] ["id"])) else: log("Success : User updated. id : " + str(messaging_event["sender"] ["id"])) except (RuntimeError, TypeError, NameError, IndexError): print "Unexpected error:", sys.exc_info( )[0] # log("-----myUser.diagnosis------ " + str(myUser.diagnosis)) elif myUser.diagnosis == 'empty': search_result = search.search_symtom_limit( message, 5) log("----------- " + str(search_result)) if len(search_result) > 0: send_message(myUser.id, "Give me a sec!") sid = str(search_result[0]["id"]) log("************ " + sid) myUser.diagnosis = diagnose.init_diagnose( sid, myUser.age, myUser.gender, myUser.id) log("-----myUser.diagnosis First Time------ " + str(myUser.diagnosis)) myUser.symptom = str( myUser.diagnosis.question.items[0] ["id"]) response = str( myUser.diagnosis.question.text.encode( 'utf8')) if "image_url" in myUser.diagnosis.question.extras: send_message_image( myUser.id, myUser.diagnosis. question.extras["image_url"]) if str(myUser.diagnosis.question.type ) == "group_single" or str( myUser.diagnosis.question.type ) == "group_multiple": response = response + "\n " + str( myUser.diagnosis.question.items[0] ["name"].encode('utf8')) + "? " for x in myUser.diagnosis.question.items[ 0]["choices"]: response = response + "\n - " + str( x["label"]) myUser.question_count = myUser.question_count + 1 send_message(myUser.id, response) if psql.update_user( messaging_event["sender"]["id"], myUser) == 0: log("Error : User not found for update. id : " + str(messaging_event["sender"] ["id"])) else: log("Success : User updated. id : " + str(messaging_event["sender"] ["id"])) else: send_message( myUser.id, "Sorry, Server appears to be busy at the moment. Please try again later." ) # if message.get("text"): # get message # message = message["text"] # if symptom_mode: # symptoms = 3 # print symptoms # # if myUser.symptom == None # # myUser.symptom = apiai_symptom(message) # assuming user put symptom # # elif # elif alert_mode: # pass # else: # if message == "Hi": # init_buttom_template(myUser.id) # else: # send_message(myUser.id, "Say 'Hi' to the DoctorBot to get started!") elif message.get("attachments"): # get attachment attach = message["attachments"][ 0] # loop over attachments? if attach["type"] == "location": latitude = attach["payload"]["coordinates"][ "lat"] longitude = attach["payload"]["coordinates"][ "long"] revers_geo_code_url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + str( latitude) + "," + str( longitude ) + "&key=" + googleApiKey + "" r = urllib.urlopen(revers_geo_code_url) rdata = r.read() # log("revers_geo_code_url data : ") # log(rdata) ddata = json.loads(rdata) hospitals = [] for addrs_com in ddata["results"][0][ "address_components"]: hospitals.extend( psql.get_hospitals( addrs_com["long_name"])) log(len(hospitals)) maxi = 0 if len(hospitals) > 10: maxi = 10 else: maxi = len(hospitals) hospitals_distance_duration_latitude_longitude = [] for x in range(0, maxi): log("hospitals raw data : " + str(x) + " : " + str(hospitals[x])) distance_matrix_url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + str( latitude) + "," + str( longitude ) + "&destinations=" + str( hospitals[x][4]) + "," + str( hospitals[x][5] ) + "&key=" + googleApiKey + "" log(distance_matrix_url) r = urllib.urlopen(distance_matrix_url) rdata = r.read() log("distance_matrix_url data : ") log(rdata) ddata = json.loads(rdata) if ddata["rows"][0]["elements"][0][ "status"] == 'OK': if ddata["rows"][0]["elements"][0][ "distance"]["value"] < 10000: hospitals_distance_duration_latitude_longitude.append( [ hospitals[x], ddata["rows"] [0]["elements"][0] ["distance"]["text"], ddata["rows"][0] ["elements"][0]["duration"] ["text"], hospitals[x][4], hospitals[x][5], ddata[ "destination_addresses"] ]) # hospitals_distance_duration_latitude_longitude = sorted(hospitals_distance_duration_latitude_longitude, key=lambda hospital: hospitals_distance_duration_latitude_longitude[2]) maxi = 0 if len(hospitals_distance_duration_latitude_longitude ) > 3: maxi = 3 else: maxi = len( hospitals_distance_duration_latitude_longitude ) for x in range(0, maxi): hospital_buttom_template( messaging_event["sender"]["id"], hospitals_distance_duration_latitude_longitude[ x]) map_template( messaging_event["sender"]["id"], hospitals_distance_duration_latitude_longitude[ x][0][0], hospitals_distance_duration_latitude_longitude[ x][3], hospitals_distance_duration_latitude_longitude[ x][4], hospitals_distance_duration_latitude_longitude[ x][5]) if len(hospitals_distance_duration_latitude_longitude ) > 0: log("Telenor hospitals not found") else: clinic_type = "hospital" clinicsURL = "https://api.foursquare.com/v2/venues/search?ll=" + str( latitude ) + "," + str( longitude ) + "&radius=15000&query=" + clinic_type + "&client_id=1TCDH3ZYXC3NYNCRVL1RL4WEGDP4CHZSLPMKGCBIHAYYVJWA&client_secret=VASKTPATQLSPXIFJZQ0EZ4GDH2QAZU1QGEEZ4YDCKYA11V2J&v=20160917" r = urllib.urlopen(clinicsURL) hospitals = [] latitudes = [] longitudes = [] data = json.loads(r.read()) venues = data["response"]["venues"] maxi = 0 if len(venues) > 4: maxi = 4 else: maxi = len(venues) for x in range(0, maxi): hospitals.append(venues[x]["name"]) send_message( myUser.id, "Option #" + str(x + 1) + ": " + venues[x]["name"].encode('utf8')) latitudes.append( venues[x]["location"]["lat"]) longitudes.append( venues[x]["location"]["lng"]) message = "Location: " + str( latitude) + ", " + str(longitude) mapurl = "https://maps.googleapis.com/maps/api/staticmap?center=" + str( latitude ) + "," + str( longitude ) + "&markers=color:green%7C" + str( latitude ) + "," + str( longitude ) + "&key=" + googleApiKey + "&size=800x800" for y in range(0, maxi): mapurl = mapurl + "&markers=color:red%7Clabel:H%7C" + str( latitudes[y]) + "," + str( longitudes[y]) send_message( myUser.id, "And here they are on a map :)") #sendImage send_message_image(myUser.id, mapurl) elif attach["type"] == "image": image_url = attach["payload"]["url"] message = image_url #.replace("/p100x100/","/p200x200/") send_message_image(myUser.id, message) # if messaging_event.get("delivery"): # delivery confirmation # pass # if messaging_event.get("optin"): # optin confirmation # pass log("********Symtom End******** " + str(myUser.symptom)) log("-----myUser.diagnosis End------ " + str(myUser.diagnosis)) log("******** return 'OK', 200 ******** ") return "OK", 200