def send_info(message): config_dict = get_default_config() config_dict['language'] = 'ua' # your language here, eg. Ukrainian owm = OWM('KEY', config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(message.text) w = observation.weather # Temp temp = w.temperature('celsius') temp_current = temp['temp'] temp_min = temp['temp_min'] temp_max = temp['temp_max'] feels_like = temp['feels_like'] # Wind wind_info = observation.weather.wind(unit='meters_sec') wind_speed = wind_info['speed'] wind_deg = wind_info['deg'] bot.reply_to( message, 'Температура зараз: ' + str(temp_current) + '\n \nМінімальна температура сьогодні: ' + str(temp_min) + ' градуси' '\n \nМаксимальна температура сьогодні: ' + str(temp_max) + ' градуси' + '\n \nВідчувається як: ' + str(feels_like) + ' градуси' + '\n \nШвидкість вітру' + 'сьогодні: ' + str(wind_speed) + ' метра за секунду' + '\n \n Напрям вітру у градусах від ' + 'північного ' + 'горизонту: ' + str(wind_deg))
def get_data(key, city): """ Получение данных на сегодняшний день. key - ключ от openweathermap.org city - город с уточнением страны """ get_err = False try: config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM(api_key=key, config=config_dict) mgr = owm.weather_manager() w = mgr.weather_at_place(city).weather except: get_err = "Сведения о погоде получить не удалось." data = ("%s. " "Сегодня %s, %s. " "Время %s. " % (get_greeting(), get_weekday(), get_date(), get_time())) if not get_err: data += ("Температура за окном %d ℃. " "Ветер %s, %d м в секунду. " "Атмосферное давление %d мм рт. ст. " "Относительная влажность воздуха %d %%. " "%s." % (w.temperature('celsius').get('temp'), get_wind_direction(w.wind().get('deg')), w.wind().get('speed'), w.pressure.get('press') * 0.75006375541921, w.humidity, w.detailed_status)) else: data += get_err return data
def GetWeather(): global userData, data config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM(data['weather']['api_key'], config_dict) mgr = owm.weather_manager() try: observation = mgr.weather_at_coords(data['weather']['lat'], data['weather']['lon']) except AssertionError: data['weather']['error'] = "Invalid lat/lon values" except pyowm.commons.exceptions.InvalidSSLCertificateError as e: data['weather']['error'] = "No internet connection" else: w = observation.weather data['weather']['status'] = w.detailed_status.capitalize() data['weather']['temperature'] = str( w.temperature('celsius')['temp']) + "°C" data['weather']['humidity'] = str(w.humidity) + "%" data['weather']['pressure'] = str(w.pressure['press']) + " гПa" data['weather']['wind_speed'] = str(w.wind()['speed']) + " м/с" data['weather']['icon'] = w.weather_icon_url(size='4x') location = geolocator.reverse( str(data['weather']['lat']) + "," + str(data['weather']['lon'])) data['weather']['city'] = location.raw['address'].get('city', "None") data['weather']['error'] = None
def get_curr_weather(city): try: config_dict = get_default_config() config_dict['language'] = 'ru' owm = pyowm.OWM(weather_api, config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(city) w = observation.weather # погодные характеристики pressure = str(w.pressure['press'] * 0.75) + ' мм.рт.ст' weather_now = w.detailed_status temp = str(w.temperature('celsius')['temp']) + '°C' max_temp = str(w.temperature('celsius')['temp_max']) + '°C' min_temp = str(w.temperature('celsius')['temp_min']) + '°C' temp_feels = str(w.temperature('celsius')['feels_like']) + '°C' wind = str(w.wind()['speed']) + ' м/с' humid = str(w.humidity) + ' %' return f'🌤В городе {city} сейчас {weather_now}' \ f'\n🌡Температура воздуха: {temp}' \ f'\n🌡Температура воздуха: {temp}' \ f'\n🌡[max]Максимальная температура воздуха: {max_temp}' \ f'\n🌡[min]Минимальная температура воздуха: {min_temp}' \ f'\n🌡[+-]Ощущается: {temp_feels}' \ f'\n\n💨Скорость ветра: {wind}' \ f'\n💧Влажность: {humid}' \ f'\n🌀Атмосферное давление: {pressure}' except: return f'Извините, город {city} отсутствует в моей базе данных' \ f'\nили вы неправильно ввели название города☹'
def weather_command_message(message): if str(message.text)[:8] == '/weather': city = str(message.text)[9:] city = str(city) if city == "": city = 'Москва' morph = pymorphy2.MorphAnalyzer() counties = morph.parse(city)[0] gent = counties.inflect({'loct'}) gent_new = gent.word gent_correct = gent_new.capitalize() config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM('0d16f6ffb7d46c30c1202a765e2cb0fc', config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(city) w = observation.weather cloud = str(w.detailed_status) clouds = str(w.clouds) temp = w.temperature('celsius')['temp'] temperature = str(temp).rsplit(".")[0] weather_message = (f'Сейчас в {gent_correct} {temperature} °C\n' f'Небо затянуто на {clouds}%, {cloud}') bot.send_message(message.from_user.id, weather_message) elif str(message.text)[:6] == '/covid': bot.send_message(message.from_user.id, "Пожалуйста, подождите, собираю статистику...") country = str(message.text)[7:] country = str(country) if country == "": country = 'россия' translator = Translator(from_lang="ru", to_lang="en") translation = translator.translate(country) morph = pymorphy2.MorphAnalyzer() counties = morph.parse(country)[0] gent = counties.inflect({'gent'}) gent_new = gent.word gent_correct = gent_new.capitalize() covid = Covid(source="worldometers") country_cases = covid.get_status_by_country_name( translation)['new_cases'] if country_cases == 0: country_cases = 'Статистика обновляется. Попробуйте заново через несколько часов.' else: country_cases = '+' + str(country_cases) confirmed_country_cases = covid.get_status_by_country_name( translation)['confirmed'] deaths_country_cases = covid.get_status_by_country_name( translation)['deaths'] covid_message = (f'Статистика для {gent_correct}:\n' f'Всего заболевших за сутки: {country_cases}\n' f'Всего случаев: {confirmed_country_cases}\n' f'Зафиксировано смертей: {deaths_country_cases}') bot.send_message(message.from_user.id, covid_message) else: bot.send_message( message.from_user.id, "Я пока что не знаю, что мне на это ответить. Пожалуйста, пропиши команду /help" )
def __init__(self, api_key, config=None): assert api_key is not None, 'API Key must be set' self.api_key = api_key if config is None: self.config = cfg.get_default_config() else: assert isinstance(config, dict) self.config = config
def __init__(self, city): self.city = city config_dict = get_default_config() config_dict['language'] = 'pl' owm = pyowm.OWM(self.APIkey, config_dict) loc = owm.weather_manager().weather_at_place(self.city) self.weather = loc.weather
def __init__(self): self._cords = [50.06860205597571, 19.906051141042095] self._config_dict = get_default_config() self._config_dict['language'] = 'en' self._owm = OWM('5107288b7cd05e5e4d3a167c10eb87e4', self._config_dict) self._manager = self._owm.weather_manager() self._one_call = self._manager.one_call(self._cords[0], self._cords[1]) self._current_conditions = self._one_call.current self._current_temperatures = self._read_temp_raw()
def _get_owm_config(language, url): """Get OpenWeatherMap configuration and add language to it.""" config_dict = get_default_config() config_dict["language"] = language config_dict["url"] = url config_dict['connection']['has_subdomains'] = DEFAULT_HAS_SUBDOMAINS config_dict['connection']['has_path'] = DEFAULT_HAS_PATH config_dict['connection']['use_ssl'] = DEFAULT_USE_SSL config_dict['connection']['verify_ssl_certs'] = DEFAULT_VERIFY_SSL_CERTS config_dict['connection']['use_proxy'] = DEFAULT_USE_PROXY return config_dict
def execute(self): city = self._match.group(1) config_dict = get_default_config() config_dict['language'] = 'en' owm = OWM('6d00d1d4e704068d70191bad2673e0cc', config_dict) reg = owm.city_id_registry() try: mgr = owm.weather_manager() observation = mgr.weather_at_place(city) #print(observation.location) w = re.findall('(\d+.\d+)', str(observation.location)) lon = float(w[1]) lat = float(w[2]) except: #проверка на частичное совпадение try: list_of_tuples = reg.ids_for(city, matching='like') city = list_of_tuples[0][1] except IndexError: print('No object with this name was found\n') return () #вывод списка с вариантами if len(list_of_tuples) > 1: for i in range(0, len(list_of_tuples)): print(i + 1, list_of_tuples[i][1:3]) #выбор пользователя и проверка try: select = int(input('\nSeveral matches were found. Enter a suitable number\n--> ')) city_finded = list_of_tuples[select - 1][1] list_of_locations = reg.locations_for(city_finded) city_finded = list_of_locations[0] lat = city_finded.lat lon = city_finded.lon if select < 1: print('Incorrected input\n') return () except: print('Incorrected input\n') return () print('Wait forecast for', city, '...\n') one_call = mgr.one_call(lat, lon) for i in range(3): print(datetime.now().date() + timedelta(days=1 + i)) print('Wind:', one_call.forecast_daily[i].wind().get('speed', 0), 'm/s\n' 'Cloudes:', one_call.forecast_daily[i].detailed_status, '\nDay temperature:', one_call.forecast_daily[i].temperature('celsius').get('feels_like_day', None), 'degrees Celsius', '\nNight temperature:', one_call.forecast_daily[i].temperature('celsius').get('feels_like_night', None), "degrees Celsius\n")
def weather(city_from_discord): """ Принимает на вход название города и выводит прогноз погоды """ config_dict = get_default_config() config_dict['language'] = 'ru' # your language here owm = OWM(OWM_API_KEY, config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(city_from_discord) weather = observation.weather temperature = weather.temperature('celsius')['temp'] full_message = f'{weather.detailed_status.capitalize()}, температура в городе {city_from_discord} {round(temperature)}°C' return full_message
def weather(record): try: check_city = record.replace("Pogoda", "") if check_city == "": say("Nie podano miasta. Spróbuj jeszcze raz.") else: print(check_city) # https://pyowm.readthedocs.io/en/latest/v3/code-recipes.html # from pyowm.owm import OWM # from pyowm.utils.config import get_default_config # config_dict = get_default_config() # config_dict['language'] = 'pt' # your language here, eg. Portuguese # owm = OWM('your-api-key', config_dict) config_dict = get_default_config() config_dict['language'] = 'pl' owm = pyowm.OWM('KLUCZ AP', config_dict) mng = owm.weather_manager() obs = mng.weather_at_place(check_city + ', PL') w = obs.weather temp = w.temperature('celsius') print(w) act_temp = int(temp['temp']) print(act_temp) say("Aktualna temperatura w stopniach celcjusza w mieście " + check_city + " wynosi:") say(act_temp) say("Odczuwalna:") say(temp['feels_like']) say("Minimalna temparatura:") say(temp['temp_min']) say("Maksymalna temperatura:") say(temp["temp_max"]) actstat = w.detailed_status print(actstat) say("Aktualnie jest na dworze:") say(actstat) if 'deszcz' in actstat or 'burza' in actstat or 'mżawka' in actstat or 'śnieg' in actstat: say('Lepiej dobrze się ubierz.') except Exception as e: print(e) say("Prawdopodnie podano nieprawidłowe parametry. Spróbuj jeszcze raz." )
def weather(citys): config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM('4ffbfb8067b16513c81acdfe9df4454d') city = citys mgr = owm.weather_manager() observation = mgr.weather_at_place(city) w = observation.weather temperature = w.temperature('celsius')['temp'] status = w.detailed_status wind = w.wind()['speed'] humidity = w.humidity talk( f"Температура в городе {city} {int(temperature)} градусов. {status}. Скорость ветра {wind} метра в секунду. " f"Влажность воздуха {humidity} процента")
def __init__(self): config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM('fd5321547e631b45b33d6d1cc673754f') mgr = owm.weather_manager() self.observation = mgr.weather_at_place('Харьков') self.w = self.observation.weather self.status = self.w.detailed_status # 'clouds' self.w.wind() # {'speed': 4.6, 'deg': 330} self.humidity = self.w.humidity # 87 self.temp = self.w.temperature('celsius')['temp'] # {'temp_max': 10.5, 'temp': 9.7, 'temp_min': 9.0} # w.rain # {} self.heat_index = self.w.heat_index # None self.clouds = self.w.clouds # 75 self.place = "Харьков" self.r = sr.Recognizer() self.engine = pyttsx3.init() self.adress = [] self.tallys = [] self.j = 0 self.x = 0 self.task_number = 0 self.ndel = ['морган', 'морген', 'морг', 'моргэн', 'морда', 'ладно', 'не могла бы ты', 'пожалуйста', 'сколько', 'текущее', 'сейчас'] self.commands = ['привет', 'выключи комп', 'выруби компьютер', 'пока', 'покажи список команд', 'выключи компьютер', 'выключай компьютер', 'вырубись', 'отключись', 'подбрось монетку', 'подкинь монетку', 'кинь монетку', 'открой vk', 'открой браузер', 'включи vk', 'открой интернет', 'открой youtube', 'включи музон', 'открой viber', 'включи viber', 'открывай viber', 'найди', 'найти', 'ищи', 'кто такой', 'как дела', 'как жизнь', 'как настроение', 'как ты', 'открой лаунчер аризоны', 'запусти лаунчер аризоны', 'запускай лаунчер аризоны', 'включай лаунчер аризоны', 'заходи на аризону', 'включай аризону', 'текущее время', 'сколько времени', 'сколько время', 'сейчас времени', 'который час', 'крути винилы', 'крути винил', 'какая погода', 'погода', 'погода на улице', 'какая погода на улице', 'история запросов', 'выведи историю запросов', 'покажи историю запросов', 'открой музыку', 'вруби музыку', 'переведи', 'планы', 'на будущее', 'что планируется', 'открой протокол разработки', 'протокол разработки', ]
def get_weather(): #get place, temperature and status from openweathermap.org config_dict = get_default_config() config_dict['language'] = 'ru' # your language here API = ('6d00d1d4e704068d70191bad2673e0cc') owm = OWM(API, config_dict) mgr = owm.weather_manager() place = input("Введите Ваш город: ") #get name of city from keyboard observation = mgr.weather_at_place('place') w = observation.weather status = w.detailed_status temp = w.temperature('celsius')[ 'temp'] # {'temp_max': 10.5, 'temp': 9.7, 'temp_min': 9.0} return place, temp, status
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(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 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(command_options, *args: tuple): # погода config_dict = get_default_config() config_dict['language'] = 'ru' city = command_options try: owm = OWM(settings.API, config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(city) w = observation.weather temper = w.temperature('celsius') temper0, temper_max, temper_min = str(int(temper['temp'])), int( temper['temp_max']), int(temper['temp_min']) print('Средняя температура: ', temper0, '\nМаксимальная температура: ', temper_max, '\nМинимальная температура: ', temper_min) say(f'Средняя температура за день:' + temper0) time.sleep(2) except: pass
def fetch_data(self): if hasattr(settings, 'OWM_API_KEY'): try: config_dict = get_default_config() config_dict['language'] = 'fr' owm = pyowm.OWM(settings.OWM_API_KEY, config_dict) mgr = owm.weather_manager() coords = self.poi.geom.coords w = mgr.weather_at_coords(coords[1], coords[0]).weather owm_data = json.loads(w.to_JSON()) del owm_data["temperature"] owm_data["temperature_c"] = w.get_temperature(unit="celsius") owm_data["temperature_f"] = w.get_temperature( unit="fahrenheit") owm_data["temperature_k"] = w.get_temperature(unit="kelvin") self.data = json.dumps(owm_data) self.save() except: pass
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 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 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 test(message): try: place = message.text config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM('db0f509410030e5e6b9a7eea0c30f0c3', config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(place) w = observation.weather t = w.temperature("celsius") t1 = t['temp'] t2 = t['feels_like'] t3 = t['temp_max'] t4 = t['temp_min'] wi = w.wind()['speed'] humi = w.humidity cl = w.clouds st = w.status dt = w.detailed_status ti = w.reference_time('iso') pr = w.pressure['press'] vd = w.visibility_distance bot.send_message( message.chat.id, "В городе " + str(place) + " температура " + str(t1) + " °C" + "\n" + "Максимальная температура " + str(t3) + " °C" + "\n" + "Минимальная температура " + str(t4) + " °C" + "\n" + "Ощущается как" + str(t2) + " °C" + "\n" + "Скорость ветра " + str(wi) + " м/с" + "\n" + "Давление " + str(pr) + " мм.рт.ст" + "\n" + "Влажность " + str(humi) + " %" + "\n" + "Видимость " + str(vd) + " метров" + "\n" + "Описание " + str(st) + "\n\n" + str(dt)) except: bot.send_message(message.chat.id, "Такой город не найден!") print(str(message.text), "- не найден")
def __init__(self, token: str, owm_token: str): super().__init__(token) # разделы self.__dirs = { '🔄Главное меню🔄': RangeNumberReplyButton( ['📚Школа📚', '🎲Прочее🎲', '👤Аккаунт👤', '❓Помощь❓']), '👤Аккаунт👤': RangeNumberReplyButton([ '📂Информация📂', '🔢Номер класса🔢', '🔡Буква класса🔡', '🔄Главное меню🔄' ]), '📚Школа📚': RangeNumberReplyButton([ '📃Расписание📃', '📰Новости📰', '📘Доп материалы📘', '🔄Главное меню🔄' ]), '❓Помощь❓': RangeNumberReplyButton( ('⚙️Команды⚙️', '💬Контакты💬', '©️GitHub©️', '🔄Главное меню🔄')), '🎲Прочее🎲': RangeNumberReplyButton([ '🌤Погода🌤', '😺Котики😺', '☝️Цитаты☝️', '🦠COVID-19🦠', '🔄Главное меню🔄' ]), } self.__subjects = ('Физика', 'Алгебра', 'Русский язык', 'Информатика') # txt файлы self.__questions_dirs = ('присоедениться к уроку', 'школьный сайт', 'смена ника') # погодник presets = get_default_config() presets['language'] = 'ru' self.__owm = pyowm.OWM(owm_token, presets) # бот self.__dp = Dispatcher(self) self.__eventloop = asyncio.get_event_loop()
def weather(city, radius): geo_data = [] config = get_default_config() config['language'] = 'en' owm = OWM(KEY, config=config) mgr = owm.weather_manager() reg = owm.city_id_registry() try: list_of_geopoints = reg.geopoints_for(f'{city}', country='RU') lat = list_of_geopoints[0].lat lng = list_of_geopoints[0].lon first_temp = mgr.one_call( lat=lat, lon=lng).current.temperature('celsius')["temp"] cities = parsing.html(lat, lng, radius) except: return None for city in cities: try: list_of_geopoints = reg.geopoints_for(f'{city}') weather = mgr.one_call(lat=list_of_geopoints[0].lat, lon=list_of_geopoints[0].lon).current temp = weather.temperature('celsius') if abs(temp["temp"] - first_temp) <= 7: geo_data.append([ city[0].upper() + city.lower()[1:], temp["temp"], temp["feels_like"] // 1, weather.detailed_status[0].upper() + weather.detailed_status[1:] ]) ''' print(f'Температура в городе {city[0].upper()+city.lower()[1:]} {temp["temp"]}, ощущается как {temp["feels_like"]//1},\ {weather.detailed_status}') ''' except: pass return geo_data
def get_weath(message): config_dict = get_default_config() config_dict['language'] = 'ru' owm = pyowm.OWM(config.API_WEATHER) try: mgr = owm.weather_manager() observation = mgr.weather_at_place(message.text) w = observation.weather temp = w.temperature('celsius')["temp"] print(temp) stat = w.status print(stat) answer = "В городе <b>" + message.text + "</b> сейчас " + w.detailed_status + "\n" print(answer) hum = w.humidity print(hum) time = w.reference_time(timeformat='iso') wind = w.wind()["speed"] print(wind) answer += "Температура в районе <b>" + str(temp) + "°C</b>\nСкорость ветра: <b>" + str( wind) + "м/с</b>" + "\n" + "Влажность: <b>" + str(hum) + "%</b>" + "\n" + "Время: " + str(time) + "\n" if temp < 0: answer += "Сейчас холодно, лучше одеться потеплее." elif temp < 15: answer += "Сейчас прохладно, не забудь курточку." elif temp > 25: answer += "Жарковато, не забудь водичку." else: answer += "Температура в норме, в принципе, жить можно!" print(answer) return answer except Exception: answer = 'Ошибка! Город не найден.' print(message.text) return answer
async def _weather(self, ctx, *, city): config_dict = get_default_config() config_dict['language'] = 'ru' owm = pyowm.OWM('290ad7a9c0c0a979294080fa2dbf5bd4', config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(city) w = observation.weather temp = w.temperature('celsius')['temp'] tempfeellike = w.temperature('celsius')['feels_like'] icon = w.weather_icon_url(size='2x') wind = w.wind()['speed'] emb = discord.Embed(title=f"в городе __**{city}**__", colour=self.client.COLORS['BASE']) emb.add_field(name="Температура:", value=f"{temp}°C") if tempfeellike != temp: emb.add_field(name="Температура ощущается как:", value=f"{tempfeellike}°C") emb.add_field(name="Скорость ветра:", value=f"{wind}м/с") emb.add_field(name="Погода:", value=f"{w.detailed_status}") emb.set_thumbnail(url=icon) await ctx.reply(embed=emb)
def send_weather(message): print(message.text) photo = open('C:/Users/Вячеслав/PycharmProjects/TestWeatherBot/1.jpg', 'rb') if message.text == "Слава+Катя=?": bot.send_photo(message.chat.id, photo) answer = "Мой создатель оставил сообщение для тебя\n\n" \ "Катя, я счастлив, что уже почти 2 года знаком с тобой," \ "и всем сердцем люблю тебя, родная\n" \ "─▄█▀█▄──▄███▄─\n▐█░██████████▌\n─██▒█████████─\n──▀████████▀──\n─────▀██▀─────" else: config_dict = config.get_default_config() config_dict['language'] = "ru" owm = OWM('0e9163d3d6c0fb02ddf0b1ca5363fda2', config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(message.text) w = observation.weather temp = w.temperature('celsius')['temp'] S = str(w) i = S.find("detailed_status", 80) status = S[(i + 16):(len(S) - 1)] answer = "В городе " + str(message.text) + " сейчас " + status answer += "\nТемпература около " + str( temp) + " градусов цельсия" + "\n" if temp < 0: answer += "Уже меньше нуля, одевайся теплее!" elif temp < 10: answer += "Достаточно холодно, понадобится шапка!" elif temp < 20: answer += "Не так холодно, но не жара." else: answer += "Уфф, одевай че по кайфу, жарко!" bot.send_message(message.chat.id, answer)
#telegram_bot import pyowm import telebot from pyowm.utils.config import get_default_config config_dict = get_default_config() config_dict['language'] = 'ru' owm = pyowm.OWM('4ecd09d1d2a7375673797f77c4b84899', config_dict) mgr = owm.weather_manager() bot = telebot.TeleBot('1636422665:AAFBrkQpE-jvMR4Mcz6DsVnY3tfVQS7zlfw') @bot.message_handler(content_types=['text']) def send_echo(message): #while True: try: observation = mgr.weather_at_place(message.text) w = observation.weather #bot.reply_to(message, message.text) #break #except NotFoundError: #answer = 'Город не найден' temp = w.temperature('celsius')["temp"] answer = 'В городе ' + message.text + ' сейчас ' + w.detailed_status + '\n' answer += 'Температура сейчас в районе ' + str(temp) + '\n\n'