def current_weather(): api_key = '3ee50f44c4e30cacbd795358f1c6531d' city_entry = cityE.get() country_entry = countryE.get() lat = latitudeE.get() lon = longitudeE.get() current_data_header = [] current_data = [] geo_locator = Nominatim(user_agent="WinPS") if city_entry != '' and country_entry != '': owm = OWM(api_key) mgr = owm.weather_manager() loc = city_entry + ', ' + country_entry observation = '' try: observation = mgr.weather_at_place(loc) except: t.messagebox.showinfo( 'WinPS-1.1 INFO!!', 'Something bad Happened.\nCheck your Internet connection and make sure location is entered correctly.!' ) log_details.config(state='normal') log_details.insert(t.INSERT, '\nSomething bad Happened.\n') log_details.insert( t.INSERT, '\nCheck your Internet connection and make sure location is entered correctly !!\n' ) log_details.config(state='disabled') current_data_header = [ 'Time', 'Location', 'Temperature', 'Wind Speed', 'Description', 'Pressure' ] # current weather section................................................................................... data = [] curr_time = datetime.datetime.now() current_time = curr_time.strftime("%H:%M:%S") curr_date = str(curr_time.day) + '/' + str( curr_time.month) + '/' + str(curr_time.year) curr_time_stamp = str(current_time) + ' on ' + curr_date data.append(curr_time_stamp) data.append(loc) temperature = observation.weather.temperature('celsius')[ 'temp'] # temperature data.append(temperature) wind = observation.weather.wind()['speed'] # speed in mps data.append(wind) windSpeed = wind * 3.6 # speed in kps weather = observation.weather status = weather.detailed_status # status data.append(status) pressure = observation.weather.pressure[ 'press'] # atmospheric pressure data.append(pressure) current_data.append(data) elif lat != '' and lon != '': owm = OWM(api_key) mgr = owm.weather_manager() location = geo_locator.reverse(lat + "," + lon) address = location.raw['address'] city_name = address.get('city', '') if city_name == '': city_name = address.get('town', '') country_name = address.get('country', '') loc = str(city_name) + ', ' + str(country_name) observation = '' try: observation = mgr.weather_at_coords(float(lat), float(lon)) except: t.messagebox.showinfo( 'WinPS-1.1 INFO!!', 'Something bad Happened.\nCheck your Internet connection and make sure location is entered correctly.!' ) log_details.config(state='normal') log_details.insert(t.INSERT, '\nSomething bad Happened.\n') log_details.insert( t.INSERT, '\nCheck your Internet connection and make sure location is entered correctly !!\n' ) log_details.config(state='disabled') current_data_header = [ 'Time', 'Location', 'Temperature', 'Wind Speed', 'Description', 'Pressure' ] # current weather section................................................................................... data = [] curr_time = datetime.datetime.now() current_time = curr_time.strftime("%H:%M:%S") curr_date = str(curr_time.day) + '/' + str( curr_time.month) + '/' + str(curr_time.year) curr_time_stamp = str(current_time) + ' on ' + curr_date data.append(curr_time_stamp) data.append(str(loc)) temperature = observation.weather.temperature('celsius')[ 'temp'] # temperature data.append(temperature) wind = observation.weather.wind()['speed'] # speed in mps data.append(wind) windSpeed = wind * 3.6 # speed in kps weather = observation.weather status = weather.detailed_status # status data.append(status) pressure = observation.weather.pressure[ 'press'] # atmospheric pressure data.append(pressure) current_data.append(data) log_details.config(state='normal') log_details.insert( t.INSERT, '\n\n-------------Current Weather Section-------------\n') log_details.insert(t.INSERT, str(loc) + '\n') log_details.insert(t.INSERT, 'Date: ' + str(curr_date) + '\n') log_details.insert(t.INSERT, 'Time: ' + str(current_time) + '\n') log_details.insert( t.INSERT, 'Current Temperature: ' + str(temperature) + ' degree C\n') log_details.insert(t.INSERT, 'Current Wind Speed in mps: ' + str(wind) + ' m/s\n') log_details.insert( t.INSERT, 'Current Wind Speed in kph: ' + str(windSpeed) + ' km/h\n') log_details.insert( t.INSERT, 'Current Atmospheric Pressure: ' + str(pressure) + '\n') log_details.insert(t.INSERT, 'Current Status: ' + str(status) + '\n') log_details.config(state='disabled') if not os.path.isfile('current_weather_data.csv'): try: with open('current_weather_data.csv', 'w', encoding="UTF8", newline='') as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow(current_data_header) csv_writer.writerows(current_data) except PermissionError: t.messagebox.showerror( 'WinPS-1.1', 'Permission Denied to entry data.\nMake Sure The data file is closed.' ) log_details.config(state='normal') log_details.insert( t.INSERT, '\nPermission Denied to entry data.\n\nMake Sure The data file is closed.\n\n' ) log_details.config(state='disabled') else: if os.stat('current_weather_data.csv').st_size == 0: try: with open('current_weather_data.csv', 'w', encoding="UTF8", newline='') as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow(current_data_header) csv_writer.writerows(current_data) except PermissionError: t.messagebox.showerror( 'WinPS-1.1', 'Permission Denied to entry data.\nMake Sure The data file is closed.' ) log_details.config(state='normal') log_details.insert( t.INSERT, '\nPermission Denied to entry data.\n\nMake Sure The data file is closed.\n' ) log_details.config(state='disabled') else: try: with open('current_weather_data.csv', 'a', encoding="UTF8", newline='') as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerows(current_data) except PermissionError: t.messagebox.showerror( 'WinPS-1.1', 'Permission Denied to entry data.\nMake Sure The data file is closed.' ) log_details.config(state='normal') log_details.insert( t.INSERT, '\nPermission Denied to entry data.\n\nMake Sure The data file is closed.\n' ) log_details.config(state='disabled') current_situation_d(temperature, wind, windSpeed, pressure) choice_enter.delete(0, 'end')
def main(say, widget): for i in trigger: if i in say: weather_city = say.replace(i, '') weather_city = weather_city.replace(' ', '') for toExclude in excludeList: weather_city = weather_city.replace(toExclude, '') try: id = OWM('e45bc007f87a48d597d60091779f2d88', config_dict) mgr = id.weather_manager() last = weather_city[-1] # Склонение введённого пользователем города. if last == 'е': try: city = weather_city.replace(weather_city[-1], "а") observation = mgr.weather_at_place(city) w = observation.weather except Exception: pass try: city = weather_city[:-1] observation = mgr.weather_at_place(city) w = observation.weather except Exception: pass try: city = weather_city.replace(weather_city[-1], "ь", count=1) observation = mgr.weather_at_place(city) w = observation.weather except Exception: pass try: city = weather_city observation = mgr.weather_at_place(city) w = observation.weather except Exception: pass elif last == 'о': try: city = weather_city observation = mgr.weather_at_place(city) w = observation.weather except Exception: pass elif last == 'и': try: city = weather_city.replace(weather_city[-1], "ь") observation = mgr.weather_at_place(city) w = observation.weather except Exception: pass else: try: city = weather_city observation = mgr.weather_at_place(city) w = observation.weather except Exception: pass toSpeak = "В " + weather_city + " сейчас " + str( int(w.temperature('celsius')['temp']) ) + " градусов по цельсию, " + w.detailed_status + "." if float(w.temperature('celsius')['temp']) >= 20: toSpeak += "\nСейчас на улице жарко. Идите загорать." elif float(w.temperature('celsius')['temp']) <= 19 and float( w.temperature('celsius')['temp']) >= 10: toSpeak += "\nЗа окном прохладно. Оденьте куртку." elif float(w.temperature('celsius')['temp']) <= 9 and float( w.temperature('celsius')['temp']) >= 0: toSpeak += "\nНа улице холодно. Оденьтесь в осеннюю одежду." else: toSpeak += "\nНа улице очень холодно, лучше туда не ходить. Выпейте горячего чаю." except Exception: toSpeak = "Такого города не существует или у меня нет подключения к интернету!" break else: toSpeak = "" if toSpeak != "": speak.speak(toSpeak, widget) return toSpeak
#easy_waether from pyowm.owm import OWM from pyowm.utils.config import get_default_config config_dict = get_default_config() config_dict['language'] = 'ru' # your language here owm = OWM('my_api', config_dict) city_name = input("Введите город/страну: ") mgr = owm.weather_manager() observation = mgr.weather_at_place(city_name) w = observation.weather print("В " + city_name + " сейчас " + w.detailed_status) wind_speed = w.wind()["speed"] #temp_min = w.temperature('celsius')["temp_min"] #temp_max = w.temperature('celsius')["temp_max"] temp = w.temperature('celsius')["temp"] print("Текущая темпереатура: " + str(temp) + "C") #print("Минимальная темпереатура: " + str(temp_min)) #print("Максимальная темпереатура: " + str(temp_max)) print("Скорость ветра: " + str(wind_speed) + " м/с ")
class owmWxWorker(object): def __init__(self, data, scheduler): self.data = data self.weather_frequency = data.config.weather_update_freq self.time_format = data.config.time_format self.icons = get_csv("ecIcons_utf8.csv") self.apikey = data.config.weather_owm_apikey self.network_issues = False self.owm = OWM(self.apikey) self.owm_manager = self.owm.weather_manager() scheduler.add_job(self.getWeather, 'interval', minutes=self.weather_frequency, jitter=60, id='owmWeather') #Check every 5 mins for testing only #scheduler.add_job(self.CheckForUpdate, 'cron', minute='*/5') #Get initial obs self.getWeather() def getWeather(self): if self.data.config.weather_units == "metric": self.data.wx_units = ["C", "kph", "mm", "miles", "hPa", "ca"] else: self.data.wx_units = ["F", "mph", "in", "miles", "MB", "us"] #while True: lat = self.data.latlng[0] lon = self.data.latlng[1] #Testing #lat = 32.653 #lon = -83.7596 try: debug.info("Refreshing OWM current observations weather") obs = self.owm_manager.weather_at_coords(lat, lon) self.network_issues = False self.data.wx_updated = True #except PyOWMError as e: # #raise ValueError(e) # debug.error("Unable to get OWM data error:{0}".format(e)) # self.data.wx_updated = False # self.network_issues = True # pass except Exception as e: debug.error("Unable to get OWM data error:{0}".format(e)) self.data.wx_updated = False self.network_issues = True pass if not self.network_issues: wx = obs.weather.to_dict() if self.time_format == "%H:%M": wx_timestamp = datetime.datetime.now().strftime("%m/%d %H:%M") else: wx_timestamp = datetime.datetime.now().strftime( "%m/%d %I:%M %p") owm_wxcode = int(wx.get("weather_code")) if owm_wxcode in range(200, 299): # Thunderstorm Class owm_icon = 200 elif owm_wxcode in range(300, 399): # Drizzle Class owm_icon = 300 elif owm_wxcode in range(500, 599): # Rain Class owm_icon = 500 elif owm_wxcode in range(600, 699): # Rain Class owm_icon = 600 elif owm_wxcode in range(800, 805): # Rain Class owm_icon = 801 else: owm_icon = owm_wxcode #Get condition and icon from dictionary for row in range(len(self.icons)): if int(self.icons[row]["OWMCode"]) == owm_icon: wx_icon = self.icons[row]['font'] break else: wx_icon = '\uf07b' wx_summary = wx.get("detailed_status") # Get wind information. if self.data.config.weather_units != "metric": wx_wind = obs.weather.wind(unit='miles_hour') else: wx_wind = obs.weather.wind() owm_windspeed = wx_wind['speed'] if 'gust' in wx_wind: owm_windgust = wx_wind['gust'] else: owm_windgust = 0 if self.data.config.weather_units == "metric": # Convert m/s to km/h owm_windspeed = wind_kmph(owm_windspeed) owm_windgust = wind_kmph(owm_windgust) # Get icon and text wind direction owm_winddir = wx_wind.get("deg", 0.0) winddir = degrees_to_direction(owm_winddir) wx_windgust = str(round(owm_windgust, 1)) + self.data.wx_units[1] wx_windspeed = str(round(owm_windspeed, 1)) + self.data.wx_units[1] # Get temperature and apparent temperature based on weather units if self.data.config.weather_units == "metric": owm_temp = obs.weather.temperature('celsius')['temp'] owm_app_temp = obs.weather.temperature('celsius')['feels_like'] check_windchill = 10.0 else: owm_temp = obs.weather.temperature('fahrenheit')['temp'] owm_app_temp = obs.weather.temperature( 'fahrenheit')['feels_like'] check_windchill = 50.0 if owm_app_temp == None: if float(owm_temp) < check_windchill: windchill = round( wind_chill(float(owm_temp), float(owm_windspeed), "mps"), 1) wx_app_temp = str(windchill) + self.data.wx_units[0] wx_temp = str(round(owm_temp, 1)) + self.data.wx_units[0] else: if self.data.config.weather_units == "metric": wx_app_temp = wx.get('humidity') else: wx_app_temp = wx.get('heat_index') if wx_app_temp == None: app_temp = usaheatindex(float(owm_temp), wx.get_humidity()) wx_app_temp = str(round(temp_f(app_temp), 1)) + self.data.wx_units[0] else: wx_app_temp = str(round(owm_app_temp, 1)) + self.data.wx_units[0] wx_temp = str(round(owm_temp, 1)) + self.data.wx_units[0] wx_humidity = str(wx.get('humidity')) + "%" wx_dewpoint = str( round(dew_point(float(owm_temp), wx.get('humidity')), 1)) + self.data.wx_units[0] wx_pressure = str( wx.get('pressure')['press']) + " " + self.data.wx_units[4] # Always set icon to N/A as owm doesn't return tendency for pressure wx_tendency = '\uf07b' vis_distance = wx.get('visibility_distance') if vis_distance == None: vis_distance = 24100 if self.data.config.weather_units == "metric": owm_visibility = round(vis_distance / 1000, 1) wx_visibility = str(owm_visibility) + " km" else: owm_visibility = round(vis_distance * 0.000621371, 1) wx_visibility = str(owm_visibility) + " mi" self.data.wx_current = [ wx_timestamp, wx_icon, wx_summary, wx_temp, wx_app_temp, wx_humidity, wx_dewpoint ] self.data.wx_curr_wind = [ wx_windspeed, winddir[0], winddir[1], wx_windgust, wx_pressure, wx_tendency, wx_visibility ] debug.info(self.data.wx_current) debug.info(self.data.wx_curr_wind)
class TestOWM(unittest.TestCase): __test_instance = OWM('fake-api-key') def test_instantiation(self): with self.assertRaises(TypeError): OWM() with self.assertRaises(AssertionError): OWM(None) with self.assertRaises(AssertionError): OWM('fake-api-key', 123456) result = OWM('fake-api-key', dict()) self.assertIsInstance(result, OWM) def test_properties(self): version = self.__test_instance.version self.assertIsInstance(version, tuple) config = self.__test_instance.configuration self.assertIsInstance(config, dict) def test_repr(self): print(self.__test_instance) def test_city_id_registry(self): result = self.__test_instance.city_id_registry() self.assertIsNotNone(result) self.assertIsInstance(result, CityIDRegistry) def test_stations_manager(self): result = self.__test_instance.stations_manager() self.assertTrue(result is not None) self.assertIsInstance(result, StationsManager) def test_alert_manager(self): result = self.__test_instance.alert_manager() self.assertTrue(result is not None) self.assertIsInstance(result, AlertManager) def test_uvindex_manager(self): result = self.__test_instance.uvindex_manager() self.assertTrue(result is not None) self.assertIsInstance(result, UVIndexManager) def test_airpollution_manager(self): result = self.__test_instance.airpollution_manager() self.assertTrue(result is not None) self.assertIsInstance(result, AirPollutionManager) def test_agro_manager(self): result = self.__test_instance.agro_manager() self.assertTrue(result is not None) self.assertIsInstance(result, AgroManager) def test_weather_manager(self): result = self.__test_instance.weather_manager() self.assertTrue(result is not None) self.assertIsInstance(result, WeatherManager) def test_tile_manager(self): result = self.__test_instance.tile_manager('test') self.assertIsNotNone(result) self.assertIsInstance(result, TileManager)
from pyowm.owm import OWM from pyowm.utils.config import get_default_config from pyowm.utils import timestamps from datetime import datetime config = get_default_config() # создали стандартный конфиг , чтобы изменить язык config['language'] = 'ru' # изменили язык owm = OWM('488c435162b187b2632cda6bfe005d78', config) mgr = owm.weather_manager() def search_weather_data(city): # город , о ктором мы получим информацию о погоде weather = mgr.weather_at_place(city).weather temperature = int(weather.temperature('celsius')['temp']) # получили температуру в градусах Цельсия if temperature > 25: temperature_smile = ' 🌡🔥' elif temperature >= 20 and int(temperature) <= 25: temperature_smile = ' 🌡🤤' elif temperature < 20 and int(temperature) >= 10: temperature_smile = ' 🌡😐' elif temperature < 10 and int(temperature) >= 0: temperature_smile = ' 🌡☹' else: temperature_smile = ' 🌡❄'
class wxForecast(object): def __init__(self, data, scheduler): self.data = data self.scheduler = scheduler self.weather_frequency = data.config.weather_update_freq self.time_format = data.config.time_format self.icons = get_icons("ecIcons_utf8.csv") self.network_issues = data.network_issues self.currdate = datetime.now() self.apikey = data.config.weather_owm_apikey self.max_days = data.config.weather_forecast_days if self.data.config.weather_data_feed.lower() == "owm": self.owm = OWM(self.apikey) self.owm_manager = self.owm.weather_manager() # Get forecast for next day, every forecast_update hours hour_update = '*/' + str(self.data.config.weather_forecast_update) scheduler.add_job(self.getForecast, 'cron', hour=hour_update,minute=0,id='forecast') #Check every 5 mins for testing only #scheduler.add_job(self.GetForecast, 'cron', minute='*/5') nextrun = scheduler.get_job('forecast').next_run_time debug.info("Updating weather forecast every {} hour(s) starting @ {}".format((self.data.config.weather_forecast_update),nextrun.strftime("%H:%M"))) #debug.info(scheduler.print_jobs()) #Set up units [temp, wind speed,precip, storm distance] #Use these eventhough some are included in data feed if self.data.config.weather_units == "metric": self.data.wx_units = ["C","kph","mm","miles","hPa","ca"] else: self.data.wx_units = ["F","mph","in","miles","MB","us"] #Get initial forecast self.getForecast() def getForecast(self): #self.data.wx_forecast = [] wx_forecast = [] icon_code = None summary = None temp_high = None temp_low = None self.currdate = datetime.now() # For testing #self.data.wx_forecast = [['Tue 08/25', 'Mainly Clear', '\uf02e', '-29C', '-14C'], ['Wed 08/26', 'Light Rain Shower', '\uf02b', '27C', '18C'], ['Thu 08/27', 'Clear', '\uf02e', '23C', '13C']] if self.data.config.weather_data_feed.lower() == "ec": debug.info("Refreshing EC daily weather forecast") try: self.data.ecData.update() except Exception as e: debug.error("Unable to update EC forecast. Error: {}".format(e)) forecasts = [] forecasts = self.data.ecData.daily_forecasts #debug.warning(forecasts) if len(forecasts) > 0: forecasts_updated = True else: forecasts_updated = False debug.error("EC Forecast not updated.... ") #Loop through the data and create the forecast #Number of days to add to current day for the date string, this will be incremented index = 1 forecast_day = 1 while index <= self.max_days and forecasts_updated: #Create the date nextdate = self.currdate + timedelta(days=forecast_day) nextdate_name = nextdate.strftime("%A") nextdate = nextdate.strftime("%a %m/%d") forecast_day += 1 #Loop through forecast and get the day equal to nextdate_name for day_forecast in forecasts: for k,v in day_forecast.items(): if k == "period" and v == nextdate_name: #print(day_forecast) summary = day_forecast['text_summary'] icon_code = day_forecast['icon_code'] temp_high = day_forecast['temperature'] + self.data.wx_units[0] # Get the nextdate_name + " night" night_forecast = next((sub for sub in forecasts if sub['period'] == nextdate_name + " night"), None) temp_low = night_forecast['temperature'] + self.data.wx_units[0] break if icon_code == None: wx_icon = '\uf07b' wx_summary = "N/A" #debug.warning("Forecasts returned: {}".format(forecasts)) else: #Get condition and icon from dictionary #debug.warning("icons length {}".format(len(self.icons))) for row in range(len(self.icons)): if int(self.icons[row]["ForecastCode"]) == int(icon_code): wx_icon = self.icons[row]['font'] wx_summary = self.icons[row]['Description'] break else: wx_icon = '\uf07b' wx_summary = "N/A" if wx_summary == "N/A": debug.error("Icon not found in icon spreadsheet: EC icon code: {} : EC Summary {}.".format(icon_code,summary)) wx_forecast.append([nextdate,wx_summary,wx_icon,temp_high,temp_low]) index += 1 if self.data.config.weather_data_feed.lower() == "owm": debug.info("Refreshing OWM daily weather forecast") #lat = self.data.latlng[0] #lon = self.data.latlng[1] one_call = None try: one_call = self.owm_manager.one_call(lat=self.data.latlng[0],lon=self.data.latlng[1]) except Exception as e: debug.error("Unable to get OWM data error:{0}".format(e)) self.data.forecast_updated = False self.network_issues = True return index=1 forecast = [] while index <= self.max_days: nextdate = self.currdate + timedelta(days=index) nextdate = nextdate.strftime("%a %m/%d") icon_code = int(one_call.forecast_daily[index].weather_code) summary = one_call.forecast_daily[index].detailed_status if self.data.config.weather_units == "metric": temp_high = one_call.forecast_daily[index].temperature('celsius').get('max', None) temp_low = one_call.forecast_daily[index].temperature('celsius').get('min', None) else: temp_high = one_call.forecast_daily[index].temperature('fahrenheit').get('max', None) temp_low = one_call.forecast_daily[index].temperature('fahrenheit').get('min', None) #Round high and low temps to two digits only (ie 25 and not 25.61) temp_hi = str(round(float(temp_high))) + self.data.wx_units[0] temp_lo = str(round(float(temp_low))) + self.data.wx_units[0] if icon_code in range(200,299): # Thunderstorm Class owm_icon = 200 elif icon_code in range(300,399): # Drizzle Class owm_icon = 300 elif icon_code in range(500,599): # Rain Class owm_icon = 500 elif icon_code in range(600,699): # Rain Class owm_icon = 600 elif icon_code in range(800,805): # Rain Class owm_icon = 801 else: owm_icon = icon_code #Get the icon, only for the day if icon_code == None: wx_icon = '\uf07b' wx_summary = "N/A" else: #Get condition and icon from dictionary for row in range(len(self.icons)): if int(self.icons[row]["OWMCode"]) == owm_icon: wx_icon = self.icons[row]['font'] wx_summary = self.icons[row]['Description'] break else: wx_icon = '\uf07b' wx_summary = "N/A" wx_forecast.append([nextdate,summary,wx_icon,temp_hi,temp_lo]) index += 1 debug.info("New forecast: {}".format(wx_forecast)) if self.data.wx_forecast != wx_forecast: debug.info("Forecast has changed and been updated....") self.data.wx_forecast = wx_forecast else: debug.info("Forecast has not changed, no update needed....") self.data.forecast_updated = True self.network_issues = False debug.info(self.data.wx_forecast) nextrun = self.scheduler.get_job('forecast').next_run_time debug.info("Weather forecast next update @ {}".format(nextrun.strftime("%H:%M")))
class TextColors: OK = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' RESET = '\033[0m' class WeatherArt: rain = "\n __ _\n _( )_( )_\n (_ _ _)\n / /(_) (__)\n / / / / / /\n/ / / / / /" clouds = "\n __ _\n _( )_( )_\n (_ _ _)\n (_) (__)\n" clear = "\n ; : ;\n . \_,!,_/ ,\n `.,' `.,'\n / \\ \n~ -- : : -- ~\n \ /\n ,'`._ _.'`.\n ' / `!` \ `\n ; : ;" apiKey = 'INSERT KEY HERE' owm = OWM(apiKey) mgr = owm.weather_manager() COUNTRY = 'US' host = '127.0.0.1' port = 1234 address = (host, port) buffersize = 1024 socket_server = None conn_pool = [] regex = re.compile(r"(\d{5})") regex2 = re.compile(r"(\[.*?\])") tmp = {}
from pyowm.owm import OWM from pyowm.utils.config import get_default_config config_dict = get_default_config() config_dict['language'] = 'ru' # your language here owm = OWM('2bc4da0ae9b4979d0faaa70a8980655b', config_dict) place = input("В каком городе/стране: ") mgr = owm.weather_manager() observation = mgr.weather_at_place(place) w = observation.weather temp = w.temperature('celsius')["temp"] config_dict = owm.configuration print("В городе " + place + " сейчас " + str(w.detailed_status)) print("Температура сейчас в районе: " + str(temp)) if temp < 8: print('Сейчас очень холодно, одевайся тепло!') elif temp < 20: print('Сейчас холодно, оденься потеплее.') else: print('Температура норм, одевайся свободно.')
class Weather(inkycal_module): """Weather class parses weather details from openweathermap """ name = "Weather (openweathermap) - Get weather forecasts from openweathermap" requires = { "api_key": { "label": "Please enter openweathermap api-key. You can create one for free on openweathermap", }, "location": { "label": "Please enter your location in the following format: City, Country-Code. " + "You can also enter the location ID found in the url " + "e.g. https://openweathermap.org/city/4893171 -> ID is 4893171" } } optional = { "round_temperature": { "label": "Round temperature to the nearest degree?", "options": [True, False], }, "round_windspeed": { "label": "Round windspeed?", "options": [True, False], }, "forecast_interval": { "label": "Please select the forecast interval", "options": ["daily", "hourly"], }, "units": { "label": "Which units should be used?", "options": ["metric", "imperial"], }, "hour_format": { "label": "Which hour format do you prefer?", "options": [24, 12], }, "use_beaufort": { "label": "Use beaufort scale for windspeed?", "options": [True, False], }, } def __init__(self, config): """Initialize inkycal_weather module""" super().__init__(config) config = config['config'] # Check if all required parameters are present for param in self.requires: if not param in config: raise Exception(f'config is missing {param}') # required parameters self.api_key = config['api_key'] self.location = config['location'] # optional parameters self.round_temperature = config['round_temperature'] self.round_windspeed = config['round_windspeed'] self.forecast_interval = config['forecast_interval'] self.units = config['units'] self.hour_format = int(config['hour_format']) self.use_beaufort = config['use_beaufort'] # additional configuration self.owm = OWM(self.api_key).weather_manager() self.timezone = get_system_tz() self.locale = config['language'] self.weatherfont = ImageFont.truetype( fonts['weathericons-regular-webfont'], size=self.fontsize) # give an OK message print(f"{filename} loaded") def generate_image(self): """Generate image for this module""" # Define new image size with respect to padding im_width = int(self.width - (2 * self.padding_left)) im_height = int(self.height - (2 * self.padding_top)) im_size = im_width, im_height logger.info(f'Image size: {im_size}') # Create an image for black pixels and one for coloured pixels im_black = Image.new('RGB', size=im_size, color='white') im_colour = Image.new('RGB', size=im_size, color='white') # Check if internet is available if internet_available() == True: logger.info('Connection test passed') else: logger.exception('Network could not be reached :(') raise def get_moon_phase(): """Calculate the current (approximate) moon phase""" dec = decimal.Decimal diff = now - arrow.get(2001, 1, 1) days = dec(diff.days) + (dec(diff.seconds) / dec(86400)) lunations = dec("0.20439731") + (days * dec("0.03386319269")) position = lunations % dec(1) index = math.floor((position * dec(8)) + dec("0.5")) return { 0: '\uf095', 1: '\uf099', 2: '\uf09c', 3: '\uf0a0', 4: '\uf0a3', 5: '\uf0a7', 6: '\uf0aa', 7: '\uf0ae' }[int(index) & 7] def is_negative(temp): """Check if temp is below freezing point of water (0°C/30°F) returns True if temp below freezing point, else False""" answer = False if temp_unit == 'celsius' and round(float( temp.split('°')[0])) <= 0: answer = True elif temp_unit == 'fahrenheit' and round(float( temp.split('°')[0])) <= 0: answer = True return answer # Lookup-table for weather icons and weather codes weathericons = { '01d': '\uf00d', '02d': '\uf002', '03d': '\uf013', '04d': '\uf012', '09d': '\uf01a ', '10d': '\uf019', '11d': '\uf01e', '13d': '\uf01b', '50d': '\uf014', '01n': '\uf02e', '02n': '\uf013', '03n': '\uf013', '04n': '\uf013', '09n': '\uf037', '10n': '\uf036', '11n': '\uf03b', '13n': '\uf038', '50n': '\uf023' } def draw_icon(image, xy, box_size, icon, rotation=None): """Custom function to add icons of weather font on image image = on which image should the text be added? xy = xy-coordinates as tuple -> (x,y) box_size = size of text-box -> (width,height) icon = icon-unicode, looks this up in weathericons dictionary """ x, y = xy box_width, box_height = box_size text = icon font = self.weatherfont # Increase fontsize to fit specified height and width of text box size = 8 font = ImageFont.truetype(font.path, size) text_width, text_height = font.getsize(text) while (text_width < int(box_width * 0.9) and text_height < int(box_height * 0.9)): size += 1 font = ImageFont.truetype(font.path, size) text_width, text_height = font.getsize(text) text_width, text_height = font.getsize(text) # Align text to desired position x = int((box_width / 2) - (text_width / 2)) y = int((box_height / 2) - (text_height / 2)) # Draw the text in the text-box draw = ImageDraw.Draw(image) space = Image.new('RGBA', (box_width, box_height)) ImageDraw.Draw(space).text((x, y), text, fill='black', font=font) if rotation != None: space.rotate(rotation, expand=True) # Update only region with text (add text with transparent background) image.paste(space, xy, space) # column1 column2 column3 column4 column5 column6 column7 # |----------|----------|----------|----------|----------|----------|----------| # | time | temperat.| moonphase| forecast1| forecast2| forecast3| forecast4| # | current |----------|----------|----------|----------|----------|----------| # | weather | humidity | sunrise | icon1 | icon2 | icon3 | icon4 | # | icon |----------|----------|----------|----------|----------|----------| # | | windspeed| sunset | temperat.| temperat.| temperat.| temperat.| # |----------|----------|----------|----------|----------|----------|----------| # Calculate size rows and columns col_width = im_width // 7 # Ratio width height image_ratio = im_width / im_height if image_ratio >= 4: row_height = im_height // 3 else: logger.info('Please consider decreasing the height.') row_height = int((im_height * (1 - im_height / im_width)) / 3) logger.debug(f"row_height: {row_height} | col_width: {col_width}") # Calculate spacings for better centering spacing_top = int((im_width % col_width) / 2) spacing_left = int((im_height % row_height) / 2) # Define sizes for weather icons icon_small = int(col_width / 3) icon_medium = icon_small * 2 icon_large = icon_small * 3 # Calculate the x-axis position of each col col1 = spacing_top col2 = col1 + col_width col3 = col2 + col_width col4 = col3 + col_width col5 = col4 + col_width col6 = col5 + col_width col7 = col6 + col_width # Calculate the y-axis position of each row line_gap = int((im_height - spacing_top - 3 * row_height) // 4) row1 = line_gap row2 = row1 + line_gap + row_height row3 = row2 + line_gap + row_height # Draw lines on each row and border ############################################################################ ## draw = ImageDraw.Draw(im_black) ## draw.line((0, 0, im_width, 0), fill='red') ## draw.line((0, im_height-1, im_width, im_height-1), fill='red') ## draw.line((0, row1, im_width, row1), fill='black') ## draw.line((0, row1+row_height, im_width, row1+row_height), fill='black') ## draw.line((0, row2, im_width, row2), fill='black') ## draw.line((0, row2+row_height, im_width, row2+row_height), fill='black') ## draw.line((0, row3, im_width, row3), fill='black') ## draw.line((0, row3+row_height, im_width, row3+row_height), fill='black') ############################################################################ # Positions for current weather details weather_icon_pos = (col1, 0) temperature_icon_pos = (col2, row1) temperature_pos = (col2 + icon_small, row1) humidity_icon_pos = (col2, row2) humidity_pos = (col2 + icon_small, row2) windspeed_icon_pos = (col2, row3) windspeed_pos = (col2 + icon_small, row3) # Positions for sunrise, sunset, moonphase moonphase_pos = (col3, row1) sunrise_icon_pos = (col3, row2) sunrise_time_pos = (col3 + icon_small, row2) sunset_icon_pos = (col3, row3) sunset_time_pos = (col3 + icon_small, row3) # Positions for forecast 1 stamp_fc1 = (col4, row1) icon_fc1 = (col4, row1 + row_height) temp_fc1 = (col4, row3) # Positions for forecast 2 stamp_fc2 = (col5, row1) icon_fc2 = (col5, row1 + row_height) temp_fc2 = (col5, row3) # Positions for forecast 3 stamp_fc3 = (col6, row1) icon_fc3 = (col6, row1 + row_height) temp_fc3 = (col6, row3) # Positions for forecast 4 stamp_fc4 = (col7, row1) icon_fc4 = (col7, row1 + row_height) temp_fc4 = (col7, row3) # Create current-weather and weather-forecast objects if self.location.isdigit(): logging.debug('looking up location by ID') weather = self.owm.weather_at_id(int(self.location)).weather forecast = self.owm.forecast_at_id(int(self.location), '3h') else: logging.debug('looking up location by string') weather = self.owm.weather_at_place(self.location).weather forecast = self.owm.forecast_at_place(self.location, '3h') # Set decimals dec_temp = None if self.round_temperature == True else 1 dec_wind = None if self.round_windspeed == True else 1 # Set correct temperature units if self.units == 'metric': temp_unit = 'celsius' elif self.units == 'imperial': temp_unit = 'fahrenheit' logging.debug(f'temperature unit: {temp_unit}') logging.debug( f'decimals temperature: {dec_temp} | decimals wind: {dec_wind}') # Get current time now = arrow.utcnow() if self.forecast_interval == 'hourly': logger.debug("getting hourly forecasts") # Forecasts are provided for every 3rd full hour # find out how many hours there are until the next 3rd full hour if (now.hour % 3) != 0: hour_gap = 3 - (now.hour % 3) else: hour_gap = 3 # Create timings for hourly forcasts forecast_timings = [ now.shift(hours=+hour_gap + _).floor('hour') for _ in range(0, 12, 3) ] # Create forecast objects for given timings forecasts = [ forecast.get_weather_at(forecast_time.datetime) for forecast_time in forecast_timings ] # Add forecast-data to fc_data dictionary fc_data = {} for forecast in forecasts: temp = '{}°'.format( round(forecast.temperature(unit=temp_unit)['temp'], ndigits=dec_temp)) icon = forecast.weather_icon_name fc_data['fc' + str(forecasts.index(forecast) + 1)] = { 'temp': temp, 'icon': icon, 'stamp': forecast_timings[forecasts.index(forecast)].to( get_system_tz()).format('H.00' if self.hour_format == 24 else 'h a') } elif self.forecast_interval == 'daily': logger.debug("getting daily forecasts") def calculate_forecast(days_from_today): """Get temperature range and most frequent icon code for forecast days_from_today should be int from 1-4: e.g. 2 -> 2 days from today """ # Create a list containing time-objects for every 3rd hour of the day time_range = list( arrow.Arrow.range( 'hour', now.shift(days=days_from_today).floor('day'), now.shift(days=days_from_today).ceil('day')))[::3] # Get forecasts for each time-object forecasts = [ forecast.get_weather_at(_.datetime) for _ in time_range ] # Get all temperatures for this day daily_temp = [ round(_.temperature(unit=temp_unit)['temp'], ndigits=dec_temp) for _ in forecasts ] # Calculate min. and max. temp for this day temp_range = f'{max(daily_temp)}°/{min(daily_temp)}°' # Get all weather icon codes for this day daily_icons = [_.weather_icon_name for _ in forecasts] # Find most common element from all weather icon codes status = max(set(daily_icons), key=daily_icons.count) weekday = now.shift(days=days_from_today).format( 'ddd', locale=self.locale) return {'temp': temp_range, 'icon': status, 'stamp': weekday} forecasts = [calculate_forecast(days) for days in range(1, 5)] fc_data = {} for forecast in forecasts: fc_data['fc' + str(forecasts.index(forecast) + 1)] = { 'temp': forecast['temp'], 'icon': forecast['icon'], 'stamp': forecast['stamp'] } for key, val in fc_data.items(): logger.debug((key, val)) # Get some current weather details temperature = '{}°'.format( round(weather.temperature(unit=temp_unit)['temp'], ndigits=dec_temp)) weather_icon = weather.weather_icon_name humidity = str(weather.humidity) sunrise_raw = arrow.get(weather.sunrise_time()).to(self.timezone) sunset_raw = arrow.get(weather.sunset_time()).to(self.timezone) logger.debug(f'weather_icon: {weather_icon}') if self.hour_format == 12: logger.debug('using 12 hour format for sunrise/sunset') sunrise = sunrise_raw.format('h:mm a') sunset = sunset_raw.format('h:mm a') elif self.hour_format == 24: logger.debug('using 24 hour format for sunrise/sunset') sunrise = sunrise_raw.format('H:mm') sunset = sunset_raw.format('H:mm') # Format the windspeed to user preference if self.use_beaufort == True: logger.debug("using beaufort for wind") wind = str(weather.wind(unit='beaufort')['speed']) elif self.use_beaufort == False: if self.units == 'metric': logging.debug('getting windspeed in metric unit') wind = str(weather.wind(unit='meters_sec')['speed']) + 'm/s' elif self.units == 'imperial': logging.debug('getting windspeed in imperial unit') wind = str( weather.wind(unit='miles_hour')['speed']) + 'miles/h' dec = decimal.Decimal moonphase = get_moon_phase() # Fill weather details in col 1 (current weather icon) draw_icon(im_colour, weather_icon_pos, (col_width, im_height), weathericons[weather_icon]) # Fill weather details in col 2 (temp, humidity, wind) draw_icon(im_colour, temperature_icon_pos, (icon_small, row_height), '\uf053') if is_negative(temperature): write(im_black, temperature_pos, (col_width - icon_small, row_height), temperature, font=self.font) else: write(im_black, temperature_pos, (col_width - icon_small, row_height), temperature, font=self.font) draw_icon(im_colour, humidity_icon_pos, (icon_small, row_height), '\uf07a') write(im_black, humidity_pos, (col_width - icon_small, row_height), humidity + '%', font=self.font) draw_icon(im_colour, windspeed_icon_pos, (icon_small, icon_small), '\uf050') write(im_black, windspeed_pos, (col_width - icon_small, row_height), wind, font=self.font) # Fill weather details in col 3 (moonphase, sunrise, sunset) draw_icon(im_colour, moonphase_pos, (col_width, row_height), moonphase) draw_icon(im_colour, sunrise_icon_pos, (icon_small, icon_small), '\uf051') write(im_black, sunrise_time_pos, (col_width - icon_small, row_height), sunrise, font=self.font) draw_icon(im_colour, sunset_icon_pos, (icon_small, icon_small), '\uf052') write(im_black, sunset_time_pos, (col_width - icon_small, row_height), sunset, font=self.font) # Add the forecast data to the correct places for pos in range(1, len(fc_data) + 1): stamp = fc_data[f'fc{pos}']['stamp'] icon = weathericons[fc_data[f'fc{pos}']['icon']] temp = fc_data[f'fc{pos}']['temp'] write(im_black, eval(f'stamp_fc{pos}'), (col_width, row_height), stamp, font=self.font) draw_icon(im_colour, eval(f'icon_fc{pos}'), (col_width, row_height + line_gap * 2), icon) write(im_black, eval(f'temp_fc{pos}'), (col_width, row_height), temp, font=self.font) border_h = row3 + row_height border_w = col_width - 3 #leave 3 pixels gap # Add borders around each sub-section draw_border(im_black, (col1, row1), (col_width * 3 - 3, border_h), shrinkage=(0, 0)) for _ in range(4, 8): draw_border(im_black, (eval(f'col{_}'), row1), (border_w, border_h), shrinkage=(0, 0)) # return the images ready for the display return im_black, im_colour
import telebot import pyowm owm = pyowm.OWM('92db96166090b594b9cabe79fc540697') from pyowm.owm import OWM from pyowm.utils.config import get_default_config config_dict = get_default_config() config_dict['language'] = 'ru' # your language here, eg. Portuguese owm = OWM('92db96166090b594b9cabe79fc540697', config_dict) bot = telebot.TeleBot("1524283639:AAGkT1mcgdg8wvW9VPrHchNMsHm5_mbYG6M") @bot.message_handler(content_types=["text"]) def send_echo(message): observation = owm.weather_manager().weather_at_place(message.text) w = observation.weather temp = w.temperature('celsius')['temp'] answer = f'Погодка: {w.detailed_status}\n' answer += f'Температурка: {temp}' "\n" if temp > +20: answer += f"А может погулять сходишь??? На улице хорошо мать твою!" elif temp > -20: answer += f"Обстановка так себе, что делать будешь?" bot.send_message(message.chat.id, answer) bot.polling(none_stop=True)
from pyowm.owm import OWM from bocik import token_holder owm = OWM(token_holder.WEATHER_TOKEN) mgr = owm.weather_manager() def get_weather_at_city(city): observation = mgr.weather_at_place(city) weather = observation.weather message_to_send = f"Miasto: {city} \n " \ f"Status: {weather.detailed_status.lower()} \n " \ f"Temperatura: od {weather.temperature('celsius')['temp_min']} do {weather.temperature('celsius')['temp_max']} °C\n " \ f"Obecna temperatura: {weather.temperature('celsius')['temp']} °C" return message_to_send
from pyowm.owm import OWM owm = OWM('2992f4fa8670a7ae1ce7f58c4777326e') mgr = owm.weather_manager() observation = mgr.weather_at_place('Moscow,RU') print(observation.weather.temperature('celsius')['temp'])
from pyowm.owm import OWM from pyowm.utils.config import get_default_config import telebot config_dict = get_default_config() config_dict['language'] = 'ru' # your language here owm = OWM('2bc4da0ae9b4979d0faaa70a8980655b', config_dict) bot = telebot.TeleBot("973670127:AAF6oHnSggW0HFhjPG-tJC3xNjOpW-hehTw") @bot.message_handler(content_types=['text']) def send_echo(message): config_dict = owm.configuration mgr = owm.weather_manager() observation = mgr.weather_at_place(message.text) w = observation.weather temp = w.temperature('celsius')["temp"] answer = "В городе " + message.text + " сейчас " + w.detailed_status + "\n" answer += "Температура сейчас в районе: " + str(temp) + "\n\n" if temp < 8: answer += 'Сейчас очень холодно, одевайся тепло!' elif temp < 20: answer += 'Сейчас холодно, оденься потеплее.' else: answer += 'Температура норм, одевайся свободно.' bot.send_message(message.chat.id, answer) bot.polling(none_stop=True)