Beispiel #1
0
def main(path):
    """
    Main function called when starting weatherBot. The path is to the configuration file.
    :type path: str
    :param path: path to configuration file
    """
    # pylint: disable=broad-except,no-member
    global CACHE
    load_config(os.path.abspath(path))
    initialize_logger(CONFIG['log']['enabled'], CONFIG['log']['log_path'])
    logging.debug(CONFIG)
    keys.set_twitter_env_vars()
    keys.set_darksky_env_vars()
    CACHE['throttles']['default'] = pytz.utc.localize(datetime.utcnow()).astimezone(pytz.utc)
    with open(CONFIG['basic']['strings'], 'r') as file_stream:
        try:
            weatherbot_strings = yaml.safe_load(file_stream)
            logging.debug(weatherbot_strings)
            wb_string = models.WeatherBotString(weatherbot_strings)
        except yaml.YAMLError as err:
            logging.error(err, exc_info=True)
            logging.error('Could not read YAML file, please correct, run yamllint, and try again.')
            exit()

    location = CONFIG['default_location']
    updated_time = utils.datetime_to_utc('UTC', datetime.utcnow()) - timedelta(minutes=30)
    try:
        while True:
            # check for new location every 30 minutes
            now_utc = utils.datetime_to_utc('UTC', datetime.utcnow())
            if CONFIG['variable_location']['enabled'] and updated_time + timedelta(minutes=30) < now_utc:
                location = get_location_from_user_timeline(CONFIG['variable_location']['user'], location)
                updated_time = now_utc
            forecast = get_forecast_object(location.lat, location.lng, CONFIG['basic']['units'],
                                           wb_string.language)
            if forecast is not None:
                weather_data = models.WeatherData(forecast, location)
                if weather_data.valid:
                    CACHE = get_cache()
                    tweet_logic(weather_data, wb_string)
                CACHE['throttles'] = cleanse_throttles(CACHE['throttles'], now_utc)
                set_cache(CACHE)
                time.sleep(CONFIG['basic']['refresh'] * 60)
            else:
                time.sleep(60)
    except Exception as err:
        logging.error(err)
        logging.error('We got an exception!', exc_info=True)
        if CONFIG['basic']['dm_errors']:
            api = get_tweepy_api()
            api.send_direct_message(screen_name=api.me().screen_name,
                                    text=str(random.randint(0, 9999)) + traceback.format_exc())
Beispiel #2
0
def main(path):
    """
    Main function called when starting weatherBot. The path is to the configuration file.
    :type path: str
    :param path: path to configuration file
    """
    # pylint: disable=broad-except,no-member
    global CACHE
    load_config(os.path.abspath(path))
    initialize_logger(CONFIG['log']['enabled'], CONFIG['log']['log_path'])
    logging.debug(CONFIG)
    keys.set_twitter_env_vars()
    keys.set_darksky_env_vars()
    CACHE['throttles']['default'] = pytz.utc.localize(datetime.utcnow()).astimezone(pytz.utc)
    with open(CONFIG['basic']['strings'], 'r') as file_stream:
        try:
            weatherbot_strings = yaml.safe_load(file_stream)
            logging.debug(weatherbot_strings)
            wb_string = models.WeatherBotString(weatherbot_strings)
        except yaml.YAMLError as err:
            logging.error(err, exc_info=True)
            logging.error('Could not read YAML file, please correct, run yamllint, and try again.')
            exit()

    location = CONFIG['default_location']
    updated_time = utils.datetime_to_utc('UTC', datetime.utcnow()) - timedelta(minutes=30)
    try:
        while True:
            # check for new location every 30 minutes
            now_utc = utils.datetime_to_utc('UTC', datetime.utcnow())
            if CONFIG['variable_location']['enabled'] and updated_time + timedelta(minutes=30) < now_utc:
                location = get_location_from_user_timeline(CONFIG['variable_location']['user'], location)
                updated_time = now_utc
            forecast = get_forecast_object(location.lat, location.lng, CONFIG['basic']['units'],
                                           wb_string.language)
            if forecast is not None:
                weather_data = models.WeatherData(forecast, location)
                if weather_data.valid:
                    CACHE = get_cache()
                    tweet_logic(weather_data, wb_string)
                CACHE['throttles'] = cleanse_throttles(CACHE['throttles'], now_utc)
                set_cache(CACHE)
                time.sleep(CONFIG['basic']['refresh'] * 60)
            else:
                time.sleep(60)
    except Exception as err:
        logging.error(err)
        logging.error('We got an exception!', exc_info=True)
        if CONFIG['basic']['dm_errors']:
            api = get_tweepy_api()
            api.send_direct_message(screen_name=api.me().screen_name,
                                    text=str(random.randint(0, 9999)) + traceback.format_exc())
 def test_set_twitter_env_vars(self):
     """Test that Twitter environmental variables are set to values in keys.py"""
     keys.set_twitter_env_vars()
     self.assertIsNotNone(os.environ['WEATHERBOT_CONSUMER_KEY'])
     self.assertIsNotNone(os.environ['WEATHERBOT_CONSUMER_SECRET'])
     self.assertIsNotNone(os.environ['WEATHERBOT_ACCESS_TOKEN'])
     self.assertIsNotNone(os.environ['WEATHERBOT_ACCESS_TOKEN_SECRET'])
     del os.environ['WEATHERBOT_CONSUMER_KEY']
     del os.environ['WEATHERBOT_CONSUMER_SECRET']
     del os.environ['WEATHERBOT_ACCESS_TOKEN']
     del os.environ['WEATHERBOT_ACCESS_TOKEN_SECRET']
     keys.set_twitter_env_vars()
     self.assertEqual(os.getenv('WEATHERBOT_CONSUMER_KEY'), 'xxx')
     self.assertEqual(os.getenv('WEATHERBOT_CONSUMER_SECRET'), 'xxx')
     self.assertEqual(os.getenv('WEATHERBOT_ACCESS_TOKEN'), 'xxx')
     self.assertEqual(os.getenv('WEATHERBOT_ACCESS_TOKEN_SECRET'), 'xxx')
Beispiel #4
0
def main():
    try:
        initialize_logger(LOG_PATHNAME)
        set_twitter_env_vars()
        if VARIABLE_LOCATION:
            set_flickr_env_vars()
        updated_time = datetime.now()
        woeid = WOEID
        while True:
            # check for new location every 30 minutes
            if VARIABLE_LOCATION and updated_time + timedelta(minutes=30) < datetime.now():
                woeid = get_woeid_from_variable_location(woeid, USER_FOR_LOCATION)
                updated_time = datetime.now()
            weather_data = get_weather_variables(get_weather(woeid, UNIT))
            if weather_data['valid'] is True:
                tweet_logic(weather_data)
            time.sleep(60)
    except Exception as err:
        logging.error(err)
        logging.error('We got an exception!', exc_info=True)
def main(path):
    global throttle_times
    try:
        load_config(os.path.abspath(path))
        initialize_logger(CONFIG['log']['enabled'], CONFIG['log']['log_path'])
        keys.set_twitter_env_vars()
        keys.set_forecastio_env_vars()

        location = CONFIG['default_location']
        updated_time = utils.get_utc_datetime('UTC', datetime.utcnow()) - timedelta(minutes=30)
        while True:
            # check for new location every 30 minutes
            now_utc = utils.get_utc_datetime('UTC', datetime.utcnow())
            if CONFIG['variable_location']['enabled'] and updated_time + timedelta(minutes=30) < now_utc:
                location = get_location_from_user_timeline(CONFIG['variable_location']['user'], location)
                updated_time = now_utc
            forecast = get_forecast_object(location['lat'], location['lng'], CONFIG['basic']['units'])
            if forecast is not None:
                weather_data = get_weather_variables(forecast, location)
                if weather_data['valid'] is True:
                    tweet_logic(weather_data)
                # cleanse throttle_times of expired keys
                to_delete = [key for key, expires in throttle_times.items() if expires <= now_utc]
                for key in to_delete:
                    if key != 'default':
                        del throttle_times[key]
                time.sleep(CONFIG['basic']['refresh'] * 60)
            else:
                time.sleep(60)
    except Exception as err:
        logging.error(err)
        logging.error('We got an exception!', exc_info=True)
        if CONFIG['basic']['dm_errors']:
            api = get_tweepy_api()
            api.send_direct_message(screen_name=api.me().screen_name,
                                    text=str(random.randint(0, 9999)) + traceback.format_exc())
    def test_set_twitter_env_vars(self):
        """Test that Twitter environmental variables are set to values in keys.py"""
        keys.set_twitter_env_vars()
        self.assertIsNotNone(os.environ['WEATHERBOT_CONSUMER_KEY'])
        self.assertIsNotNone(os.environ['WEATHERBOT_CONSUMER_SECRET'])
        self.assertIsNotNone(os.environ['WEATHERBOT_ACCESS_TOKEN'])
        self.assertIsNotNone(os.environ['WEATHERBOT_ACCESS_TOKEN_SECRET'])
        del os.environ['WEATHERBOT_CONSUMER_KEY']
        del os.environ['WEATHERBOT_CONSUMER_SECRET']
        del os.environ['WEATHERBOT_ACCESS_TOKEN']
        del os.environ['WEATHERBOT_ACCESS_TOKEN_SECRET']
        keys.set_twitter_env_vars()
        self.assertEqual(os.getenv('WEATHERBOT_CONSUMER_KEY'), 'xxx')
        self.assertEqual(os.getenv('WEATHERBOT_CONSUMER_SECRET'), 'xxx')
        self.assertEqual(os.getenv('WEATHERBOT_ACCESS_TOKEN'), 'xxx')
        self.assertEqual(os.getenv('WEATHERBOT_ACCESS_TOKEN_SECRET'), 'xxx')

    def test_set_darksky_env_vars(self):
        """Test that the Dark Sky environmental variable is set to value in keys.py"""
        keys.set_darksky_env_vars()
        self.assertIsNotNone(os.environ['WEATHERBOT_DARKSKY_KEY'])
        del os.environ['WEATHERBOT_DARKSKY_KEY']
        keys.set_darksky_env_vars()
        self.assertEqual(os.getenv('WEATHERBOT_DARKSKY_KEY'), 'xxx')


if __name__ == '__main__':
    keys.set_twitter_env_vars()
    keys.set_darksky_env_vars()
    unittest.main()