示例#1
0
def userdel():
    username = request.args.get('username', '')
    Flag = user.DelUser(username)
    if Flag:
        UserList = user.GetUser(gconf.UserFile)
        return render_template('users.html',
                               userlist=UserList,
                               color='green',
                               Flag=u'恭喜,用户%s删除成功' % (username))
    else:
        UserList = user.GetUser(gconf.UserFile)
        return render_template('users.html',
                               userlist=UserList,
                               color='red',
                               Flag=u'抱歉,用户%s删除失败' % (username))
示例#2
0
def update():
    params = request.args if request.method == 'GET' else request.form
    uid = params.get('uid', '')
    password = params.get('password', '')
    sex = params.get('sex', None)
    age = params.get('age', None)
    phone = params.get('phone', None)
    email = params.get('email', None)
    role = params.get('role', None)

    # 查询出数据,post和get方法共用
    sql = 'select * from user where id= %s' % uid
    rt_user = user.GetUser(sql)[0]

    if request.method == 'GET':
        return render_template('userupdate.html', user=rt_user)
    else:
        if password == '':
            return render_template('userupdate.html', user=rt_user, error=u'密码不能为空')
        args = (password,sex,age,phone,email,role,uid)
        print args
        if user.UserUpdate(args):
            return redirect('/user/list/')
        else:
            return render_template('userupdate.html', error=u'更新添加失败')
示例#3
0
def update():
    # 查询出数据,post和get方法共用
    params = request.args if request.method == 'GET' else request.form
    uid = params.get('uid', '')
    sql = 'select * from user where id= %s' % uid
    rt_user = user.GetUser(sql)[0]

    # 判断请求规则
    if request.method == 'GET':
        return render_template('userupdate.html', user=rt_user)
    else:
        # 获取前端通过POST传进来的数据,通过列表生成式处理成字典
        data = dict((k, v[0]) for k, v in dict(request.form).items())
        print data
        # 判断密码为空则提示错误
        if data['password'] == '':
            return render_template('userupdate.html',
                                   user=rt_user,
                                   error=u'密码不能为空')
        # 生成sql里需要的参数
        args = (data['password'], data['sex'], data['age'], data['phone'],
                data['email'], data['role'], data['uid'])
        print args
        # 执行更新动作
        if user.UserUpdate(args):
            return redirect('/user/list/')
        else:
            return render_template('userupdate.html',
                                   user=rt_user,
                                   error=u'更新失败')
示例#4
0
def useradd():
    params = request.args if request.method == 'GET' else request.form
    username, password, age = params.get('username', ''), params.get(
        'password', ''), params.get('age', '')
    Flag = user.JudgUser(username)
    print Flag
    if Flag:
        return render_template('createuser.html',
                               userexist=u'抱歉,用户%s已经存在' % (username))
    else:
        Flag = user.AddUser(username, password, age)
        if Flag:
            UserList = user.GetUser(gconf.UserFile)
            return render_template('users.html',
                                   userlist=UserList,
                                   color='green',
                                   Flag=u'恭喜,添加成功')
        else:
            return render_template('createuser.html',
                                   userexist=u'抱歉,用户%s添加失败' % (username))
示例#5
0
def userchange():
    params = request.args if request.method == 'GET' else request.form
    username, password, age = params.get('username', ''), params.get(
        'password', ''), params.get('age', '')
    Flag = user.ChangeUser(username, password, age)
    if Flag == 'samepassword':
        return render_template('modifyuser.html',
                               username=username,
                               password=password,
                               age=age,
                               samepassword=u'抱歉,用户%s修改后的密码不能和原密码相同' %
                               (username))
    elif Flag:
        UserList = user.GetUser(gconf.UserFile)
        return render_template('users.html',
                               userlist=UserList,
                               color='green',
                               Flag=u'恭喜,修改成功')
    else:
        return render_template('modifyuser.html',
                               error=u'抱歉,用户%s修改失败' % (username))
示例#6
0
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 myUser, myMovie

    if "object" in data:
        if data["object"] == "page":
            for entry in data["entry"]:
                for messaging_event in entry["messaging"]:
                    Domain_Whitelisting(myUser, "https://www.youtube.com")
                    Domain_Whitelisting(myUser, "https://m.youtube.com")
                    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"])
                            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]
                        subtitleBulk = messaging_event["postback"][
                            "payload"].split(":")[1]
                        payload = messaging_event["postback"]["payload"].split(
                            ":")[2]

                        if title == 'BusTickets':
                            myUser.stage = 'BusTickets'
                            user.UpdateUser(messaging_event["sender"]["id"],
                                            myUser)

                            message = payload
                            log("message : " + message)
                            send_message(myUser.id, message)
                        elif title == 'MovieTickets':
                            myUser.stage = 'MovieTickets'
                            user.UpdateUser(messaging_event["sender"]["id"],
                                            myUser)

                            if movie_tickets.CheckMyMovie(
                                    messaging_event["sender"]["id"]):
                                myMovie = movie_tickets.GetMyMovie(
                                    messaging_event["sender"]["id"])
                                log("MyMovie Found : " + str(myMovie.fbid) +
                                    " id : " + str(myMovie.id))
                            else:
                                myMovie = movie_tickets.CreateMyMovie(
                                    messaging_event["sender"]["id"])
                                log("MyMovie Created : " + str(myMovie.fbid) +
                                    " id : " + str(myMovie.id))

                            message = payload
                            log("message : " + message)
                            subtitle = subtitleBulk.split("%")[0]
                            selectedMovie = subtitleBulk.split("%")[1]
                            selectedTheater = subtitleBulk.split("%")[2]
                            selectedDate = subtitleBulk.split("%")[3]
                            selectedTime = subtitleBulk.split("%")[4]
                            if selectedMovie != 'NoMovie':
                                myMovie.movie = selectedMovie
                            if selectedTheater != 'NoTheater':
                                myMovie.theater = selectedTheater
                            if selectedDate != 'NoDate':
                                myMovie.date = selectedDate
                            if selectedTime != 'NoTime':
                                myMovie.time = selectedTime

                            movie_tickets.UpdateMyMovie(myMovie.id, myMovie)

                            if subtitle == 'SelectMovie':
                                #                               send_message(myUser.id, message)
                                ai = apiai.ApiAI(ClientAccessToken)
                                apiaiRequest = ai.text_request()
                                apiaiRequest.lang = 'en'  # optional, default value equal 'en'
                                apiaiRequest.query = "Purchase movie ticket"
                                apiaiResponse = apiaiRequest.getresponse()
                                apiaiData = json.loads(apiaiResponse.read())
                                log("api ai return data : " + str(apiaiData))
                                Api_ai_Extract_Response(apiaiData, myUser)
                            if subtitle == 'SelectTheater':
                                #                               send_message(myUser.id, message)
                                ai = apiai.ApiAI(ClientAccessToken)
                                apiaiRequest = ai.text_request()
                                apiaiRequest.lang = 'en'  # optional, default value equal 'en'
                                apiaiRequest.query = "I want to buy movie tickets for " + str(
                                    selectedMovie)
                                apiaiResponse = apiaiRequest.getresponse()
                                apiaiData = json.loads(apiaiResponse.read())
                                log("api ai return data : " + str(apiaiData))
                                Api_ai_Extract_Response(apiaiData, myUser)
                            if subtitle == 'SelectDate':
                                #                               send_message(myUser.id, message)
                                ai = apiai.ApiAI(ClientAccessToken)
                                apiaiRequest = ai.text_request()
                                apiaiRequest.lang = 'en'  # optional, default value equal 'en'
                                apiaiRequest.query = "Movie " + str(
                                    myMovie.movie) + " Theater " + str(
                                        myMovie.theater)
                                apiaiResponse = apiaiRequest.getresponse()
                                apiaiData = json.loads(apiaiResponse.read())
                                log("api ai return data : " + str(apiaiData))
                                Api_ai_Extract_Response(apiaiData, myUser)

                        elif title == 'ActDeactServices':
                            myUser.stage = 'ActDeactServices'
                            user.UpdateUser(messaging_event["sender"]["id"],
                                            myUser)

                            message = payload
                            log("message : " + message)
                            send_message(myUser.id, message)
#                            send_message_quick_location(myUser.id)

                    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"]

                        if message.get("text"):  # get message
                            message = message["text"]
                            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 message.upper() == "SUPPORTBOT" or message.upper() == "HI" or message.upper() == "HELLO":
#                                init_button_template(myUser)
                            if message.upper() == "DEV MYUSER":
                                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 TEST SQLCONNECT MLK":
                                psql.connect()
                            else:
                                ai = apiai.ApiAI(ClientAccessToken)
                                apiaiRequest = ai.text_request()
                                apiaiRequest.lang = 'en'  # optional, default value equal 'en'
                                apiaiRequest.query = message
                                apiaiResponse = apiaiRequest.getresponse()
                                apiaiData = json.loads(apiaiResponse.read())
                                log("api ai return data : " + str(apiaiData))
                                Api_ai_Extract_Response(apiaiData, myUser)

                        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
示例#7
0
def users():
    UserList = user.GetUser(gconf.UserFile)
    return render_template('users.html', userlist=UserList)
示例#8
0
def userlist():
    user_list = user.GetUser()
    return render_template('userlist.html',user_list=user_list)
示例#9
0
def userlist():
    sql = "select * from user"
    user_list = user.GetUser(sql)
    return render_template('userlist.html', user_list=user_list)
示例#10
0
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
示例#11
0
def users():
    if not 'username' in session:
        return render_template('login.html', error=u'请先登录!')
    else:
        UserList = user.GetUser(gconf.UserFile)
        return render_template('users.html', userlist=UserList)