|
| 1 | +from __future__ import absolute_import |
| 2 | +from __future__ import division |
| 3 | +from __future__ import unicode_literals |
| 4 | + |
| 5 | +from rasa_sdk import Action |
| 6 | +from rasa_sdk.events import SlotSet, AllSlotsReset |
| 7 | +import requests |
| 8 | +import json |
| 9 | +from random import randint |
| 10 | +import datetime |
| 11 | +import os |
| 12 | +import yaml |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | + |
| 17 | +class ActionPlaceSearch(Action): |
| 18 | + def name(self): |
| 19 | + #define the name of the action |
| 20 | + return 'action_place_search' |
| 21 | + |
| 22 | + def run(self, dispatcher, tracker, domain): |
| 23 | + #retrieve slot values |
| 24 | + query = tracker.get_slot('query') |
| 25 | + radius = tracker.get_slot('number') |
| 26 | + |
| 27 | + #retrieve google api key |
| 28 | + with open("./ga_credentials.yml", 'r') as ymlfile: |
| 29 | + cfg = yaml.load(ymlfile) |
| 30 | + key = cfg['credentials']['GOOGLE_KEY'] |
| 31 | + |
| 32 | + #get user's current location |
| 33 | + get_origin = requests.post( |
| 34 | + "https://www.googleapis.com/geolocation/v1/geolocate?key={}".format(key)).json() |
| 35 | + print(get_origin) |
| 36 | + origin_lat = get_origin['location']['lat'] |
| 37 | + origin_lng = get_origin['location']['lng'] |
| 38 | + |
| 39 | + #look for a place using all the details |
| 40 | + place = requests.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={},{}&radius={}&type={}&key={}'.format(origin_lat, origin_lng, radius, query, key)).json() |
| 41 | + if len(place['results'])==0: |
| 42 | + dispatcher.utter_message("Sorry, I didn't find anything") |
| 43 | + return [SlotSet('location_match', 'none')] |
| 44 | + else: |
| 45 | + for i in place['results']: |
| 46 | + if 'rating' and 'vicinity' in i.keys(): |
| 47 | + name = i['name'] |
| 48 | + rating = i['rating'] |
| 49 | + address = i['vicinity'] |
| 50 | + if i['opening_hours']['open_now']==True: |
| 51 | + opening_hours = 'open' |
| 52 | + else: |
| 53 | + opening_hours = 'closed' |
| 54 | + break |
| 55 | + speech = "I found a {} called {} based on your specified parameters.".format(query, name) |
| 56 | + dispatcher.utter_message(speech) #send the response back to the user |
| 57 | + return [SlotSet('location_match', 'one'), SlotSet('rating', rating), SlotSet('address', address), SlotSet('opening_hours', opening_hours)] #set returned details as slots |
| 58 | + |
| 59 | + |
| 60 | + |
0 commit comments