def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: crypto = tracker.get_slot('crypto') df = pd.read_csv('cryptodata/' + crypto + 'usd.csv', usecols=[1, 2, 3, 4, 5]) df = df[['Date', 'Close']].dropna() df = df[::-1] n = df.shape[0] data = [] for i in range(n): d = {} d['x'] = df.Date.values[i] d['y'] = df.Close.values[i] data.append(d) chart_data = { "payload": "chart", "data": { "title": "Price Trend of " + crypto, "labels": df.Date.values, "backgroundColor": ["#36a2eb"], "chartsData": data, "chartType": "line", "displayLegend": "false" } } dispatcher.utter_custom_json(chart_data) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: newsapi = NewsApiClient(api_key='50f272bcae1f4491b90864cad6f20628') top_headlines = newsapi.get_top_headlines( q='COVID-19', language='en', ) #for article in top_headlines['articles']: #dispatcher.utter_message(str(article['title'])) #print("Title : ", article['title']) #dispatcher.utter_message(str(article['description'])) #print("Description : ",article['description']) #hyperlink_format = '<a href = "{link}" target="_blank">{text}</a>' list1 = [] for article in top_headlines['articles']: description = str(article['description']) hyperlink_format = '<a href = "{link}" target="_blank">{text}</a>' hyperlink_format = hyperlink_format.format(link=article['url'], text='here') hyperlink_message = ". Click " + hyperlink_format + " to read enitre article" description = description + hyperlink_message #print(description) x = {"title": article['title'], "description": description} list1.append(x) dispatcher.utter_custom_json({"payload": "collapsible", "data": list1}) return []
def submit(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: url = tracker.get_slot("link_2_url") try: co2_in_tons = self.kb.calculate_emissions(tracker, unit="short_tons") except ValueError as e: logger.error(f"calculate_emissions failed with: {e}") dispatcher.utter_message("Sorry, I was unable to calculate that.") return [] departure_airport = tracker.get_slot("travel_departure") departure_iata = tracker.get_slot("iata_departure") destination_airport = tracker.get_slot("travel_destination") destination_iata = tracker.get_slot("iata_destination") message = f"A one-way flight from {departure_airport} ({departure_iata}) to {destination_airport} ({destination_iata}) "\ f"emits {co2_in_tons} of CO2. " \ f"It would be amazing if you bought offsets for that carbon! " \ f"There are some great, UN-certified projects you can pick from." if tracker.get_latest_input_channel() == "facebook": payload = hyperlink_payload(tracker, message, "Buy Offsets", url) dispatcher.utter_custom_json(payload) else: dispatcher.utter_message(message + f" [Buy Offsets]({url})") return [ SlotSet("travel_departure"), SlotSet("iata_departure"), SlotSet("travel_destination"), SlotSet("iata_destination"), SlotSet("travel_flight_class") ]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print("====Inside ActionSearchRestaurants Without Cuisine====") print() location = tracker.get_slot("location") cuisine = tracker.get_slot("cuisine") lat = tracker.get_slot("latitude") lon = tracker.get_slot("longitude") entity_id = tracker.get_slot("location_id") entity_type = tracker.get_slot("location_type") city_id = tracker.get_slot("city_id") locationEntity = next(tracker.get_latest_entity_values("location"), None) cuisineEntity = next(tracker.get_latest_entity_values("cuisine"), None) user_locationEntity = next( tracker.get_latest_entity_values("user_location"), None) ##set the cuisine to any of the cuisine name or you leave it empyt cuisine_id = "" restaurants = zomatoApi.searchRestaurants(entity_id, entity_type, cuisine_id, "") dispatcher.utter_message( "Here are the few restaurants I have found 😋!!!") dispatcher.utter_custom_json({ "payload": "cardsCarousel", "data": restaurants })
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: project='DMPP' issue_id=tracker.get_slot('issue_id') print("captured slot {}".format(issue_id)) #call show issues api issue_details=jira_exec.get_issue_detail(issue_id) dispatcher.utter_custom_json(issue_details) #dispatcher.utter_message(text="Issue details are as below") return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: myloc = geocoder.ip('me') print(myloc.latlng) lat = str(myloc.latlng[0]) longi = str(myloc.latlng[1]) url = "https://www.google.co.in/maps/search/covid+19+Testing+center/@{},{}".format( lat, longi) r = requests.get(url) string_1 = re.findall(r"null,\\(.*?)Owner", r.text) covid_list_name = [] for i in string_1: string_2 = i.rsplit("\\", 1) string_3 = string_2[1] string_3 = string_3[1:] string_3 = string_3[:-1] string_3 = string_3.strip() covid_list_name.append(string_3) covid_list_directions = [] for name in covid_list_name: replaced = name.replace(" ", "+") url_directions = "https://www.google.co.in/maps/dir//{}".format( replaced) covid_list_directions.append(url_directions) final_hospital_address = [] for i1 in string_1: string_2_dir = i1.rsplit("\\n,null,\\", 1) #print("OK") string_3_dir = string_2_dir[1] string_4_dir = string_3_dir.split("\\")[0] string_4_dir = string_4_dir[1:] final_hospital_address.append(string_4_dir) final_list_hospitals = [] for k in range(0, len(covid_list_name)): hyperlink_format = '<a href = "{link}" target="_blank">{text}</a>' hyperlink_format = hyperlink_format.format( link=covid_list_directions[k], text='here') hyperlink_message = ". Click " + hyperlink_format + " for directions" desc = final_hospital_address[k] + hyperlink_message desc = "<b> Address : </b>" + desc x = {"title": covid_list_name[k], "description": desc} final_list_hospitals.append(x) dispatcher.utter_custom_json({ "payload": "collapsible", "data": final_list_hospitals }) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]): print("Inside get a2 form action get data ") msg = { "message": "Here you go", "purposeCodeControl": "S0603", "purposeCodeDesc": "Transfer for general insurance premium including reinsurance premium; and term life insurance premium", "fxRateControl": "72.123", "nameControl": "Mr Vikram ", "panControl": "BFBEE56GT1", "canfill": "true" } dispatcher.utter_custom_json(msg) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]): ent_list = tracker.latest_message['entities'] ent = "" if len(ent_list) != 0: ent = ent_list[0]['value'] print("Inside code action") msg = { "message": "Please fill purpose code S0603", "purposeCodeControl": "S0603", "purposeCodeDesc": "Transfer for general insurance premium including reinsurance premium; and term life insurance premium", "canfill": "true" } dispatcher.utter_custom_json(msg) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]): ent_list = tracker.latest_message['entities'] ent = "" if len(ent_list) != 0: ent = ent_list[0]['value'] print("Inside code action") msg = { "message": "Please fill purpose code S0702", "purposeCodeControl": "S0702", "purposeCodeDesc": "Investment banking – brokerage, under writing commission etc", "canfill": "true" } dispatcher.utter_custom_json(msg) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: act = tracker.get_slot('activity') needs = convertNeeds(tracker.get_slot('needs')) #print(needs) age = tracker.get_slot('age') location = tracker.get_slot('location') # 미성년자 방지 if age == '10s' and act == 'pub': act = 'cafe' message = {} resultPlaces = recommendPlace(location, needs, act) #resultPlace = ['브와두스','cafe','north',None,'09-23','제주 수제 타르트와 케이크 맛집으로 유명한','https://i.imgur.com/TrEHjNb.png','https://www.instagram.com/voixdoucebakery/','in'] if resultPlaces != []: if len(resultPlaces) > 5: resultPlaces = ranking(resultPlaces) elements = [] for place in resultPlaces: #print(place) elements.append(resultMessegeUnit(place)) message = { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": elements } } } dispatcher.utter_message("다음을 추천해요.") dispatcher.utter_message( "말씀주신 원하는 시간에 오늘 방문가능하고, 주신 정보와 날씨도 고려해서 추천한 데이터입니다 :)") dispatcher.utter_custom_json(message) print("추천완료") else: dispatcher.utter_message("조금 더 정보를 모아올께요!") print("추천실패") return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: elements = [{ "title": "Sample Title 1", "subtitle": "Sample Subtitle 1", "image_url": "https://i.imgur.com/nGF1K8f.jpg" }, { "title": "Sample Title 2", "subtitle": "Sample Title 2", "image_url": "https://i.imgur.com/nGF1K8f.jpg" }, { "title": "Sample Title 3", "subtitle": "Sample Title 3", "image_url": "https://i.imgur.com/nGF1K8f.jpg" }] dispatcher.utter_custom_json(elements) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: song_name = tracker.get_slot('song_name') if song_name is not None: machine = SongMachine() data = machine.fetchSong(song_name) if data['url'] is not '': dispatcher.utter_custom_json({ "payload": 'audio', "url": data['url'], 'title': data['title'] }) else: dispatcher.utter_message( "I couldn't find the song you asked for.") else: dispatcher.utter_message("What song should I play?") return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]): ent_list = tracker.latest_message['entities'] ent = "" if len(ent_list) != 0: ent = ent_list[0]['value'] msg = "getting trends from db" client = pymongo.MongoClient("mongodb://localhost:27017/") tera_db = client["tera"] intents = tera_db["intents"] from bson.son import SON group_query = [{ "$group": { "_id": "$name", "count": { "$sum": 1 } } }, { "$sort": SON([("count", -1), ("_id", -1)]) }, { "$limit": 3 }] trends = [] group_by_results = intents.aggregate(group_query) for cursor in group_by_results: res = intents.find({ "name": cursor.get("_id") }).sort("confidence", -1).limit(1) trends.append(res[0].get("text")) msg = { "message": "People also asked : ", "showTrends": "true", "valueOfResponse": trends } dispatcher.utter_custom_json(msg) return []
def validate_is_kontrak_aktif(self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> Optional[Dict]: if tracker.latest_message.get('intent', {}).get('name') != 'cancel': if value is True: dispatcher.utter_custom_json( json_message={ "text": "Mohon dapat menyebutkan nomor kontrak yang sebenarnya" }) elif value is False: dispatcher.utter_custom_json( json_message={ "text": "Mohon masukan nomor kontrak yang terakhir ditagihkan kepada Anda" }) else: value = None dispatcher.utter_template("utter_invalid_value", tracker=tracker) return {_IS_KONTRAK_AKTIF: value}
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]): ent_list = tracker.latest_message['entities'] ent = "" if len(ent_list) != 0: ent = ent_list[0]['value'] base_url = "https://api.exchangeratesapi.io/latest?" complete_url = base_url + "&base=USD" print("User wants base currency as " + complete_url) response = requests.get(complete_url) x = response.json() msg = "" res = "" fx_rate = "" if x["rates"] != "error" and ent is not None and ent != "": #if x[rates] message = x["rates"] for key, value in message.items(): if key == ent.upper(): fx_rate = str(value) msg = msg + str(key) + "/USD" + " " + str(value) + "" msg = msg + "( Source : European Central Bank )" res = { "message": msg, "fxRateControl": fx_rate, "canfill": "true" } else: msg = "Please enter quote currency" res = {"message": msg} print("inside action currency is entity is ::" + str(ent)) dispatcher.utter_custom_json(res) if ent is not None and ent != "": msg = "Also for fx rate refer <a href=\"https://www.gbm.hsbc.com/evolve/overview/\" target=\"_blank\">HSBC evolve</a>" dispatcher.utter_message(msg) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print() print("======Inside Action Search Best Restaurants====") print() ## extract the required slots location = tracker.get_slot("location") cuisine = tracker.get_slot("cuisine") lat = tracker.get_slot("latitude") lon = tracker.get_slot("longitude") entity_id = tracker.get_slot("location_id") entity_type = tracker.get_slot("location_type") city_id = tracker.get_slot("city_id") ## extract the entities locationEntity = next(tracker.get_latest_entity_values("location"), None) cuisineEntity = next(tracker.get_latest_entity_values("cuisine"), None) user_locationEntity = next( tracker.get_latest_entity_values("user_location"), None) latEntity = next(tracker.get_latest_entity_values("latitude"), None) lonEntity = next(tracker.get_latest_entity_values("longitude"), None) ## if we latitude & longitude entities are found, set it to slot if (latEntity and lonEntity): lat = latEntity lon = lonEntity ## if user wants to search the best restaurants in his current location if (user_locationEntity or (latEntity and lonEntity)): ##check if we already have the user location coordinates stoed in slots if (lat == None and lon == None): dispatcher.utter_message( "Sure, please allow me to access your location 🧐") dispatcher.utter_custom_json({"payload": "location"}) return [] else: locationEntities = zomatoApi.getLocationDetailsbyCoordinates( lat, lon) location = locationEntities["title"] city_id = locationEntities["city_id"] entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] ## store the user provided details to slot SlotSet("location", locationEntities["title"]) SlotSet("city_id", locationEntities["city_id"]) SlotSet("location_id", locationEntities["entity_id"]) SlotSet("location_type", locationEntities["entity_type"]) ## if user wants to search best restaurants by location name if (locationEntity): locationEntities = zomatoApi.getLocationDetailsbyName( locationEntity) entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] city_id = locationEntities["city_id"] print("Entities: ", entity_id, " ", entity_type, " ", city_id, " ", locationEntity) ## search the best restaurts by calling zomatoApi api restaurants = zomatoApi.getLocationDetails(entity_id, entity_type) ## check if restaurants details found if (len(restaurants) > 0): dispatcher.utter_message( "Here are few top rated restaurants that I have found 🤩") dispatcher.utter_custom_json({ "payload": "cardsCarousel", "data": restaurants["best_restaurants"] }) return [] dispatcher.utter_message( "Sorry we couldn't find any best restaurants ☹️".format( cuisine, location)) return [UserUtteranceReverted()]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dict_of_rec = { "about_treatment":"Lifestyle and home remedies" ,"overveiw": "Overview" ,"causes": "Causes" ,"prevention": "Prevention","about_symptoms": "Symptoms"} last_intent = tracker.latest_message['intent'].get('name').split(".")[-1] parent_intent = tracker.latest_message['intent'].get('name').split(".")[0] disease = tracker.get_slot("disease") print(last_intent) print(parent_intent) intent = tracker.latest_message['intent'].get('name') print(intent) shan_text = [ { "recipient_id": "bot", "type":"text", "text": "Hi again!" } ] shan_btn = [ { "recipient_id": "bot", "type":"button", "buttons": [ { "title": "about products", "payload": "about products" }, { "title": "founders of Medsamaan", "payload": "founders of Medsamaan" }, { "title": "about Medsamaan", "payload": "about Medsamaan" } ] } ] shan_img = [ { "recipient_id": "bot", "type":"image", "images": [ { "text": "about products", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" } ] } ] shan_img_btn =[ { "recipient_id": "bot", "type" : "image_button", "buttons": [ { "title": "about products", "payload": "about products" }, { "title": "founders of Medsamaan", "payload": "founders of Medsamaan" }, { "title": "about Medsamaan", "payload": "about Medsamaan" } ], "images": [ { "text": "about products", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" }, { "text": "founders of Medsamaan", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" }, { "text": "about Medsamaan", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" } ] } ] shan_img_btn_txt =[ { "recipient_id": "bot", "type" : "image_button_text", "text":"cnocvowecowlcwwobvnw wobwevc nwocwe wowbveviosecewv obfnweof vwovnw vwowf eofefne fefoefqefqefqefoaeflaefne faeoffb ofef", "buttons": [ { "title": "about products", "payload": "about products" }, { "title": "founders of Medsamaan", "payload": "founders of Medsamaan" }, { "title": "about Medsamaan", "payload": "about Medsamaan" } ], "images": [ { "text": "about products", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" }, { "text": "founders of Medsamaan", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" }, { "text": "about Medsamaan", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" } ] } ] dict_of_rec = { "about_treatment":"Lifestyle and home remedies" ,"overveiw": "Overview" ,"causes": "Causes" ,"prevention": "Prevention","about_symptoms": "Symptoms"} disease = tracker.get_slot("disease") intent = tracker.latest_message['intent'].get('name') print(intent) if intent == "shantanu_img": dispatcher.utter_custom_json(shan_img) elif intent == "shantanu_text": dispatcher.utter_custom_json(shan_text) elif intent == "shantanu_btn": dispatcher.utter_custom_json(shan_btn) elif intent == "shantanu_img_btn": dispatcher.utter_custom_json(shan_img_btn) elif intent == "shantanu_text_img_button": dispatcher.utter_custom_json(shan_img_btn_txt) elif parent_intent == "smalltalk": wks = ms_sm_wks cell = wks.find(last_intent) ## row & col of search element answer = wks.cell(cell.row, cell.col+3).value ## dispatched answer dispatcher.utter_message(answer) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) elif intent =="prevention": wks = disease_symptom_overview print(disease) cell = wks.find(disease.capitalize()) ## row & col of search element answer = wks.cell(cell.row, cell.col+4).value #list_of_rem = list(dict_of_rec.keys()).remove(intent) list_of_rem = list(dict_of_rec.keys()) list_of_rem.remove(intent) # dispatcher.utter_message("Overview for " + disease) # dispatcher.utter_message(answer) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) list_of_buttons = [] for i in list_of_rem: temp_dict ={} temp_dict['title'] = disease +" of "+ dict_of_rec[i] temp_dict['payload'] = i +" of "+ disease list_of_buttons.append(temp_dict) shan_text_btn = [ { "recipient_id": "bot", "type":"text_button", "text":"Related Topics to Look For:", "buttons": list_of_buttons } ] dispatcher.utter_custom_json(shan_text_btn) elif intent=="about_treatment": wks = disease_symptom_overview cell = wks.find(disease.capitalize()) ## row & col of search element answer = wks.cell(cell.row, cell.col+1).value # dispatcher.utter_message("Treatment for " + disease) # dispatcher.utter_message(answer) list_of_rem = list(dict_of_rec.keys()) list_of_rem.remove(intent) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) list_of_buttons = [] for i in list_of_rem: temp_dict ={} temp_dict['title'] = disease +" of "+ dict_of_rec[i] temp_dict['payload'] = i +" of "+ disease list_of_buttons.append(temp_dict) shan_text_btn = [ { "recipient_id": "bot", "type":"text_button", "text":"Related Topics to Look For:", "buttons": list_of_buttons } ] dispatcher.utter_custom_json(shan_text_btn) elif intent=="prevention": wks = disease_symptom_overview cell = wks.find(disease.capitalize()) ## row & col of search element answer = wks.cell(cell.row, cell.col+4).value #list_of_rem = list(dict_of_rec.keys()).remove(intent) list_of_rem = list(dict_of_rec.keys()) list_of_rem.remove(intent) # dispatcher.utter_message("Overview for " + disease) # dispatcher.utter_message(answer) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) list_of_buttons = [] for i in list_of_rem: temp_dict ={} temp_dict['title'] = disease +" of "+ dict_of_rec[i] temp_dict['payload'] = i +" of "+ disease list_of_buttons.append(temp_dict) shan_text_btn = [ { "recipient_id": "bot", "type":"text_button", "text":"Related Topics to Look For:", "buttons": list_of_buttons } ] dispatcher.utter_custom_json(shan_text_btn) elif intent=="about_symptoms": wks = disease_symptom_overview cell = wks.find(disease.capitalize()) ## row & col of search element answer = wks.cell(cell.row, cell.col+5).value #list_of_rem = list(dict_of_rec.keys()).remove(intent) list_of_rem = list(dict_of_rec.keys()) list_of_rem.remove(intent) # dispatcher.utter_message("Symptoms for " + disease) # dispatcher.utter_message(answer) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) list_of_buttons = [] print(list_of_rem) for i in list_of_rem: temp_dict ={} temp_dict['title'] = disease +" of "+ dict_of_rec[i] temp_dict['payload'] = i +" of "+ disease list_of_buttons.append(temp_dict) shan_text_btn = [ { "recipient_id": "bot", "type":"text_button", "text":"Related Topics to Look For:", "buttons": list_of_buttons } ] dispatcher.utter_custom_json(shan_text_btn) elif intent=="overview": wks = disease_symptom_overview cell = wks.find(disease.capitalize()) ## row & col of search element answer = wks.cell(cell.row, cell.col+2).value #list_of_rem = list(dict_of_rec.keys()).remove(intent) list_of_rem = list(dict_of_rec.keys()) list_of_rem.remove(intent) # dispatcher.utter_message("Overview for " + disease) # dispatcher.utter_message(answer) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) list_of_buttons = [] for i in list_of_rem: temp_dict ={} temp_dict['title'] = disease +" of "+ dict_of_rec[i] temp_dict['payload'] = i +" of "+ disease list_of_buttons.append(temp_dict) shan_text_btn = [ { "recipient_id": "bot", "type":"text_button", "text":"Related Topics to Look For:", "buttons": list_of_buttons } ] dispatcher.utter_custom_json(shan_text_btn) elif intent=="symptom_checker": user_uttered_msg = tracker.latest_message["text"] infermedica_api.configure(app_id='d91c00d6',app_key='50573fae6348390c63e87e7c5b584547') api = infermedica_api.get_api() headers = { 'App-Id': 'd91c00d6', 'App-Key': '50573fae6348390c63e87e7c5b584547', 'Content-Type': 'application/json', } data = str({"text":user_uttered_msg}) response = requests.post('https://api.infermedica.com/v2/parse', headers=headers, data=data) response.text request = infermedica_api.Diagnosis(sex='male', age=30) syms = response.json()['mentions'] for i in syms: request.add_symptom(i['id'], i['choice_id']) print(request) # call diagnosis request = api.diagnosis(request) request = request.condition for i in request: shan_text = [ { "recipient_id": "bot", "type":"text", "text": i['common_name']+": "+str(i['probability']) } ] dispatcher.utter_custom_json(shan_text) elif "locate" in intent: url='https://maps.googleapis.com/maps/api/place/textsearch/json?'# where you will send your requests api_key='' #enter your api key generated, if not generated then generate at https://cloud.google.com/maps-platform/?apis=places url2 = 'https://maps.googleapis.com/maps/api/place/details/json?' def maps(search,location): x = [] i =0 while((x == [] or x==None) and i<10): x=requests.get(url+'query={}&key={}'.format(search.lower()+"+"+"in"+"+"+location.lower(),api_key)).json()['results'] i+=1 #Extracted 'results' out of the api data . 'results' would come in json #return(x) if len(x)<1: print("No "+search.lower()+" found at {0}".format(location)) # if query invalid then prompt the user to be more general else: RANGE=3 # default 3 results would be displayed . Change accordingly if len(x)<3:RANGE=2 if len(x)<2:RANGE=1 print("nearest ".format(RANGE) + search.lower() + " locations found at {} :\n".format(location)) for i in range(RANGE): y = None j = 0 while((y==[] or y=={} or y==None) and j<10): y = requests.get(url2+'place_id={}&key={}'.format(x[i]['place_id'],api_key)).json()#['formatted_phone_number']#["formatted_phone_number"] j+=1 if 'result' in y: shan_text = [ { "recipient_id": "bot", "type":"name_descript", "items": [{"name":x[i]['name'], "descript":x[i]['formatted_address']+"\n"+y['result']['formatted_phone_number']+"\n"+"https://www.google.com/maps/place/?q=place_id:"+x[i]['place_id']}] } ] else: shan_text = [ { "recipient_id": "bot", "type":"name_descript", "items": [{"name":x[i]['name'], "descript":x[i]['formatted_address']+"\n"+"https://www.google.com/maps/place/?q=place_id:"+x[i]['place_id']}] } ] dispatcher.utter_custom_json(shan_text) loc = tracker.get_slot('current_location') if intent=="locate_clinic": maps("hospital",loc) elif intent=="locate_doctor": maps("doctor",loc) "text": i['common_name']+":"+i['probability'] } ]
def submit( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> List[Dict[Text, Any]]: url = tracker.get_slot("link_2_url") try: co2_in_tons = self.kb.calculate_emissions(tracker, unit="short_tons") except ValueError as e: logger.error(f"calculate_emissions failed with: {e}") dispatcher.utter_message("Sorry, I was unable to calculate that.") return [] departure_airport = tracker.get_slot("travel_departure") departure_iata = tracker.get_slot("iata_departure") destination_airport = tracker.get_slot("travel_destination") destination_iata = tracker.get_slot("iata_destination") stopover_airport = tracker.get_slot("travel_stopover") stopover_iata = tracker.get_slot("iata_stopover") previous_entered_flight = tracker.get_slot("previous_entered_flight") if not stopover_iata: message = ( f"A one-way flight from {departure_airport} ({departure_iata}) to {destination_airport} ({destination_iata}) " f"emits {co2_in_tons[0]} of CO2. " f"It would be amazing if you bought offsets for that carbon! " f"There are some great, UN-certified projects you can pick from." ) else: message = ( f"The trip from {departure_airport} ({departure_iata}) to {destination_airport} ({destination_iata}) " f"via {stopover_airport} ({stopover_iata}) emits {float(co2_in_tons[0].split()[0])+float(co2_in_tons[1].split()[0]):.1f} {co2_in_tons[0].split()[1]} of CO2. " f"The first leg emits {co2_in_tons[0]} of CO2. " f"The second leg emits {co2_in_tons[1]} of CO2." f"It would be amazing if you bought offsets for that carbon! " f"There are some great, UN-certified projects you can pick from." ) if tracker.get_latest_input_channel() == "facebook": payload = hyperlink_payload(tracker, message, "Buy Offsets", url) dispatcher.utter_custom_json(payload) else: dispatcher.utter_message(message + f" [Buy Offsets]({url})") slots_to_set = [ SlotSet("travel_departure"), SlotSet("iata_departure"), SlotSet("travel_destination"), SlotSet("iata_destination"), SlotSet("travel_stopover"), SlotSet("iata_stopover"), SlotSet("travel_flight_class"), ] if tracker.get_slot("travel_stopover"): return slots_to_set + [ SlotSet("previous_entered_flight"), ] else: return slots_to_set
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]): print("Inside get a2 form action") msg = {"message": "Here you go", "formCode": "A2"} dispatcher.utter_custom_json(msg) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: response = requests.get( "https://api.covid19india.org/data.json").json() state_name = str((tracker.latest_message)['text']) state_name = state_name.lower() print(state_name) states_dict = enchant.PyPWL("states.txt") word_exists = states_dict.check(state_name) print("word exists: ", word_exists) if not word_exists: #get suggestions for the input word suggestions = states_dict.suggest(state_name) print("input:", state_name) print("suggestions:", suggestions) if (len(suggestions) != 0): state_name = suggestions[0] #state = None entities = tracker.latest_message['entities'] print(entities) #for e in entities: # if(e['entity'] == "state"): # state = e['value'] #message = "Enter proper state name" for data in response["statewise"]: if data["state"] == state_name.title(): print("Active = " + data["active"] + " Confirmed = " + data["confirmed"] + " Deaths = " + data["deaths"] + " Recovered = " + data["recovered"]) message = "Active = " + data["active"] + " Confirmed = " + data[ "confirmed"] + " Deaths = " + data[ "deaths"] + " Recovered = " + data["recovered"] active = int(data["active"]) confirmed = int(data["confirmed"]) deaths = int(data["deaths"]) recovered = int(data["recovered"]) print(active) labels = ['Active', 'Confirmed', 'Deaths', 'Recovered'] backgroundColor = [ "#36a2eb", "#ffcd56", "#ff6384", "#009688", "#c45850" ] #chartsData = [555,242,145,23] chartsData = [] chartsData.extend((active, confirmed, deaths, recovered)) data = { "title": state_name.upper(), "labels": labels, "backgroundColor": backgroundColor, "chartsData": chartsData, "chartType": "pie", "displayLegend": "true" } #dispatcher.utter_message(state_name) #dispatcher.utter_message(message) dispatcher.utter_custom_json({"payload": "chart", "data": data}) return []
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print() print("====Inside ActionAskCuisine====") print() location = tracker.get_slot("location") cuisine = tracker.get_slot("cuisine") lat = tracker.get_slot("latitude") lon = tracker.get_slot("longitude") locationEntity = next(tracker.get_latest_entity_values("location"), None) cuisineEntity = next(tracker.get_latest_entity_values("cuisine"), None) user_locationEntity = next( tracker.get_latest_entity_values("user_location"), None) latEntity = next(tracker.get_latest_entity_values("latitude"), None) lonEntity = next(tracker.get_latest_entity_values("longitude"), None) location = tracker.get_slot("location") cuisine = tracker.get_slot("cuisine") lat = tracker.get_slot("latitude") lon = tracker.get_slot("longitude") entity_id = tracker.get_slot("location_id") entity_type = tracker.get_slot("location_type") city_id = tracker.get_slot("city_id") if (latEntity and lonEntity): lat = latEntity lon = lonEntity if (user_locationEntity or (latEntity and lonEntity)): if (lat == None and lon == None): dispatcher.utter_message( "Sure, please allow me to access your location 🧐") dispatcher.utter_custom_json({"payload": "location"}) return [] else: locationEntities = zomatoApi.getLocationDetailsbyCoordinates( lat, lon) location = locationEntities["title"] city_id = locationEntities["city_id"] entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] SlotSet("location", locationEntities["title"]) SlotSet("city_id", locationEntities["city_id"]) SlotSet("location_id", locationEntities["entity_id"]) SlotSet("location_type", locationEntities["entity_type"]) if (locationEntity): locationEntities = zomatoApi.getLocationDetailsbyName( locationEntity) entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] city_id = locationEntities["city_id"] SlotSet("location", locationEntities["title"]) print("locationDetails: ", locationEntities) print() ## check if the restaurants are available in the user provided location if (locationEntities["restaurants_available"] == "no"): dispatcher.utter_message( "Sorry, No restaurants available in the location you have provided 🤯" ) return [UserUtteranceReverted()] else: locationDetails = zomatoApi.getLocationDetails( locationEntities["entity_id"], locationEntities["entity_type"]) dispatcher.utter_template("utter_ask_cuisine", tracker) dispatcher.utter_custom_json({ "payload": "quickReplies", "data": locationDetails["top_cuisines"] }) return [ SlotSet("city_id", locationEntities["city_id"]), SlotSet("location_id", locationEntities["entity_id"]), SlotSet("location_type", locationEntities["entity_type"]) ]
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: print() print("====Inside ActionSearchRestaurants====") print() ## extract the required slots location = tracker.get_slot("location") cuisine = tracker.get_slot("cuisine") lat = tracker.get_slot("latitude") lon = tracker.get_slot("longitude") entity_id = tracker.get_slot("location_id") entity_type = tracker.get_slot("location_type") city_id = tracker.get_slot("city_id") ## extract the entities locationEntity = next(tracker.get_latest_entity_values("location"), None) cuisineEntity = next(tracker.get_latest_entity_values("cuisine"), None) user_locationEntity = next( tracker.get_latest_entity_values("user_location"), None) latEntity = next(tracker.get_latest_entity_values("latitude"), None) lonEntity = next(tracker.get_latest_entity_values("longitude"), None) ## if we latitude & longitude entities are found, set it to slot if (latEntity and lonEntity): lat = latEntity lon = lonEntity ## if user wants to search restaurants in his current location if (user_locationEntity or (latEntity and lonEntity)): ##check if we already have the user location coordinates stoed in slots if (lat == None and lon == None): dispatcher.utter_message( "Sure, please allow me to access your location 🧐") dispatcher.utter_custom_json({"payload": "location"}) return [] else: locationEntities = zomatoApi.getLocationDetailsbyCoordinates( lat, lon) location = locationEntities["title"] city_id = locationEntities["city_id"] entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] ## store the user provided details to slot SlotSet("location", locationEntities["title"]) SlotSet("city_id", locationEntities["city_id"]) SlotSet("location_id", locationEntities["entity_id"]) SlotSet("location_type", locationEntities["entity_type"]) ## if user wants to search restaurants by location name if (locationEntity): locationEntities = zomatoApi.getLocationDetailsbyName( locationEntity) if (locationEntities["restaurants_available"] == "no"): dispatcher.utter_message( "Sorry I couldn't find any restaurants 😓") return [] entity_id = locationEntities["entity_id"] entity_type = locationEntities["entity_type"] city_id = locationEntities["city_id"] SlotSet("location", locationEntities["title"]) ##get the cuisine id for the cuisine name user provided cuisine_id = zomatoApi.getCuisineId(cuisine, city_id) print("Entities: ", entity_id, " ", entity_type, " ", cuisine_id, " ", location, " ", cuisine) print() ## if we didn't find the restaurant for which user has provided the cuisine name if (cuisine_id == None): dispatcher.utter_message( "Sorry we couldn't find any restaurants that serves {} cuisine in {}" .format(cuisine, location)) return [UserUtteranceReverted()] else: ## search the restaurts by calling zomatoApi api restaurants = zomatoApi.searchRestaurants(entity_id, entity_type, cuisine_id, "") ## check if restaurants found if (len(restaurants) > 0): dispatcher.utter_message( "Here are the few restaurants that matches your preferences 😋" ) dispatcher.utter_custom_json({ "payload": "cardsCarousel", "data": restaurants }) return [] dispatcher.utter_message( "Sorry we couldn't find any restaurants that serves {} cuisine in {} 😞" .format(cuisine, location)) return [UserUtteranceReverted()]
def check_slot(self, slot, tracker: Tracker, dispatcher: CollectingDispatcher) -> {}: message = None if slot == _KENDALA_NOMOR_KONTRAK: text = "Silakan ketik angka di bawah apabila sesuai dengan kendala Anda\n"\ "1. penagihan atas kontrak orang lain\n"\ "2. nomor kontrak belum diterima\n"\ "3. lainnya, sambungkan Live Agent" message = QuickRepliesBuilder()\ .set_text(value=text)\ .set_content(title="1", payload="1")\ .set_content(title="2", payload="2")\ .set_content(title="3", payload="3")\ .channel(channel=tracker.get_latest_input_channel())\ .build() elif slot == _IS_KONTRAK_AKTIF: message = QuickRepliesBuilder()\ .set_text("Apakah Anda memiliki kontrak aktif?") \ .set_content(title="Iya", payload="iya") \ .set_content(title="Tidak", payload="tidak") \ .channel(channel=tracker.get_latest_input_channel()) \ .build() elif slot == _NOMOR_KONTRAK: message = {} elif slot == _IS_FOLLOW_UP_CABANG: if tracker.get_slot(_KENDALA_NOMOR_KONTRAK) == '2': data_user = self.get_user_data(tracker) is_kontrak_kenal = tracker.get_slot(_IS_KONTRAK_KENAL) if isinstance(is_kontrak_kenal, bool): if is_kontrak_kenal is True: message_list_bucket = self.generate_contract( show_nomor_kontrak=True, data_user=data_user) for message_list in message_list_bucket: dispatcher.utter_message(''.join(message_list)) else: data_user.nomor_dipilih.sort() contract_list = [] sum_contract_list = data_user.sum_contract_list for i in data_user.nomor_dipilih: contract_list.append(sum_contract_list[int(i) - 1]) data_user.sum_contract_list = contract_list self.update_user_data(data_user=data_user) message_list_bucket = self.generate_contract( show_nomor_kontrak=True, data_user=data_user) for message_list in message_list_bucket: dispatcher.utter_message(''.join(message_list)) message = QuickRepliesBuilder() \ .set_text("Apakah Anda bersedia cabang kami melakukan follow up kepada Anda maksimal 2x24 jam?") \ .set_content(title="Iya", payload="iya") \ .set_content(title="Tidak", payload="tidak") \ .channel(channel=tracker.get_latest_input_channel()) \ .build() elif slot == _NOMOR_KTP: message = { "text": "Kami membutuhkan data Anda untuk melakukan pencocokan data terlebih dulu " "sebagai keamanan data. Silakan ketik NIK Anda" } elif slot == _IS_KONTRAK_KENAL: message = {} data_user = self.get_user_data(tracker) dispatcher.utter_message( "Apakah Anda mengenal kontrak dibawah ini?") data_user.index = 1 message_list_bucket = self.generate_contract(data_user=data_user) for message_list in message_list_bucket: dispatcher.utter_message(''.join(message_list)) qr_content = [] if data_user.index > 1: for i in range(1, data_user.index, 1): qr_content.append({"title": str(i), "payload": str(i)}) qr_message = QuickRepliesBuilder()\ .set_text("Silakan ketik pilihan Anda")\ .set_content_by_dictionary(qr_content)\ .set_content(title="Iya, semua", payload="iya, semua")\ .set_content(title="Tidak", payload="tidak")\ .channel(tracker.get_latest_input_channel())\ .build() dispatcher.utter_custom_json(qr_message) logging.debug(f'message: {message}') return message