def __init__(self, auth, username, password, latitude, longitude): self.auth = auth self.username = username self.password = password self.latitude = latitude self.longitude = longitude self.player_stats = {} self.pokemon = {} # Player State self.warned = None self.banned = None # Things needed for requests self.inventory_timestamp = None # instantiate pgoapi self.api = PGoApi() self.api.activate_hash_server(cfg_get('hash_key')) self.api.set_position(self.latitude, self.longitude, random.randrange(3, 170)) self.last_request = None if have_proxies(): self.proxy = get_new_proxy() self.log_info("Using Proxy: {}".format(self.proxy)) self.api.set_proxy({'http': self.proxy, 'https': self.proxy})
def __init__( self, group=None, target=None, name=None, worker_no=None, points=None, ): super(Slave, self).__init__(group, target, name) self.worker_no = worker_no local_data.worker_no = worker_no self.points = points self.count_points = len(self.points) self.step = 0 self.cycle = 0 self.seen_per_cycle = 0 self.total_seen = 0 self.error_code = None self.running = True center = self.points[0] self.api = PGoApi() self.api.activate_signature(config.ENCRYPT_PATH) self.api.set_position(center[0], center[1], 100) # lat, lon, alt if hasattr(config, 'PROXIES') and config.PROXIES: self.api.set_proxy(config.PROXIES)
def worker(wid,Tthreads): workStart = int((wid*len(scans))/Tthreads) workStop = int(((wid+1)*len(scans))/Tthreads) print 'worker {} is doing steps {} to {}'.format(wid,workStart,workStop) #login api = PGoApi() api.set_position(0,0,0) if not api.login(config['auth_service'], config['users'][wid]['username'], config['users'][wid]['password']): print 'worker {} unable to log in'.format(wid) return #iterate startTime = time.time() refDelay = 0 for scanpass in ['first','second','third','fourth','fifth','sixth']: print 'worker {} is doing {} pass'.format(wid,scanpass) for i in xrange(workStart,workStop): doScan(scans[i][0], scans[i][1], api) curTime=time.time() curDelay=curTime-startTime print 'worker {} took {} seconds to reach end of {} pass'.format(wid,curDelay,scanpass) refDelay = refDelay+600 while refDelay<curDelay: refDelay = refDelay+3600 if scanpass != 'sixth': print 'now sleeping for {}'.format(refDelay-curDelay) time.sleep(refDelay-curDelay)
def main(): logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s') logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("pgoapi").setLevel(logging.INFO) logging.getLogger("rpc_api").setLevel(logging.INFO) config = init_config() if not config: return if config.debug: logging.getLogger("requests").setLevel(logging.INFO) logging.getLogger("pgoapi").setLevel(logging.INFO) logging.getLogger("rpc_api").setLevel(logging.INFO) position = get_pos_by_name(config.location) if config.test: return pokemon_names = json.load(open("name_id.json")) api = PGoApi(config.__dict__, pokemon_names, position) if not api.login(config.auth_service, config.username, config.password, config.cached): return while True: try: api.main_loop() except Exception as e: log.exception('Main loop has an ERROR, restarting %s', e) sleep(30) main() import ipdb # noqa ipdb.set_trace() # noqa
def __init__(self, scan_config): Thread.__init__(self) self.daemon = True self.name = 'search_thread' self.api = PGoApi(config['SIGNATURE_LIB_PATH']) self.scan_config = scan_config
def initialize_api(self): device_info = get_device_info(self.account) self.logged_in = False self.ever_authenticated = False self.empty_visits = 0 self.account_seen = 0 self.api = PGoApi(device_info=device_info) if config.HASH_KEY: self.api.activate_hash_server(config.HASH_KEY) self.api.set_position(*self.location) if self.proxy: self.api.set_proxy({'http': self.proxy, 'https': self.proxy}) self.api.set_logger(self.logger) if self.account.get('provider') == 'ptc' and self.account.get( 'refresh'): self.api._auth_provider = AuthPtc( username=self.username, password=self.account['password'], timeout=config.LOGIN_TIMEOUT) self.api._auth_provider.set_refresh_token( self.account.get('refresh')) self.api._auth_provider._access_token = self.account.get('auth') self.api._auth_provider._access_token_expiry = self.account.get( 'expiry') if self.api._auth_provider.check_access_token(): self.api._auth_provider._login = True self.logged_in = True self.ever_authenticated = True
def accept_tos_helper(username, password, location, proxy): print "Trying to accept Terms of Service for {}.".format(username) failMessage = "Maybe the HTTPS proxy is not working? {} did not accept Terms of Service.".format( username) api = PGoApi() if proxy != None: api.set_proxy({"https": proxy}) location = location.replace(" ", "") location = location.split(",") api.set_position(float(location[0]), float(location[1]), 0.0) api.set_authentication(provider='ptc', username=username, password=password) response = api.app_simulation_login() if response == None: print "Servers do not respond to login attempt. " + failMessage return time.sleep(1) req = api.create_request() req.mark_tutorial_complete(tutorials_completed=0, send_marketing_emails=False, send_push_notifications=False) response = req.call() if response == None: print "Servers do not respond to accepting the ToS. " + failMessage return print('Accepted Terms of Service for {}'.format(username))
def __init__(self, auth, username, password, job_queue): self.auth = auth self.username = username self.password = password self.job_queue = job_queue # Stats self.last_request = None self.previous_encounter = None self.last_msg = "" self.total_encounters = 0 # Things needed for requests self.inventory_timestamp = None # Collects the last few pauses between encounters to measure a "encounters per hour" value self.past_pauses = deque() self.encounters_per_hour = float(0) # instantiate pgoapi self.api = PGoApi() self.api.activate_hash_server(cfg_get('hash_key')) if have_proxies(): self.proxy = get_new_proxy() self.log_info("Using Proxy: {}".format(self.proxy)) self.api.set_proxy({ 'http': self.proxy, 'https': self.proxy })
def main(): logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s') logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("pgoapi").setLevel(logging.INFO) logging.getLogger("rpc_api").setLevel(logging.INFO) if platform.system() == 'Windows': os.system("title Pokemon GO API Python") os.system("cls") else: # Catches "Lunux" and "Darwin" (OSX), among others os.system("clear") config = pokecli.init_config() if not config: return position = pokecli.get_pos_by_name(config.location) if config.test: return api = PGoApi() api.set_position(*position) if not api.login(config.auth_service, config.username, config.password): return print '[!] todo from here ..' exit()
def entry(): args = parse_arguments(sys.argv[1:]) api = PGoApi() prog = re.compile("^(\-?\d+\.\d+),?\s?(\-?\d+\.\d+)$") res = prog.match(args.location) if res: print('Using the following coordinates: {}'.format(args.location)) position = (float(res.group(1)), float(res.group(2)), 0) else: print(('Failed to parse the supplied coordinates ({}).' + ' Please try again.').format(args.location)) return if args.hash_key: print "Using hash key: {}.".format(args.hash_key) api.activate_hash_server(args.hash_key) with open(str(args.file)) as f: credentials = [x.strip().split(',')[0:] for x in f.readlines()] for provider, username, password in credentials: try: if check_account(provider, username, password, position, api): # Success! csv_format = provider + ',' + username + ',' + password appendFile(csv_format, 'working.csv') except ServerSideRequestThrottlingException: print('Server side throttling, waiting for 10 seconds.') time.sleep(10) check_account(provider, username, password, position, api) except NotLoggedInException: print('Could not login, waiting for 10 seconds.') time.sleep(10) check_account(provider, username, password, position, api)
def main(): # log settings # log format logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s') # log level for http request class logging.getLogger("requests").setLevel(logging.WARNING) # log level for main pgoapi class logging.getLogger("pgoapi").setLevel(logging.INFO) # log level for internal pgoapi class logging.getLogger("rpc_api").setLevel(logging.INFO) config = init_config() if not config: return if config.debug: logging.getLogger("requests").setLevel(logging.DEBUG) logging.getLogger("pgoapi").setLevel(logging.DEBUG) logging.getLogger("rpc_api").setLevel(logging.DEBUG) splitloc = config.location.split(",") position = (float(splitloc[0]), float(splitloc[1]), 0) if config.test: return # instantiate pgoapi api = PGoApi() # provide player position on the earth api.set_position(*position) if not api.login(config.auth_service, config.username, config.password): return
def asdf(request): config = settings.PGOAPI_CONFIG if request.GET['latitude'] and request.GET['longitude']: position = float(request.GET['latitude']), float(request.GET['longitude']), 0 else: return HttpResponseBadRequest() api = PGoApi() api.set_position(*position) if not api.login(config['auth_service'], config['username'], config['password']): return HttpResponse('Unauthorized', status=401) map_objects = get_map_objects_call(api,position) wild_pokemons = parse_wild_pokemon(map_objects) broadcast_wild_pokemon(wild_pokemons) steps = 7 distance = 130 degrees = generate_swirl_degrees(steps) for i in range(0,steps*steps-1): print ('-----------------------') print (str(i) + ' step') position = GreatCircleDistance(meters=distance).destination(Point(position[0],position[1]),degrees[i]) map_objects = get_map_objects_call(api,position) wild_pokemons = parse_wild_pokemon(map_objects) broadcast_wild_pokemon(wild_pokemons) return HttpResponse()
def api(self): if self._api is None: self._api = PGoApi(provider=self.account.get('auth') or 'google', username=self.account.get('user'), password=self.account.get('pass')) if POKEHASH is not None: self._api.activate_hash_server(POKEHASH) return self._api
def __init__ (self, scan_queue=None, dispatch_queue=None): if scan_queue is None or dispatch_queue is None: raise ValueError("missing scan/dispatch queues") self._scan_queue = scan_queue self._dispatch_queue = dispatch_queue self._user_queue = Queue() self._lock = Lock() self._threads = [] self._users = [] self._signature_lib_path = "" if sys.platform.startswith("linux"): self._signature_lib_path = pub_config["pgo_api"]["linux_signature_lib_file"] elif sys.platform.startswith("darwin"): self._signature_lib_path = pub_config["pgo_api"]["darwin_signature_lib_file"] elif sys.platform.startswith("win"): self._signature_lib_path = pub_config["pgo_api"]["win_signature_lib_file"] else: raise ValueError("un-supported system") self._num_threads = pub_config["scanner"]["num_threads"] self._min_sec_before_reauth = pub_config["scanner"]["min_sec_before_reauth"] self._max_tries = pub_config["scanner"]["max_tries_per_request"] self._sleep_sec = pub_config["scanner"]["sleep_per_try_sec"] self._scan_throttle_sec = pub_config["scanner"]["scan_throttle_sec"] self._delay_between_login_sec = pub_config["scanner"]["delay_between_login_sec"] self._boundary = private_config["location"] # automatically handle IP bans by restarting/switching vpn servers self._restart_vpn_file = pub_config["scanner"]["restart_vpn_file"] self._switch_vpn_file = pub_config["scanner"]["switch_vpn_file"] self._max_vpn_retries_before_switch = pub_config["scanner"]["max_vpn_retries_before_switch"] self._delay_between_vpn_retries = pub_config["scanner"]["delay_between_vpn_retries_sec"] self._num_vpn_retries = 0 self._last_vpn_retry = time.time() users = private_config["poke_api"]["accounts"] for user_data in users: device_info = {} device_info['device_id'] = uuid.uuid4().hex device_info['device_brand'] = "Apple" device_info['device_model'] = "iPhone" device_info['device_model_boot'] = "iPhone8,2" device_info['hardware_manufacturer'] = "Apple" device_info['hardware_model'] = "N66AP" device_info['firmware_brand'] = "iPhone OS" device_info['firmware_type'] = "9.3.3" user = PGoApi(device_info=device_info) user._last_call = 0 user._data = user_data self._users.append(user) self._user_queue.put(user) self.auth_users() self.start_threads(self._num_threads)
def login(self, subNumber, numActiveAtOnce): self.api = PGoApi() time.sleep(random.uniform(1, 2)) #self.api.activate_signature(config.ENCRYPT_PATH) center = self.points[0] time.sleep(random.uniform(1, 2)) self.api.set_position(center[0], center[1], 0) # lat, lon, alt if hasattr(config, 'PROXIES') and config.PROXIES: time.sleep(random.uniform(1, 2)) self.api.set_proxy(config.PROXIES) username, password, service = utils.get_worker_account( self.worker_no, subNumber, numActiveAtOnce) self.username = username self.subNumber = subNumber self.numActiveAtOnce = numActiveAtOnce while True: try: time.sleep(random.uniform(1, 2)) self.api.set_authentication( username=username, password=password, provider=service, ) #if not loginsuccess: # self.error_code = 'LOGINFAIL2' # #self.restart() # return False except pgoapi_exceptions.AuthException: logger.warning('Login failed!') self.error_code = 'LOGINFAIL1' #self.restart() return False # continue except pgoapi_exceptions.NotLoggedInException: logger.error('Invalid credentials') self.error_code = 'BAD LOGIN' #self.restart() return False continue except pgoapi_exceptions.ServerBusyOrOfflineException: logger.info('Server too busy - restarting') self.error_code = 'BUSY' #self.restart() return False except pgoapi_exceptions.ServerSideRequestThrottlingException: logger.info('Server throttling - sleeping for a bit') time.sleep(random.uniform(1, 5)) continue except Exception: logger.exception('A wild exception appeared!') self.error_code = 'EXCEPTION' #self.restart() #return continue break return True
def make_api(user, passwd): api = PGoApi() # provide player position on the earth api.set_position(*default_position) if not api.login('ptc', user, passwd): return return api
def get_token(service, username, password): global global_token, api if global_token is None: api = PGoApi() if api.login(service, username, password): global_token = api._auth_provider._auth_token return global_token else: return global_token
def login(args, position): log.info('Attempting login to Pokemon Go.') api = PGoApi() while not api.login(args.auth_service, args.username, args.password, *position): log.info('Failed to login to Pokemon Go. Trying again.') time.sleep(config['REQ_SLEEP']) log.info('Login to Pokemon Go successful.') return api
def init_api(self): self.logger.info("Initializing api...") self.api = PGoApi() self.api.login(self.config.auth, self.config.username, self.config.password, self.config.latitude, self.config.longitude, 10, app_simulation=False)
def setup_api(self): """Prepare and sign in to API""" self.api = PGoApi() if not self.api.login(self.config.auth_service, str(self.config.username), str(self.config.password)): print "Login error" exit(0) print "Signed in"
def worker(wid,Tthreads): workStart = int((wid*len(scans))/Tthreads) workStop = int(((wid+1)*len(scans))/Tthreads) print 'worker {} is doing steps {} to {}'.format(wid,workStart,workStop) #login api = PGoApi() api.set_position(0,0,0) if not api.login(config['auth_service'], config['users'][wid]['username'], config['users'][wid]['password']): print 'worker {} unable to log in'.format(wid) return #iterate startTime = time.time() print 'worker {} is doing first pass'.format(wid) for i in xrange(workStart,workStop): doScan(scans[i][0], scans[i][1], api) time.sleep(0.2) curTime=time.time() print 'worker {} took {} seconds to do first pass now sleeping for {}'.format(wid,curTime-startTime,600-(curTime-startTime)) time.sleep(600-(curTime-startTime)) print 'worker {} is doing second pass'.format(wid) for i in xrange(workStart,workStop): doScan(scans[i][0], scans[i][1], api) time.sleep(0.2) curTime=time.time() print 'worker {} took {} seconds to do second pass now sleeping for {}'.format(wid,curTime-startTime,1200-(curTime-startTime)) time.sleep(1200-(curTime-startTime)) print 'worker {} is doing third pass'.format(wid) for i in xrange(workStart,workStop): doScan(scans[i][0], scans[i][1], api) time.sleep(0.2) curTime=time.time() print 'worker {} took {} seconds to do third pass now sleeping for {}'.format(wid,curTime-startTime,1800-(curTime-startTime)) time.sleep(1800-(curTime-startTime)) print 'worker {} is doing fourth pass'.format(wid) for i in xrange(workStart,workStop): doScan(scans[i][0], scans[i][1], api) time.sleep(0.2) curTime=time.time() print 'worker {} took {} seconds to do fourth pass now sleeping for {}'.format(wid,curTime-startTime,2400-(curTime-startTime)) time.sleep(2400-(curTime-startTime)) print 'worker {} is doing fifth pass'.format(wid) for i in xrange(workStart,workStop): doScan(scans[i][0], scans[i][1], api) time.sleep(0.2) curTime=time.time() print 'worker {} took {} seconds to do fifth pass now sleeping for {}'.format(wid,curTime-startTime,3000-(curTime-startTime)) time.sleep(3000-(curTime-startTime)) print 'worker {} is doing sixth pass'.format(wid) for i in xrange(workStart,workStop): doScan(scans[i][0], scans[i][1], api) time.sleep(0.2) curTime=time.time() print 'worker {} took {} seconds to do sixth pass'.format(wid,curTime-startTime)
def main(): setup_logging() api = PGoApi() api.set_position(*CONFIG.STARTING_POSITION) while not api.login(**credentials): sleep(2) while True: clean_up_inventory(api) sleep(CONFIG.CLEANUP_POLL_TIME + random.uniform(-1, 1) * CONFIG.POLL_JITTER)
def __init__(self, provider="google", username="", password=""): self._api = PGoApi() self.provider = provider self.username = username self.password = password self.current_position = (0, 0, 0) self.state = StateManager() self._pending_calls = {} self._pending_calls_keys = []
def setup_api(self): """Prepare and sign in to API""" self.api = PGoApi() self.get_location() if not self.api.login(self.config.auth_service, str(self.config.username), str(self.config.password), self.position[0], self.position[1], self.position[2]): print "Login error" exit(0) print "Signed in"
def main(): # instantiate pgoapi api = PGoApi() position = get_pos_by_name(LOCATION) # provide player position on the earth api.set_position(*position) if not api.login('ptc', PTC_USERNAME, PTC_PASSWORD): return # execute the RPC call response_dict = api.call() pokemon_json = find_poi(api, position[0], position[1])
def login(location=None): global API global CANCEL_FETCH init() try: API = PGoApi() CANCEL_FETCH = True position = getLocationByName(location) API.set_position(*position) goog_username = os.environ.get('GOOG_USERNAME', "Invalid") goog_password = os.environ.get('GOOG_PASSWORD', "Invalid") login_type = "google" log.info('[+] Authentication with Google...') if not API.login(login_type, goog_username, goog_password): log.warn('[-] Trouble logging in via Google') log.info('[+] Authentication with PTC...') ptc_username = os.environ.get('PTC_USERNAME', "Invalid") ptc_password = os.environ.get('PTC_PASSWORD', "Invalid") login_type = "ptc" if not API.login(login_type, ptc_username, ptc_password): log.error("[-] Trouble logging in via PTC. Stopping") return False API.get_player() response_dict = API.call() getPoiData(position[0], position[1]) return True except Exception as e: log.error("Error login" + str(e)); return false
def setup_api(self): self.api = PGoApi() self.api.activate_hash_server(self.config.hash_key) self.get_location() print u'Signing in…' if not self.api.login( self.config.auth_service, self.config.username, self.config.password, self.position[0], # latitude self.position[1], # longitude self.position[2] # altitude ): print 'Login error' exit(0)
def perform_scout(p): global api, last_scout_timestamp, encounter_cache if not args.scout_account_username: return { "msg": "No scout account configured." } pokemon_name = get_pokemon_name(p.pokemon_id) # Check cache once in a non-blocking way if p.encounter_id in encounter_cache: result = encounter_cache[p.encounter_id] log.info(u"Cached scout-result: level {} {} with CP {}.".format(result["level"], pokemon_name, result["cp"])) return result scoutLock.acquire() try: # Check cache again after mutually exclusive access if p.encounter_id in encounter_cache: result = encounter_cache[p.encounter_id] log.info(u"Cached scout-result: level {} {} with CP {}.".format(result["level"], pokemon_name, result["cp"])) return result # Delay scouting now = time.time() if last_scout_timestamp is not None and now < last_scout_timestamp + scout_delay_seconds: wait_secs = last_scout_timestamp + scout_delay_seconds - now log.info("Waiting {} more seconds before next scout use.".format(wait_secs)) time.sleep(wait_secs) log.info(u"Scouting a {} at {}, {}".format(pokemon_name, p.latitude, p.longitude)) step_location = jitterLocation([p.latitude, p.longitude, 42]) if api is None: # instantiate pgoapi api = PGoApi() api.set_position(*step_location) api.set_proxy({'http': args.scout_account_proxy, 'https': args.scout_account_proxy}) account = { "auth_service": args.scout_account_auth, "username": args.scout_account_username, "password": args.scout_account_password, } check_login(args, account, api, None, False) if args.hash_key: key = key_scheduler.next() log.debug('Using key {} for this scout use.'.format(key)) api.activate_hash_server(key) request_result = encounter_request(long(b64decode(p.encounter_id)), p.spawnpoint_id, p.latitude, p.longitude) # Update last timestamp last_scout_timestamp = time.time() finally: scoutLock.release() return parse_scout_result(request_result, p.encounter_id, pokemon_name)
def setup_api(args, status): # Create the API instance this will use. if args.mock != '': api = FakePogoApi(args.mock) else: device_info = generate_device_info() api = PGoApi(device_info=device_info) # New account - new proxy. if args.proxy: # If proxy is not assigned yet or if proxy-rotation is defined # - query for new proxy. if ((not status['proxy_url']) or ((args.proxy_rotation is not None) and (args.proxy_rotation != 'none'))): proxy_num, status['proxy_url'] = get_new_proxy(args) if args.proxy_display.upper() != 'FULL': status['proxy_display'] = proxy_num else: status['proxy_display'] = status['proxy_url'] if status['proxy_url']: log.debug('Using proxy %s', status['proxy_url']) api.set_proxy({ 'http': status['proxy_url'], 'https': status['proxy_url']}) return api
def __init__(self, config, pokemon_names, start_pos): self.api = PGoApi() self.log = logging.getLogger(__name__) self._start_pos = start_pos self._posf = start_pos self._walk_count = 1 self.first_fort = {} self.config = config self.evolved_pokemon_ids = [] self.released_pokemon_ids = [] self.player_level = 1 self.GPX_lat = [] self.GPX_lon = [] self._pokeball_type = 1 self.GMAPS_KEY = config.get("GMAPS_API_KEY", "") self.MIN_KEEP_IV = config.get("MIN_KEEP_IV", 0) self.KEEP_CP_OVER = config.get("KEEP_CP_OVER", 0) self.RELEASE_DUPLICATES = config.get("RELEASE_DUPLICATE", 0) self.DUPLICATE_CP_FORGIVENESS = config.get("DUPLICATE_CP_FORGIVENESS", 0) self.MAX_BALL_TYPE = config.get("MAX_BALL_TYPE", 0) self.SLOW_BUT_STEALTH = config.get("SLOW_BUT_STEALTH", 0) self.AUTO_HATCHING = config.get("AUTO_HATCHING", False) self.EVOLVE_POKEMON = config.get("EVOLVE_POKEMON", []) self._req_method_list = [] self._heartbeat_number = 0 self.pokemon_names = pokemon_names self.pokeballs = [0, 0, 0, 0] # pokeball counts. set to 0 to force atleast one fort check before trying to capture pokemon self.map_cells = dict() self.min_item_counts = dict( ((getattr(Inventory, key), value) for key, value in config.get('MIN_ITEM_COUNTS', {}).iteritems()) )
def _get_asset_digest(self, asset_time): i = random.randint(0, 3) result = 2 page_offset = 0 page_timestamp = 0 while result == 2: # ===== GET_ASSET_DIGEST responses = self.perform_request(lambda req: req.get_asset_digest( platform=1, app_version=PGoApi.get_api_version(), paginate=True, page_offset=page_offset, page_timestamp=page_timestamp), buddy_walked=False, get_inbox=False) if i > 2: time.sleep(1.45) i = 0 else: i += 1 time.sleep(.2) try: response = responses['GET_ASSET_DIGEST'] except KeyError: break result = response.result page_offset = response.page_offset page_timestamp = response.timestamp_ms self._asset_time = asset_time
def can_start_scanning(args): # Currently supported pgoapi. pgoapi_version = "1.2.0" api_version_error = ( 'The installed pgoapi is out of date. Please refer to ' + 'http://rocketmap.readthedocs.io/en/develop/common-issues/' + 'faq.html#i-get-an-error-about-pgooapi-version' ) # Assert pgoapi >= pgoapi_version. if (not hasattr(pgoapi, "__version__") or StrictVersion(pgoapi.__version__) < StrictVersion(pgoapi_version)): log.critical(api_version_error) return False # Abort if we don't have a hash key set. if not args.hash_key: log.critical('Hash key is required for scanning. Exiting.') return False # Check the PoGo api pgoapi implements against what RM is expecting try: if PGoApi.get_api_version() != int(args.api_version.replace('.', '0')): log.critical(api_version_error) return False except AttributeError: log.critical(api_version_error) return False return True
def _setup_api(self): # instantiate pgoapi self.api = PGoApi() # provide player position on the earth self._set_starting_position() if not self.api.login(self.config.auth_service, str(self.config.username), str(self.config.password)): self.logger.error('Login Error, server busy', 'red') exit(0) # chain subrequests (methods) into one RPC call # get player profile call # ---------------------- self.api.get_player() response_dict = self.api.call() currency_1 = "0" currency_2 = "0" player = response_dict['responses']['GET_PLAYER']['player_data'] print response_dict # @@@ TODO: Convert this to d/m/Y H:M:S creation_date = datetime.datetime.fromtimestamp( player['creation_timestamp_ms'] / 1e3) pokecoins = '0' stardust = '0' balls_stock = self.pokeball_inventory() if 'amount' in player['currencies'][0]: pokecoins = player['currencies'][0]['amount'] if 'amount' in player['currencies'][1]: stardust = player['currencies'][1]['amount'] self.logger.info('[#] Username: {username}'.format(**player)) self.logger.info('[#] Acccount Creation: {}'.format(creation_date)) self.logger.info('[#] Bag Storage: {}/{}'.format( self.get_inventory_count('item'), player['max_item_storage'])) self.logger.info('[#] Pokemon Storage: {}/{}'.format( self.get_inventory_count('pokemon'), player[ 'max_pokemon_storage'])) self.logger.info('[#] Stardust: {}'.format(stardust)) self.logger.info('[#] Pokecoins: {}'.format(pokecoins)) self.logger.info('[#] PokeBalls: ' + str(balls_stock[1])) self.logger.info('[#] GreatBalls: ' + str(balls_stock[2])) self.logger.info('[#] UltraBalls: ' + str(balls_stock[3])) self.get_player_info() if self.config.initial_transfer: worker = InitialTransferWorker(self) worker.work() self.logger.info('[#]') self.update_inventory()
def setup_api(args, status, account): reset_account(account) # Create the API instance this will use. if args.mock != '': api = FakePogoApi(args.mock) else: identifier = account['username'] + account['password'] device_info = generate_device_info(identifier) api = PGoApiWrapper(PGoApi(device_info=device_info)) # New account - new proxy. if args.proxy: # If proxy is not assigned yet or if proxy-rotation is defined # - query for new proxy. if ((not status['proxy_url']) or (args.proxy_rotation != 'none')): proxy_num, status['proxy_url'] = get_new_proxy(args) if args.proxy_display.upper() != 'FULL': status['proxy_display'] = proxy_num else: status['proxy_display'] = status['proxy_url'] if status['proxy_url']: log.debug('Using proxy %s', status['proxy_url']) api.set_proxy({ 'http': status['proxy_url'], 'https': status['proxy_url'] }) if (status['proxy_url'] not in args.proxy): log.warning( 'Tried replacing proxy %s with a new proxy, but proxy ' + 'rotation is disabled ("none"). If this isn\'t intentional, ' + 'enable proxy rotation.', status['proxy_url']) return api
def _setup_api(self): self.api = PGoApi() self._set_starting_position() if not self.api.login(self.config.auth_service, self.config.username, self.config.password): return # chain subrequests (methods) into one RPC call # get player profile call # ---------------------- self.api.get_player() response_dict = self.api.call() #print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2))) currency_1="0" currency_2="0" try: if 'amount' in response_dict['responses']['GET_PLAYER']['profile']['currency'][0]: currency_1=response_dict['responses']['GET_PLAYER']['profile']['currency'][0]['amount'] if 'amount' in response_dict['responses']['GET_PLAYER']['profile']['currency'][1]: currency_2=response_dict['responses']['GET_PLAYER']['profile']['currency'][1]['amount'] print 'Profile:' print ' Username: '******'responses']['GET_PLAYER']['profile']['username']) print ' Bag size: ' + str(response_dict['responses']['GET_PLAYER']['profile']['item_storage']) print ' Pokemon Storage Size: ' + str(response_dict['responses']['GET_PLAYER']['profile']['poke_storage']) print ' Account Creation: ' + str(response_dict['responses']['GET_PLAYER']['profile']['creation_time']) print ' Currency: ' print ' ' + str(response_dict['responses']['GET_PLAYER']['profile']['currency'][0]['type']) + ': ' + str(currency_1) print ' ' + str(response_dict['responses']['GET_PLAYER']['profile']['currency'][1]['type']) + ': ' + str(currency_2) except: print('Exception during print player profile')
def boot(service_container): # PoGoApi parameters config = service_container.get('config.core') if os.path.isfile(os.path.join(os.getcwd(), config['load_library'])): config['load_library'] = os.path.join(os.getcwd(), config['load_library']) service_container.set_parameter('pogoapi.provider', config['login']['auth_service']) service_container.set_parameter('pogoapi.username', config['login']['username']) service_container.set_parameter('pogoapi.password', config['login']['password']) service_container.set_parameter('pogoapi.shared_lib', config['load_library']) service_container.register_singleton('pgoapi', PGoApi()) service_container.register_singleton( 'google_maps', googlemaps.Client(key=config["mapping"]["gmapkey"])) if config['movement']['path_finder'] in ['google', 'direct']: service_container.set_parameter( 'path_finder', config['movement']['path_finder'] + '_path_finder') else: raise Exception('You must provide a valid path finder') if config['movement']['navigator'] in ['fort', 'waypoint', 'camper']: service_container.set_parameter( 'navigator', config['movement']['navigator'] + '_navigator') else: raise Exception('You must provide a valid navigator')
class PokemonSearch: def __init__(self): self.api = PGoApi() self.load_config() self.pos = utils.get_pos_by_name(self.config["loc"]) self.api.set_position(*self.pos) self.logged_in = self.login() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s', filename=".log") # log level for http request class logging.getLogger("requests").setLevel(logging.WARNING) # log level for main pgoapi class logging.getLogger("pgoapi").setLevel(logging.INFO) # log level for internal pgoapi class logging.getLogger("rpc_api").setLevel(logging.INFO) def login(self): return self.api.login(self.config["auth"], self.config['username'], self.config['password']) def load_config(self): filename = 'config.json' dirname = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(dirname, filename)) as config_file: self.config = json.load(config_file) def set_location(self, lat, lng): self.pos = (float(lat), float(lng), 0) self.api.set_position(*self.pos) def find_pokemon_around_me(self): return self.find_pokemon() def find_pokemon(self): step_size = 0.0015 step_limit = 16 coords = utils.generate_spiral(self.pos[0], self.pos[1], step_size, step_limit) pokemons = [] for coord in coords: time.sleep(5) lat = coord["lat"] lng = coord["lng"] self.api.set_position(lat, lng, 0) cell_ids = utils.get_cell_ids(lat, lng) timestamps = [0,] * len(cell_ids) response_dict = self.api.get_map_objects(latitude = pgoutil.f2i(lat), longitude = pgoutil.f2i(lng), since_timestamp_ms = timestamps, cell_id = cell_ids) if 'GET_MAP_OBJECTS' in response_dict['responses']: if 'status' in response_dict['responses']['GET_MAP_OBJECTS']: if response_dict['responses']['GET_MAP_OBJECTS']['status'] == 1: for map_cell in response_dict['responses']['GET_MAP_OBJECTS']['map_cells']: if 'wild_pokemons' in map_cell: for pokemon in map_cell['wild_pokemons']: pokemons.append(pokemon) return {v['encounter_id']:v for v in pokemons}.values()
def __init__(self, auth, username, password, job_queue): self.auth = auth self.username = username self.password = password self.job_queue = job_queue # Stats self.last_request = None self.last_msg = "" self.total_scouts = 0 # Holds timestamps of scout requests of the last hour self.history = deque() # instantiate pgoapi self.api = PGoApi() self.api.activate_hash_server(cfg_get('hash_key'))
def main(): # log settings # log format logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s') # log level for http request class logging.getLogger("requests").setLevel(logging.WARNING) # log level for main pgoapi class logging.getLogger("pgoapi").setLevel(logging.INFO) # log level for internal pgoapi class logging.getLogger("rpc_api").setLevel(logging.INFO) config = init_config() if not config: return if config.debug: logging.getLogger("requests").setLevel(logging.DEBUG) logging.getLogger("pgoapi").setLevel(logging.DEBUG) logging.getLogger("rpc_api").setLevel(logging.DEBUG) position = get_pos_by_name(config.location) if not position: return if config.test: return # instantiate pgoapi api = PGoApi() # provide player position on the earth api.set_position(*position) if not api.login(config.auth_service, config.username, config.password): return # chain subrequests (methods) into one RPC call # get player profile call # ---------------------- response_dict = api.get_player() # apparently new dict has binary data in it, so formatting it with this method no longer works, pprint works here but there are other alternatives # print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2))) print('Response dictionary: \n\r{}'.format(pprint.PrettyPrinter(indent=4).pformat(response_dict))) find_poi(api, position[0], position[1])
def setup_api(self): self.api = PGoApi() if not self.api.login(self.config.auth_service, str(self.config.username), str(self.config.password)): print("Login error") exit(0) print("Signed in")
def main(): timeStart = time.time() # log settings # log format logging.basicConfig( level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s') # log level for http request class logging.getLogger("requests").setLevel(logging.WARNING) # log level for main pgoapi class logging.getLogger("pgoapi").setLevel(logging.INFO) # log level for internal pgoapi class logging.getLogger("rpc_api").setLevel(logging.INFO) config = init_config() if not config: return if config.debug: logging.getLogger("requests").setLevel(logging.DEBUG) logging.getLogger("pgoapi").setLevel(logging.DEBUG) logging.getLogger("rpc_api").setLevel(logging.DEBUG) position = get_pos_by_name(config.location) if config.test: return # instantiate pgoapi api = PGoApi() # provide player position on the earth api.set_position(*position) if not api.login(config.auth_service, config.username, config.password): return # chain subrequests (methods) into one RPC call # get player profile call # ---------------------- #api.get_player() # execute the RPC call #response_dict = api.call() #print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2))) find_poi(api, position[0], position[1])
def main(): # log settings # log format logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s') # log level for http request class logging.getLogger("requests").setLevel(logging.WARNING) # log level for main pgoapi class logging.getLogger("pgoapi").setLevel(logging.INFO) # log level for internal pgoapi class logging.getLogger("rpc_api").setLevel(logging.INFO) config = init_config() if not config: return if config.debug: logging.getLogger("requests").setLevel(logging.DEBUG) logging.getLogger("pgoapi").setLevel(logging.DEBUG) logging.getLogger("rpc_api").setLevel(logging.DEBUG) position = get_pos_by_name(config.location) if config.test: return # instantiate pgoapi api = PGoApi() # provide player position on the earth api.set_position(*position) if not api.login(config.auth_service, config.username, config.password): return # chain subrequests (methods) into one RPC call # get player profile call api.get_player() # get inventory call #api.get_inventory() # get map objects call timestamp = "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" cellid = get_cellid(position[0], position[1]) api.get_map_objects(latitude=f2i(position[0]), longitude=f2i(position[1]), since_timestamp_ms=timestamp, cell_id=cellid) # get download settings call #api.download_settings(hash="4a2e9bc330dae60e7b74fc85b98868ab4700802e") # execute the RPC call response_dict = api.call() print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
def __init__(self, worker_no, points, cell_ids, db_processor, cell_ids_executor, network_executor, start_step=0, device_info=None, proxies=None): self.worker_no = worker_no # Set of all points that worker needs to visit self.points = points self.count_points = len(self.points) # Cache for cell_ids for all points self.cell_ids = cell_ids # asyncio/thread references self.future = None # worker's own future self.db_processor = db_processor self.cell_ids_executor = cell_ids_executor self.network_executor = network_executor # Some handy counters self.start_step = start_step # allow worker to pick up where it left self.step = 0 self.cycle = 0 self.seen_per_cycle = 0 self.total_seen = 0 # State variables self.running = True # not running worker should be restarted self.killed = False # killed worker will stay killed self.restart_me = False # ask overseer for restarting self.logged_in = False # Other variables self.last_step_run_time = 0 self.last_api_latency = 0 self.error_code = 'INIT' # And now, configure logger and PGoApi center = self.points[0] self.logger = logging.getLogger('worker-{}'.format(worker_no)) self.device_info = device_info self.api = PGoApi(device_info=device_info) self.api.activate_signature(config.ENCRYPT_PATH) self.api.set_position(center[0], center[1], center[2]) # lat, lon, alt self.api.set_logger(self.logger) self.proxies = proxies self.api.set_proxy(self.proxies)
def _reset_api(self): self._api = PGoApi(device_info=self._generate_device_info()) self._download_settings_hash = None self._asset_time = 0 self._item_templates_time = 0 # Timestamp when last API request was made self._last_request = 0 # Timestamp of last get_map_objects request self._last_gmo = self._last_request # Timestamp for incremental inventory updates self._last_timestamp_ms = None # Timestamp when previous user action is completed self._last_action = 0
def main(): logging.basicConfig( level=logging.WARNING, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s') logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("pgoapi").setLevel( logging.INFO ) # FIXME we need to work on what should be show normally and what should be shown durin debug logging.getLogger("rpc_api").setLevel(logging.INFO) config = init_config() if not config: return if config.verbose: logging.getLogger("requests").setLevel(logging.DEBUG) logging.getLogger("pgoapi").setLevel( logging.DEBUG ) # FIXME we need to work on what should be show normally and what should be shown durin debug logging.getLogger("rpc_api").setLevel(logging.DEBUG) position = get_pos_by_name(config.location) if config.test: return pokemon_names = json.load(open("name_id.json")) api = PGoApi(config.__dict__, pokemon_names, position) thread.start_new_thread(start_server, (api, )) if not api.login(config.auth_service, config.username, config.password, config.cached): return while True: try: api.main_loop() except Exception as e: log.exception('Main loop has an ERROR, restarting %s', e) sleep(30) main() import ipdb # noqa ipdb.set_trace() # noqa
def logged_in(self): if self.api._auth_provider and self.api._auth_provider._ticket_expire: min_batch_duration = self.batch_size * (self.scan_interval + 1) expired = self.api._auth_provider._ticket_expire / 1000 - time.time() < min_batch_duration if expired: logging.info('login ticket expired for %s', self.credentials[1]) self.api = PGoApi() return not expired else: return False
def __init__(self, credentials, cell_queue, report_callback): super(ScanThread, self).__init__() self.credentials = credentials self.scan_interval = 5 # Any faster than 1 scan / 5s and we get empty responses self.cell_queue = cell_queue self.api = PGoApi() self.batch_size = 10 self.report_callback = report_callback self.daemon = True self.error_backoff = self.scan_interval
def _setup_api(self): # instantiate pgoapi self.api = PGoApi() # provide player position on the earth self._set_starting_position() if not self.api.login(self.config.auth_service, self.config.username, self.config.password): return # chain subrequests (methods) into one RPC call # get player profile call # ---------------------- self.api.get_player() response_dict = self.api.call() #print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2))) currency_1="0" currency_2="0" player = response_dict['responses']['GET_PLAYER']['profile'] ### @@@ TODO: Convert this to d/m/Y H:M:S creation_date = datetime.datetime.fromtimestamp(player['creation_time'] / 1e3) pokecoins = '0' stardust = '0' if 'amount' in player['currency'][0]: pokecoins = player['currency'][0]['amount'] if 'amount' in player['currency'][1]: stardust = player['currency'][1]['amount'] #try: if 'amount' in response_dict['responses']['GET_PLAYER']['profile']['currency'][0]: currency_1=response_dict['responses']['GET_PLAYER']['profile']['currency'][0]['amount'] if 'amount' in response_dict['responses']['GET_PLAYER']['profile']['currency'][1]: currency_2=response_dict['responses']['GET_PLAYER']['profile']['currency'][1]['amount'] print('[#]') print('[#] Username: '******'username'])) print('[#] Acccount Creation: ' + str(creation_date)) print('[#] Bag Storage: ' + str(self.getInventoryCount('item')) + '/' + str(player['item_storage'])) print('[#] Pokemon Storage: ' + str(self.getInventoryCount('pokemon')) + '/' + str(player['poke_storage'])) print('[#] Stardust: ' + str(stardust)) print('[#] Pokecoins: ' + str(pokecoins)) self.getPlayerInfo() print('[#]') # except: # print('Exception during print player profile') self.update_inventory();
def solveCaptchas(mode, username, password, location, captchakey2): print(mode) print(username) print(password + "|") captchatimeout=1000 login_retry = 0 user_agent = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36") api = PGoApi() location = location.replace(" ", "") location = location.split(",") api.set_position(float(location[0]), float(location[1]), 0.0) while (login_retry < 3): print("Login...") if api.login(mode, username, password): break login_retry = login_retry + 1 if(login_retry == 3): print(("Login failed for {user}. Check data and try again.").format(user = username)) return time.sleep(10) req = api.create_request() req.check_challenge() response = req.call() captcha_url = response['responses']['CHECK_CHALLENGE']['challenge_url']; if len(captcha_url) == 1: print(("No captcha for user: {user}").format(user = username)) #skip, captcha not necessary else: print(("Captcha required for user: {user}").format(user = username)) #print("CaptchaURL: {}".format(captcha_url)) if captchakey2 != "": dcap = dict(DesiredCapabilities.PHANTOMJS) dcap["phantomjs.page.settings.userAgent"] = user_agent driver = webdriver.PhantomJS(desired_capabilities=dcap) else: driver = webdriver.Chrome() driver.set_window_size(600, 600) driver.get(captcha_url) if captchakey2 == "": #Do manual captcha entry print("You did not pass a 2captcha key. Please solve the captcha manually.") elem = driver.find_element_by_class_name("g-recaptcha") driver.execute_script("arguments[0].scrollIntoView(true);", elem) # Waits 1 minute for you to input captcha try: WebDriverWait(driver, 60).until(EC.text_to_be_present_in_element_value((By.NAME, "g-recaptcha-response"), "")) print "Solved captcha" token = driver.execute_script("return grecaptcha.getResponse()") #print ("Recaptcha token: {}".format(token)) activateUser(api, token) time.sleep(1) except TimeoutException, err: print("Timed out while manually solving captcha") else:
def main(): logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s') logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("pgoapi").setLevel(logging.INFO) logging.getLogger("rpc_api").setLevel(logging.INFO) config = init_config() if not config: return if config.debug: # logging.getLogger("requests").setLevel(logging.INFO) logging.getLogger("pgoapi").setLevel(logging.DEBUG) # logging.getLogger("rpc_api").setLevel(logging.INFO) position = get_pos_by_name(config.location) if config.test: return pokemon_data = json.load(open("pokemon_data.json")) api = PGoApi(config.__dict__, pokemon_data, position, config.printstats) try: api.login(config.auth_service, config.username, config.password, config.cached) except Exception as e: log.error(colored('Login failed, restarting [%s]', 'red'), e) sleep(30) main() while True: try: api.main_loop() except Exception as e: log.error(colored('Main loop has an ERROR, restarting [%s]', 'red'), e) sleep(30) main() import ipdb; ipdb.set_trace()
def accept_tos(username, password): api = PGoApi() api.set_position(40.7127837, -74.005941, 0.0) api.login('ptc', username, password) time.sleep(2) req = api.create_request() req.mark_tutorial_complete(tutorials_completed=0, send_marketing_emails=False, send_push_notifications=False) response = req.call() print('Accepted Terms of Service for {}'.format(username))
def _download_remote_config_version(self): # ===== DOWNLOAD_REMOTE_CONFIG_VERSION responses = self.perform_request( lambda req: req.download_remote_config_version( platform=1, app_version=PGoApi.get_api_version()), buddy_walked=False, get_inbox=False) if 'DOWNLOAD_REMOTE_CONFIG_VERSION' not in responses: raise Exception("Call to download_remote_config_version did not" " return proper response.") remote_config = responses['DOWNLOAD_REMOTE_CONFIG_VERSION'] return remote_config.asset_digest_timestamp_ms / 1000000, \ remote_config.item_templates_timestamp_ms / 1000
def __init__(self): self.api = PGoApi() self.load_config() self.pos = utils.get_pos_by_name(self.config["loc"]) self.api.set_position(*self.pos) self.logged_in = self.login() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s', filename=".log") # log level for http request class logging.getLogger("requests").setLevel(logging.WARNING) # log level for main pgoapi class logging.getLogger("pgoapi").setLevel(logging.INFO) # log level for internal pgoapi class logging.getLogger("rpc_api").setLevel(logging.INFO)