Ejemplo n.º 1
0
    def run(
            self,
            dispatcher,  # type: CollectingDispatcher
            tracker,  # type: Tracker
            domain,  # type:  Dict[Text, Any]
    ):  # type: (...) -> List[Dict[Text, Any]]

        subscribe = tracker.get_slot('subscribe')

        if subscribe:
            response = "You've been successfully subscribed"
        else:
            response = "You've been successfully unsubscribed"

        dispatcher.utter_message(response)

        return [SlotSet('subscribe', subscribe)]
Ejemplo n.º 2
0
    def run(self, dispatcher, tracker, domain):
        return_slots = []
        #print(tracker.slots[0])
        for slot in tracker.slots:
            if tracker.slots[slot] != None:
                print(tracker.slots[slot])
                return_slots.append(SlotSet(slot, None))

        file = open("history.txt", "a")
        file.write("Story \n")
        for item in story:
            file.write(str(item) + "\n")
        story.clear()
        file.write("\n")
        file.close()

        return return_slots
Ejemplo n.º 3
0
    def run(self, dispatcher, tracker, domain):
        # type: (Dispatcher, DialogueStateTracker, Domain) -> List[Event]

        user_artist_name = tracker.get_slot('artist_name')

        client = SpotifyAPI(client_id, client_secret)

        artist_object = client.search(user_artist_name)
        artist_id = artist_object['artists']['items'][0]['id']
        tracks_object = client.get_track(artist_id)
        tracks_object = client.get_track(artist_id)['tracks']
        track_object = tracks_object[random.randin(0, len(tracks_object))]
        track_name = track_object['name']
        track_url_preview = track_object['preview_url']

        dispatcher.utter_message(track_name)
        return [SlotSet("artist_name", user_artist_name)]
Ejemplo n.º 4
0
    def run(self, dispatcher, tracker, domain):
        spacy_entities = ['place', 'date', 'name', 'organisation']
        duckling = [
            'money', 'duration', 'distance', 'ordinals', 'time',
            'amount-of-money', 'numbers'
        ]

        entity_to_extract = next(tracker.get_latest_entity_values('entity'),
                                 None)

        extractor = 'ner_crf'
        if entity_to_extract in spacy_entities:
            extractor = 'ner_spacy'
        elif entity_to_extract in duckling:
            extractor = 'ner_duckling_http'

        return [SlotSet('entity_extractor', extractor)]
Ejemplo n.º 5
0
    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List['Event']:

        # Fallback caused by TwoStageFallbackPolicy
        if (len(tracker.events) >= 4 and tracker.events[-4].get('name')
                == 'action_default_ask_affirmation'):

            return [
                SlotSet('feedback_value', 'negative'),
                Form('feedback_form'),
                FollowupAction('feedback_form')
            ]

        # Fallback caused by Core
        else:
            dispatcher.utter_template('utter_default', tracker)
            return [UserUtteranceReverted()]
    def run(self, dispatcher, tracker, domain):

        hol = tracker.get_slot('holidays')

        # replace with API call ...

        # switch (hol):
        #   case 'Herbstferien':
        #       response = 'Im Herbst'
        #       break
        #   ...

        # ... until here!

        response = 'Ich weiss nix von ' + hol
        dispatcher.utter_message(response)
        return [SlotSet('holidays', hol)]
Ejemplo n.º 7
0
    def run(self, dispatcher, tracker, domain):

        # the entity can be one of two entities from duckling,
        # number or amount-of-money
        budget = next(tracker.get_latest_entity_values('number'), None)
        if not budget:
            budget = next(tracker.get_latest_entity_values('amount-of-money'),
                          None)

        # as a fallback, if no entity is recognised (e.g. in a sentence
        # like "I have no money") we store the whole user utterance in the slot
        # In future this should be stored in a `budget_unconfirmed` slot where
        # the user will then be asked to confirm this is there budget
        if not budget:
            budget = tracker.latest_message.get('text')

        return [SlotSet('budget', budget)]
Ejemplo n.º 8
0
    def validate(self, dispatcher: CollectingDispatcher, tracker: Tracker,
                 domain: Dict[Text, Any]) -> List[Dict]:
        """Validate extracted requested slot
            else reject the execution of the form action
        """
        # extract other slots that were not requested
        # but set by corresponding entity
        slot_values = self.extract_other_slots(dispatcher, tracker, domain)

        # extract requested slot
        slot_to_fill = tracker.get_slot(REQUESTED_SLOT)
        if slot_to_fill:
            slot_values.update(
                self.extract_requested_slot(dispatcher, tracker, domain))
            if not slot_values:
                # reject form action execution
                # if some slot was requested but nothing was extracted
                # it will allow other policies to predict another action
                raise ActionExecutionRejection(
                    self.name(), "Failed to validate slot {0} "
                    "with action {1}"
                    "".format(slot_to_fill, self.name()))

        # we'll check when validation failed in order
        # to add appropriate utterances
        for slot, value in slot_values.items():
            if slot == 'account_type':
                if value.lower() not in self.account_db():
                    dispatcher.utter_template('utter_wrong_account', tracker)
                    # validation failed, set slot to None
                    slot_values[slot] = None

            elif slot == 'account_number':
                if not self.is_int(value) or int(value) <= 0:
                    dispatcher.utter_template('utter_wrong_account', tracker)
                    # validation failed, set slot to None
                    slot_values[slot] = None

            elif slot == 'branch':
                if not self.is_int(value) or int(value) <= 0:
                    dispatcher.utter_template('utter_wrong_branch', tracker)
                    # validation failed, set slot to None
                    slot_values[slot] = None

        # validation succeed, set the slots values to the extracted values
        return [SlotSet(slot, value) for slot, value in slot_values.items()]
Ejemplo n.º 9
0
    def run(
            self,
            dispatcher,  # type: CollectingDispatcher
            tracker,  # type: Tracker
            domain,  # type:  Dict[Text, Any]
    ):  # type: (...) -> List[Dict[Text, Any]]

        user_horoscope_sign = tracker.get_slot('horoscope_sign')
        url = f'http://horoscope-api.herokuapp.com/horoscope/today/{user_horoscope_sign}'

        res = requests.get(url)
        todays_horoscope = res.json()['horoscope']
        response = f"Here's your horoscope for today:\n {todays_horoscope}"

        dispatcher.utter_message(response)

        return [SlotSet('horoscope_sign', user_horoscope_sign)]
Ejemplo n.º 10
0
 def run(self, dispatcher, tracker, domain):
     curs, conn = connection()
     scheme_name = tracker.get_slot('scheme_name')
     query = "select scheme_name, scheme_detail, scheme_link from schemes where scheme_name='%s'" % (
         scheme_name, )
     curs.execute(query)
     results = curs.fetchall()
     for r in results:
         dispatcher.utter_message("Scheme Name: " + r[0] +
                                  "\nScheme Details: " +
                                  r[1])  # send the message back to the user
         dispatcher.utter_message(
             "For more information of this scheme, please visit: " + r[2])
     curs.close()
     conn.close()
     gc.collect()
     return [SlotSet('scheme_name',
                     scheme_name)]  #syntax: SlotSet('slot_name', var_name)
Ejemplo n.º 11
0
    def run(self, dispatcher, tracker, domain):
        plant = tracker.get_slot('plant')

        if plant == "kangkung":
            response = """Siram {} 1x tiap hari dengan campuran 1 liter air dan 7-9 ml nutrisi AB Mix.""".format(
                plant)
        elif plant == "sawi":
            response = """Siram {} 2x tiap hari pada saat pagi dan sore, tetapi jika dilihat masih dalam keadaan lembab, maka tidak perlu disiram lagi, kak.""".format(
                plant)
        elif plant == "tomat":
            response = """Untuk perawatan {}, kakak bisa menggunakan gembor manual atau selang fertilisasi. Disarankan menggunakan selang fertilisasi karena prosesnya akan lebih mudah.""".format(
                plant)
        elif plant == "cabai" or plant == "cabe":
            response = """Kakak bisa menyiram {} 1x tiap hari. Bisa juga ditambahkan nutrisi 5 ml nutrisi A + 5 ml nutrisi B dicampur dengan 1 liter air tiap 10 hari sekali""".format(
                plant)

        dispatcher.utter_message(response)
        return [SlotSet('plant', plant)]
Ejemplo n.º 12
0
    def run(self, dispatcher, tracker, domain):
        # type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict[Text, Any]]

        coin = tracker.get_slot('coin')[0]
        coin_map = {"bitcoin": 1, "ether": 1027}
        response = get(
            f"https://api.coinmarketcap.com/v2/ticker/{coin_map[coin]}/")
        try:
            price = response.json()['data']['quotes']['USD']['price']
        except Exception as e:
            price = None
        if price:
            response = f"El valor de {coin} es actualmente USD{price:.2f}"
        else:
            response = f"No pude obtener el valor de {coin}"

        dispatcher.utter_message(response)
        return [SlotSet("coin", coin)]
Ejemplo n.º 13
0
	def run(self, dispatcher, tracker, domain):
		cat = tracker.get_slot('cat');
		
		cat_url = 'https://api.thecatapi.com/v1/breeds/search?q=' + cat;
		
		response = requests.get(cat_url);
		cat_content = response.content.decode();
		cat_json = json.loads(cat_content);
		
		try:
			answer = 'This is the information about {} I could find for you: {}'.format(cat_json[0]['name'], cat_json[0]['description']);
			
		except:
			answer = "Pawrdon me, human. I haven't been able to find infurrmation about your desired cat.";
			
		dispatcher.utter_message(answer);
		
		return [SlotSet('cat', cat)];
Ejemplo n.º 14
0
    def request_next_slot(
            self,
            dispatcher,  # type: CollectingDispatcher
            tracker,  # type: Tracker
            domain  # type: Dict[Text, Any]
    ):
        # type: (...) -> Optional[List[Dict]]
        """Request the next slot and utter template if needed,
            else return None"""

        for slot in self.required_slots(tracker):
            if self._should_request_slot(tracker, slot):
                logger.debug("Request next slot '{}'".format(slot))
                dispatcher.utter_template("utter_ask_{}".format(slot), tracker)
                return [SlotSet(REQUESTED_SLOT, slot)]

        logger.debug("No slots left to request")
        return None
Ejemplo n.º 15
0
    def run(self, dispatcher, tracker, domain):
        try:
            subscribe_slot = tracker.get_slot('subscribe')
            subscribe = (tracker.latest_message)['text']

            if subscribe == 'True':
                response = 'You are successfully subscribed'
            else:
                response = 'You are not subscribed'
            # else:
            # 	response='not subscribed'
        except:
            response = 'subscribed'
            #subscribe = 'not working'

        dispatcher.utter_message(response)
        dispatcher.utter_message(subscribe_slot)
        return [SlotSet('subscribe', subscribe)]
Ejemplo n.º 16
0
 def run(self, dispatcher, tracker, domain):
     from apixu.client import ApixuClient
     api_key = '2ba4cf94bbc2427791294257191205' #your apixu key
     client = ApixuClient(api_key)
     loc = tracker.get_slot('location')
     current = client.current(q=loc)
     country = current['location']['country']
     city = current['location']['name']
     condition = current['current']['condition']['text']
     temperature_c = current['current']['temp_c']
     humidity = current['current']['humidity']
     wind_mph = current['current']['wind_mph']
     response = """It is currently {} in {} at the moment. The temperature is {} degrees, the humidity is {}% and the 
                     wind speed is {} mph.""".format(condition, city, temperature_c, humidity, wind_mph)
     ##loc = tracker.get_slot('location')
     ##response = "weather is absolutely fantastic"
     dispatcher.utter_message(response)
     return [SlotSet('location',loc)]
Ejemplo n.º 17
0
    def run(self, dispatcher, tracker, domain):
        plant = tracker.get_slot('plant')

        if plant == "kangkung":
            response = """Pupuk untuk tanaman {} adalah pupuk hidroponik seperti AB Mix hidroponik sayur kak""".format(
                plant)
        elif plant == "sawi":
            response = """Pupuk yang cocok untuk tanaman {} adalah pupuk organik atau pupuk kandang""".format(
                plant)
        elif plant == "tomat":
            response = """Untuk tumbuhan {} gunakan pupuk kandang yang sudah didekomposisi dengan EM4 lalu dicmpur dengan PHONSKA dan SP36 dengan perbandingan 2:1""".format(
                plant)
        elif plant == "cabai" or plant == "cabe":
            response = """Pupuk yang cocok untuk tanaman {} adalah campuran tanah humus, arang sekam, dan pupuk kandang kering""".format(
                plant)

        dispatcher.utter_message(response)
        return [SlotSet('plant', plant)]
Ejemplo n.º 18
0
    def run(self, dispatcher, tracker, domain):
        dispatcher.utter_message(
            "You're looking for information related to modules. Would you give me some "
            "more information on what you are looking for?")

        return [
            SlotSet("mensaName", None),
            SlotSet("menuCourse", None),
            SlotSet("price", 0.0),
            SlotSet("vegetarian", False),
            SlotSet("vegan", False),
            SlotSet("mensaMatch", None)
        ]
Ejemplo n.º 19
0
    def validate(self, dispatcher, tracker, domain):
        # type: (CollectingDispatcher, Tracker, Dict[Text, Any]) -> List[Dict]
        """Extract and validate value of requested slot.

        If nothing was extracted reject execution of the form action.
        Subclass this method to add custom validation and rejection logic
        """

        # extract other slots that were not requested
        # but set by corresponding entity or trigger intent mapping
        slot_values = self.extract_other_slots(dispatcher, tracker, domain)

        # extract requested slot
        slot_to_fill = tracker.get_slot(REQUESTED_SLOT)
        if slot_to_fill:
            slot_values.update(self.extract_requested_slot(dispatcher, tracker, domain))

            if not slot_values:
                # reject to execute the form action
                # if some slot was requested but nothing was extracted
                # it will allow other policies to predict another action
                raise ActionExecutionRejection(
                    self.name(),
                    "Failed to extract slot {0} "
                    "with action {1}"
                    "".format(slot_to_fill, self.name()),
                )

        for slot, value in list(slot_values.items()):
            validate_func = getattr(
                self, "validate_{}".format(slot), lambda *x: {slot: value}
            )
            validation_output = validate_func(value, dispatcher, tracker, domain)
            if not isinstance(validation_output, dict):
                logger.warning(
                    "Returning values in helper validation methods is deprecated. "
                    + "Your method should return a dict of {'slot_name': value} instead."
                )
                validation_output = {slot: validation_output}
            slot_values.update(validation_output)

        # validation succeed, set slots to extracted values
        return [SlotSet(slot, value) for slot, value in slot_values.items()]
Ejemplo n.º 20
0
 def run(self, dispatcher, tracker, domain):
     try:
         headers = {"Content-Type": "application/json"}
         tracker_state = tracker.current_state()
         sender_id = tracker_state['sender_id']
         message = tracker.latest_message.get('text')
         message_list = message.split()
         repo_fullname = message_list[-1]
         project_owner = repo_fullname.split("/")[0]
         repo_name = repo_fullname.split("/")[-1]
         self.save_repo_to_db(headers, message, repo_name, sender_id,
                              project_owner)
         self.set_webhook(headers, project_owner, repo_name, sender_id)
         selected_repo = "Ok, vou ficar monitorando "\
                         "o repositório {rep}.".format(
                             rep=repo_name)
         info_message = "Caso queira saber o que eu faço, "\
             "me peça ajuda 😉"
         dispatcher.utter_message(selected_repo)
         dispatcher.utter_message(info_message)
         return [SlotSet('repository_github', repo_name)]
     except KeyError:
         dispatcher.utter_message(
             "Não consegui encontrar o seu usuário no GitHub, "
             "por favor verifique ele e me manda novamente.")
     except IndexError:
         dispatcher.utter_message(
             "Não consegui encontrar o seu usuário no GitHub, "
             "por favor verifique ele e me manda novamente.")
     except NewConnectionError:
         dispatcher.utter_message(
             "Estou com problemas para me conectar, me manda "
             "mais uma mensagem pra ver se dessa vez dá certo.")
     except ValueError:
         dispatcher.utter_message(
             "Estou com problemas para me conectar, me manda "
             "mais uma mensagem pra ver se dessa vez dá certo.")
     except HTTPError:
         existent_user = "******"\
                         "do GitHub. Sinto muito, mas no momento "\
                         "não é possível cadastrar um novo usuário"\
                         " do GitHub ou alterá-lo."
         dispatcher.utter_message(existent_user)
Ejemplo n.º 21
0
    def run(self, dispatcher, tracker, domain):
        from apixu.client import ApixuClient
        api_key = 'c3e1096f0ccc478cb40101824192704'
        client = ApixuClient(api_key)

        loc = tracker.get_slot('location')
        current = client.current(q=loc)

        country = current['location']['country']
        city = current['location']['name']
        condition = current['current']['condition']['text']
        temperature_c = current['current']['humidity']
        humidity = current['current']['humidity']

        response = """It is currently {} in {} at the moment.The temperature is {} degrees.""".format(
            condition, city, temperature_c)

        dispatcher.utter_message(response)
        return [SlotSet('location', loc)]
Ejemplo n.º 22
0
 def run(self, dispatcher, tracker, domain):
     name = tracker.get_slot('pokemon').lower()
     if not name:
         response = "Sorry it seems there is no such pokemon :("
         name = "Sorry"
     elif name:
         requester = requests.get(
             'https://pokeapi.co/api/v2/pokemon/{}/'.format(name))
         req_json = requester.json()
         pokemon_name = req_json['forms'][0]['name'].upper()
         pokemon_attack = req_json['abilities'][0]['ability']['name']
         pokemon_height = req_json['height']
         pokemon_type = req_json['types'][0]['type']['name']
         pokemon_weight = req_json['weight']
         response = "Pokedex Information\n________________\n*Pokemon Name:{}\n*Type:{}\n*Height:{}\n*Weight:{}\n*Attack:{}\nThank You".format(
             pokemon_name, pokemon_type, pokemon_height, pokemon_weight,
             pokemon_attack)
     dispatcher.utter_message(response)
     return [SlotSet('pokemon', name)]
Ejemplo n.º 23
0
    def run(self, dispatcher, tracker, domain):
        defendant = tracker.get_slot('defendant')
        item = tracker.get_slot('item')
        person = graph.nodes.match("被告人", name=defendant).first()
        response = "这个系统还够完善, 没有找到{}关于'{}'的信息, 抱歉哦..".format(defendant, item)
        if (item == None or defendant == None):
            dispatcher.utter_message("服务器开小差了")
            return []

        # < id >: 0
        # name: 张青红出生地: 浙江省云和县出生日期: 1979
        # 年8月14日性别: 女户籍所在地: 云和县凤凰山街道上前溪100号文化程度: 初中文化案件号: (2017)浙1125刑初148号毒品数量: 31.3
        # 克民族: 汉族现住址: 丽水市莲都区水阁工业区齐垵村20号2楼职业: 务工
        if item.find("个人资料") != -1:
            response = "{},{},{}生,户籍所在:{}, {}程度, 现住{}, 贩毒{}".format(
                defendant, person['性别'], person['出生日期'], person['户籍所在地'],
                person['文化程度'], person['现住址'], person['毒品数量'])
        elif item.find("出生地") != -1:
            response = "{}的出生地是{}".format(defendant, person['出生地'])
        elif item.find("生日") != -1:
            response = "{}的生日是{}".format(defendant, person['出生日期'])
        elif item.find("性别") != -1:
            response = "{}的性别是:{}".format(defendant, person['性别'])
        elif item.find("户籍所在地") != -1:
            response = "{}的户籍所在地是:{}".format(defendant, person['户籍所在地'])
        elif item.find("文化程度") != -1:
            response = "{}的文化程度是:{}".format(defendant, person['文化程度'])
        elif item.find("贩毒量") != -1:
            response = "{}的贩毒量是:{}".format(defendant, person['毒品数量'])
        elif item.find("民族") != -1:
            response = "{}的民族是:{}".format(defendant, person['民族'])
        elif item.find("现住址") != -1:
            response = "{}的现住址是:{}".format(defendant, person['现住址'])
        elif item.find("职业") != -1:
            response = "{}的职业是:{}".format(defendant, person['职业'])

        graph_data = retrieveDataFromNeo4j(
            "MATCH path = (n)-[r]->(m) where n.name =~ '.*{}.*' RETURN path".
            format(defendant))
        with SocketIO('localhost', 8080) as socketIO:
            socketIO.emit('data', graph_data)
        dispatcher.utter_message(response)
        return [SlotSet('defendant', defendant)]
Ejemplo n.º 24
0
    def run(self, dispatcher, tracker, domain):
        context = tracker.get_slot("course_type")

        if not context or context == "admissions":
            response = "I can only provide this information for short courses. Is this what you were looking for?"
            buttons = [{
                "title": "Yes",
                "payload": "/confirmation"
            }, {
                "title": "No",
                "payload": "/denial"
            }]
            dispatcher.utter_button_message(response, buttons)
            return

        else:
            response = "The building will be confirmed by email three days before the start date, and the room number will be listed at reception before the class!"
            dispatcher.utter_message(response)
            return [SlotSet("course_type", "short")]
Ejemplo n.º 25
0
    def run(self, dispatcher, tracker, domain):
        buttons = []
        for t in FACILITY_TYPES:
            r = FACILITY_TYPES[t]
            payload = "/inform{\"selected_type_slot\": \"" + r.get(
                "resource") + "\"}"

            buttons.append({
                "title": "{}".format(r.get("name").title()),
                "payload": payload
            })
        dispatcher.utter_button_template("utter_greet",
                                         buttons,
                                         tracker,
                                         button_type="custom")
        return [
            SlotSet("provider_types_slot",
                    FACILITY_TYPES if FACILITY_TYPES is not None else [])
        ]
Ejemplo n.º 26
0
    def run(self, dispatcher, tracker, domain):

        loc = tracker.get_slot('location')

        import requests, json
        city = loc
        response = requests.get(
            "http://api.openweathermap.org/data/2.5/weather?appid=15295460f958fff5afe709d205204238&q={}"
            .format(city))

        description = response.json()['weather'][0]['description']
        temp = response.json()['main']['temp']
        print(description, temp)

        response = """It is currently {} in {} at the moment. The temperature is {} degrees kelvin""".format(
            description, loc, temp)

        dispatcher.utter_message(response)
        return [SlotSet('location', loc)]
Ejemplo n.º 27
0
	def run(self, dispatcher, tracker, domain):
		from apixu.client import ApixuClient
		api_key = '27b0bd86e04b4cafb4183613190707' 
		client = ApixuClient(api_key)
		
		loc = tracker.get_slot('location')
		current = client.current(q= loc)
		
		country = current['location']['country']
		city = current['location']['name']
		condition = current['current']['condition']['text']
		temperature_c = current['current']['temp_c']
		humidity = current['current']['humidity']
		wind_mph = current['current']['wind_mph']

		response = """It is currently {} in {} at the moment. The temperature is {} degrees, the humidity is {}% and the wind speed is {} mph.""".format(condition, city, temperature_c, humidity, wind_mph)
						
		dispatcher.utter_message(response)
		return [SlotSet('location',loc)]
Ejemplo n.º 28
0
    def run(self, dispatcher, tracker, domain):
        date = tracker.get_slot("date")
        city = tracker.get_slot("city")

        try:
            con = sqlite3.connect('SQL/view.db')
            cur = con.cursor()
            cur.execute(f"SELECT * from view_weather WHERE 縣市 = '{city}'")
            rows = cur.fetchall()
            for data in rows:
                if date.find("5") >= 0:
                    dispatcher.utter_message(
                        f"12月5日,根據中央氣象局資料,當天天氣可能有{data[2]}\n")
                    tracker.slots["weather"] = data[2]
                    weather = tracker.get_slot("weather")
                elif date.find("6") >= 0:
                    dispatcher.utter_message(
                        f"12月5日,根據中央氣象局資料,當天天氣可能有{data[3]}\n")
                    tracker.slots["weather"] = data[3]
                    weather = tracker.get_slot("weather")
                elif date.find("7") >= 0:
                    dispatcher.utter_message(
                        f"12月5日,根據中央氣象局資料,當天天氣可能有{data[4]}\n")
                    tracker.slots["weather"] = data[4]
                    weather = tracker.get_slot("weather")
                elif date.find("8") >= 0:
                    dispatcher.utter_message(
                        f"12月5日,根據中央氣象局資料,當天天氣可能有{data[5]}\n")
                    tracker.slots["weather"] = data[5]
                    weather = tracker.get_slot("weather")
        except Exception as e:
            logging.error(str(e))
        finally:
            cur.close()
            con.close()

        return [
            SlotSet("date", date if date is not None else []),
            SlotSet("weather", weather if weather is not None else []),
            SlotSet("city", city if city is not None else []),
            SlotSet("mountain", []),
            SlotSet("family", []),
            SlotSet("spring", []),
            SlotSet("temple", [])
        ]
Ejemplo n.º 29
0
    def run(self, dispatcher, tracker, domain):
        city = tracker.get_slot('location')

        complete_url = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&APPID=eb31f2106de4654"

        response = requests.get(complete_url)

        data = response.json()

        x = data['main']
        temp = round(x['temp'] - 273.15, 2)
        place = data["name"]
        x = data['weather']
        desc = x[0]['main']

        weather_data = "It's {}*C currently in {}. The weather can be described as {}".format(
            temp, place, desc)
        dispatcher.utter_message(weather_data)

        return [SlotSet("location", city)]
Ejemplo n.º 30
0
    def run(self, dispatcher, tracker, domain):
        from apixu.client import ApixuClient

        api_key = "ed0b641d57bb4629a5c140954181509"
        client = ApixuClient(api_key)

        loc = tracker.get_slot("location")
        current = client.getCurrentWeather(q=loc)

        city = current["location"]["name"]
        condition = current["current"]["condition"]["text"]
        temperature_c = current["current"]["temp_c"]
        humidity = current["current"]["humidity"]
        wind_mph = current["current"]["wind_mph"]

        response = """It is currently {} in {} at the moment. The temperature is {} degrees, the humidity is {}% and the wind speed is {} mph.""".format(
            condition, city, temperature_c, humidity, wind_mph)

        dispatcher.utter_message(response)
        return [SlotSet("location", loc)]