def test_zip_case(self): """Test simple weather api case.""" weather_api = WeatherAPI() weather_tx = weather_api.get_weather_data() self.assertIsNotNone(weather_tx) self.assertEquals(weather_tx.city, TEST_CITY_TX_NAME) getLogger(__name__).debug(weather_tx) weather_pa = weather_api.get_weather_data(PA_ZIP_CODE) self.assertIsNotNone(weather_pa) getLogger(__name__).debug(weather_pa) self.assertEquals(weather_pa.city, TEST_CITY_PA_NAME) self.assertIsNotNone(weather_tx.temperature) self.assertIsNotNone(weather_tx.pressure) self.assertTrue(TEST_STRING_CONTAINS in weather_tx.__repr__()) self.assertNotEquals(weather_tx.city, weather_pa.city)
def test_simple_case(self): """Test simple weather api case.""" weather_api = WeatherAPI() pain_data = weather_api.get_weather_data() self.assertIsNotNone(pain_data) self.assertIsNotNone(pain_data.temperature) self.assertIsNotNone(pain_data.pressure) self.assertTrue(TEST_STRING_CONTAINS in pain_data.__repr__()) self.assertIsNone(pain_data.save(10, self.db_path)) self.assertIsNone(pain_data.save(0, self.db_path)) self.assertIsNone(pain_data.save(5, self.db_path)) self.assertEquals(pain_data.get_pain_item_count(self.db_path), 3) with self.assertRaises(type(INVALID_PAIN_INPUT_EXCEPTION)): pain_data.save(100) with self.assertRaises(type(INVALID_PAIN_INPUT_EXCEPTION)): pain_data.save(-100) with self.assertRaises(ValueError): pain_data.save('test') self.assertEquals(len(pain_data.get_pain_items(self.db_path)), 3)
def weather_handler(update, context): # if update.message.text == WEATHER_CONVERSATION_COMMANDS[0]: # update.message.reply_text('current weather', reply_markup=telegram.ReplyKeyboardRemove()) # TODO: send a current weather from yandex there #lon = context.user_data["location"]['longitude'] #lat = context.user_data["location"]['latitude'] print(context) lat = 55.75396 lon = 37.620393 if update.message.text == WEATHER_CONVERSATION_COMMANDS[0]: update.message.reply_text('current weather', reply_markup=telegram.ReplyKeyboardRemove()) weather = WeatherAPI(YANDEX_WEATHER_API_KEY).get_current_weather( lat=lat, lon=lon) update.message.reply_text(str(weather)) # TODO: send a current weather from yandex there elif update.message.text == WEATHER_CONVERSATION_COMMANDS[1]: update.message.reply_text('forecast', reply_markup=telegram.ReplyKeyboardRemove()) # TODO: send a forecast of weather from yandex there return ConversationHandler.END
def do_weather(self, event): '''Parse and handle the weather requested event''' msg_data = event.data.get("data") requestor_name = event.data.get("user_name") room_id = event.data.get("room_id") pattern = "^(.*)\s(.*)\s(\d*)" groups = re.findall(pattern, msg_data) location = groups[0][2] weather_response = WeatherAPI.get_weather(self.api_key, location) # Parsing for OpenWeatherMap # pp = pprint.PrettyPrinter() # pp.pprint(weather_response) # wr_city = weather_response["name"] # wr_main = weather_response["main"] # wr_main_temp = wr_main["temp"] # wr_weather = weather_response["weather"][0] # wr_weather_desc = wr_weather["description"] # wr_main_temp_f = (wr_main_temp * (9/5.0)) - 459.67 # Parsing for Wunderground # pp = pprint.PrettyPrinter() # wr = weather_response["current_observation"] # pp.pprint(wr) wr_city = weather_response["current_observation"]["display_location"]["city"] wr_main_temp_f = weather_response["current_observation"]["temperature_string"] wr_weather_desc = weather_response["current_observation"]["weather"].lower() # Create the response payload message = "{}, {} is {} and is {}".format( requestor_name, wr_city, wr_main_temp_f, wr_weather_desc) # Post the response self.post_result(room_id, message) return message
def weather_handler(update, context): lon = context.user_data["location"]['longitude'] lat = context.user_data["location"]['latitude'] if update.message.text == WEATHER_CONVERSATION_COMMANDS[0]: update.message.reply_text('current weather', reply_markup=telegram.ReplyKeyboardRemove()) # TODO: send a current weather from yandex there weather_for_reply = WeatherAPI( YANDEX_WEATHER_API_KEY).get_current_weather(lat=lat, lon=lon) update.message.reply_text('\n'.join( [f'{key}: {value}' for (key, value) in weather_for_reply.items()])) elif update.message.text == WEATHER_CONVERSATION_COMMANDS[1]: update.message.reply_text('forecast', reply_markup=telegram.ReplyKeyboardRemove()) # TODO: send a forecast of weather from yandex there weather_for_days = WeatherAPI(YANDEX_WEATHER_API_KEY).get_forecast( lat=lat, lon=lon) weather_for_reply = [] for day in weather_for_days: weather_for_reply.append(', '.join( [f'{key}: {value}' for (key, value) in day.items()])) update.message.reply_text('\n\n'.join(weather_for_reply)) return ConversationHandler.END
AQI_CITY = None def _exec(cmd): rc = os.system(cmd) if (rc != 0): print("`%s` failed with error %d" % (cmd, rc)) exit(rc) if len(sys.argv) < 4: print("Need 3 or more argument for API key, latitude, longitud, " "[is_landscape] [aqi_city_name_for_landscape]") exit(1) weather_obj = WeatherAPI(sys.argv[1], sys.argv[2], sys.argv[3]) if len(sys.argv) >= 5 and sys.argv[4] != 0: SVG_FILE = SVG_LANSCAPE_FILE if len(sys.argv) >= 6 and sys.argv[5]: AQI_CITY = sys.argv[5] # Open SVG to process output = codecs.open(SVG_FILE, "r", encoding="utf-8").read() _MAP = { "$I": WeatherAPI.condition, "$H": WeatherAPI.temp_max, "$L": WeatherAPI.temp_min, }
def start_telegram_bot(): updater = Updater(TELEGRAM_KEY, use_context=True) dp = updater.dispatcher # setup commands dp.add_handler(CommandHandler("start", start)) event_conversation = ConversationHandler( entry_points=[CommandHandler("weather", get_weather_start)], states={ 0: [MessageHandler(Filters.location, coordinates_handler)], 1: [MessageHandler(Filters.regex(f'^({"|".join(WEATHER_CONVERSATION_COMMANDS)})'), weather_handler)] }, fallbacks=[CommandHandler("cancel", cancel)] ) dp.add_handler(event_conversation) dp.add_error_handler(error) # Start the Bot updater.start_polling() # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle() if __name__ == '__main__': weather_api = WeatherAPI(YANDEX_WEATHER_API_KEY) start_telegram_bot()
AQI_CITY = os.environ.get("KW_AQI_CITY", None) if os.environ.get("KW_INCLUDE_SCI") is not None: INCLUDE_SCI = True WEATHER_KEY = os.environ.get("KW_WEATHER_KEY") LATITUDE = os.environ.get("KW_LATITUDE") LONGTITUDE = os.environ.get("KW_LONGTITUDE") if WEATHER_KEY is None or LATITUDE is None or LONGTITUDE is None: print("Need KW_WEATHER_KEY and KW_LATITUDE and KW_LONGTITUDE " "environment variables") exit(1) weather_obj = WeatherAPI(WEATHER_KEY, LATITUDE, LONGTITUDE) # Open SVG to process output = codecs.open(SVG_FILE, "r", encoding="utf-8").read() _MAP = { "$I": WeatherAPI.condition, "$H": WeatherAPI.temp_max, "$L": WeatherAPI.temp_min, } for x in _MAP.keys(): for i in range(MAX_WEATHER_DAY_COUNT + 1): output = output.replace("%s%d" % (x, i), "%s" % _MAP[x](weather_obj, i))
def __init__(self, weather_api=WeatherAPI()): """Initializer with option passed in weather api.""" self._weather_api = weather_api
def main(): EventProcessor(VkAPI(token=TOKEN), WeatherAPI(api_key=OPENWEATHER_API_KEY)).process_events()
import codecs import datetime import os import sys from weather_api import WeatherAPI CODE_FOLDER = os.path.dirname(os.path.realpath(__file__)) OUTPUT="/var/www/html/weather/weather.png" if len(sys.argv) != 4: print("Need 3 argument for API key, latitude, longitud") exit(1) weather_obj = WeatherAPI(sys.argv[1], sys.argv[2], sys.argv[3]) # Open SVG to process output = codecs.open("%s/weather-script-preprocess.svg" % CODE_FOLDER, "r", encoding="utf-8").read() # Update weather condition output = output.replace("ICON_ONE", weather_obj.condition(0)); output = output.replace("ICON_TWO", weather_obj.condition(1)); output = output.replace("ICON_THREE", weather_obj.condition(2)); output = output.replace("ICON_FOUR", weather_obj.condition(3)); # Update hightest temp