Esempio n. 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
Esempio n. 2
0
 def initialize(config):
     bot = PokemonGoBot(config)
     bot.start()
     initialize_task(bot, config)
     bot.metrics.capture_stats()
     bot.health_record = BotEvent(config)
     return bot
Esempio n. 3
0
def main():
    # log settings
    # log format
    #logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    sys.stderr = codecs.getwriter('utf8')(sys.stderr)

    config = init_config()
    if not config:
        return

    logger.log('[x] Sekolah Pokemon v2.0 by Bhagas', 'green')
    logger.log('[x] Menjalankan Konfigurasi', 'yellow')

    try:
        bot = PokemonGoBot(config)
        bot.start()

        logger.log('[x] Menjalankan PokemonGo Bot....', 'green')

        while (True):
            bot.take_step()

    except KeyboardInterrupt:
        logger.log('[x] Keluar PokemonGo Bot', 'red')
Esempio n. 4
0
def main():
    # log settings
    # log format
    #logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    sys.stderr = codecs.getwriter('utf8')(sys.stderr)

    config = init_config()
    if not config:
        return

    logger.log('[x] PokemonGO Bot v1.0', 'green')
    logger.log('[x] Configuration initialized', 'yellow')

    while True:
        try:
            bot = PokemonGoBot(config)
            bot.start()

            logger.log('[x] Starting PokemonGo Bot....', 'green')

            while True:
                bot.take_step()

        except KeyboardInterrupt:
            logger.log('[x] Exiting PokemonGo Bot', 'red')
            # TODO Add number of pokemon catched, pokestops visited, highest CP
            # pokemon catched, etc.
            break
        except:
            logger.log('[x] sleep 5s attempting to restart the bot', 'red')
            time.sleep(5)
Esempio n. 5
0
def main():
    # log settings
    # log format
    #logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    sys.stderr = codecs.getwriter('utf8')(sys.stderr)

    config = init_config()
    if not config:
        return

    logger.log('[x] PokemonGO Bot v1.0', 'green')
    logger.log('[x] Configuration initialized', 'yellow')

    try:
        bot = PokemonGoBot(config)
        bot.start()

        logger.log('[x] Starting PokemonGo Bot....', 'green')

        while True:
            bot.take_step()

    except NotLoggedInException:
        logger.log('[x] Restarting PokemonGo Bot....', 'red')
        main()

    except KeyboardInterrupt:
        logger.log('[x] Exiting PokemonGo Bot', 'red')
Esempio n. 6
0
def main():
    # log settings
    # log format
    # logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    colorama.init()

    config = init_config()
    if not config:
        return

    logger.log('[x] PokemonGO Bot v1.0', 'green')
    logger.log('[x] Configuration initialized', 'yellow')

    try:
        bot = PokemonGoBot(config)
        bot.start()

        logger.log('[x] Starting PokemonGo Bot....', 'green')

        while True:
            bot.take_step()

    except KeyboardInterrupt:
        logger.log('[x] Exiting PokemonGo Bot', 'red')
Esempio n. 7
0
def main():
    # log settings
    # log format
    #logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    sys.stderr = codecs.getwriter('utf8')(sys.stderr)

    config = init_config()
    if not config:
        return

    logger.log('[x] PokemonGO Bot v1.0', 'green')
    logger.log('[x] Configuration initialized', 'yellow')

    finished = False

    loop = 0
    user_data_lastlocation = 'data/last-location-%s.json' % (config.username)
    while not finished:
        try:
            bot = PokemonGoBot(config)
            bot.start()

            logger.log('[x] Starting PokemonGo Bot....', 'green')

            while True:
                bot.take_step()

        except KeyboardInterrupt:
            logger.log('[x] Exiting PokemonGo Bot', 'red')
            finished = True
            # TODO Add number of pokemon catched, pokestops visited, highest CP
            # pokemon catched, etc.
        except NotLoggedInException:
             logger.log('[x] Error while connecting to the server, please wait %s minutes' % config.reconnecting_timeout, 'red')
             time.sleep(config.reconnecting_timeout * 60)
             if len(config.start_points) > 0:
                 pos = config.start_points[loop]
                 loop = (loop + 1) % len(config.start_points)

                 if os.path.isfile(user_data_lastlocation):
                     with open(user_data_lastlocation, 'w') as outfile:
                         outfile.truncate()
                         json.dump({'lat': pos[0], 'lng': pos[1]}, outfile)
                         logger.log('[#] Change start position to ({}, {})'.format(pos[0], pos[1]), 'yellow')
        except ServerBusyOrOfflineException:
             logger.log('[x] Server is busy, please wait 30 seconds', 'red')
             time.sleep(30)
        except GeocoderQuotaExceeded:
            logger.log('[x] The given maps api key has gone over the requests limit.', 'red')
            finished = True
        except:
            raise
Esempio n. 8
0
    def test_init():
        logger = Mock()
        logger.log = Mock(return_value=None)

        config_namespace = create_core_test_config()
        api_wrapper = create_mock_api_wrapper(config_namespace)
        event_manager = EventManager()
        player_service = Player(api_wrapper, event_manager, logger)
        pokemon_service = PokemonService(api_wrapper)
        mapper = Mapper(config_namespace, api_wrapper, Mock(), logger)
        path_finder = DirectPathFinder(config_namespace)
        stepper = Stepper(config_namespace, api_wrapper, path_finder, logger)
        navigator = FortNavigator(config_namespace, api_wrapper)

        bot = PokemonGoBot(config_namespace, api_wrapper, player_service,
                           pokemon_service, event_manager, mapper, stepper,
                           navigator, logger)

        assert len(bot.pokemon_list) == 151
        assert len(bot.item_list) == 30
        assert bot.position == (0, 0, 0)

        assert bot.config is config_namespace
        assert bot.api_wrapper is api_wrapper
        assert bot.player_service is player_service
        assert bot.pokemon_service is pokemon_service
        assert bot.event_manager is event_manager
        assert bot.mapper is mapper
        assert bot.stepper is stepper
        assert bot.navigator is navigator
        assert bot.logger is logger
Esempio n. 9
0
def main():
    # log settings
    # log format
    # logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    colorama.init()

    config = init_config()
    if not config:
        return

    logger.log('[x] PokemonGO Bot v1.0', 'green')
    logger.log('[x] Configuration initialized', 'yellow')

    try:
        bot = PokemonGoBot(config)
        bot.start()

        logger.log('[x] Starting PokemonGo Bot....', 'green')

        while True:
            bot.take_step()

    except KeyboardInterrupt:
        logger.log('[x] Exiting PokemonGo Bot', 'red')
        # TODO Add number of pokemon catched, pokestops visited, highest CP
        # pokemon catched, etc.

    except RuntimeError as e:
        # softban encountered
        logger.log("[x] " + str(e), 'red')
        # restart the program
        sleep_time = random.randint(3600, 7200)
        logger.log("[x] softban error, restart the bot in " + str(sleep_time) +" seconds", "yellow")
        time.sleep(sleep_time)
        main()

    except Exception as e:
        sleep_time = random.randint(10, 120)
        logger.log("[x] " + str(e), 'red')
        logger.log("[x] Unexpected error, restart the bot in " + str(sleep_time) +" seconds", "yellow")
        time.sleep(sleep_time)
        main()
Esempio n. 10
0
    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
Esempio n. 11
0
    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
Esempio n. 12
0
def main():
    reload(sys)
    sys.setdefaultencoding("utf-8")
    # log settings
    # log format
    #logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    sys.stderr = codecs.getwriter('utf8')(sys.stderr)

    config = init_config()
    if not config:
        return

    logger.log('[x] PokemonGO Bot v1.0', 'green')
    logger.log('[x] Configuration initialized', 'yellow')
    logger.log('[x] Fly distance is {}m'.format(config.fly_distance), 'yellow')

    try:
        bot = PokemonGoBot(config)
        bot.start()
        emailer.email_status(bot)

        logger.log('[x] Starting PokemonGo Bot....', 'green')

        while True:
            bot.take_step()

    except KeyboardInterrupt:
        logger.log('[x] Exiting PokemonGo Bot', 'red')
        # TODO Add number of pokemon catched, pokestops visited, highest CP
        # pokemon catched, etc.
    except Exception as e:
        # emailer.email_status(bot)
        # emailer.email(config.sender, config.recipient, 'Pokemon Bot Error ({})'.format(config.username), 
        #     str(e), config.smtp_server, config.smtp_port, config.email_password)
        print_red('[x] {}'.format(e))
        print_red('Sleep 1min and restart the bot...')
        sleep(60)
        print_red('Restarting bot...')
        main()
Esempio n. 13
0
def main():
    # log settings
    # log format
    #logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    sys.stderr = codecs.getwriter('utf8')(sys.stderr)

    config = init_config()
    if not config:
        return

    logger.log('[x] PokemonGO Bot v1.0', 'green')
    logger.log('[x] Configuration initialized', 'yellow')

    try:
        bot = PokemonGoBot(config)
        bot.start()

        logger.log('[x] Starting PokemonGo Bot....', 'green')

        while True:
            bot.take_step()

    except KeyboardInterrupt:
        logger.log('[x] Exiting PokemonGo Bot', 'red')
Esempio n. 14
0
 def run_bot():
     try: 
         bot = PokemonGoBot(cfg)
         bot.setup_logging(logger)
         bot.start()
         while True:
             bot.take_step()
     except KeyError:
         logger.info('Pokemon server return incomplete data. Re-login')
     except NotLoggedInException:
         logger.info('Token expired. Re-login')
Esempio n. 15
0
def main():
    logging.basicConfig(filename='log.log', format='%(asctime)s %(message)s')

    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    sys.stderr = codecs.getwriter('utf8')(sys.stderr)

    config = init_config()
    if not config:
        return

    logger.log('[x] PokemonGO Bot v1.0', 'green')
    logger.log('[x] Configuration initialized', 'yellow')

    try:
        bot = PokemonGoBot(config)
        bot.start()

        logger.log('[x] Starting PokemonGo Bot....', 'green')

        while True:
            bot.take_step()

    except KeyboardInterrupt:
        logger.log('[x] Exiting PokemonGo Bot', 'red')
Esempio n. 16
0
    def _create_generic_bot(config):
        logger = Mock()
        logger.log = Mock()
        config_namespace = create_core_test_config(config)
        api_wrapper = create_mock_api_wrapper(config_namespace)
        event_manager = Mock()
        player_service = Player(api_wrapper, event_manager, logger)
        pokemon_service = PokemonService(api_wrapper)
        mapper = Mapper(config_namespace, api_wrapper, Mock(), logger)
        path_finder = DirectPathFinder(config_namespace)
        stepper = Stepper(config_namespace, api_wrapper, path_finder, logger)
        navigator = FortNavigator(config_namespace, api_wrapper)

        return PokemonGoBot(config_namespace, api_wrapper, player_service,
                            pokemon_service, event_manager, mapper, stepper,
                            navigator, logger)
Esempio n. 17
0
def create_mock_bot(user_config=None):
    config_namespace = create_core_test_config(user_config)

    event_manager = EventManager()
    logger = Logger(event_manager)
    api_wrapper = create_mock_api_wrapper(config_namespace)
    player_service = Player(api_wrapper, event_manager, logger)
    pokemon_service = Pokemon(api_wrapper)
    mapper = Mapper(config_namespace, api_wrapper, Mock(), logger)
    path_finder = DirectPathFinder(config_namespace)
    stepper = Stepper(config_namespace, api_wrapper, path_finder, logger)
    navigator = FortNavigator(config_namespace, api_wrapper)

    bot = PokemonGoBot(config_namespace, api_wrapper, player_service,
                       pokemon_service, event_manager, mapper, stepper,
                       navigator, logger)

    return bot
Esempio n. 18
0
def main():
    logger.log('PokemonGO Bot v1.0', 'green')
    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    sys.stderr = codecs.getwriter('utf8')(sys.stderr)

    config = init_config()
    if not config:
        return
    logger.log('Configuration initialized', 'yellow')

    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()

            logger.log('Starting PokemonGo Bot....', 'green')

            while True:
                bot.tick()

        except KeyboardInterrupt:
            logger.log('Exiting PokemonGo Bot', 'red')
            finished = True
            report_summary(bot)
        except (NotLoggedInException, ServerBusyOrOfflineException):
            logger.log('[x] Error while connecting to the server, please wait %s minutes' % config.reconnecting_timeout, 'red')
            time.sleep(config.reconnecting_timeout * 60)
        except ServerSideRequestThrottlingException:
            logger.log('Server is throttling, reconnecting in 30sec')
            time.sleep(30)
        except GeocoderQuotaExceeded:
            logger.log('[x] The given maps api key has gone over the requests limit.', 'red')
            finished = True
        except:
            # always report session summary and then raise exception
            report_summary(bot)
            raise
Esempio n. 19
0
 def initialize(config):
     bot = PokemonGoBot(config)
     return bot
Esempio n. 20
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}
                        )
Esempio n. 21
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}
                        )
Esempio n. 22
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
Esempio n. 23
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})
Esempio n. 24
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},
                    )