def run(self, dispatcher, tracker, domain): from apixu.client import ApixuClient api_key = '1425533582cd4b6db2c20015192801' client = ApixuClient(api_key) loc = tracker.get_slot('location') forecast_date = tracker.get_slot('time') date_format = "%Y-%m-%d" today = time.strftime(date_format, time.localtime()) if forecast_date is not None: forecast_date = forecast_date[:10] else: forecast_date = today delta = datetime.strptime(forecast_date, date_format) - datetime.strptime(today, date_format) forecast_weather = {} try: forecast_weather = client.forecast(q=loc, days=delta.days + 1) except ApixuException as e: print(e.message) dispatcher.utter_message('No matching location found. Please try again') forecast = [weather for weather in forecast_weather['forecast']['forecastday'] if forecast_date in weather.values()] city = forecast_weather['location']['name'] condition = forecast[0]['day']['condition']['text'] temperature_c = forecast[0]['day']['avgtemp_c'] response = f'The weather in {city} is {condition}, the temperature is {temperature_c}.' dispatcher.utter_message(response) return [SlotSet('location', loc)]
def forecast_weather(args): _city, _country_code = get_loc() client = ApixuClient("cc33a1e3237a4b78b3174104190206") forecast = client.forecast(q=f'{ _city},{_country_code}', days=7) print(f"{'Date':^12}|{'Min Temp':^10}|{'Max Temp':^10}|{'Condition':^15}") print(f"{'*'*47:^47}") for day in forecast['forecast']['forecastday']: print(f"{day['date']:^12}|{day['day']['mintemp_c']:^10}|{day['day']['maxtemp_c']:^10}|{day['day']['condition']['text']:^15}")
def run(self, dispatcher, tracker, domain): from apixu.client import ApixuClient api_key = '119d8d02020f4b548fe104203191104' client = ApixuClient(api_key) loc = tracker.get_slot('location') current = client.forecast(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)]
def test_forecast_no_api_key(self): client = ApixuClient() with self.assertRaises(ApixuException) as cm: client.forecast() self.assertEqual(cm.exception.code, errors.API_KEY_NOT_PROVIDED)
def test_forecast_invalid_api_key(self): client = ApixuClient('INVALID_KEY') with self.assertRaises(ApixuException) as cm: client.forecast() self.assertEqual(cm.exception.code, errors.API_KEY_INVALID)
def test_forecast(): api_key = os.environ['APIXUKEY'] client = ApixuClient(api_key) forecast = client.forecast('London', 1, 12) validate(forecast, schema.read("forecast.json"))
class apixu(awp): def __init__(self, location, listOfTimePredictions): self.name = "apixu" self.allowedTimePredictions = "N-0-0" super(apixu, self).__init__(self.name, listOfTimePredictions) self.login() self.setLocation(location) numOfDays = len(self.WD.keys()) def login(self): if self.login_data["apikey"]: self.client = ApixuClient(self.login_data["apikey"]) else: warnings.warn( 'MWP_WARNING. The "%s" Weather Package(WP) has not been \ properly activated due to the apikey' % (self.name.upper())) def setLocation(self, location): self.location = location def update(self): listOfTimePredictions = self.WD.keys() numOfDays = 0 for timePrediction in listOfTimePredictions: day = int(timePrediction.split("-")[0]) if day > numOfDays: numOfDays = day numOfDays += 1 forecast = self.client.forecast(q=self.location, days=numOfDays) for api_periods in self.weather.keys(): if api_periods == "daily": self.weather[api_periods] = forecast["forecast"]["forecastday"] elif api_periods == "currently": self.weather[api_periods] = forecast["current"] for timePrediction in listOfTimePredictions: self.setTemperature(timePrediction) self.setWindVelocity(timePrediction) self.setRainProbability(timePrediction) self.setRainIntensity(timePrediction) self.setRelativeHumidity(timePrediction) def setTemperature(self, timePrediction="0-0-0"): #Units: ºC value = self.setWeatherProperty(timePrediction, 'temp_c') self.WD[timePrediction]["Temperature"] = value def setWindVelocity(self, timePrediction="0-0-0"): #Units: m/s value = self.setWeatherProperty(timePrediction, 'wind_kph') self.WD[timePrediction][ "WindVelocity"] = value / 3.6 if value else value def setRainProbability(self, timePrediction="0-0-0"): #Units: Percentatge [0-1] #Warning: Apixu does not calculate Weather Prediction self.WD[timePrediction]["RainProbability"] = None def setRainIntensity(self, timePrediction="0-0-0"): #Units: mm/hour value = self.setWeatherProperty(timePrediction, 'precip_mm') self.WD[timePrediction]["RainIntensity"] = value def setRelativeHumidity(self, timePrediction="0-0-0"): #Units: Percentatge [0-1] value = self.setWeatherProperty(timePrediction, 'humidity') self.WD[timePrediction][ "RelativeHumidity"] = value / 100.0 if value else value def setWeatherProperty(self, timePrediction, WP): value = None day, hour, minute, predictionType = decomposeTimePrediction( timePrediction) try: if day: value = self.weather[predictionType][day]["day"][WP] elif not day and \ not hour and \ not minute : value = self.weather[predictionType][WP] except: print("WP[%s]: \"%s\" is not available for \"%s\" prediction. " % (self.name, WP, predictionType)) return value
import os from apixu.client import ApixuClient api_key = os.environ['APIXUKEY'] client = ApixuClient(api_key=api_key, lang="es") forecast = client.forecast(q='London', days=2) print(forecast['location']['name']) print(forecast['current']['last_updated_epoch']) print(forecast['current']['condition']['text']) for day in forecast['forecast']['forecastday']: print(day['date']) print(day['day']['maxtemp_c']) ''' { "location":{ "name":"London", "region":"City of London, Greater London", "country":"United Kingdom", "lat":51.52, "lon":-0.11, "tz_id":"Europe/London", "localtime_epoch":1548103480, "localtime":"2019-01-21 20:44" }, "current":{