예제 #1
0
 def initialize(config):
     bot = PokemonGoBot(config)
     bot.start()
     initialize_task(bot, config)
     bot.metrics.capture_stats()
     bot.health_record = BotEvent(config)
     return bot
예제 #2
0
def main():
    bot = False

    def handle_sigint(*args):
        raise SIGINTRecieved

    signal.signal(signal.SIGINT, handle_sigint)

    def initialize_task(bot, config):
        tree = TreeConfigBuilder(bot, config.raw_tasks).build()
        bot.workers = tree

    def initialize(config):
        from pokemongo_bot.datastore import Datastore

        ds = Datastore(conn_str='/data/{}.db'.format(config.username))
        for directory in ['pokemongo_bot', 'pokemongo_bot/cell_workers']:
            ds.migrate(directory + '/migrations')

        bot = PokemonGoBot(ds.get_connection(), config)

        return bot

    def setup_logging(config):
        log_level = logging.ERROR

        if config.debug:
            log_level = logging.DEBUG

        logging.getLogger("requests").setLevel(log_level)
        logging.getLogger("websocket").setLevel(log_level)
        logging.getLogger("socketio").setLevel(log_level)
        logging.getLogger("engineio").setLevel(log_level)
        logging.getLogger("socketIO-client").setLevel(log_level)
        logging.getLogger("pgoapi").setLevel(log_level)
        logging.getLogger("rpc_api").setLevel(log_level)

        if config.logging:
            logging_format = '%(message)s'
            logging_format_options = ''

            if ('show_log_level'
                    not in config.logging) or config.logging['show_log_level']:
                logging_format = '[%(levelname)s] ' + logging_format
            if ('show_process_name' not in config.logging
                ) or config.logging['show_process_name']:
                logging_format = '[%(name)10s] ' + logging_format
            if ('show_thread_name' not in config.logging
                ) or config.logging['show_thread_name']:
                logging_format = '[%(threadName)s] ' + logging_format
            if ('show_datetime'
                    not in config.logging) or config.logging['show_datetime']:
                logging_format = '[%(asctime)s] ' + logging_format
                logging_format_options = '%Y-%m-%d %H:%M:%S'

            formatter = Formatter(logging_format, logging_format_options)
            for handler in logging.root.handlers[:]:
                handler.setFormatter(formatter)

    def start_bot(bot, config):
        bot.start()
        initialize_task(bot, config)
        bot.metrics.capture_stats()
        bot.health_record = BotEvent(config)
        return bot

    def get_commit_hash():
        try:
            hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'],
                                           stderr=subprocess.STDOUT)
            if all(c in string.hexdigits for c in hash[:-1]):
                with open('version', 'w') as f:
                    f.write(hash)
        except:
            pass

        if not os.path.exists('version'):
            return 'unknown'

        with open('version') as f:
            return f.read()[:8]

    try:
        if six.PY2:
            sys.stdout = codecs.getwriter('utf8')(sys.stdout)
            sys.stderr = codecs.getwriter('utf8')(sys.stderr)

        logger.info('PokemonGO Bot v1.0')
        logger.info('commit: ' + get_commit_hash())

        config, config_file = init_config()
        if not config:
            return

        logger.info('Configuration initialized')
        health_record = BotEvent(config)
        health_record.login_success()

        setup_logging(config)

        finished = False

        while not finished:
            min_wait_time = int(config.reconnecting_timeout * 0.8 * 60)
            max_wait_time = int(config.reconnecting_timeout * 1.2 * 60)
            wait_time = randint(min_wait_time, max_wait_time)
            try:
                bot = initialize(config)
                bot = start_bot(bot, config)
                config_changed = check_mod(config_file)

                bot.event_manager.emit('bot_start',
                                       sender=bot,
                                       level='info',
                                       formatted='Starting bot...')

                while True:
                    bot.tick()
                    if config.live_config_update_enabled and config_changed():
                        logger.info('Config changed! Applying new config.')
                        config, _ = init_config()

                        if config.live_config_update_tasks_only:
                            initialize_task(bot, config)
                        else:
                            bot = initialize(config)
                            bot = start_bot(bot, config)

            except KeyboardInterrupt:
                bot.event_manager.emit('bot_exit',
                                       sender=bot,
                                       level='info',
                                       formatted='Exiting bot.')
                finished = True
                report_summary(bot)

            except NotLoggedInException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Not logged in, reconnecting in {:d} seconds'.
                    format(wait_time))
                time.sleep(wait_time)
            except ServerBusyOrOfflineException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted=
                    'Server busy or offline, reconnecting in {:d} seconds'.
                    format(wait_time))
                time.sleep(wait_time)
            except ServerSideRequestThrottlingException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted=
                    'Server is throttling, reconnecting in {:d} seconds'.
                    format(wait_time))
                time.sleep(wait_time)
            except PermaBannedException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted=
                    'Probably permabanned, Game Over ! Play again at https://club.pokemon.com/us/pokemon-trainer-club/sign-up/'
                )
                time.sleep(36000)
            except NoPlayerPositionSetException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted=
                    'No player position set, reconnecting in {:d} seconds'.
                    format(wait_time))
                time.sleep(wait_time)

    except GeocoderQuotaExceeded:
        raise Exception("Google Maps API key over requests limit.")
    except SIGINTRecieved:
        if bot:
            bot.event_manager.emit(
                'bot_interrupted',
                sender=bot,
                level='info',
                formatted='Bot caught SIGINT. Shutting down.')
            report_summary(bot)

    except Exception as e:
        # always report session summary and then raise exception
        if bot:
            report_summary(bot)

        raise
    finally:
        # Cache here on SIGTERM, or Exception.  Check data is available and worth caching.
        if bot:
            if len(bot.recent_forts) > 0 and bot.recent_forts[
                    -1] is not None and bot.config.forts_cache_recent_forts:
                cached_forts_path = os.path.join(
                    _base_dir, 'data',
                    'recent-forts-%s.json' % bot.config.username)
                try:
                    with open(cached_forts_path, 'w') as outfile:
                        json.dump(bot.recent_forts, outfile)
                    bot.event_manager.emit('cached_fort',
                                           sender=bot,
                                           level='debug',
                                           formatted='Forts cached.')
                except IOError as e:
                    bot.event_manager.emit(
                        'error_caching_forts',
                        sender=bot,
                        level='debug',
                        formatted='Error caching forts for {path}',
                        data={'path': cached_forts_path})
예제 #3
0
def main():
    bot = False

    def handle_sigint(*args):
        raise SIGINTRecieved

    signal.signal(signal.SIGINT, handle_sigint)

    def initialize_task(bot, config):
        tree = TreeConfigBuilder(bot, config.raw_tasks).build()
        bot.workers = tree

    def initialize(config):
        bot = PokemonGoBot(config)
        return bot

    def start_bot(bot, config):
        bot.start()
        initialize_task(bot, config)
        bot.metrics.capture_stats()
        bot.health_record = BotEvent(config)
        return bot

    def get_commit_hash():
        try:
            hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'],
                                           stderr=subprocess.STDOUT)
            if all(c in string.hexdigits for c in hash[:-1]):
                with open('version', 'w') as f:
                    f.write(hash)
        except:
            pass

        if not os.path.exists('version'):
            return 'unknown'

        with open('version') as f:
            return f.read()[:8]

    try:
        logger.info('PokemonGO Bot v1.0')
        logger.info('commit: ' + get_commit_hash())
        sys.stdout = codecs.getwriter('utf8')(sys.stdout)
        sys.stderr = codecs.getwriter('utf8')(sys.stderr)

        config, config_file = init_config()
        if not config:
            return

        logger.info('Configuration initialized')
        health_record = BotEvent(config)
        health_record.login_success()

        finished = False

        while not finished:
            try:
                bot = initialize(config)
                bot = start_bot(bot, config)
                config_changed = check_mod(config_file)

                bot.event_manager.emit('bot_start',
                                       sender=bot,
                                       level='info',
                                       formatted='Starting bot...')

                while True:
                    bot.tick()
                    if config.live_config_update_enabled and config_changed():
                        logger.info('Config changed! Applying new config.')
                        config, _ = init_config()

                        if config.live_config_update_tasks_only:
                            initialize_task(bot, config)
                        else:
                            bot = initialize(config)
                            bot = start_bot(bot, config)

            except KeyboardInterrupt:
                bot.event_manager.emit('bot_exit',
                                       sender=bot,
                                       level='info',
                                       formatted='Exiting bot.')
                finished = True
                report_summary(bot)

            except NotLoggedInException:
                wait_time = config.reconnecting_timeout * 60
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Log logged in, reconnecting in {:d}'.format(
                        wait_time))
                time.sleep(wait_time)
            except ServerBusyOrOfflineException:
                bot.event_manager.emit('api_error',
                                       sender=bot,
                                       level='info',
                                       formatted='Server busy or offline')
                time.sleep(wait_time)
            except ServerSideRequestThrottlingException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server is throttling, reconnecting in 30 seconds'
                )
                time.sleep(30)
            except PermaBannedException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted=
                    'Probably permabanned, Game Over ! Play again at https://club.pokemon.com/us/pokemon-trainer-club/sign-up/'
                )
                time.sleep(36000)
            except NoPlayerPositionSetException:
                bot.event_manager.emit('api_error',
                                       sender=bot,
                                       level='info',
                                       formatted='No player position set')
                time.sleep(wait_time)

    except GeocoderQuotaExceeded:
        raise Exception("Google Maps API key over requests limit.")
    except SIGINTRecieved:
        if bot:
            bot.event_manager.emit(
                'bot_interrupted',
                sender=bot,
                level='info',
                formatted='Bot caught SIGINT. Shutting down.')
            report_summary(bot)

    except Exception as e:
        # always report session summary and then raise exception
        if bot:
            report_summary(bot)

        raise
    finally:
        # Cache here on SIGTERM, or Exception.  Check data is available and worth caching.
        if bot:
            if len(bot.recent_forts) > 0 and bot.recent_forts[
                    -1] is not None and bot.config.forts_cache_recent_forts:
                cached_forts_path = os.path.join(
                    _base_dir, 'data',
                    'recent-forts-%s.json' % bot.config.username)
                try:
                    with open(cached_forts_path, 'w') as outfile:
                        json.dump(bot.recent_forts, outfile)
                    bot.event_manager.emit(
                        'cached_fort',
                        sender=bot,
                        level='debug',
                        formatted='Forts cached.',
                    )
                except IOError as e:
                    bot.event_manager.emit(
                        'error_caching_forts',
                        sender=bot,
                        level='debug',
                        formatted='Error caching forts for {path}',
                        data={'path': cached_forts_path})
예제 #4
0
def main():
    bot = False

    def handle_sigint(*args):
        raise SIGINTRecieved
    signal.signal(signal.SIGINT, handle_sigint)

    def initialize_task(bot, config):
        tree = TreeConfigBuilder(bot, config.raw_tasks).build()
        bot.workers = tree

    def initialize(config):
        from pokemongo_bot.datastore import Datastore

        ds = Datastore(conn_str='/data/{}.db'.format(config.username))
        for directory in ['pokemongo_bot', 'pokemongo_bot/cell_workers']:
            ds.migrate(directory + '/migrations')

        bot = PokemonGoBot(ds.get_connection(), config)

        return bot

    def start_bot(bot, config):
        bot.start()
        initialize_task(bot, config)
        bot.metrics.capture_stats()
        bot.health_record = BotEvent(config)
        return bot

    def get_commit_hash():
        try:
            hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'],
                                           stderr=subprocess.STDOUT)
            if all(c in string.hexdigits for c in hash[:-1]):
                with open('version', 'w') as f:
                    f.write(hash)
        except:
            pass

        if not os.path.exists('version'):
            return 'unknown'

        with open('version') as f:
            return f.read()[:8]

    try:
        logger.info('PokemonGO Bot v1.0')
        logger.info('commit: ' + get_commit_hash())
        sys.stdout = codecs.getwriter('utf8')(sys.stdout)
        sys.stderr = codecs.getwriter('utf8')(sys.stderr)

        config, config_file = init_config()
        if not config:
            return

        logger.info('Configuration initialized')
        health_record = BotEvent(config)
        health_record.login_success()

        finished = False

        while not finished:
            try:
                bot = initialize(config)
                bot = start_bot(bot, config)
                config_changed = check_mod(config_file)

                bot.event_manager.emit(
                    'bot_start',
                    sender=bot,
                    level='info',
                    formatted='Starting bot...'
                )

                while True:
                    bot.tick()
                    if config.live_config_update_enabled and config_changed():
                        logger.info('Config changed! Applying new config.')
                        config, _ = init_config()

                        if config.live_config_update_tasks_only:
                            initialize_task(bot, config)
                        else:
                            bot = initialize(config)
                            bot = start_bot(bot, config)

            except KeyboardInterrupt:
                bot.event_manager.emit(
                    'bot_exit',
                    sender=bot,
                    level='info',
                    formatted='Exiting bot.'
                )
                finished = True
                report_summary(bot)

            except NotLoggedInException:
                wait_time = config.reconnecting_timeout * 60
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Log logged in, reconnecting in {:d}'.format(wait_time)
                )
                time.sleep(wait_time)
            except ServerBusyOrOfflineException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server busy or offline'
                )
                time.sleep(wait_time)
            except ServerSideRequestThrottlingException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server is throttling, reconnecting in 30 seconds'
                )
                time.sleep(30)
            except PermaBannedException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Probably permabanned, Game Over ! Play again at https://club.pokemon.com/us/pokemon-trainer-club/sign-up/'
                )
                time.sleep(36000)
            except NoPlayerPositionSetException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='No player position set'
                )
                time.sleep(wait_time)

    except GeocoderQuotaExceeded:
        raise Exception("Google Maps API key over requests limit.")
    except SIGINTRecieved:
        if bot:
            bot.event_manager.emit(
                'bot_interrupted',
                sender=bot,
                level='info',
                formatted='Bot caught SIGINT. Shutting down.'
            )
            report_summary(bot)

    except Exception as e:
        # always report session summary and then raise exception
        if bot:
            report_summary(bot)

        raise
    finally:
        # Cache here on SIGTERM, or Exception.  Check data is available and worth caching.
        if bot:
            if len(bot.recent_forts) > 0 and bot.recent_forts[-1] is not None and bot.config.forts_cache_recent_forts:
                cached_forts_path = os.path.join(
                    _base_dir, 'data', 'recent-forts-%s.json' % bot.config.username
                )
                try:
                    with open(cached_forts_path, 'w') as outfile:
                        json.dump(bot.recent_forts, outfile)
                    bot.event_manager.emit(
                        'cached_fort',
                        sender=bot,
                        level='debug',
                        formatted='Forts cached.',
                    )
                except IOError as e:
                    bot.event_manager.emit(
                        'error_caching_forts',
                        sender=bot,
                        level='debug',
                        formatted='Error caching forts for {path}',
                        data={'path': cached_forts_path}
                        )
예제 #5
0
def main():
    bot = False

    def handle_sigint(*args):
        raise SIGINTRecieved
    signal.signal(signal.SIGINT, handle_sigint)

    def get_commit_hash():
        try:
            hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'], stderr=subprocess.STDOUT)[:-1]

            return hash if all(c in string.hexdigits for c in hash) else "not found"
        except:
            return "not found"

    try:
        logger.info('PokemonGO Bot v1.0')
        logger.info('commit: ' + get_commit_hash())
        sys.stdout = codecs.getwriter('utf8')(sys.stdout)
        sys.stderr = codecs.getwriter('utf8')(sys.stderr)

        config = init_config()
        if not config:
            return

        logger.info('Configuration initialized')
        health_record = BotEvent(config)
        health_record.login_success()

        finished = False

        while not finished:
            try:
                bot = PokemonGoBot(config)
                bot.start()
                tree = TreeConfigBuilder(bot, config.raw_tasks).build()
                bot.workers = tree
                bot.metrics.capture_stats()
                bot.health_record = health_record

                bot.event_manager.emit(
                    'bot_start',
                    sender=bot,
                    level='info',
                    formatted='Starting bot...'
                )

                while True:
                    bot.tick()

            except KeyboardInterrupt:
                bot.event_manager.emit(
                    'bot_exit',
                    sender=bot,
                    level='info',
                    formatted='Exiting bot.'
                )
                finished = True
                report_summary(bot)

            except NotLoggedInException:
                wait_time = config.reconnecting_timeout * 60
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Log logged in, reconnecting in {:d}'.format(wait_time)
                )
                time.sleep(wait_time)
            except ServerBusyOrOfflineException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server busy or offline'
                )
            except ServerSideRequestThrottlingException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server is throttling, reconnecting in 30 seconds'
                )
                time.sleep(30)

    except PermaBannedException:
         bot.event_manager.emit(
            'api_error',
            sender=bot,
            level='info',
            formatted='Probably permabanned, Game Over ! Play again at https://club.pokemon.com/us/pokemon-trainer-club/sign-up/'
         )
    except GeocoderQuotaExceeded:
        raise Exception("Google Maps API key over requests limit.")
    except SIGINTRecieved:
        if bot:
            bot.event_manager.emit(
                'bot_interrupted',
                sender=bot,
                level='info',
                formatted='Bot caught SIGINT. Shutting down.'
            )
            report_summary(bot)
    except Exception as e:
        # always report session summary and then raise exception
        if bot:
            report_summary(bot)

        raise
    finally:
        # Cache here on SIGTERM, or Exception.  Check data is available and worth caching.
        if bot:
            if bot.recent_forts[-1] is not None and bot.config.forts_cache_recent_forts:
                cached_forts_path = os.path.join(
                    _base_dir, 'data', 'recent-forts-%s.json' % bot.config.username
                )
                try:
                    with open(cached_forts_path, 'w') as outfile:
                        json.dump(bot.recent_forts, outfile)
                    bot.event_manager.emit(
                        'cached_fort',
                        sender=bot,
                        level='debug',
                        formatted='Forts cached.',
                    )
                except IOError as e:
                    bot.event_manager.emit(
                        'error_caching_forts',
                        sender=bot,
                        level='debug',
                        formatted='Error caching forts for {path}',
                        data={'path': cached_forts_path}
                        )
예제 #6
0
 def start_bot(bot, config):
     bot.start(bot)
     initialize_task(bot, config)
     bot.metrics.capture_stats()
     bot.health_record = BotEvent(config)
     return bot
예제 #7
0
def main():
    bot = False

    def handle_sigint(*args):
        raise SIGINTRecieved

    signal.signal(signal.SIGINT, handle_sigint)

    def initialize_task(bot, config):
        tree = TreeConfigBuilder(bot, config.raw_tasks).build()
        bot.workers = tree

    def yes_no(question):
        # raw_input returns the empty string for "enter"
        yes = set(['yes', 'y', 'ye', ''])
        no = set(['no', 'n'])
        print question
        choice = raw_input().lower()
        if choice in yes:
            return True
        elif choice in no:
            return False
        else:
            print "Please respond with 'yes' or 'no'"
            return None

    def initialize(config):
        from pokemongo_bot.datastore import Datastore
        killswitch_url = 'https://raw.githubusercontent.com/PokemonGoF/PokemonGo-Bot/dev/killswitch.json'

        # Allow user to by pass warning without question
        if config.bypass_warning:
            bypass_warning = config.bypass_warning
        else:
            bypass_warning = False

        if config.killswitch:
            response = urllib2.urlopen(killswitch_url)
            killswitch_data = json.load(response)
            response.close()

            if killswitch_data['killswitch']:
                print "\033[91mKill Switch Activated By: \033[0m" + format(
                    killswitch_data['activated_by'])
                print "\033[91mMessage: \033[0m\n" + format(
                    killswitch_data['message']) + "\n\n\n"
                sys.exit(1)

        try:
            import pkg_resources
            pgoapi_version = pkg_resources.get_distribution("pgoapi").version
            if pgoapi_version != '2.13.0':
                yn = None
                while yn == None:
                    if not bypass_warning:
                        yn = yes_no(
                            "Warning: A new pokemon API version is found.\n Run following command to get latest update: `pip install -r requirements.txt --upgrade` \n Do you want to contine? Y/N"
                        )
                    else:
                        print "Warning: A new pokemon API version is found.\n Run following command to get latest update: `pip install -r requirements.txt --upgrade` \n You have chose to bypass warning, bot will continue running."
                        yn = True
                        time.sleep(5)
                if not yn:
                    sys.exit(1)

        except pkg_resources.DistributionNotFound:
            print 'Seems you forgot to install python modules.'
            print 'Run: `pip install -r requirements.txt`'
            sys.exit(1)
        except ImportError as e:
            print e
            pass

        ds = Datastore(conn_str='/data/{}.db'.format(config.username))
        for directory in ['pokemongo_bot', 'pokemongo_bot/cell_workers']:
            ds.migrate(directory + '/migrations')

        bot = PokemonGoBot(ds.get_connection(), config)

        return bot

    def setup_logging(config):
        log_level = logging.ERROR

        if config.debug:
            log_level = logging.DEBUG

        logging.getLogger("requests").setLevel(log_level)
        logging.getLogger("websocket").setLevel(log_level)
        logging.getLogger("socketio").setLevel(log_level)
        logging.getLogger("engineio").setLevel(log_level)
        logging.getLogger("socketIO-client").setLevel(log_level)
        logging.getLogger("pgoapi").setLevel(log_level)
        logging.getLogger("rpc_api").setLevel(log_level)

        if config.logging:
            logging_format = '%(message)s'
            logging_format_options = ''

            if ('show_log_level'
                    not in config.logging) or config.logging['show_log_level']:
                logging_format = '[%(levelname)s] ' + logging_format
            if ('show_process_name' not in config.logging
                ) or config.logging['show_process_name']:
                logging_format = '[%(name)10s] ' + logging_format
            if ('show_thread_name' not in config.logging
                ) or config.logging['show_thread_name']:
                logging_format = '[%(threadName)s] ' + logging_format
            if ('show_datetime'
                    not in config.logging) or config.logging['show_datetime']:
                logging_format = '[%(asctime)s] ' + logging_format
                logging_format_options = '%Y-%m-%d %H:%M:%S'

            formatter = Formatter(logging_format, logging_format_options)
            for handler in logging.root.handlers[:]:
                handler.setFormatter(formatter)

    def start_bot(bot, config):
        bot.start(bot)
        initialize_task(bot, config)
        bot.metrics.capture_stats()
        bot.health_record = BotEvent(config)
        return bot

    def get_commit_hash():
        try:
            hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'],
                                           stderr=subprocess.STDOUT)
            if all(c in string.hexdigits for c in hash[:-1]):
                with open('version', 'w') as f:
                    f.write(hash)
        except:
            pass

        if not os.path.exists('version'):
            return 'unknown'

        with open('version') as f:
            return f.read()[:8]

    try:
        if six.PY2:
            sys.stdout = codecs.getwriter('utf8')(sys.stdout)
            sys.stderr = codecs.getwriter('utf8')(sys.stderr)

        logger.info('PokemonGO Bot v1.0')
        logger.info('commit: ' + get_commit_hash())

        config, config_file = init_config()
        if not config:
            return

        logger.info('Configuration initialized')
        health_record = BotEvent(config)
        health_record.login_success()

        setup_logging(config)

        finished = False

        while not finished:
            min_wait_time = int(config.reconnecting_timeout * 0.8 * 60)
            max_wait_time = int(config.reconnecting_timeout * 1.2 * 60)
            wait_time = randint(min_wait_time, max_wait_time)
            try:
                bot = initialize(config)
                bot = start_bot(bot, config)
                config_changed = check_mod(config_file)

                bot.event_manager.emit('bot_start',
                                       sender=bot,
                                       level='info',
                                       formatted='Starting bot...')

                while True:
                    bot.tick()
                    if config.live_config_update_enabled and config_changed():
                        logger.info('Config changed! Applying new config.')
                        config, _ = init_config()

                        if config.live_config_update_tasks_only:
                            initialize_task(bot, config)
                        else:
                            bot = initialize(config)
                            bot = start_bot(bot, config)

            except KeyboardInterrupt:
                bot.event_manager.emit('bot_exit',
                                       sender=bot,
                                       level='info',
                                       formatted='Exiting bot.')
                finished = True
                report_summary(bot)

            except NotLoggedInException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Not logged in, reconnecting in {:d} seconds'.
                    format(wait_time))
                time.sleep(wait_time)
            except ServerBusyOrOfflineException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted=
                    'Server busy or offline, reconnecting in {:d} seconds'.
                    format(wait_time))
                time.sleep(wait_time)
            except ServerSideRequestThrottlingException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted=
                    'Server is throttling, reconnecting in {:d} seconds'.
                    format(wait_time))
                time.sleep(wait_time)
            except PermaBannedException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted=
                    'Probably permabanned, Game Over ! Play again at https://club.pokemon.com/us/pokemon-trainer-club/sign-up/'
                )
                time.sleep(36000)
            except NoPlayerPositionSetException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted=
                    'No player position set, reconnecting in {:d} seconds'.
                    format(wait_time))
                time.sleep(wait_time)

    except GeocoderQuotaExceeded:
        raise Exception("Google Maps API key over requests limit.")
    except SIGINTRecieved:
        if bot:
            bot.event_manager.emit(
                'bot_interrupted',
                sender=bot,
                level='info',
                formatted='Bot caught SIGINT. Shutting down.')
            report_summary(bot)

    except Exception as e:
        # always report session summary and then raise exception
        if bot:
            report_summary(bot)

        raise
    finally:
        # Cache here on SIGTERM, or Exception.  Check data is available and worth caching.
        if bot:
            if len(bot.recent_forts) > 0 and bot.recent_forts[
                    -1] is not None and bot.config.forts_cache_recent_forts:
                cached_forts_path = os.path.join(
                    _base_dir, 'data',
                    'recent-forts-%s.json' % bot.config.username)
                try:
                    with open(cached_forts_path, 'w') as outfile:
                        json.dump(bot.recent_forts, outfile)
                    bot.event_manager.emit('cached_fort',
                                           sender=bot,
                                           level='debug',
                                           formatted='Forts cached.')
                except IOError as e:
                    bot.event_manager.emit(
                        'error_caching_forts',
                        sender=bot,
                        level='debug',
                        formatted='Error caching forts for {path}',
                        data={'path': cached_forts_path})
예제 #8
0
def main():
    bot = False
    
    try:
        logger.info('PokemonGO Bot v1.0')
        sys.stdout = codecs.getwriter('utf8')(sys.stdout)
        sys.stderr = codecs.getwriter('utf8')(sys.stderr)

        config = init_config()
        if not config:
            return

        logger.info('Configuration initialized')
        health_record = BotEvent(config)
        health_record.login_success()

        finished = False

        while not finished:
            try:
                bot = PokemonGoBot(config)
                bot.start()
                tree = TreeConfigBuilder(bot, config.raw_tasks).build()
                bot.workers = tree
                bot.metrics.capture_stats()
                bot.health_record = health_record

                bot.event_manager.emit(
                    'bot_start',
                    sender=bot,
                    level='info',
                    formatted='Starting bot...'
                )

                while True:
                    bot.tick()

            except KeyboardInterrupt:
                bot.event_manager.emit(
                    'bot_exit',
                    sender=bot,
                    level='info',
                    formatted='Exiting bot.'
                )
                finished = True
                report_summary(bot)

            except NotLoggedInException:
                wait_time = config.reconnecting_timeout * 60
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formmated='Log logged in, reconnecting in {:s}'.format(wait_time)
                )
                time.sleep(wait_time)
            except ServerBusyOrOfflineException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server busy or offline'
                )
            except ServerSideRequestThrottlingException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server is throttling, reconnecting in 30 seconds'
                )
                time.sleep(30)

    except GeocoderQuotaExceeded:
        raise Exception("Google Maps API key over requests limit.")
    except Exception as e:
        # always report session summary and then raise exception
        if bot:
            report_summary(bot)

        raise e
예제 #9
0
def main():
    bot = False

    def handle_sigint(*args):
        raise SIGINTRecieved

    signal.signal(signal.SIGINT, handle_sigint)

    try:
        logger.info("PokemonGO Bot v1.0")
        sys.stdout = codecs.getwriter("utf8")(sys.stdout)
        sys.stderr = codecs.getwriter("utf8")(sys.stderr)

        config = init_config()
        if not config:
            return

        logger.info("Configuration initialized")
        health_record = BotEvent(config)
        health_record.login_success()

        finished = False

        while not finished:
            try:
                bot = PokemonGoBot(config)
                bot.start()
                tree = TreeConfigBuilder(bot, config.raw_tasks).build()
                bot.workers = tree
                bot.metrics.capture_stats()
                bot.health_record = health_record

                bot.event_manager.emit("bot_start", sender=bot, level="info", formatted="Starting bot...")

                while True:
                    bot.tick()

            except KeyboardInterrupt:
                bot.event_manager.emit("bot_exit", sender=bot, level="info", formatted="Exiting bot.")
                finished = True
                report_summary(bot)

            except NotLoggedInException:
                wait_time = config.reconnecting_timeout * 60
                bot.event_manager.emit(
                    "api_error",
                    sender=bot,
                    level="info",
                    formatted="Log logged in, reconnecting in {:d}".format(wait_time),
                )
                time.sleep(wait_time)
            except ServerBusyOrOfflineException:
                bot.event_manager.emit("api_error", sender=bot, level="info", formatted="Server busy or offline")
            except ServerSideRequestThrottlingException:
                bot.event_manager.emit(
                    "api_error", sender=bot, level="info", formatted="Server is throttling, reconnecting in 30 seconds"
                )
                time.sleep(30)

    except PermaBannedException:
        bot.event_manager.emit(
            "api_error",
            sender=bot,
            level="info",
            formatted="Probably permabanned, Game Over ! Play again at https://club.pokemon.com/us/pokemon-trainer-club/sign-up/",
        )
    except GeocoderQuotaExceeded:
        raise Exception("Google Maps API key over requests limit.")
    except SIGINTRecieved:
        if bot:
            bot.event_manager.emit(
                "bot_interrupted", sender=bot, level="info", formatted="Bot caught SIGINT. Shutting down."
            )
            report_summary(bot)
    except Exception as e:
        # always report session summary and then raise exception
        if bot:
            report_summary(bot)

        raise
    finally:
        # Cache here on SIGTERM, or Exception.  Check data is available and worth caching.
        if bot:
            if bot.recent_forts[-1] is not None and bot.config.forts_cache_recent_forts:
                cached_forts_path = os.path.join(_base_dir, "data", "recent-forts-%s.json" % bot.config.username)
                try:
                    with open(cached_forts_path, "w") as outfile:
                        json.dump(bot.recent_forts, outfile)
                    bot.event_manager.emit("cached_fort", sender=bot, level="debug", formatted="Forts cached.")
                except IOError as e:
                    bot.event_manager.emit(
                        "error_caching_forts",
                        sender=bot,
                        level="debug",
                        formatted="Error caching forts for {path}",
                        data={"path": cached_forts_path},
                    )
예제 #10
0
def main():
    bot = False

    def handle_sigint(*args):
        raise SIGINTRecieved
    signal.signal(signal.SIGINT, handle_sigint)

    def initialize_task(bot, config):
        tree = TreeConfigBuilder(bot, config.raw_tasks).build()
        bot.workers = tree
    
    def yes_no(question):
        # raw_input returns the empty string for "enter"
        yes = set(['yes','y', 'ye', ''])
        no = set(['no','n'])
        print question
        choice = raw_input().lower()
        if choice in yes:
            return True
        elif choice in no:
            return False
        else:
            print "Please respond with 'yes' or 'no'"
            return None

    def initialize(config):
        from pokemongo_bot.datastore import Datastore
        killswitch_url = 'https://raw.githubusercontent.com/PokemonGoF/PokemonGo-Bot/dev/killswitch.json'
        
        # Allow user to by pass warning without question
        if config.bypass_warning:
            bypass_warning = config.bypass_warning
        else:
            bypass_warning = False
            
        if config.killswitch:
            response = urllib2.urlopen(killswitch_url)
            killswitch_data = json.load(response)
            response.close()

            if killswitch_data['killswitch']:
                print "\033[91mKill Switch Activated By: \033[0m" + format(killswitch_data['activated_by'])
                print "\033[91mMessage: \033[0m\n" + format(killswitch_data['message']) + "\n\n\n"
                sys.exit(1)
    
        try:
            import pkg_resources
            pgoapi_version = pkg_resources.get_distribution("pgoapi").version
            if pgoapi_version != '2.13.0':
                yn=None
                while yn==None:
                    if not bypass_warning:
                        yn = yes_no("Warning: A new pokemon API version is found.\n Run following command to get latest update: `pip install -r requirements.txt --upgrade` \n Do you want to contine? Y/N")
                    else:
                        print "Warning: A new pokemon API version is found.\n Run following command to get latest update: `pip install -r requirements.txt --upgrade` \n You have chose to bypass warning, bot will continue running."
                        yn = True
                        time.sleep(5)
                if not yn:
                    sys.exit(1)

        except pkg_resources.DistributionNotFound:
            print 'Seems you forgot to install python modules.'
            print 'Run: `pip install -r requirements.txt`'
            sys.exit(1)
        except ImportError as e:
            print e
            pass

        ds = Datastore(conn_str='/data/{}.db'.format(config.username))
        for directory in ['pokemongo_bot', 'pokemongo_bot/cell_workers']:
            ds.migrate(directory + '/migrations')

        bot = PokemonGoBot(ds.get_connection(), config)

        return bot

    def setup_logging(config):
        log_level = logging.ERROR

        if config.debug:
            log_level = logging.DEBUG

        logging.getLogger("requests").setLevel(log_level)
        logging.getLogger("websocket").setLevel(log_level)
        logging.getLogger("socketio").setLevel(log_level)
        logging.getLogger("engineio").setLevel(log_level)
        logging.getLogger("socketIO-client").setLevel(log_level)
        logging.getLogger("pgoapi").setLevel(log_level)
        logging.getLogger("rpc_api").setLevel(log_level)

        if config.logging:
            logging_format = '%(message)s'
            logging_format_options = ''

            if ('show_log_level' not in config.logging) or config.logging['show_log_level']:
                logging_format = '[%(levelname)s] ' + logging_format
            if ('show_process_name' not in config.logging) or config.logging['show_process_name']:
                logging_format = '[%(name)10s] ' + logging_format
            if ('show_thread_name' not in config.logging) or config.logging['show_thread_name']:
                logging_format = '[%(threadName)s] ' + logging_format
            if ('show_datetime' not in config.logging) or config.logging['show_datetime']:
                logging_format = '[%(asctime)s] ' + logging_format
                logging_format_options = '%Y-%m-%d %H:%M:%S'

            formatter = Formatter(logging_format,logging_format_options)
            for handler in logging.root.handlers[:]:
                handler.setFormatter(formatter)

    def start_bot(bot, config):
        bot.start(bot)
        initialize_task(bot, config)
        bot.metrics.capture_stats()
        bot.health_record = BotEvent(config)
        return bot

    def get_commit_hash():
        try:
            hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'],
                                           stderr=subprocess.STDOUT)
            if all(c in string.hexdigits for c in hash[:-1]):
                with open('version', 'w') as f:
                    f.write(hash)
        except:
            pass

        if not os.path.exists('version'):
            return 'unknown'

        with open('version') as f:
            return f.read()[:8]

    try:
        if six.PY2:
            sys.stdout = codecs.getwriter('utf8')(sys.stdout)
            sys.stderr = codecs.getwriter('utf8')(sys.stderr)

        logger.info('PokemonGO Bot v1.0')
        logger.info('commit: ' + get_commit_hash())

        config, config_file = init_config()
        if not config:
            return

        logger.info('Configuration initialized')
        health_record = BotEvent(config)
        health_record.login_success()

        setup_logging(config)

        finished = False

        while not finished:
            min_wait_time = int(config.reconnecting_timeout * 0.8 * 60)
            max_wait_time = int(config.reconnecting_timeout *  1.2 * 60)
            wait_time = randint(min_wait_time, max_wait_time)
            try:
                bot = initialize(config)
                bot = start_bot(bot, config)
                config_changed = check_mod(config_file)

                bot.event_manager.emit(
                    'bot_start',
                    sender=bot,
                    level='info',
                    formatted='Starting bot...'
                )

                while True:
                    bot.tick()
                    if config.live_config_update_enabled and config_changed():
                        logger.info('Config changed! Applying new config.')
                        config, _ = init_config()

                        if config.live_config_update_tasks_only:
                            initialize_task(bot, config)
                        else:
                            bot = initialize(config)
                            bot = start_bot(bot, config)

            except KeyboardInterrupt:
                bot.event_manager.emit(
                    'bot_exit',
                    sender=bot,
                    level='info',
                    formatted='Exiting bot.'
                )
                finished = True
                report_summary(bot)

            except NotLoggedInException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Not logged in, reconnecting in {:d} seconds'.format(wait_time)
                )
                time.sleep(wait_time)
            except ServerBusyOrOfflineException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server busy or offline, reconnecting in {:d} seconds'.format(wait_time)
                )
                time.sleep(wait_time)
            except ServerSideRequestThrottlingException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server is throttling, reconnecting in {:d} seconds'.format(wait_time)
                )
                time.sleep(wait_time)
            except PermaBannedException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Probably permabanned, Game Over ! Play again at https://club.pokemon.com/us/pokemon-trainer-club/sign-up/'
                )
                time.sleep(36000)
            except NoPlayerPositionSetException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='No player position set, reconnecting in {:d} seconds'.format(wait_time)
                )
                time.sleep(wait_time)

    except GeocoderQuotaExceeded:
        raise Exception("Google Maps API key over requests limit.")
    except SIGINTRecieved:
        if bot:
            bot.event_manager.emit(
                'bot_interrupted',
                sender=bot,
                level='info',
                formatted='Bot caught SIGINT. Shutting down.'
            )
            report_summary(bot)

    except Exception as e:
        # always report session summary and then raise exception
        if bot:
            report_summary(bot)

        raise
    finally:
        # Cache here on SIGTERM, or Exception.  Check data is available and worth caching.
        if bot:
            if len(bot.recent_forts) > 0 and bot.recent_forts[-1] is not None and bot.config.forts_cache_recent_forts:
                cached_forts_path = os.path.join(
                    _base_dir, 'data', 'recent-forts-%s.json' % bot.config.username
                )
                try:
                    with open(cached_forts_path, 'w') as outfile:
                        json.dump(bot.recent_forts, outfile)
                    bot.event_manager.emit(
                        'cached_fort',
                        sender=bot,
                        level='debug',
                        formatted='Forts cached.'
                    )
                except IOError as e:
                    bot.event_manager.emit(
                        'error_caching_forts',
                        sender=bot,
                        level='debug',
                        formatted='Error caching forts for {path}',
                        data={'path': cached_forts_path}
                        )
예제 #11
0
def main():
    bot = False

    def handle_sigint(*args):
        raise SIGINTRecieved

    signal.signal(signal.SIGINT, handle_sigint)

    try:
        logger.info('PokemonGO Bot v1.0')
        sys.stdout = codecs.getwriter('utf8')(sys.stdout)
        sys.stderr = codecs.getwriter('utf8')(sys.stderr)

        config = init_config()
        if not config:
            return

        logger.info('Configuration initialized')
        health_record = BotEvent(config)
        health_record.login_success()

        finished = False

        while not finished:
            try:
                bot = PokemonGoBot(config)
                bot.start()
                tree = TreeConfigBuilder(bot, config.raw_tasks).build()
                bot.workers = tree
                bot.metrics.capture_stats()
                bot.health_record = health_record

                bot.event_manager.emit('bot_start',
                                       sender=bot,
                                       level='info',
                                       formatted='Starting bot...')

                while True:
                    bot.tick()

            except KeyboardInterrupt:
                bot.event_manager.emit('bot_exit',
                                       sender=bot,
                                       level='info',
                                       formatted='Exiting bot.')
                finished = True
                report_summary(bot)

            except NotLoggedInException:
                wait_time = config.reconnecting_timeout * 60
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Log logged in, reconnecting in {:d}'.format(
                        wait_time))
                time.sleep(wait_time)
            except ServerBusyOrOfflineException:
                bot.event_manager.emit('api_error',
                                       sender=bot,
                                       level='info',
                                       formatted='Server busy or offline')
            except ServerSideRequestThrottlingException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server is throttling, reconnecting in 30 seconds'
                )
                time.sleep(30)

    except PermaBannedException:
        bot.event_manager.emit(
            'api_error',
            sender=bot,
            level='info',
            formatted=
            'Probably permabanned, Game Over ! Play again at https://club.pokemon.com/us/pokemon-trainer-club/sign-up/'
        )
    except GeocoderQuotaExceeded:
        raise Exception("Google Maps API key over requests limit.")
    except SIGINTRecieved:
        if bot:
            bot.event_manager.emit(
                'bot_interrupted',
                sender=bot,
                level='info',
                formatted='Bot caught SIGINT. Shutting down.')
            report_summary(bot)
    except Exception as e:
        # always report session summary and then raise exception
        if bot:
            report_summary(bot)

        raise
    finally:
        # Cache here on SIGTERM, or Exception.  Check data is available and worth caching.
        if bot:
            if bot.recent_forts[
                    -1] is not None and bot.config.forts_cache_recent_forts:
                cached_forts_path = os.path.join(
                    _base_dir, 'data',
                    'recent-forts-%s.json' % bot.config.username)
                try:
                    with open(cached_forts_path, 'w') as outfile:
                        json.dump(bot.recent_forts, outfile)
                    bot.event_manager.emit(
                        'cached_fort',
                        sender=bot,
                        level='debug',
                        formatted='Forts cached.',
                    )
                except IOError as e:
                    bot.event_manager.emit(
                        'error_caching_forts',
                        sender=bot,
                        level='debug',
                        formatted='Error caching forts for {path}',
                        data={'path': cached_forts_path})
예제 #12
0
def main():
    bot = False

    try:
        def handle_sigint(*args):
            raise SIGINTRecieved
        signal.signal(signal.SIGINT, handle_sigint)

        logger.info('PokemonGO Bot v1.0')
        sys.stdout = codecs.getwriter('utf8')(sys.stdout)
        sys.stderr = codecs.getwriter('utf8')(sys.stderr)

        config = init_config()
        if not config:
            return

        logger.info('Configuration initialized')
        health_record = BotEvent(config)
        health_record.login_success()

        finished = False

        while not finished:
            try:
                bot = PokemonGoBot(config)
                bot.start()
                tree = TreeConfigBuilder(bot, config.raw_tasks).build()
                bot.workers = tree
                bot.metrics.capture_stats()
                bot.health_record = health_record

                bot.event_manager.emit(
                    'bot_start',
                    sender=bot,
                    level='info',
                    formatted='Starting bot...'
                )

                while True:
                    bot.tick()

            except (KeyboardInterrupt, SIGINTRecieved):
                bot.event_manager.emit(
                    'bot_exit',
                    sender=bot,
                    level='info',
                    formatted='Exiting bot.'
                )
                finished = True
                report_summary(bot)

            except NotLoggedInException:
                wait_time = config.reconnecting_timeout * 60
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Log logged in, reconnecting in {:d}'.format(wait_time)
                )
                time.sleep(wait_time)
            except ServerBusyOrOfflineException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server busy or offline'
                )
            except ServerSideRequestThrottlingException:
                bot.event_manager.emit(
                    'api_error',
                    sender=bot,
                    level='info',
                    formatted='Server is throttling, reconnecting in 30 seconds'
                )
                time.sleep(30)

    except GeocoderQuotaExceeded:
        raise Exception("Google Maps API key over requests limit.")
    except Exception as e:
        # always report session summary and then raise exception
        if bot:
            report_summary(bot)

        raise
    finally:
        # Cache here on SIGTERM, or Exception.  Check data is available and worth caching.
        if bot:
            if bot.recent_forts[-1] is not None and bot.config.forts_cache_recent_forts:
                cached_forts_path = os.path.join(
                    _base_dir, 'data', 'recent-forts-%s.json' % bot.config.username
                )
                try:
                    with open(cached_forts_path, 'w') as outfile:
                        json.dump(bot.recent_forts, outfile)
                    bot.event_manager.emit(
                        'cached_fort',
                        sender=bot,
                        level='debug',
                        formatted='Forts cached.',
                    )
                except IOError as e:
                    bot.event_manager.emit(
                        'error_caching_forts',
                        sender=bot,
                        level='debug',
                        formatted='Error caching forts for {path}',
                        data={'path': cached_forts_path}
                        )