def getNowWeather(self, place=None): try: from apixu.client import ApixuClient, ApixuException client = ApixuClient(api_key) if not place: current = client.getCurrentWeather(q='Buea') else: current = client.getCurrentWeather(q=str(place)) cur_ = current['current'] self.pressure.text = str(cur_['pressure_mb']) + ' mb' self.tmp_value.text = str(cur_['temp_c']) + u'\u00b0' + ' C' self.temperature.text = str(cur_['temp_c']) + u'\u00b0' + ' C' self.humidity.text = str(cur_['humidity']) + '%' # self.sunrise.text = to be done self.visibility.text = str(cur_['vis_km']) + ' Km' self.local_time.text = str(current['location']['localtime']) self.precipitation.text = str(cur_['precip_mm']) + 'mm' self.feels.text = str(cur_['feelslike_c']) + u'\u00b0' + ' C' self.region.text = str(current['location']['region']) self.country.text = str(current['location']['country']) self.sky_state.text = str(cur_['condition']['text']) self.wind.text = str(cur_['wind_kph']) + 'kph' self.pressure.text = str(cur_['pressure_mb']) + 'mb' self.humidity.text = str(cur_['humidity']) except ConnectionError: ConErrorPop().open()
def run(self, dispatcher, tracker, domain): # from apixu.client import ApixuClient api_key = '6941d2731345403db6481426182012' client = ApixuClient(api_key) # # try: loc = tracker.get_slot('location') if loc != None: try: current = client.getCurrentWeather(q=loc) except: response = "Sorry I unable fetch weather, Some problem in fetching the data, Please retry or try some other location." dispatcher.utter_message(response) return [SlotSet('location',None)] # 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 = """Thanks for waiting.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) # response = 'testing' dispatcher.utter_message(response) return [SlotSet('location',None)] else: response = """Sorry ,I can't fetch,Please try someother location or rephases and type it""" dispatcher.utter_message(response) return [SlotSet('location',None)]
def get_weather_data(place): client = ApixuClient(apixukey) try: current = client.getCurrentWeather(q=place) res = place, get_temp(current) except ApixuException: res = None return res
def run(self, dispatcher, tracker, domain): from apixu.client import ApixuClient api_key = '5ed103a862bd442182385105181306' client = ApixuClient(api_key) loc = tracker.get_slot('location') current = client.getCurrentWeather(q=loc) city = current['location']['name'] condition = current['current']['condition']['text'] response = """It is currently {} in {} at the moment.""".format( condition, city) dispatcher.utter_message(response) return [SlotSet('location', loc)]
def getApixu(ApiKey): # create the Apixu client obj & query current & 7 forecast weather data try: client = ApixuClient(ApiKey) # these weather are in a dict form [json] currentWeather = client.getCurrentWeather(q = "Harare") # get current weather for Hre forecastWeather = client.getForecastWeather(q = "Harare", days = 7) # get weather forecast for Hre return True, currentWeather, forecastWeather except ApixuException as e: return False, "[!] Error querying data {}".format(e.message)
def run(self, dispatcher, tracker, domain): from apixu.client import ApixuClient api_key = "d1881979fb4d4ee4879110427182103" client = ApixuClient(api_key) loc = tracker.get_slot('location') current = client.getCurrentWeather(loc) country = current['location']['country'] city = current['location']['name'] condition = current['current']['condition']['text'] temperatur = current['current']['temp_c'] humudity = current['current']['humidity'] wind_mph = current['current']['wind_mph'] response = """ It is currently {} in {} at the moment. The remperatur is {} degrees, the humidity is {}% and wind speed is {} mph. """.format(condition, city, temperatur, humudity, wind_mph) dispatcher.utter_message(response) return [SlotSet('location', loc)]
def run(self, dispatcher, tracker, domain): from apixu.client import ApixuClient api_key = '...' #your apixu key client = ApixuClient(api_key) loc = tracker.get_slot('location') current = client.getCurrentWeather(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 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)]
def run(self,dispatcher, tracker, domain): api_key = "9b14178e623944e4b3631246181904" client = ApixuClient(api_key) loc = tracker.get_slot('location') current = client.getCurrentWeather(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'] windspeed = current['current']['wind_mph'] response = """It is currently {} in {} at the moment. The temperature " \ "is {} degrees, humidity is {}% and the wind speed is {} mph""".format(condition, city, temperature_c, humidity, windspeed) dispatcher.utter_message(response) return [SlotSet('location',loc)]
def run(self, dispatcher, tracker, domain): from apixu.client import ApixuClient api_key = config("APIXU_KEY") client = ApixuClient(api_key) loc = tracker.get_slot('location') current = client.getCurrentWeather(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 = f"""It is currently {condition} in {city}, {country}. The temperature is {temperature_c} degrees, the humidity is {humidity}% and the wind speed is {wind_mph} mph.""" dispatcher.utter_message(response) return [SlotSet('location', loc)]
def run (self,dispatcher,tracker,domain): from apixu.client import ApixuClient api_key = 'a2a1f7505d534755929211912181705' client = ApixuClient(api_key) loc = tracker.get_slot('location') current = client.getCurrentWeather(q=loc) # the response is a dictionnary 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, celsius,wind_mph) dispatcher.utter_message(response) return[SlotSet('location',loc)]
def weather(self, irc, msg, args, place): '''<place> Current weather for a <place>. ''' api_key = self.registryValue('api_key') if not api_key: irc.error( 'The API key is missing. ' 'Please configure the plugins.Weather.api_key directive.', Raise=True, ) place = place.lower() if place in Weather.PLACES: place = Weather.PLACES[place] try: client = ApixuClient(api_key) response = client.getCurrentWeather(q=place) last_updated = datetime.fromtimestamp( response['current']['last_updated_epoch'], ).strftime('%Y-%m-%d %H:%M') irc.reply( 'The current temperature in {l[name]}, ' '{l[country]} is {w[temp_c]} °C ' '(feels like {w[feelslike_c]} °C). ' 'Conditions: {w[condition][text]}. ' 'Humidity: {w[humidity]} %. ' 'Wind: {w[wind_dir]} {w[wind_kph]} km/h ({d}).'.format( w=response['current'], l=response['location'], d=last_updated, ) ) except Exception as e: irc.error(unicode(e))
def run(self, dispatcher, tracker, domain): from apixu.client import ApixuClient api_key = '1499cd68946d4387b6c175525181806' # your apixu key client = ApixuClient(api_key) loc = tracker.get_slot('location') current = client.getCurrentWeather(q=loc) country = current['location']['country'] city = current['location']['name'] condition = current['current']['condition']['text'] temperature_c = current['current']['temp_c'] feelslike_c = current['current']['feelslike_c'] humidity = current['current']['humidity'] wind_kph = current['current']['wind_kph'] response = """It is currently {} in {}/{} at the moment. \nThe temperature is {} oC feels like {} oC.\n The humidity is {}% and the wind speed is {} kph.""".format( condition, city, country, temperature_c, feelslike_c, humidity, wind_kph) dispatcher.utter_message(response) return [SlotSet('location', loc)]
def run(self, dispatcher, tracker, domain): from apixu.client import ApixuClient, ApixuException api_key = '' #Provide your apixu Key here client = ApixuClient(api_key) #TODO: retrieve the slot value and make an api call loc = tracker.get_slot('location') current = client.getCurrentWeather(q=loc) country = current['location']['country'] city = current['location']['name'] condition = current['current']['condition']['text'] temperature_c = current['current']['temp_c'] temperature_f = current['current']['temp_f'] humidity = current['current']['humidity'] wind_mph = current['current']['wind_mph'] #TODO: create a response message and dispatch it to the output channel 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 run(self, dispatcher, tracker, domain): api_key = 'bc28bfb2026a474f808213126182805' #your apixu key client = ApixuClient(api_key) city = tracker.get_slot("city") current = client.getCurrentWeather(q=city) country = current['location']['country'] city = current['location']['name'] condition = current['current']['condition']['text'] temperature_c = current['current']['temp_c'] humidity = current['current']['humidity'] wind_kph = current['current']['wind_kph'] wind_dir = current['current']['wind_dir'] cloud = current['current']['cloud'] feelslike_c = current['current']['feelslike_c'] response = """It is currently {} in {}, {} at the moment. The temperature is {} degrees, the humidity is {}% and the wind speed is {} kph coming from the {}. Cloud covering is {}% and thermal sensation is {} degrees.""".format( condition, city, country, temperature_c, humidity, wind_kph, wind_dir, cloud, feelslike_c) dispatcher.utter_message(response) return [SlotSet('city', city)]
'Mumbwa', 'Muyombe' ] towns_seven = [ 'Mwinilunga', 'Nchelenge', 'Ndola', 'Ngoma', 'Nkana', 'Pemba', 'Petauke', 'Samfya', 'Senanga' ] towns_eight = [ 'Serenje', 'Sesheke', 'Shiwa', 'Ngandu', 'Siavonga', 'Sikalongo', 'Sinazongwe', 'Solwezi', 'Zambezi', 'Zimba' ] towns = towns_one + towns_two + towns_three + towns_four + towns_five + towns_six + towns_seven + towns_eight for x in towns: print x current = client.getCurrentWeather(q=x) #r.db('test').table_create('weather_2').run() ''' tables = """CREATE TABLE IF NOT EXISTS %s ( `id` int(11) NOT NULL AUTO_INCREMENT, `cloud` int(5) DEFAULT NULL, `condition_text` varchar(20) DEFAULT NULL, `condition_code` int(5) DEFAULT NULL, `icon` text, `temperature` float DEFAULT NULL, `humidity` int(5) DEFAULT NULL, `wind_degree` int(5) DEFAULT NULL, `wind_dir` varchar(5) DEFAULT NULL, `wind_kph` float DEFAULT NULL, `localtime` text, `region` varchar(30) DEFAULT NULL,
def test_getCurrentWeather_invalid_api_key(self): client = ApixuClient('INVALID_KEY') with self.assertRaises(ApixuException) as cm: client.getCurrentWeather() self.assertEqual(cm.exception.code, 2006)
lines = out_decode.split('\n') return lines # Reads temperature, outputs farenhiet def read_temp(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 temp_f = temp_c * 9.0 / 5.0 + 32.0 return temp_f weather = client.getCurrentWeather(q='22304') data_time = calendar.timegm(time.gmtime()) measured_temp = read_temp() temp_f = weather['current']['temp_f'] # show temprature in f auth=os.getenv('TEMP_EXPLICIT_AUTH') uid=os.getenv('TEMP_UID') url=os.getenv('TEMP_FIREBASE_URL') auth = firebase.FirebaseAuthentication(auth, 'Ignore', extra={'explicitAuth': auth, 'uid':uid }) print auth.extra firebase = firebase.FirebaseApplication(url, auth) print temp_f
# Town names array, helps to grab the data for each specific town. towns_one = ['Chadiza', 'Chama', 'Chavuma', 'Chembe', 'Chibombo', 'Chiengi', 'Chililabombwe', 'Chilubi', 'Chingola', 'Chinsali'] towns_two = ['Chipata', 'Chirundu', 'Choma', 'Gwembe', 'Isoka', 'Kabwe', 'Kafue', 'Kalabo'] towns_three = ['Kalomo', 'Kaoma', 'Kapiri', 'Kasama', 'Kasempa', 'Kataba', 'Katete', 'Kawambwa', 'Kazembe'] towns_four = ['Kazungula', 'Kitwe', 'Livingstone', 'Luangwa', 'Luanshya', 'Lukulu', 'Lundazi'] towns_five = ['Lusaka', 'Maamba', 'Makeni', 'Mansa', 'Mazabuka', 'Mbala', 'Mbereshi', 'Milenge'] towns_six = ['Mkushi', 'Mongu', 'Monze', 'Mpika', 'Mporokoso', 'Mpulungu', 'Mufulira', 'Mumbwa', 'Muyombe'] towns_seven = ['Mwinilunga', 'Nchelenge', 'Ndola', 'Ngoma', 'Nkana', 'Pemba', 'Petauke', 'Samfya', 'Senanga'] towns_eight = ['Serenje', 'Sesheke', 'Shiwa', 'Ngandu', 'Siavonga', 'Sikalongo', 'Sinazongwe', 'Solwezi', 'Zambezi', 'Zimba'] towns = towns_one + towns_two + towns_three + towns_four + towns_five + towns_six + towns_seven + towns_eight for x in towns: print x current = client.getCurrentWeather(q=x) tables = """CREATE TABLE IF NOT EXISTS %s ( `id` int(11) NOT NULL AUTO_INCREMENT, `cloud` int(5) DEFAULT NULL, `condition_text` varchar(20) DEFAULT NULL, `condition_code` int(5) DEFAULT NULL, `icon` text, `temperature` float DEFAULT NULL, `humidity` int(5) DEFAULT NULL, `wind_degree` int(5) DEFAULT NULL, `wind_dir` varchar(5) DEFAULT NULL, `wind_kph` float DEFAULT NULL, `localtime` text, `region` varchar(30) DEFAULT NULL, `tz_id` varchar(50) DEFAULT NULL,
def get_weather_api_json(request, location): api_key = '78f26cd450d44500953134819172807' client = ApixuClient(api_key) current = client.getCurrentWeather(q=location) return JsonResponse(current)
def test_getCurrentWeather_no_api_key(self): client = ApixuClient() with self.assertRaises(ApixuException) as cm: client.getCurrentWeather() self.assertEqual(cm.exception.code, 1002)
def get_weather(self): client = ApixuClient(os.environ.get("APIXU_API_KEY")) current = client.getCurrentWeather(q='Sydney') return current.get("current").get("temp_c")
def on_get(self, req, resp): #Alphabet list to check against client's state entry for proper weather API routing clientlog = open('/Weather API Conflict/logs/accesslog.txt', "a") alphabet = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z' ] alphabetlow = [ letter.lower() for letter in alphabet ] #using .lower method in case client enter state with lowercase letter print(alphabet) print(alphabetlow) city = req.get_param('city') zipcode = req.get_param('zip') state = req.get_param('state') print('Client requesting weather information for ' + city + ', ' + state + ' with zipcode of ' + zipcode) statebegins = state[0:1] if (re.match("^[A-Za-z ]+$", state) and re.match("^[A-Za-z ]+$", city) and re.match("^[0-9]+$", zipcode)): print('All characters are letters') try: if ( statebegins in alphabet[0:13] ): #send client request to openweather API if state begins with A - M clientlog.write( str(datetime.now()) + ': Client requesting weather information for ' + city + ', ' + state + ' with zipcode of ' + zipcode) print( state + ' weather information must be requested from Open Weather Api' ) logger.info( 'Starting Weather forecast request to OpenWeather API') resp.status = falcon.HTTP_200 owapikey = "0c9597524a3f445d77b02ccda4e6b577" request_url = "https://api.openweathermap.org/data/2.5/weather" request_param = {'zip': zipcode, 'appid': owapikey} request_header = {} request_response = requests.get(url=request_url, params=request_param, headers=request_header) request_url2 = "https://api.openweathermap.org/data/2.5/forecast" request_param2 = {'zip': zipcode, 'appid': owapikey} request_header2 = {} request_response2 = requests.get(url=request_url2, params=request_param2, headers=request_header2) weatherinfo = request_response.json() wi = weatherinfo weatherinfo2 = request_response2.json() wi2 = weatherinfo2 print(request_url) #construct weather information response from OpenWeather API tobody = ('Location: ' + wi['name'] + '\n' + 'Current Temperature: ' + str(wi['main']['temp']) + '\n' + 'Tom. High: ' + str(wi2['list'][0]['main']['temp_max']) + '\n' + 'Tom. Low: ' + str(wi2['list'][0]['main']['temp_min']) + '\n' + 'Current Weather Conditions: ' + wi['weather'][0]['description'] + '\n' + 'Tom. Weather Conditions: ' + wi2['list'][0]['weather'][0]['description'] + '\n' + 'Sunrise: ' + str(wi['sys']['sunrise']) + '\n' + 'Sunset: ' + str(wi['sys']['sunset'])) jsonbodyow = { 'Location': wi['name'], 'Current Temperature': str(wi['main']['temp']), 'Tom. High': str(wi2['list'][0]['main']['temp_max']), 'Tom. Low': str(wi2['list'][0]['main']['temp_min']), 'Current Weather Conditions': wi['weather'][0]['description'], 'Tom. Weather Conditions': wi2['list'][0]['weather'][0]['description'], 'Sunrise': str(wi['sys']['sunrise']), 'Sunset': str(wi['sys']['sunset']) } #Print nonjsonformatted weather info to terminal #print(tobody) owjsonbody = json.dumps(jsonbodyow) jsonbodyload = json.loads(owjsonbody) print(owjsonbody) #display weather information in client body nonjsonformatted #resp.body = (tobody) #JSON Formatted body response resp.append_header('API', 'Open Weather API') resp.body = owjsonbody elif ( statebegins in alphabet[13:25] ): #send client request to apixu API if state begins with N - Z print( state + ' weather information must be requested from APIXU Api' ) logger.info( 'Starting Weather forecast request to APIXU API') resp.status = falcon.HTTP_200 xuapikey = "b8f9f07b62c7415fa8862117183108" client = ApixuClient(xuapikey) current = client.getCurrentWeather(q=zipcode) forecast = client.getForecastWeather(q=zipcode, days=2) #construct weather information response from APIXU tobodyxu = ( 'Location: ' + current['location']['name'] + '\n' + 'Current Temperature: ' + str(current['current']['temp_c']) + '\n' + 'Tom. High: ' + str(forecast['forecast']['forecastday'] [1]['day']['maxtemp_c']) + '\n' + 'Tom. Low: ' + str(forecast['forecast']['forecastday'] [1]['day']['mintemp_c']) + '\n' + 'Current Weather Conditions: ' + current['current']['condition']['text'] + '\n' + 'Tom. Weather Conditions: ' + str(forecast['forecast']['forecastday'][1]['day'] ['condition']['text']) + '\n' + 'Sunrise: ' + forecast['forecast']['forecastday'][0]['astro'] ['sunrise'] + '\n' + 'Sunset: ' + forecast['forecast'] ['forecastday'][0]['astro']['sunset']) #Weather information formatted for JSON conversion jsonbodyxu = { ' Location': current['location']['name'], 'Current Temperature': str(current['current']['temp_c']), 'Tom. High': str(forecast['forecast']['forecastday'][1]['day'] ['maxtemp_c']), 'Tom. Low': str(forecast['forecast']['forecastday'][1]['day'] ['mintemp_c']), 'Current Weather Conditions': current['current']['condition']['text'], 'Tom. Weather Conditions': str(forecast['forecast']['forecastday'][1]['day'] ['condition']['text']), 'Sunrise': forecast['forecast']['forecastday'][0]['astro'] ['sunrise'], 'Sunset': forecast['forecast']['forecastday'][0]['astro'] ['sunset'] } #Print nonjsonformatted weather info to terminal #print(tobodyxu) jsonbody = json.dumps(jsonbodyxu) jsonbodyload = json.loads(jsonbody) print(jsonbody) #display weather information in client body nonjsonformatted #resp.body = (tobodyxu) #Json Formatted Body Response resp.body = (jsonbody) else: #respond with error if client enters invalid state i.e. first character is not a letter print('Error in parameters issued by client') resp.status = falcon.HTTP_406 resp.body = 'You have entered an invalid State parameter.' except Exception: logger.error('Something major has gone wrong', exc_info=True) else: resp.status = falcon.HTTP_406 logger.error('Client entered invalid parameters', exc_info=True) #resp.body = 'Your input contains invalid characters.' raise falcon.HTTPError('Bad request', 'Your input contains invalid characters.')
from apixu.client import ApixuClient, ApixuException api_key = '9838870ce6324daf95d161656180811' client = ApixuClient(api_key) # Constant names apixu_limit_weather = 7 # 7 days limit apixu_month_limit_calls = 10000 # 10000 limit calls per month # Variable names order = "weather" ########################### # current weather ########################### current = client.getCurrentWeather(q='London') # "current" is a dict with a structure like this: """ { 'current': { 'cloud': 0, 'condition': { 'code': 1000, 'icon': 'http://www.apixu.com/static/weather/64x64/day/113.png', 'text': 'Sunny' }, 'feelslike_c': 24.6, 'feelslike_f': 76.2, 'humidity': 36, 'last_updated': '2015-06-29 13:30', 'last_updated_epoch': 1435584602, 'precip_in': 0.0,
from apixu.client import ApixuClient api_key = '8cf4dc262c664ae59b0223043183010' client = ApixuClient(api_key) current = client.getCurrentWeather(q='in atlanta') print(current['current']['condition']['text'])