示例#1
0
def request_uber(code, state):
    """Request an Uber."""

    if "NO_DEBUG" not in os.environ:
        redirect_url = "http://0.0.0.0:5000/callback?code=%s&state=%s" % (
            code, state)

        uber_session = uber_auth_flow.get_session(redirect_url)
        uber_ride_client = UberRidesClient(uber_session, sandbox_mode=True)

        credentials = uber_session.oauth2credential
        access_token = credentials.access_token

        uber_ride_client.cancel_current_ride()

        response = uber_ride_client.request_ride(
            product_id=session["uber_ride_type"],
            start_latitude=session["origin_lat"],
            start_longitude=session["origin_lng"],
            end_latitude=session["dest_lat"],
            end_longitude=session["dest_lng"])

        ride_details = response.json

        print response.status_code

    time = uber_client.get_pickup_time_estimates(
        session["origin_lat"],
        session["origin_lng"],
        product_id=session["uber_ride_type"])

    eta = time.json
    minutes = eta["times"][0]["estimate"] / 60

    session["ride_type"] = "Uber"

    get_time(minutes)
示例#2
0
    def __uber_action(self, nlu_entities=None):
        uber = None
        
                
        if nlu_entities is not None:
            if 'location' in nlu_entities:
                 entities3=nlu_entities['search_query'][0]["value"]
                 entities1=nlu_entities['location'][0]["value"]
                 entities2=nlu_entities['location'][1]["value"]
                 print entities3
                 print entities1
                 print entities2

        if entities1 and entities2  is not None:
            response= requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=' %entities1) #add key
            resp_json_payload = response.json()

            lat1=(resp_json_payload['results'][0]['geometry']['location']['lat'])
            lng1=(resp_json_payload['results'][0]['geometry']['location']['lng'])

            response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=' %entities2)  #add key

            resp_json_payload = response.json()
            
            lat2=(resp_json_payload['results'][0]['geometry']['location']['lat'])
            lng2=(resp_json_payload['results'][0]['geometry']['location']['lng'])

            oauth2credential = OAuth2Credential(
            client_id='', #add client id
            access_token='', #get access token
            expires_in_seconds= '2592000',
            scopes='all_trips delivery history history_lite places profile request request_receipt ride_widgets',
            grant_type='authorization_code',
            redirect_url='', #add redirect_url
            client_secret='', #add client secret
            refresh_token='', # add refresh token
        )

            session = Session(oauth2credential=oauth2credential)
            client = UberRidesClient(session, sandbox_mode=True)

            print (client)

            response = client.get_products(lat1, lng1)
            credentials = session.oauth2credential
            #print (response)
            response = client.get_user_profile()
            profile = response.json
            
            # response_uber = client.get_price_estimates(
            #     start_latitude=lat1,
            #     start_longitude=lng1,
            #     end_latitude=lat2,
            #     end_longitude=lng2,
            #     seat_count=1
            # )

            # estimate = response_uber.json.get('prices')

            # print estimate[0]['high_estimate']
            # print estimate[0]['low_estimate']
            # print estimate[0]['localized_display_name']
            # print estimate[0]['currency_code']
            # currency = estimate[0]['currency_code']
            # hi_est =  str(estimate[0]['high_estimate']) + str(estimate[0]['currency_code'])
            # low_est =  str(estimate[0]['low_estimate']) + str(estimate[0]['currency_code'])
            # type_cab =  estimate[0]['localized_display_name']
             

            # print estimate[0]

            response = client.get_products(lat1, lng1)
            products = response.json.get('products')
            #print(products)
            if entities3 == 'Uber go':
                for i in range(1,5):
                    if products[i]['display_name']=='uberGO':
                        product_id = products[i].get('product_id')
                        type_cab = products[i].get('display_name')
            elif entities3 == 'Uber pool':
                for i in range(1,5):
                    if products[i]['display_name']=='POOL':
                        product_id = products[i].get('product_id')
                        type_cab = products[i].get('display_name')
            else:
                product_id = products[0].get('product_id')
                type_cab = products[0].get('display_name')

            

            estimate = client.estimate_ride(
                product_id=product_id,
                start_latitude=lat1,
                start_longitude=lng1,
                end_latitude=lat2,
                end_longitude=lng2,
                seat_count=1
            )
            fare = estimate.json.get('fare') 
            bas = fare['display'] 
            client.cancel_current_ride()
            response = client.request_ride(
             product_id=product_id,
             start_latitude=lat1,
             start_longitude=lng1,
             end_latitude=lat2,
             end_longitude=lng2,
             seat_count=1,
             fare_id=fare['fare_id']
            )  

            request = response.json
            print request
            request_id = request.get('request_id')
            url = 'https://sandbox-api.uber.com/v1.2/sandbox/requests/' + request_id
            ur = 'https://sandbox-api.uber.com/v1.2/requests/' + request_id + '/map'

            token = "" #insert token

            data = {
                "status": "accepted"

                }

            headers = {'Authorization': 'Bearer ' + token, "Content-Type": "application/json"}

#Call REST API
            respons = requests.put(url, data=json.dumps(data), headers=headers)
            respon = requests.get(ur, headers=headers)
            response = client.get_ride_details(request_id)
            ride = response.json
            print ride

            status = ride.get('status')
            dri_name = ride.get('driver').get('name')
            dri_pic = ride.get('driver').get('picture_url')

            eta = ride.get('destination').get('eta')   
            car_pix = ride.get('vehicle').get('picture_url')

            
            # product_name1 = products[3]['display_name'] #GO
            # product_nam2 = products[2]['display_name'] #POOL

            uber_action = "Sure. Booking your uber from %s to %s. Your cab type is %s and estimated time of arrival is %s and fare will be approx %s" % (entities1, entities2, type_cab, eta, bas)
            cab_data = {"cabtype": type_cab, 'maxfare': bas, "minfare": eta, 'to': entities2, 'from': entities1, 'status':status, 'driver': dri_name, 'pic': dri_pic, 'car': car_pix, 'map':ur}
            #print cab_data

            requests.post("http://localhost:8080/cab", data=json.dumps(cab_data))
            self.speech.synthesize_text(uber_action)
            
           
        else:
            self.__text_action("I'm sorry, I don't think that their is any cab available between these two locations.")                
示例#3
0
class Uber_api(object):
    def __init__(self):
        self.url, self.auth_flow = get_auth_url()

    def get_AuthUrl(self):
        return self.url

    def get_AuthCredentials(self, red_url, cred):
        if red_url:
            session = self.auth_flow.get_session(red_url)
            self.client = UberRidesClient(session, sandbox_mode=False)
            cred = session.oauth2credential
            return cred
        else:
            session = Session(oauth2credential=cred)
            self.client = UberRidesClient(session, sandbox_mode=False)

    def user_profile(self):

        reponse = self.client.get_user_profile()
        profile = reponse.json

        first_name = profile.get('first_name')
        last_name = profile.get('last_name')
        email = profile.get('email')

        return first_name, last_name, email

    def user_history(self):

        reponse = self.client.get_user_activity()
        history = reponse.json

        return history

    def get_products(self, lat=37.77, lng=-122.41):

        response = self.client.get_products(lat, lng).json
        #self.product_id = pdct[0].get('product_id')

        return response

    def get_estimate_pricess(self,
                             start_latitude=37.77,
                             start_longitude=-122.41,
                             end_latitude=37.79,
                             end_longitude=-122.41):

        res = self.client.get_price_estimates(start_latitude=start_latitude,
                                              start_longitude=start_longitude,
                                              end_latitude=end_latitude,
                                              end_longitude=end_longitude).json

        return res

    def get_estimate_time(self,
                          start_latitude=37.77,
                          start_longitude=-122.41,
                          product_id='57c0ff4e-1493-4ef9-a4df-6b961525cf92'):

        res = self.client.get_pickup_time_estimates(
            start_latitude=start_latitude,
            start_longitude=start_longitude,
            product_id=product_id).json

        return res

    def get_estimate_price(self,
                           st_lat=37.77,
                           st_lng=-122.41,
                           dt_lat=37.79,
                           dt_lng=-122.41,
                           seat_count=2,
                           product_id='a1111c8c-c720-46c3-8534-2fcdd730040d'):

        estimate = self.client.estimate_ride(product_id=product_id,
                                             start_latitude=st_lat,
                                             start_longitude=st_lng,
                                             end_latitude=dt_lat,
                                             end_longitude=dt_lng,
                                             seat_count=seat_count)
        est = estimate.json.get('fare')
        #self.fare_id = est['fare_id']

        return est

    def request_ride(self,
                     st_lat=37.77,
                     st_lng=-122.41,
                     dt_lat=37.79,
                     dt_lng=-122.41,
                     seat_count=2,
                     prod_id='',
                     fare_id=''):

        response = self.client.request_ride(product_id=prod_id,
                                            start_latitude=st_lat,
                                            start_longitude=st_lng,
                                            end_latitude=dt_lat,
                                            end_longitude=dt_lng,
                                            seat_count=seat_count,
                                            fare_id=fare_id)

        req = response.json
        #self.request_id = req.get('request_id')

        return req

    def riders_details(self, req_id="221448y7e32ye"):
        res = self.client.get_ride_details(req_id)
        ride = res.json

        return ride

    def process_request(self, req_id):
        status = 'accepted'
        self.client.update_sandbox_ride(req_id, status)
        #status = ['in_progress','accepted','completed']
#
#        for i in range(len(status)):
#            self.client.update_sandbox_ride(req_id,status[i])
#            time.sleep(15)

    def cancel_current_ride(self):
        res = self.client.cancel_current_ride()

        return res.json

    def cancel_ride(self, req_id):
        res = self.client.cancel_ride(req_id)

        return res.json
示例#4
0
    def __uber_action(self, nlu_entities=None):
        uber = None

        if nlu_entities is not None:
            if 'location' in nlu_entities:
                entities3 = nlu_entities['search_query'][0]["value"]
                entities1 = nlu_entities['location'][0]["value"]
                entities2 = nlu_entities['location'][1]["value"]
                print(entities3)
                print(entities1)
                print(entities2)

        if entities1 and entities2 is not None:
            response = requests.get(
                'https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyAx_nPgGLpiiak3Ey0YgDaJjoqlcjZko1A'
                % entities1)  # add key
            resp_json_payload = response.json()

            lat1 = (
                resp_json_payload['results'][0]['geometry']['location']['lat'])
            lng1 = (
                resp_json_payload['results'][0]['geometry']['location']['lng'])

            response = requests.get(
                'https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyAx_nPgGLpiiak3Ey0YgDaJjoqlcjZko1A'
                % entities2)  # add key

            resp_json_payload = response.json()

            lat2 = (
                resp_json_payload['results'][0]['geometry']['location']['lat'])
            lng2 = (
                resp_json_payload['results'][0]['geometry']['location']['lng'])

            oauth2credential = OAuth2Credential(
                client_id='FxkO4ImvByXu-7Dm1vYMHcKIt3C-3-LX ',  # add client id
                access_token=
                'JA.   -HsSUvO2XciOsCC3M25dwxYZTxyr4T9WKRKW8SawMVLucIKNmSZSZtvuE2LUMfb_ykrWxDAAAAIhIo1wfiuri3URzNyQAAABiMGQ4NTgwMy0zOGEwLTQyYjMtODA2ZS03YTRjZjhlMTk2ZWU',  # get access token
                expires_in_seconds='2592000',
                scopes=
                'all_trips delivery history history_lite places profile request request_receipt ride_widgets',
                grant_type='authorization_code',
                redirect_url=
                'http://localhost:8080/redirect_uri',  # add redirect_url
                client_secret=
                'hAjOfJ-OPiQ3dntDT9KtiLxwitcXrxu8-pNPRuzP',  # add client secret
                refresh_token='',  # add refresh token
            )

            from uber_rides.auth import AuthorizationCodeGrant
            redirect_url = 'https://localhost:8080/redirect_uri',  # add redirect_url

            auth_flow = AuthorizationCodeGrant(
                client_id='FxkO4ImvByXu-7Dm1vYMHcKIt3C-3-LX ',  # add client id
                # access_token='JA.VUNmGAAAAAAAEgASAAAABwAIAAwAAAAAAAAAEgAAAAAAAAG8AAAAFAAAAAAADgAQAAQAAAAIAAwAAAAOAAAAkAAAABwAAAAEAAAAEAAAAKJLlVbnq3rq5cidLOUCeZZsAAAAxfnlfHgkh1D_dT92vApueOOrPLV79RicmAdIVBZXV4jUZfneV1jq3pcF2Xwdd5AIaCpvZxVY32u-HsSUvO2XciOsCC3M25dwxYZTxyr4T9WKRKW8SawMVLucIKNmSZSZtvuE2LUMfb_ykrWxDAAAAIhIo1wfiuri3URzNyQAAABiMGQ4NTgwMy0zOGEwLTQyYjMtODA2ZS03YTRjZjhlMTk2ZWU',  # get access token
                # expires_in_seconds='2592000',
                scopes=
                'all_trips delivery history history_lite places profile request request_receipt ride_widgets',
                # scopes='ride_widgets',
                # grant_type='authorization_code',
                redirect_url=
                'https://localhost:8080/redirect_uri',  # add redirect_url
                client_secret=
                'hAjOfJ-OPiQ3dntDT9KtiLxwitcXrxu8-pNPRuzP',  # add client secret
                # refresh_token='',  # add refresh token
            )
            redirect_url = 'https://localhost:8080/redirect_uri',  # add redirect_url

            auth_url = auth_flow.get_authorization_url()
            #session = auth_flow.get_session(redirect_url)

            session = Session(oauth2credential=oauth2credential)
            print(session)
            client = UberRidesClient(session, sandbox_mode=True)

            print(client)

            response = client.get_products(lat1, lng1)
            credentials = session.oauth2credential
            print(response)
            response = client.get_user_profile()
            profile = response.json
            print(profile)
            # response_uber = client.get_price_estimates(
            #     start_latitude=lat1,
            #     start_longitude=lng1,
            #     end_latitude=lat2,
            #     end_longitude=lng2,
            #     seat_count=1
            # )

            # estimate = response_uber.json.get('prices')

            # print estimate[0]['high_estimate']
            # print estimate[0]['low_estimate']
            # print estimate[0]['localized_display_name']
            # print estimate[0]['currency_code']
            # currency = estimate[0]['currency_code']
            # hi_est =  str(estimate[0]['high_estimate']) + str(estimate[0]['currency_code'])
            # low_est =  str(estimate[0]['low_estimate']) + str(estimate[0]['currency_code'])
            # type_cab =  estimate[0]['localized_display_name']

            # print estimate[0]

            response = client.get_products(lat1, lng1)
            products = response.json.get('products')
            # print(products)
            if entities3 == 'Uber go':
                for i in range(1, 5):
                    if products[i]['display_name'] == 'uberGO':
                        product_id = products[i].get('product_id')
                        type_cab = products[i].get('display_name')
            elif entities3 == 'Uber pool':
                for i in range(1, 5):
                    if products[i]['display_name'] == 'POOL':
                        product_id = products[i].get('product_id')
                        type_cab = products[i].get('display_name')
            else:
                product_id = products[0].get('product_id')
                type_cab = products[0].get('display_name')

            estimate = client.estimate_ride(product_id=product_id,
                                            start_latitude=lat1,
                                            start_longitude=lng1,
                                            end_latitude=lat2,
                                            end_longitude=lng2,
                                            seat_count=1)
            fare = estimate.json.get('fare')
            bas = fare['display']
            client.cancel_current_ride()
            response = client.request_ride(product_id=product_id,
                                           start_latitude=lat1,
                                           start_longitude=lng1,
                                           end_latitude=lat2,
                                           end_longitude=lng2,
                                           seat_count=1,
                                           fare_id=fare['fare_id'])

            request = response.json
            print(request)
            request_id = request.get('request_id')
            url = 'https://sandbox-api.uber.com/v1.2/sandbox/requests/' + request
            ur = 'https://sandbox-api.uber.com/v1.2/requests/' + request + '/map'

            token = "hAjOfJ-OPiQ3dntDT9KtiLxwitcXrxu8-pNPRuzP"  # insert token

            data = {"status": "accepted"}

            headers = {
                'Authorization': 'Bearer ' + token,
                "Content-Type": "application/json"
            }

            # Call REST API
            response = requests.put(url,
                                    data=json.dumps(data),
                                    headers=headers)
            response = requests.get(ur, headers=headers)
            response = client.get_ride_details(request_id)
            ride = response.json
            print(ride)

            status = ride.get('status')
            dri_name = ride.get('driver').get('name')
            dri_pic = ride.get('driver').get('picture_url')

            eta = ride.get('destination').get('eta')
            car_pix = ride.get('vehicle').get('picture_url')

            # product_name1 = products[3]['display_name'] #GO
            # product_nam2 = products[2]['display_name'] #POOL

            uber_action = "Sure. Booking your uber from %s to %s. Your cab type is %s and estimated time of arrival is %s and fare will be approx %s" % (
                entities1, entities2, type_cab, eta, bas)
            cab_data = {
                "cabtype": type_cab,
                'maxfare': bas,
                "minfare": eta,
                'to': entities2,
                'from': entities1,
                'status': status,
                'driver': dri_name,
                'pic': dri_pic,
                'car': car_pix,
                'map': ur
            }
            # print cab_data

            requests.post("http://localhost:8080/cab",
                          data=json.dumps(cab_data))
            self.speech.synthesize_text(uber_action)

        else:
            self.__text_action(
                "I'm sorry, I don't think that their is any cab available between these two locations."
            )