def weather(place): config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM(PyOwm) mgr = owm.weather_manager() try: observation = mgr.weather_at_place(place) w = observation.weather temp = w.temperature('celsius')["temp"] degree_sign = u'\N{DEGREE SIGN}' if temp > 0: return f"В городе {place.title()} сейчас {w.detailed_status} \n Температура: +{round(temp)}{degree_sign}С" else: return f"В городе {place.title()} сейчас {w.detailed_status} \n Температура: {round(temp)}{degree_sign}С" except NotFoundError: return f'Не найден город: {place.title()}'
def get_weather_forecast(*args: tuple): """ Получение и озвучивание прогнза погоды :param args: город, по которому должен выполняться запос """ # в случае наличия дополнительного аргумента - запрос погоды происходит по нему, # иначе - используется город, заданный в настройках if args[0]: city_name = args[0][0] else: city_name = person.home_city try: # использование API-ключа, помещённого в .env-файл по примеру WEATHER_API_KEY = "01234abcd....." weather_api_key = os.getenv("WEATHER_API_KEY") open_weather_map = OWM(weather_api_key) # запрос данных о текущем состоянии погоды weather_manager = open_weather_map.weather_manager() observation = weather_manager.weather_at_place(city_name) weather = observation.weather # поскольку все ошибки предсказать сложно, то будет произведен отлов с последующим выводом без остановки программы except: play_voice_assistant_speech(translator.get("Seems like we have a trouble. See logs for more information")) traceback.print_exc() return # разбивание данных на части для удобства работы с ними status = weather.detailed_status temperature = weather.temperature('celsius')["temp"] wind_speed = weather.wind()["speed"] pressure = int(weather.pressure["press"] / 1.333) # переведено из гПА в мм рт.ст. # вывод логов print(colored("Weather in " + city_name + ":\n * Status: " + status + "\n * Wind speed (m/sec): " + str(wind_speed) + "\n * Temperature (Celsius): " + str(temperature) + "\n * Pressure (mm Hg): " + str(pressure), "yellow")) # озвучивание текущего состояния погоды ассистентом (здесь для мультиязычности требуется дополнительная работа) play_voice_assistant_speech(translator.get("It is {0} in {1}").format(status, city_name)) play_voice_assistant_speech(translator.get("The temperature is {} degrees Celsius").format(str(temperature))) play_voice_assistant_speech(translator.get("The wind speed is {} meters per second").format(str(wind_speed))) play_voice_assistant_speech(translator.get("The pressure is {} mm Hg").format(str(pressure)))
def weather(command): reg_ex = re.search('weather in (.*)', command) try: if reg_ex: city = reg_ex.group(1) owm = OWM('ab0d5e80e8dafb2cb81fa9e82431c1fa') mgr = owm.weather_manager() obs = mgr.weather_at_place(city) w = obs.weather k = w.detailed_status x = w.temperature(unit='celsius') return ( 'Current weather in %s is %s The maximum temperature is %0.2f and the minimum temperature is ' '%0.2f degree celcius ' % (city, k, x['temp_max'], x['temp_min'])) except: return "unable to fetch the weather"
def monitor_device_performance(): period = 60 # API Initialisation. owm = OWM('7ead5a3e5a333c0664faa13a659c5bc1') mgr = owm.weather_manager() # Database. client = pymongo.MongoClient( 'mongodb://' + server_address + ':27017/', username="******", password="******") db = client['hyperlynkdb'] # Assume our pv panel produces 260 watts max. max_power = 260 while(True): # Getting the weather observations. weather = {} for r in db.regions.find(): if r["name"] == 'Awaiting Allocation': continue weather[r["name"]] = mgr.weather_at_place(r["name"] + ',AU').to_dict() # Checking the performances. for dev in db.devices.find({"status":"Online"}, {"device_id": 1, "region": 1, 'aggregate_telemetries': {'$slice': -1}}): if not day_time(weather[dev["region"]]["sunrise_time"], weather[dev["region"]]["sunset_time"]): continue if not dev["aggregate_telemetries"]: continue live_power = dev["aggregate_telemetries"][0]["current_in"] * dev["aggregate_telemetries"][0]["voltage_in"] threshold = max_power * cloud_coverage_impact(weather[dev['region']]["clouds"]) if live_power <= threshold: db.devices.update_one( { "device_id": dev['device_id'] }, { "$set": { "status": "Under Performing" } } ) time.sleep(period)
def process_message(bot, u): #This is what we'll do when we get a message #Use a custom keyboard keyboard = [['Get Weather']] #Setting a Button to Get the Weather reply_markup = ReplyKeyboardMarkup.create( keyboard) #And create the keyboard if u.message.sender and u.message.text and u.message.chat: #if it is a text message then get it chat_id = u.message.chat.id user = u.message.sender.username message = u.message.text print(chat_id) print(message) if message == 'Get Weather': #if the user is asking for the weather then we ask the location bot.send_message(chat_id, 'please send me your location') else: bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait( ) #if not then just show the options elif u.message.location: #if the message contains a location then get the weather on that latitude/longitude print(u.message.location) chat_id = u.message.chat.id owm = OWM(OWMKEY) #initialize the Weather API obs = owm.weather_at_coords( u.message.location.latitude, u.message.location.longitude) #Create a weather observation w = obs.get_weather() #create the object Weather as w print(w) # <Weather - reference time=2013-12-18 09:20, status=Clouds> l = obs.get_location( ) #create a location related to our already created weather object And send the parameters status = str(w.get_detailed_status()) placename = str(l.get_name()) wtime = str(w.get_reference_time(timeformat='iso')) temperature = str(w.get_temperature('celsius').get('temp')) bot.send_message(chat_id, 'Weather Status: ' + status + ' At ' + placename + ' ' + wtime + ' Temperature: ' + temperature + 'C') #send the anwser bot.send_message( chat_id, 'please select an option', reply_markup=reply_markup).wait() #send the options again else: print( bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait())
def getWeather(self,entities): # reg_ex = re.search('current weather in (.*)', command) print(entities) try: city = getValue(entities, "city") state = getValue(entities, "state") time = getValue(entities, "time") owm = OWM(API_key='2e50289c3dac66bcb86d009dabfc4e66') print(city) obs = owm.weather_at_place(city + "," + state) w = obs.get_weather() k = w.get_status() x = w.get_temperature(unit='celsius') self.lyndaResponse( 'Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % ( city, k, x['temp_max'], x['temp_min'])) except Exception as e: print(e)
def temperature(pog): owm = OWM('8fdfb48649ee4eb956660d7bfc8d94f2') place = pog mgr = owm.weather_manager() observation = mgr.weather_at_place(place) w = observation.weather config_dict = get_default_config() config_dict['language'] = 'ru' #температура t = w.temperature("celsius") t1 = t['temp'] t2 = t['feels_like'] t3 = t['temp_max'] t4 = t['temp_min'] wi = w.wind()['speed'] speak( f"В городе {place} температура {t1}°, ощущается как {t2}°,cкорость ветра, {wi} метра в секунду" )
def get_weather(message): config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM('1995f90be9dd85a0f662ccf2870d160a', config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(message.text) w = observation.weather answer = 'в {place} сейчас {status}\n'.format(place=message.text, status=w.detailed_status) answer += 'средняя температура за сегодня ожидается: {average_temp} (минимальная температура: {min_temp}, максимальная: {max_temp})\n\n'.format( min_temp=w.temperature('celsius')['temp_min'], max_temp=w.temperature('celsius')['temp_max'], average_temp=w.temperature('celsius')['temp']) if w.rain: answer += 'на улице rain' else: answer += 'сегодня без дождя :(' bot.send_message(message.from_user.id, answer)
def _initManagerByCity(self, city: str): if self._manager is None: config = { 'subscription_type': SubscriptionTypeEnum.FREE, 'language': 'ru', 'connection': { 'use_ssl': True, 'verify_ssl_certs': True, 'use_proxy': False, 'timeout_secs': 5 }, 'proxies': { 'http': 'http://*****:*****@host:port', 'https': 'socks5://user:pass@host:port' } } self._manager = OWM(self._token, config=config).weather_manager().weather_at_place(city)
def take_id(request): API_key = '63ac529deef3fb307c5c5f5d47d4a9de' owm = OWM(API_key) form2 = {} if request.method == 'POST': form2['city'] = request.POST.get('city') check_ct = str(form2['city']) if city_check(check_ct): ct = form2['city'] obs = owm.weather_at_place(ct) w = obs.get_weather() form2['Id'] = obs.get_location().get_ID() else: form2 = {} return JsonResponse(form2) else: return redirect('index_view')
def setup_platform(hass, config, add_devices, discovery_info=None): """ Get the OpenWeatherMap sensor. """ if None in (hass.config.latitude, hass.config.longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return False try: from pyowm import OWM except ImportError: _LOGGER.exception("Unable to import pyowm. " "Did you maybe not install the 'PyOWM' package?") return False SENSOR_TYPES['temperature'][1] = hass.config.temperature_unit unit = hass.config.temperature_unit forecast = config.get('forecast', 0) owm = OWM(config.get(CONF_API_KEY, None)) if not owm: _LOGGER.error("Connection error " "Please check your settings for OpenWeatherMap.") return None data = WeatherData(owm, forecast, hass.config.latitude, hass.config.longitude) dev = [] try: for variable in config['monitored_conditions']: if variable not in SENSOR_TYPES: _LOGGER.error('Sensor type: "%s" does not exist', variable) else: dev.append(OpenWeatherMapSensor(data, variable, unit)) except KeyError: pass if forecast == 1: SENSOR_TYPES['forecast'] = ['Forecast', ''] dev.append(OpenWeatherMapSensor(data, 'forecast', unit)) add_devices(dev)
def weather_sun(cur_bot, location='Rolla'): # Set API Key API_key = '0f5e7a1e7682ce843b443549718b5f95' owm = OWM(API_key) # Returns an "observation" of weather data (NOT A FORECAST) obs = owm.weather_at_place(location) # Gets actual weather data w = obs.get_weather() #Get sunrise and sunset times sunrise = w.get_sunrise_time('iso') sunset = w.get_sunset_time('iso') # Object for getting location l = obs.get_location() location_name = l.get_name() cur_bot.post("In " + location_name + ":\nSunrise: " + sunrise + "\nSunset: " + sunset)
def get_weather(location): key = tools.get_setting("owm", "settings.npy") owm = OWM(key) mgr = owm.weather_manager() if first_run_check(): print("Weather file not found, updating...") obs = mgr.weather_at_place(location) w = obs.weather save_weather(w, obs.rec_time) else: #todo 2: Check when the weather last updated and if more than ten minutes update the weather. time = float(tools.get_setting("time_got", "weather.npy")) if (t.time() - time) > 600: print("Time for an update...") obs = mgr.weather_at_place(location) w = obs.weather save_weather(w, obs.rec_time) load_weather_from_file("weather.npy") return wt
def __call__(self, *args, **kwargs): super().__call__(*args, **kwargs) if not self._query: return self.send_telegram_message('Please pecify location') try: forecast = OWM(WEATHER_TOKEN).daily_forecast(self._query, limit=3) except owm_exceptions.OWMError: self.send_telegram_message('No such location ðŸ˜') else: weathers = forecast.get_forecast() for weather in weathers.get_weathers(): text = FORECAST_TEXT.format( fc_time=weather.get_reference_time('iso'), city=weathers.get_location().get_name(), status=weather.get_status(), temperature=weather.get_temperature('celsius'), wind=weather.get_wind(), ) self.send_telegram_message(text=text)
def weather(): owm = OWM('11147dbcb05eef551c9357d6a878d33f') city = request.args.get("q") forecast = owm.three_hours_forecast(city) weather = forecast.get_forecast().get_weathers()[0] tempreture = weather.get_temperature(unit='celsius')["temp"] factors = [[forecast.will_have_clear(), 0], [forecast.will_have_clouds(), 0], [forecast.will_have_fog(), -0.1], [forecast.will_have_rain(), -0.7 if tempreture < 0 else -0.3], [forecast.will_have_snow(), -0.4], [forecast.will_have_storm(), -0.5], [forecast.will_have_tornado(), -0.5], [forecast.will_have_hurricane(), -1]] score = 1 for factor, value in factors: if factor: score = score + value if score < 0: score = 0 score = score * 100 if score >= 80: messege = "Enjoy your Ride" elif 60 <= score < 80: messege = "Take Care" elif 30 <= score < 60: messege = "Take caution" elif score == 0: messege = "DONT DRIVE, Unless you want to die" else: messege = "Driving is dangerious" return jsonify({ "name": city, "drivability_score": score, "weather_type": weather.get_status(), "icon_url": weather.get_weather_icon_url(), "temprature": tempreture, "recommendation": messege })
def weather(text): reg_ex = re.search(' weather in (.*)', text) if reg_ex: try: city = reg_ex.group(1) owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa') obs = owm.weather_at_place(city) w = obs.get_weather() k = w.get_status() x = w.get_temperature(unit='celsius') print( 'Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min'])) speak( 'Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min'])) except: pass return 0
def weather(city): weather_say = "Weather status in " + city + " is " try: owm = OWM('d4a9d6444f7784fc3c80cae78d414838') #enter your own apikey observation = owm.weather_at_place(city) w = observation.get_weather() # print(w.get_wind) status = str(w).rsplit(" ")[5] weather_say += str( w.get_temperature('celsius')['temp'] ) + " celsius and the sky is " + status[status.rfind("=") + 1:-1] weather_say += ". The average wind speed is " + str( w.get_wind()['speed']) + " kilometres per hour" weather_say += " and the humidity is " + str( w.get_humidity()) + " percent." except: weather_say += "unavailable." return weather_say
def get_weather(zip_code, fahrenheit, celsius): #some validation on the zip code if ((len(zip_code) != 5) or not zip_code.isdigit()): print("Please enter a valid zip code") return #initialize the open weather map API instance owm = OWM(API_KEY) unit = 'fahrenheit' if (celsius): units = 'celsius' try: observation = owm.weather_at_zip_code(zip_code, "US") weather = observation.get_weather() temperature = weather.get_temperature(unit=unit) temp = temperature['temp'] high_temp = temperature['temp_max'] low_temp = temperature['temp_min'] print("Temperature: {}".format(temp)) print("High for the day: {}".format(high_temp)) print("Low for the day: {}".format(low_temp)) int_temp = int(temp) # args are the port and baud rate arduino = serial.Serial(PORT, 115200) time.sleep(2) # allow the arduino to listen on the port arduino.write("{}\n".format(int_temp).encode()) #write temp to arduino except Exception as e: # print (e) # The Open Weather Map API will throw an error if there is no # weather data for a given zip code print( "Open Weather Map was unable to identify the given zip code. Please enter a valid zip code." )
def owm(self) -> OWM: if self._owm is None: LOGGER.debug("Authenticating to OWM API") # Sadly, pyowm provides a default configuration, but it's only used # in case we don't provide any. So, unless we want to specify all # default values by ourselves, we must merge the dictionaries # before config = pyowmconfig.get_default_config() config["language"] = self.language try: self._owm = OWM(self.api_key, config=config) except UnauthorizedError as e: LOGGER.error("Unable to authenticate to OWM API") raise CrawlerDataError from e # Despite the name, this exception seems to be raised if no # connection is possible at all (e.g. no network/internet # connection). except InvalidSSLCertificateError: raise CrawlerDataError("Could not connect to OWM API") return self._owm
def currentWeather(reg_ex): """gathers weather data with given regEx as city name (from comman)""" # noinspection PyBroadException try: result = '' if reg_ex: city = reg_ex.group(1) owm = OWM('ab0d5e80e8dafb2cb81fa9e82431c1fa') mgr = owm.weather_manager() obs = mgr.weather_at_place(city) w = obs.weather k = w.status x = w.temperature(unit='celsius') result = 'Current weather in %s: %s. The maximum temperature is %0.2f ' \ 'and the minimum temperature is %0.2f degree celcius.' \ % (city, k, x['temp_max'], x['temp_min']) except Exception: result = 'The requested city ' + reg_ex.group( 1) + ' does not exist. You may try again!' return result
def form_input(): city = request.form['city'] country = request.form['country'] owm = OWM(API_key='c4c27280349fce4e3bb120031151146b') obs = owm.weather_at_place(city + "," + country) w = obs.get_weather() print(w.get_temperature("fahrenheit")) temp_dictionary = w.get_temperature("fahrenheit") current_temperature = temp_dictionary['temp'] html = " " html += '<html>\n' html += '<body>\n' html += 'The temperature in ' + city + "is" + str( current_temperature) + "!\n" html += '</body>' html += '</html>' return html
def weath_info(request): API_key = '63ac529deef3fb307c5c5f5d47d4a9de' owm = OWM(API_key) form = {} if request.method == 'POST': form['id'] = request.POST.get('id') ct = int(form['id']) obs = owm.weather_at_id(ct) w = obs.get_weather() form['stat'] = weather_status(w.get_status()) form['temperature'] = w.get_temperature('celsius')['temp'] form['wind_speed'] = w.get_wind()['speed'] form['wind_der'] = degree(w.get_wind()['deg']) form['humidity'] = w.get_humidity() form['press'] = convert_press(w.get_pressure()['press']) form['city'] = obs.get_location().get_name() return JsonResponse(form) else: return redirect('index_view')
def getWeatherData(): #네트워크 상 현 위치 추적 geo = geocoder.ip('me') latlng = geo.latlng state = geo.state print(state) # open weather map api활용 -> 분당 60회 콜 무료 owm = OWM('4cef2e1e7c19f03b36ed971bac0be5fc') obs = owm.weather_at_coords(latlng[0], latlng[1]) location = obs.get_location() print(location.get_name()) w = obs.get_weather() print(w.get_status()) result = "현재 날씨는 " + getWeatherStatus(str(w.get_status())) + "입니다." result += ("기온은" + str(w.get_temperature(unit='celsius')['temp']) + ", ") result += "습도는" + str(w.get_humidity()) + "이며 " result += "풍속은" + str(w.get_wind()['speed']) + "입니다." neopixelTemp(w.get_temperature(unit='celsius')['temp']) print(result) return result
def weather(self, speech): if ("temps" in speech and "fait" in speech) or "il fait beau" in speech \ or "il fait froid" in speech: while True: try: owm = OWM(API_key='fb55e8ac1711a0b5b3eabae65b32a603', language='fr') observation = owm.weather_at_place('Bordeaux, fr') w = observation.get_weather() self.play_answer( "weather", text= "Le temps est {} avec une température de {} degrés ..." .format(w._detailed_status, int(w.get_temperature('celsius')['temp_min']))) call(["rm", "answers/weather.mp3"]) self.end = True break except Exception as e: print(e)
def getWeathers(): plotly.tools.set_credentials_file(username='******', api_key='xxxxxxxxxxxxxx') owm = OWM('xxxxxxxxxxxxxxxxx') fc = owm.three_hours_forecast('xxxx, xxxx') f = fc.get_forecast() weathers = f.get_weathers() forecast = {} days = [] times = [] for weather in weathers: d = dateutil.parser.parse(weather.get_reference_time("iso")) day = d.strftime("%A %d %B") time = d.strftime("%H:%M") if not time in times: times.append(time) if not day in days: days.append(day) if not day in forecast: forecast[day] = [] forecast[day].append( weather.get_temperature(unit='celsius')['temp_max']) numdays = len(days) times = sorted(times, key=lambda x: datetime.datetime.strptime(x, '%H:%M')) while len(forecast[days[0]]) < 8: forecast[days[0]].insert(0, None) while len(forecast[days[numdays - 1]]) < 8: forecast[days[numdays - 1]].append(None) datasets = [] for day in days: trace = go.Scatter(x=times, y=forecast[day], name=day) datasets.append(trace) # py.iplot(datasets, filename = 'basic-line') graph = dict(data=datasets, layout=dict(title='Weather', yaxis=dict(title="Temperature"), xaxis=dict(title="Time"), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)')) graphJSON = json.dumps(graph, cls=plotly.utils.PlotlyJSONEncoder) return graphJSON
def pogru(): global banner place = input(banner+"\nВведите город/страну: ") config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM( 'ba2897bac6149400afc4876fff57e7d7', config_dict ) mgr = owm.weather_manager() observation = mgr.weather_at_place(place) w = observation.weather temp_max = w.temperature('celsius')['temp_max'] temp_medium = w.temperature('celsius')['temp'] temp_min = w.temperature('celsius')['temp_min'] speed = w.wind()['speed'] hum = w.humidity cloud = w.clouds print(banner+ '\nВ городе ' + place + ' сейчас: ' + str(w.detailed_status) + "\nМаксильмальная температура в районе: " + str(temp_max) + "°С" + "\nСредняя температура в районе: " + str(temp_medium) + "°С" + "\nМинимальная температура в районе: " + str(temp_min) + "°С" +"\nСкорость ветра: " + str(speed) + " м/с" + "\nВлажность: " + str(hum) + "%" + "\nОблачность: " + str(cloud) + "%" +'\n\nНажмите ENTER для выхода в главное меню') input()
def save_city_weather(city_name='Kiev,UA'): api_key = '46f37ceccd8eccfe06f6f7d6d9128f50' # получаем елемент класса OWM25, с которым будет работать owm = OWM(api_key) # сохраняем тек погоду и возвращаем save_last_weather(owm, city_name) last_weather = get_weather() # сохраняем прогноз на 14 дней и возвращаем save_weather_forecast(owm, city_name) last_weather_sect = get_weather(14) # формируем прогноз с периодом в 3 часа и формируем список температур list_temp = get_temperature_forecast(owm, city_name) # формируем словари из нужных нам показателей weather_dict = weather_to_dict(last_weather) forecast_pressure_dict = weather_qs_to_dict(last_weather_sect) return { 'last_weather': weather_dict, 'forecast_pressure_dict': forecast_pressure_dict, 'list_temp': list_temp }
def getWeather(message, city, bot): from pyowm import OWM from pyowm.utils import config from pyowm.utils import timestamps from pyowm.utils.config import get_default_config bot.send_chat_action(message.chat.id, 'typing') try: config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM("86f66426b23488991870e99f0b90d48b", config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(city) w = observation.weather bot.reply_to( message, "Погода в городе " + city + ": " + str(w.temperature('celsius')['temp'])) except Exception as e: print("Ошибка:", e) pass
def get_weather_city(self): owm = OWM('3a587a614352c7dc86422c337521fabe') # Мой OWM API city = self.lineEdit.text( ) # line Edit принимает название города/страны от пользователя mgr = owm.weather_manager() observation = mgr.weather_at_place( city) # Получаем погоду в заданном городе/стране w = observation.weather t = w.temperature('celsius')['temp'] # Получаем температуру # Выводим в label сообщение с текущей температурой и советом if t > 20: self.label.setText(f'Температура: {t}\nКрутая погода, кайфуй!') elif t > 0: self.label.setText( f'Температура: {t}\nТам холодно, одевайся теплее ^_^') else: self.label.setText( f'Температура: {t}\nТы сумасшедший.\nОпомнись и останься дома!' )
def __call__(self, *args, **kwargs): super().__call__(*args, **kwargs) if self._query: try: observation = OWM(WEATHER_TOKEN).weather_at_place(self._query) except owm_exceptions.OWMError: self.send_telegram_message('No such location 😭') else: weather = observation.get_weather() text = WEATHER_TEXT.format( city=observation.get_location().get_name(), status=weather.get_status(), temperature=weather.get_temperature('celsius'), wind=weather.get_wind(), humidity=weather.get_humidity(), pressure=weather.get_pressure(), ) self.prefix = self.get_emoji(weather) + ' ' + self.prefix return self.send_telegram_message(text=text) else: return self.send_telegram_message('Please specify location')