Ejemplo n.º 1
0
    def take_step(self):
        for step in range(self.steplimit2):
            #starting at 0 index
            print('looping: step {} of {}'.format((step+1), self.steplimit**2))
            print('steplimit: {} x: {} y: {} pos: {} dx: {} dy {}'.format(self.steplimit2, self.x, self.y, self.pos, self.dx, self.dy))
            # Scan location math
            if -self.steplimit2 / 2 < self.x <= self.steplimit2 / 2 and -self.steplimit2 / 2 < self.y <= self.steplimit2 / 2:
                position = (self.x * 0.0025 + self.origin_lat, self.y * 0.0025 + self.origin_lon, 0)
                if self.config.walk > 0:
                    self.api.walk(self.config.walk, *position)
                else:
                    self.api.set_position(*position)
                print(position)
            if self.x == self.y or self.x < 0 and self.x == -self.y or self.x > 0 and self.x == 1 - self.y:
                (self.dx, self.dy) = (-self.dy, self.dx)

            (self.x, self.y) = (self.x + self.dx, self.y + self.dy)
            # 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 = self._get_cellid(position[0], position[1])
            self.api.get_map_objects(latitude=f2i(position[0]), longitude=f2i(position[1]), since_timestamp_ms=timestamp, cell_id=cellid)

            response_dict = self.api.call()
            #print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
            if response_dict and 'responses' in response_dict and \
                'GET_MAP_OBJECTS' in response_dict['responses'] and \
                'status' in response_dict['responses']['GET_MAP_OBJECTS'] and \
                response_dict['responses']['GET_MAP_OBJECTS']['status'] is 1:
                #print('got the maps')
                map_cells=response_dict['responses']['GET_MAP_OBJECTS']['map_cells']
                #print('map_cells are {}'.format(len(map_cells)))
                for cell in map_cells:
                    self.bot.work_on_cell(cell,position)
            time.sleep(10)
Ejemplo n.º 2
0
    def scan(self):

        log.info('Current public IP address: %s', load(urlopen('http://httpbin.org/ip'))['origin'])

        ScanMetrics.NUM_STEPS = len(self.scan_config.COVER)
        log.info("Starting scan of {} locations".format(ScanMetrics.NUM_STEPS))

        for i, next_pos in enumerate(self.next_position()):
            log.debug('Scanning step {:d} of {:d}.'.format(i, ScanMetrics.NUM_STEPS))
            log.debug('Scan location is {:f}, {:f}'.format(next_pos[0], next_pos[1]))

            # TODO: Add error throttle

            cell_ids = get_cell_ids(next_pos[0], next_pos[1], radius=70)
            timestamps = [0, ] * len(cell_ids)
            self.api.get_map_objects(
                latitude=f2i(next_pos[0]),
                longitude=f2i(next_pos[1]),
                cell_id=cell_ids,
                since_timestamp_ms=timestamps,
                position=next_pos,
                callback=Scanner.callback)

        while not self.api.is_work_queue_empty():
            # Location change
            if self.scan_config.RESTART:
                log.info("Restarting scan")
                self.api.empty_work_queue()
            else:
                time.sleep(2)
Ejemplo n.º 3
0
def learning(api, locs):
	stuff = input('Enter coordinates: ')
	while stuff != 'no':
		lat,  longi = locs[stuff] if stuff in locs.keys() else map(float, stuff.split(', '))
		cell_ids = get_cell_ids(lat, longi)
		timestamps = [0,] * len(cell_ids)
		mapObjects = api.get_map_objects(latitude = util.f2i(lat), longitude = util.f2i(longi), since_timestamp_ms = timestamps, cell_id = cell_ids)
		if mapObjects['responses']['GET_MAP_OBJECTS']['status'] == 1:
			mapCells = mapObjects['responses']['GET_MAP_OBJECTS']['map_cells']
			pokes = None
			for cell in mapCells:
				if 'wild_pokemons' in cell.keys():
					pokes = cell
			if pokes != None:
				encounter = []
				for category in pokes.keys():
					if category  == pokeCategories[0]:
						for pokemon in pokes[category]:
							if pokemon['pokemon_data']['pokemon_id'] == 147:
								print('Dratini! Time left: ' + str(pokemon['time_till_hidden_ms']) + ' ms')
							elif pokemon['encounter_id'] not in encounter:
								print('Found Pokemon #' + str(pokemon['pokemon_data']['pokemon_id']))
								encounter.append(pokemon['encounter_id'])
					elif category == pokeCategories[1] or category == pokeCategories[2]:
						for pokemon in pokes[category]:
							if pokemon['pokemon_id'] == 147:
								print('Dratini!')
							elif pokemon['encounter_id'] not in encounter:
								print('Found Pokemon #' + str(pokemon['pokemon_id']))
								encounter.append(pokemon['encounter_id'])


		stuff = input('Enter coordinates: ')
Ejemplo n.º 4
0
def trackSpawns(api, locCenter, size): #atm size is number of circles composing the searchArea radius
	radius = .00034 # about 50m
	searchAreas = [locCenter] #locCenter needs to be tuple size 2
	for i in range(-1 * size, size):
		for j in range(-1 * size, size):
			searchAreas.append((locCenter + i * radius, locCenter + j * radius))
	searchAreas.append((locCenter + size * radius, locCenter + size * radius)) #this creates cricles in size of square, leaving too much space between circles though

	for area in searchAreas:
		lat, longi = area
		api.set_position(lat, longi, 0.0)
		cell_ids = get_cell_ids(lat, longi)
		timestamps = [0,] * len(cell_ids)
		mapObjects = api.get_map_objects(latitude = util.f2i(lat), longitude = util.f2i(longi), since_timestamp_ms = timestamps, cell_id = cell_ids)
		if mapObjects['responses']['GET_MAP_OBJECTS']['status'] == 1:
			mapCells = mapObjects['responses']['GET_MAP_OBJECTS']['map_cells']
			pokes = None
			for cell in mapCells:
				if 'wild_pokemons' in cell.keys():
					pokes = cell
			if pokes != None:
				for category in pokes.keys():
					if category  == pokeCategories[0]:
						for pokemon in pokes[category]: #save the gps coordinates and do something if the pokemon spawn has river or stream type spawns
							pass
Ejemplo n.º 5
0
 def spin_fort(self, fort):
     fort_id = fort['id']
     latitude = fort['latitude']
     longitude = fort['longitude']
     
     request = self.bot.api.create_request()
     request.fort_search(
         fort_id=fort_id,
         fort_latitude=latitude,
         fort_longitude=longitude,
         player_latitude=f2i(self.bot.position[0]),
         player_longitude=f2i(self.bot.position[1])
     )
     request.call()
     
     self.emit_event(
         'spun_fort',
         level='debug',
         formatted="Spun fort {fort_id}",
         data={
             'fort_id': fort_id,
             'latitude': latitude,
             'longitude': longitude
         }
     )
Ejemplo n.º 6
0
	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 find_poi(api, lat, lng):
    poi = {'pokemons': {}, 'forts': []}
    step_size = 0.0015
    step_limit = 49
    coords = generate_spiral(lat, lng, step_size, step_limit)
    timestamp = "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
    for coord in coords:
        lat = coord['lat']
        lng = coord['lng']
        api.set_position(lat, lng, 0)

        cellid = get_cellid(lat, lng)
        api.get_map_objects(latitude=f2i(lat), longitude=f2i(lng), since_timestamp_ms=timestamp, cell_id=cellid)

        response_dict = api.call()
        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']:
                        pokekey = get_key_from_pokemon(pokemon)
                        pokemon['hides_at'] = time.time() + pokemon['time_till_hidden_ms']/1000
                        poi['pokemons'][pokekey] = pokemon

        # time.sleep(0.51)
    print('POI dictionary: \n\r{}'.format(json.dumps(poi, indent=2)))
    print('Open this in a browser to see the path the spiral search took:')
    print_gmaps_dbug(coords)
Ejemplo n.º 8
0
    def find_close_cells(self, lat, lng):
        cellid = get_cellid(lat, lng)
        timestamp = [0, ] * len(cellid)

        self.api.get_map_objects(
            latitude=f2i(lat),
            longitude=f2i(lng),
            since_timestamp_ms=timestamp,
            cell_id=cellid
        )
        response_dict = self.api.call()
        map_objects = response_dict.get('responses', {}).get('GET_MAP_OBJECTS', {})
        status = map_objects.get('status', None)

        map_cells = []
        if status and status == 1:
            map_cells = map_objects['map_cells']
            position = (lat, lng, 0)
            map_cells.sort(
                key=lambda x: distance(
                    lat,
                    lng,
                    x['forts'][0]['latitude'],
                    x['forts'][0]['longitude']) if x.get('forts', []) else 1e6
            )
        return map_cells
Ejemplo n.º 9
0
def find_poi(api, lat, lng):
    poi = {'pokemons': {}, 'forts': []}
    step_size = 0.0005
    step_limit = 65
    coords = generate_spiral(lat, lng, step_size, step_limit)
    for coord in coords:
        lat = coord['lat']
        lng = coord['lng']
        api.set_position(lat, lng, 0)     
        #get_cellid was buggy -> replaced through get_cell_ids from pokecli
        #timestamp gets computed a different way:
        cell_ids = get_cell_ids(lat, lng)
        timestamps = [0,] * len(cell_ids)
        api.get_map_objects(latitude = util.f2i(lat), longitude = util.f2i(lng), since_timestamp_ms = timestamps, cell_id = cell_ids)
        response_dict = api.call()
        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']:
                            pokekey = get_key_from_pokemon(pokemon)
                            long_id = pokemon['longitude']
                            lat_id = pokemon['latitude']
                            poke_id = pokemon['pokemon_data']['pokemon_id']
                            time_now = str(time.strftime('%Y-%m-%dT%H:%M:%S.')) + str(int(round(time.time() * 1000)))[-3:]
                            payload = "{\n  \"tags\": [\n    {\n      \"tagId\": \"POKE5-CASINO-COSMOPOLITAN-PM_UNIT-LONGITUDE\",\n      \"errorCode\": null,\n      \"errorMessage\": null,\n      \"data\": [ \n          {\"ts\": \""+time_now+"\", \"q\": \"3\", \"v\":\""+str(long_id)+"\"}]\n    }\n  ]\n}"
                            payload2 = "{\n  \"tags\": [\n    {\n      \"tagId\": \"POKE5-CASINO-COSMOPOLITAN-PM_UNIT-LATITUDE\",\n      \"errorCode\": null,\n      \"errorMessage\": null,\n      \"data\": [ \n          {\"ts\": \""+time_now+"\", \"q\": \"3\", \"v\":\""+str(lat_id)+"\"}]\n    }\n  ]\n}"
                            payload3 = "{\n  \"tags\": [\n    {\n      \"tagId\": \"POKE5-CASINO-COSMOPOLITAN-PM_UNIT-ID\",\n      \"errorCode\": null,\n      \"errorMessage\": null,\n      \"data\": [ \n          {\"ts\": \""+time_now+"\", \"q\": \"3\", \"v\":\""+str(poke_id)+"\"}]\n    }\n  ]\n}"
                            send_long = post_data(payload)
                            send_lat = post_data(payload2)
                            send_pokeid = post_data(payload3)
                            print pokemon
Ejemplo n.º 10
0
 def send_map_request (self, user, position):
     try:
         cell_ids = util.get_cell_ids(position[0], position[1])
         user._last_call = time.time()
         timestamps = [0,] * len(cell_ids)
         return user.get_map_objects(
             latitude=util.f2i(position[0]),
             longitude=util.f2i(position[1]),
             since_timestamp_ms=timestamps,
             cell_id=cell_ids
         )
     except ServerSideAccessForbiddenException as e:
         logging.info("User {} or IP might be banned, attempting recovery...".format(user._data["username"]))
         with self._lock:
             now = time.time()
             if now - self._last_vpn_retry >= self._delay_between_vpn_retries:
                 self._last_vpn_retry = now
                 if self._num_vpn_retries < self._max_vpn_retries_before_switch:
                     logging.info("Restarting vpn ({} times so far)".format(self._num_vpn_retries))
                     subprocess.call([self._restart_vpn_file])
                     self._num_vpn_retries += 1
                 else:
                     logging.info("Restarted vpn too many times. Switching to a different vpn now")
                     subprocess.call([self._switch_vpn_file])
                     self._num_vpn_retries = 0
             # we can hold the lock for a bit during re-auth since there's
             # no point in retrying in other threads in the meantime
             self.auth_users()
     except Exception as e:
         logging.info("Uncaught exception when downloading map: {}".format(e))
     return False
Ejemplo n.º 11
0
def find_nearby_pokemon(api, lat, lng):
    step_size = 0.0015
    step_limit = 9
    coords = generate_spiral(lat, lng, step_size, step_limit)

    origin = Point(lat, lng)

    nearby_pokemon = {}

    for coord in coords:
        lat = coord['lat']
        lng = coord['lng']
        api.set_position(lat, lng, 0)

        cell_ids = get_cell_ids(lat, lng)
        timestamps = '\000' * 21
        api.get_map_objects(latitude=f2i(lat), longitude=f2i(lng), since_timestamp_ms=timestamps, cell_id=cell_ids)

        response_dict = api.call()

        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']:
                            key = get_key_from_pokemon(pokemon)
                            nearby_pokemon[key] = pokemon

                            p_lat = float(pokemon['latitude'])
                            p_lng = float(pokemon['longitude'])
                            loc = Point(p_lat, p_lng)
                            pokemon['distance'] = distance.distance(origin, loc).meters

    return nearby_pokemon
Ejemplo n.º 12
0
    def _work_at_position(self, lat, long, alt, pokemon_only=False):
        cell_id = get_cell_id_from_latlong(lat, long)
        timestamp = [0, ] * len(cell_id)
        self.api.get_map_objects(latitude=f2i(lat),
                                 longitude=f2i(long),
                                 since_timestamp_ms=timestamp,
                                 cell_id=cell_id)

        response_dict = self.api.call()
        # Passing data through last-location and location
        map_objects = response_dict.get("responses", {}).get("GET_MAP_OBJECTS")
        if map_objects is not None:
            with open("web/location-{}.json".format(self.config.username), "w") as outfile:
                json.dump({"lat": lat, "lng": long, "cells": map_objects.get("map_cells")}, outfile)
            with open("data/last-location-{}.json".format(self.config.username), "w") as outfile:
                outfile.truncate()
                json.dump({"lat": lat, "lng": long}, outfile)
            if "status" in map_objects:
                if map_objects.get("status") is 1:
                    map_cells = map_objects.get("map_cells")
                    position = lat, long, alt
                # Sort all by distance from current pos - eventually this should build graph and A* it
                map_cells.sort(key=lambda x: distance(lat, long, x["forts"][0]["latitude"], x["forts"][0]["longitude"]) if "forts" in x and x["forts"] != [] else 1e6)
                for cell in map_cells:
                    self.bot.work_on_cell(cell, position, pokemon_only)
Ejemplo n.º 13
0
    def scan(self):
        ScanMetrics.NUM_STEPS = len(self.scan_config.COVER)
        log.info("Starting scan of {} locations".format(ScanMetrics.NUM_STEPS))

        for i, next_pos in enumerate(self.next_position()):
            log.debug('Scanning step {:d} of {:d}.'.format(i, ScanMetrics.NUM_STEPS))
            log.debug('Scan location is {:f}, {:f}'.format(next_pos[0], next_pos[1]))

            # TODO: Add error throttle

            cell_ids = get_cell_ids(next_pos[0], next_pos[1], radius=70)
            timestamps = [0, ] * len(cell_ids)
            self.api.get_map_objects(
                latitude=f2i(next_pos[0]),
                longitude=f2i(next_pos[1]),
                cell_id=cell_ids,
                since_timestamp_ms=timestamps,
                position=next_pos,
                callback=Scanner.callback)

        while not self.api.is_work_queue_empty():
            # Location change
            if self.scan_config.RESTART:
                log.info("Restarting scan")
                self.api.empty_work_queue()
            else:
                time.sleep(2)

        self.api.wait_until_done()  # Work queue empty != work done
Ejemplo n.º 14
0
    def take_step(self):
        self.pos = fuzz(self.pos, tolerance=self.step_dist)

        self.bot.log.info('Position: {}, Walk Speed: {}'\
                          .format(self.pos, self.config.walk))
        self.api.walk(self.config.walk, *self.pos)

        timestamp = "\000" * 21
        cellid = _get_cellid(self.pos.lat, self.pos.lon)
        self.api.get_map_objects(latitude=f2i(self.pos.lat),
                                 longitude=f2i(self.pos.lon),
                                 since_timestamp_ms=timestamp,
                                 cell_id=cellid)
        res = self.api.call()
        try:
            map_cells = res['responses']['GET_MAP_OBJECTS']['map_cells']

            cell_forts = [c for c in map_cells if 'forts' in map_cells]
            cell_no_forts = [c for c in map_cells if 'forts' not in map_cells]

            for cell in cell_no_forts:
                self.bot.work_on_cell(cell, self.pos)
            for cell in cell_forts:
                self.bot.work_on_cell(cell, self.pos)

        except KeyError:
            print "get_map_objects returning incorrectly!"

        time.sleep(5)
Ejemplo n.º 15
0
def find_poi(api, lat, lng):
    poi = {'pokemons': {}, 'forts': []}
    step_size = 0.0015
    step_limit = 49
    coords = generate_spiral(lat, lng, step_size, step_limit)
    for coord in coords:
        lat = coord['lat']
        lng = coord['lng']
        api.set_position(lat, lng, 0)

        
        #get_cellid was buggy -> replaced through get_cell_ids from pokecli
        #timestamp gets computed a different way:
        cell_ids = get_cell_ids(lat, lng)
        timestamps = [0,] * len(cell_ids)
        response_dict = api.get_map_objects(latitude = util.f2i(lat), longitude = util.f2i(lng), since_timestamp_ms = timestamps, cell_id = cell_ids)
        if (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']:
                                pokekey = get_key_from_pokemon(pokemon)
                                pokemon['hides_at'] = time.time() + pokemon['time_till_hidden_ms']/1000
                                poi['pokemons'][pokekey] = pokemon

        # time.sleep(0.51)
    # new dict, binary data
    # print('POI dictionary: \n\r{}'.format(json.dumps(poi, indent=2)))
    print('POI dictionary: \n\r{}'.format(pprint.PrettyPrinter(indent=4).pformat(poi)))
    print('Open this in a browser to see the path the spiral search took:')
    print_gmaps_dbug(coords)
Ejemplo n.º 16
0
    def update_web_location(self, cells=[], lat=None, lng=None, alt=None):
        # we can call the function with no arguments and still get the position and map_cells
        if lat == None:
            lat = self.api._position_lat
        if lng == None:
            lng = self.api._position_lng
        if alt == None:
            alt = 0

        if cells == []:
            cellid = get_cellid(lat, lng)
            timestamp = [0, ] * len(cellid)
            self.api.get_map_objects(
                latitude=f2i(lat),
                longitude=f2i(lng),
                since_timestamp_ms=timestamp,
                cell_id=cellid
            )
            response_dict = self.api.call()
            map_objects = response_dict.get('responses', {}).get('GET_MAP_OBJECTS', {})
            status = map_objects.get('status', None)
            cells = map_objects['map_cells']

            #insert detail info about gym to fort
            for cell in cells:
                if 'forts' in cell:
                    for fort in cell['forts']:
                        if fort.get('type') != 1:
                            self.api.get_gym_details(gym_id=fort.get('id'),
                                                     player_latitude=lng,
                                                     player_longitude=lat,
                                                     gym_latitude=fort.get('latitude'),
                                                     gym_longitude=fort.get('longitude'))
                            response_gym_details = self.api.call()
                            fort['gym_details'] = response_gym_details.get('responses', {}).get('GET_GYM_DETAILS', None)

        user_data_cells = "data/cells-%s.json" % (self.config.username)
        with open(user_data_cells, 'w') as outfile:
            json.dump(cells, outfile)

        user_web_location = os.path.join('web', 'location-%s.json' % (self.config.username))
        # alt is unused atm but makes using *location easier
        try:
            with open(user_web_location,'w') as outfile:
                json.dump(
                    {'lat': lat,
                    'lng': lng,
                    'alt': alt,
                    'cells': cells
                    }, outfile)
        except IOError as e:
            logger.log('[x] Error while opening location file: %s' % e, 'red')

        user_data_lastlocation = os.path.join('data', 'last-location-%s.json' % (self.config.username))
        try:
            with open(user_data_lastlocation, 'w') as outfile:
                json.dump({'lat': lat, 'lng': lng}, outfile)
        except IOError as e:
            logger.log('[x] Error while opening location file: %s' % e, 'red')
Ejemplo n.º 17
0
 def spin_fort(self, fort):
     self.bot.api.fort_search(
         fort_id=fort['id'],
         fort_latitude=fort['latitude'],
         fort_longitude=fort['longitude'],
         player_latitude=f2i(self.bot.position[0]),
         player_longitude=f2i(self.bot.position[1])
     )
Ejemplo n.º 18
0
 def req_get_gym_details(self, gym_id, gym_lat, gym_lng, player_lat, player_lng):
     return self.perform_request(
         lambda req: req.get_gym_details(gym_id=gym_id,
                                         player_latitude=f2i(player_lat),
                                         player_longitude=f2i(player_lng),
                                         gym_latitude=gym_lat,
                                         gym_longitude=gym_lng,
                                         client_version=API_VERSION), get_inbox=True)
Ejemplo n.º 19
0
 def req_gym_get_info(self, gym_id, gym_lat, gym_lng, player_lat,
                      player_lng):
     return self.perform_request(
         lambda req: req.gym_get_info(gym_id=gym_id,
                                      player_lat_degrees=f2i(player_lat),
                                      player_lng_degrees=f2i(player_lng),
                                      gym_lat_degrees=gym_lat,
                                      gym_lng_degrees=gym_lng))
Ejemplo n.º 20
0
def gym_get_info(api, account, position, gym):
    req = api.create_request()
    req.gym_get_info(gym_id=gym['gym_id'],
                     player_lat_degrees=f2i(position[0]),
                     player_lng_degrees=f2i(position[1]),
                     gym_lat_degrees=gym['latitude'],
                     gym_lng_degrees=gym['longitude'])
    return send_generic_request(req, account)
Ejemplo n.º 21
0
    def search(self, lat, lng, step_limit, step_size):
        if self.api._auth_provider and self.api._auth_provider._ticket_expire:
            if isinstance(self.api._auth_provider._ticket_expire, (int, long)):
                remaining_time = self.api._auth_provider._ticket_expire / 1000.0 - time.time()
                if remaining_time > 60:
                    logger.info("Skipping Pokemon Go login process since already logged in for another {:.2f} seconds".format(remaining_time))
                else:
                    self.login()
            else:
                logger.warn("skipping login since _ticket_expire was a token.")
        else:
            self.login()

        # coords = generate_spiral(lat, lng, step_size, step_limit)
        coords = generate_location_steps(lat, lng, step_size, step_limit)
        all_pokemon = {}
        i = 1
        for coord in coords:
            lat = coord['lat']
            lng = coord['lng']
            self.api.set_position(lat, lng, 0)

            cell_ids = get_cell_ids(lat, lng)
            timestamps = [0,] * len(cell_ids)

            self.api.get_map_objects(latitude = f2i(lat), longitude = f2i(lng), since_timestamp_ms = timestamps, cell_id = cell_ids)
            response_dict = self.api.call()

            while not response_dict:
                logger.info('Map Download failed. Trying again.')
                self.api.get_map_objects(latitude = f2i(lat), longitude = f2i(lng), since_timestamp_ms = timestamps, cell_id = cell_ids)
                response_dict = self.api.call()
                time.sleep(REQ_SLEEP)

            try:
                pokemons, pokestops, gyms = parse_map(response_dict)
            except KeyError as e:
                logger.error('failed to parse map with key error: %s', e)

            for key in pokemons.keys():
                if not key in all_pokemon:
                    pokemon = pokemons[key]
                    expires_in = pokemon['disappear_time'] - datetime.utcnow()
                    pokemon_id = pokemon['pokemon_id']
                    pokedata = Pokedata.get(pokemon_id)
                    pokemon['name'] = pokedata['name']
                    pokemon['rarity'] = pokedata['rarity']
                    pokemon['key'] = key
                    logger.info("adding pokemon: %s - %s, rarity: %s, expires in: %s", pokemon_id, pokemon['name'], pokemon['rarity'], expires_in)
                    all_pokemon[key] = pokemon
                # else:
                #     logger.info("have duplicate poke: %s", key)

            logger.info('Completed {:5.2f}% of scan.'.format(float(i) / step_limit**2*100))
            i += 1
            time.sleep(REQ_SLEEP)
        return all_pokemon
Ejemplo n.º 22
0
    def find_pokemon(self, job):
        tries = 0
        max_tries = 3
        wild_pokemon = []
        while tries < max_tries:
            tries += 1
            try:
                (lat, lng) = self.jittered_location(job)
                self.log_info("Looking for {} at {}, {} - try {}".format(job.pokemon_name, lat, lng, tries))
                cell_ids = get_cell_ids(lat, lng)
                timestamps = [0, ] * len(cell_ids)
                response = self.perform_request(
                    lambda req: req.get_map_objects(latitude=f2i(lat),
                                                    longitude=f2i(lng),
                                                    since_timestamp_ms=timestamps,
                                                    cell_id=cell_ids))

                wild_pokemon = self.parse_wild_pokemon(response)
                if len(wild_pokemon) > 0:
                    break
            except Exception as e:
                self.log_error('Exception on GMO try {}: {}'.format(tries, repr(e)))

        if len(wild_pokemon) == 0:
            self.log_info("Still no wild Pokemon found. Giving up.")
            return False

        # find all pokemon with desired id
        candidates = filter(
            lambda pkm: pkm['pokemon_data']['pokemon_id'] == job.pokemon_id,
            wild_pokemon)

        target = None
        if len(candidates) == 1:
            # exactly one pokemon of this id found
            target = candidates[0]
        elif len(candidates) > 1:
            # multiple pokemon found, pick one with lowest distance to search position
            loc = (job.lat, job.lng)
            min_dist = False
            for pkm in candidates:
                d = geopy.distance.distance(loc, (pkm["latitude"], pkm["longitude"])).meters
                if not min_dist or d < min_dist:
                    min_dist = d
                    target = pkm

        # no pokemon found
        if target is None:
            self.log_info("No wild {} found at {}, {}.".format(job.pokemon_name, lat, lng))
            return False

        # now set encounter id and spawn point id
        self.log_info("Got encounter_id for {} at {}, {}.".format(job.pokemon_name, target['latitude'], target['longitude']))
        job.encounter_id = target['encounter_id']
        job.spawn_point_id = target["spawn_point_id"]
        return True
Ejemplo n.º 23
0
    def search(self, position, num_steps):
        if self.api._auth_provider and self.api._auth_provider._ticket_expire:
            if isinstance(self.api._auth_provider._ticket_expire, (int, long)):
                remaining_time = self.api._auth_provider._ticket_expire / 1000.0 - time.time()
                if remaining_time > 60:
                    logger.info("Skipping Pokemon Go login process since already logged in for another {:.2f} seconds".format(remaining_time))
                else:
                    self.login()
            else:
                logger.warn("skipping login since _ticket_expire was a token.")
        else:
            self.login()

        all_pokemon = {}
        num_retries = 0

        for step, coord in enumerate(generate_location_steps(position, num_steps, self.visible_range_metres), 1):
            lat = coord[0]
            lng = coord[1]
            self.api.set_position(*coord)

            cell_ids = get_cell_ids(lat, lng)
            timestamps = [0,] * len(cell_ids)

            response_dict = None
            while not response_dict:
                try:
                    self.api.get_map_objects(latitude = f2i(lat), longitude = f2i(lng), since_timestamp_ms = timestamps, cell_id = cell_ids)
                    response_dict = self.api.call()
                except:
                    logging.warn('exception happened on get_map_objects api call', exc_info=True)
                if not response_dict:
                    if num_retries < MAX_NUM_RETRIES:
                        num_retries += 1
                        logger.warn('get_map_objects failed, retrying in %s seconds, %s retries', REQ_SLEEP, num_retries)
                        time.sleep(REQ_SLEEP)
                    else:
                        logger.warn('MAX_NUM_RETRIES exceeded, retrying login...')
                        self.login()
                        raise StopIteration

            # try:
            pokemons = parse_map(response_dict)
            # except KeyError as e:
            #     logger.error('failed to parse map with key error: %s', e)

            for key in pokemons.keys():
                if not key in all_pokemon:
                    pokemon = pokemons[key]
                    all_pokemon[key] = pokemon
                    yield pokemon
                # else:
                #     logger.info("have duplicate poke: %s", key)
            total_steps = (3 * (num_steps**2)) - (3 * num_steps) + 1
            logger.info('Completed {:5.2f}% of scan.'.format(float(step) / total_steps * 100))
            time.sleep(REQ_SLEEP)
Ejemplo n.º 24
0
    def _work_at_position(self, lat, lng, alt, pokemon_only=False):
        cellid = self._get_cellid(lat, lng)
        timestamp = [
            0,
        ] * len(cellid)
        self.api.get_map_objects(latitude=f2i(lat),
                                 longitude=f2i(lng),
                                 since_timestamp_ms=timestamp,
                                 cell_id=cellid)

        response_dict = self.api.call()
        # pprint.pprint(response_dict)
        # Passing Variables through a file
        if response_dict and 'responses' in response_dict:
            if 'GET_MAP_OBJECTS' in response_dict['responses']:
                if 'map_cells' in response_dict['responses'][
                        'GET_MAP_OBJECTS']:
                    user_web_location = 'web/location-%s.json' % (
                        self.config.username)
                    if os.path.isfile(user_web_location):
                        with open(user_web_location, 'w') as outfile:
                            json.dump(
                                {
                                    'lat':
                                    lat,
                                    'lng':
                                    lng,
                                    'cells':
                                    response_dict['responses']
                                    ['GET_MAP_OBJECTS']['map_cells']
                                }, outfile)

                    user_data_lastlocation = 'data/last-location-%s.json' % (
                        self.config.username)
                    if os.path.isfile(user_data_lastlocation):
                        with open(user_data_lastlocation, 'w') as outfile:
                            outfile.truncate()
                            json.dump({'lat': lat, 'lng': lng}, outfile)

        if response_dict and 'responses' in response_dict:
            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'] is 1:
                        map_cells = response_dict['responses'][
                            'GET_MAP_OBJECTS']['map_cells']
                        position = (lat, lng, alt)
                    # Sort all by distance from current pos- eventually this should build graph & A* it
                    # print(map_cells)
                    #print( s2sphere.from_token(x['s2_cell_id']) )
                    map_cells.sort(
                        key=lambda x: distance(lat, lng, x['forts'][0][
                            'latitude'], x['forts'][0]['longitude'])
                        if 'forts' in x and x['forts'] != [] else 1e6)
                    for cell in map_cells:
                        self.bot.work_on_cell(cell, position, pokemon_only)
Ejemplo n.º 25
0
    def find_pokemon(self, job):
        tries = 0
        max_tries = 3
        wild_pokemon = []
        while tries < max_tries:
            tries += 1
            try:
                (lat, lng) = self.jittered_location(job)
                self.log_info("Looking for {} at {}, {} - try {}".format(job.pokemon_name, lat, lng, tries))
                cell_ids = get_cell_ids(lat, lng)
                timestamps = [0, ] * len(cell_ids)
                response = self.perform_request(
                    lambda req: req.get_map_objects(latitude=f2i(lat),
                                                    longitude=f2i(lng),
                                                    since_timestamp_ms=timestamps,
                                                    cell_id=cell_ids))

                wild_pokemon = self.parse_wild_pokemon(response)
                if len(wild_pokemon) > 0:
                    break
            except Exception as e:
                self.log_error('Exception on GMO try {}: {}'.format(tries, repr(e)))

        if len(wild_pokemon) == 0:
            self.log_info("Still no wild Pokemon found. Giving up.")
            return False

        # find all pokemon with desired id
        candidates = filter(
            lambda pkm: pkm['pokemon_data']['pokemon_id'] == job.pokemon_id,
            wild_pokemon)

        target = None
        if len(candidates) == 1:
            # exactly one pokemon of this id found
            target = candidates[0]
        elif len(candidates) > 1:
            # multiple pokemon found, pick one with lowest distance to search position
            loc = (job.lat, job.lng)
            min_dist = False
            for pkm in candidates:
                d = geopy.distance.distance(loc, (pkm["latitude"], pkm["longitude"])).meters
                if not min_dist or d < min_dist:
                    min_dist = d
                    target = pkm

        # no pokemon found
        if target is None:
            self.log_info("No wild {} found at {}, {}.".format(job.pokemon_name, lat, lng))
            return False

        # now set encounter id and spawn point id
        self.log_info("Got encounter_id for {} at {}, {}.".format(job.pokemon_name, target['latitude'], target['longitude']))
        job.encounter_id = target['encounter_id']
        job.spawn_point_id = target["spawn_point_id"]
        return True
Ejemplo n.º 26
0
def get_map_objects(api, account, location):
    cell_ids = get_cell_ids(location[0], location[1])
    timestamps = [0, ]*len(cell_ids)
    req = api.create_request()
    req.get_map_objects(
        latitude=f2i(location[0]),
        longitude=f2i(location[1]),
        since_timestamp_ms=timestamps,
        cell_id=cell_ids)
    return send_generic_request(req, account)
Ejemplo n.º 27
0
def map_request(api, position):
    try:
        cell_ids = util.get_cell_ids(position[0], position[1])
        timestamps = [0] * len(cell_ids)
        return api.get_map_objects(
            latitude=f2i(position[0]), longitude=f2i(position[1]), since_timestamp_ms=timestamps, cell_id=cell_ids
        )
    except Exception as e:
        log.warning("Exception while downloading map: %s", e)
        return False
Ejemplo n.º 28
0
def encounter_request(api, position, encounterid, spawnpointid):
    try:
        x = api.encounter(player_latitude=f2i(position[0]),
                          player_longitude=f2i(position[1]),
                          encounter_id=encounterid,
                          spawn_point_id=spawnpointid)
        return x
    except Exception as e:
        log.warning('Exception while Encountering pokemon: %s', e)
        return False
Ejemplo n.º 29
0
def getMapSearch(self, center, radius):
    # idea: assign outlier value to each so you know how many points each one
    # is made of in the end in the "parents" entry
    lat1 = center[0]
    lon1 = center[1]
    # because we already have a wait in the update method
    #self.plt.pause(3) # just because it's slightly more useful than time.sleep
    try:
        cell_ids = util.get_cell_ids(self.latitude, self.longitude)
        timestamps = [
            0,
        ] * len(cell_ids)  # for what purpose?
        theMap = self.player.get_map_objects(latitude=util.f2i(self.latitude),
                                             longitude=util.f2i(
                                                 self.longitude),
                                             since_timestamp_ms=timestamps,
                                             cell_id=cell_ids)
    except:
        logging.warn("Unexpexted response from get_map_objects")
        self.relog()
        return False

    try:
        cells = theMap["responses"]["GET_MAP_OBJECTS"]["map_cells"]
    except:
        logging.warn("Unexpexted response from get_map_objects")
        return False

    for i in cells:
        if "forts" in i:
            for j in i["forts"]:
                lat2 = j["latitude"]
                lon2 = j["longitude"]
                if geography.isInRange(lat1, lon1, lat2, lon2, radius):
                    if "gym_points" in j:
                        if j["id"] not in self.foundGyms:
                            self.foundGyms[j["id"]] = 1
                            self.gyms.append(j)
                            self.plot(lat2, lon2, "gd")
                    else:
                        if j["id"] not in self.foundForts:
                            self.foundForts[j["id"]] = 1
                            self.forts.append(j)
                            self.plot(lat2, lon2, "rd")
        if "spawn_points" in i:
            for j in i["spawn_points"]:
                lat2 = j["latitude"]
                lon2 = j["longitude"]
                ID = str(lat2) + str(lon2)
                ID = base64.b64encode(bytes(ID, "UTF-8"))
                if geography.isInRange(lat1, lon1, lat2, lon2, radius):
                    if ID not in self.foundSpawns:
                        self.spawns.append(j)
                        self.foundSpawns[ID] = 1
                        self.plot(lat2, lon2, "bd")
Ejemplo n.º 30
0
def find_poi(api, lat, lng, slack_client):
    poi = {'pokemons': {}, 'forts': []}
    coords = coords_square(lat, lng)
    for coord in coords:
        lat = coord['lat']
        lng = coord['lng']
        api.set_position(lat, lng, 0)

        from geopy.geocoders import Nominatim
        geolocator = Nominatim()
        cell_ids = get_cell_ids(lat, lng)
        timestamps = [0,] * len(cell_ids)
        response_dict = api.get_map_objects(latitude = util.f2i(lat), longitude = util.f2i(lng), since_timestamp_ms = timestamps, cell_id = cell_ids)
        if (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']:
                                pokekey = get_key_from_pokemon(pokemon)
                                pokemon['name'] = pokemonNames[pokemon['pokemon_data']['pokemon_id']-1]
                                pokemon['hides_at'] = (pokemon['time_till_hidden_ms']/1000)/60
                                if pokemon['name'] not in unwantedPokemon and pokemon['hides_at'] >= MINIMUM_ALERT_TIME_LB and pokemon['hides_at'] <= MINIMUM_ALERT_TIME_UB:
                                    address = geolocator.reverse(repr(pokemon['latitude'])+", "+repr(pokemon['longitude'])).address
                                    sep = ', Financial District'
                                    rest = address.split(sep, 1)[0]
                                    pokemon['location'] = rest  
                                    poi['pokemons'][pokekey] = pokemon
                                    for user in specialAlertUser:
                                        pokemonList = specialAlertUser[user]
                                        searchFor =  pokemon['name'].lower()
                                        if searchFor in  pokemonList:
                                            text = searchFor+" at "+pokemon['location']+"hidinf for"+"{0:.2f}".format(pokemon['hides_at']) + " minutes \n"
                                            slack_client.api_call(
                                                                "chat.postMessage", channel=user, text=text,
                                                                username='******', as_user = True
                                                        )
                                    
                                    
                    
            time.sleep(0.7)
    textSlack = ""
    for pokemon in poi['pokemons']:
        print(pokemon)
        textSlack += poi['pokemons'][pokemon]['name']+" at " + poi['pokemons'][pokemon]['location']+ " hiding for "+"{0:.2f}".format(poi['pokemons'][pokemon]['hides_at']) + " minutes \n"
            
            
    slack_client.api_call(
                "chat.postMessage", channel="#pokemon", text=textSlack,
                username='******', as_user = True
        )
    print('POI dictionary: \n\r{}'.format(pprint.PrettyPrinter(indent=4).pformat(poi)))
    print('Open this in a browser to see the path the spiral search took:')
    print_gmaps_dbug(coords)
Ejemplo n.º 31
0
def send_map_request(api, position):
    try:
        api.set_position(*position)
        api.get_map_objects(latitude=f2i(position[0]),
                            longitude=f2i(position[1]),
                            since_timestamp_ms=TIMESTAMP,
                            cell_id=get_cellid(position[0], position[1]))
        return api.call()
    except Exception as e:
        log.warn("Uncaught exception when downloading map " + str(e))
        return False
Ejemplo n.º 32
0
def send_map_request(api, position):
    try:
        api.set_position(*position)
        api.get_map_objects(latitude=f2i(position[0]),
                            longitude=f2i(position[1]),
                            since_timestamp_ms=TIMESTAMP,
                            cell_id=get_cellid(position[0], position[1]))
        return api.call()
    except Exception as e:
        log.warn("Uncaught exception when downloading map " + str(e))
        return False
Ejemplo n.º 33
0
    def __init__(self, lat, lon, alt=0):
        self.lat = lat
        self.lon = lon
        self.alt = alt

        self.FLOAT_LAT = lat
        self.FLOAT_LONG = lon
        if PGO:
            self.COORDS_LATITUDE = util.f2i(lat)
            self.COORDS_LONGITUDE = util.f2i(lon)
            self.COORDS_ALTITUDE = util.f2i(alt)
Ejemplo n.º 34
0
def map_request(api, position):
    try:
        api.set_position(*position)
        api.get_map_objects(latitude=f2i(position[0]),
                            longitude=f2i(position[1]),
                            since_timestamp_ms=TIMESTAMP,
                            cell_id=get_cellid(position[0], position[1]))
        return api.call()
    except Exception as e:
        log.warning('Exception while downloading map: %s', e)
        return False
Ejemplo n.º 35
0
    def get_cells(self):
        timestamp = "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
        cellid = self._get_cellid(self.position[0], self.position[1])
        self.api.get_map_objects(latitude=f2i(self.position[0]), longitude=f2i(self.position[1]),
                                     since_timestamp_ms=timestamp, cell_id=cellid)
        response_dict = self.api.call()

        try:
            if response_dict['responses']['GET_MAP_OBJECTS']['status'] is 1:
                self.cells=response_dict['responses']['GET_MAP_OBJECTS']['map_cells']
        except KeyError:
            pass
Ejemplo n.º 36
0
def doScan(sLat, sLng, api):
	#print ('scanning ({}, {})'.format(sLat, sLng))
	api.set_position(sLat,sLng,0)
	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(sLat, sLng)
	api.get_map_objects(latitude=f2i(sLat), longitude=f2i(sLng), since_timestamp_ms=timestamp, cell_id=cellid)
	response_dict = api.call()
	try:
		cells = response_dict['responses']['GET_MAP_OBJECTS']['map_cells']
	except TypeError, KeyError:
		print ('error getting map data for {}, {}'.format(sLat, sLng))
		return
Ejemplo n.º 37
0
def get_location(user, psswd, location, pokeOnly):
    splitloc = location.split(",")
    position = (float(splitloc[0]), float(splitloc[1]), 0)
    # instantiate pgoapi
    api = pgoapi.PGoApi()

    # provide player position on the earth
    api.set_position(*position)

    if not api.login('ptc', user, psswd):
        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
    # repeated fields (e.g. cell_id and since_timestamp_ms in get_map_objects) can be provided over a list
    # ----------------------
    cell_ids = get_cell_ids(position[0], position[1])
    timestamps = [
        0,
    ] * len(cell_ids)
    api.get_map_objects(latitude=util.f2i(position[0]),
                        longitude=util.f2i(position[1]),
                        since_timestamp_ms=timestamps,
                        cell_id=cell_ids)

    # spin a fort
    # ----------------------
    #fortid = '<your fortid>'
    #lng = <your longitude>
    #lat = <your latitude>
    #api.fort_search(fort_id=fortid, fort_latitude=lat, fort_longitude=lng, player_latitude=f2i(position[0]), player_longitude=f2i(position[1]))

    # release/transfer a pokemon and get candy for it
    # ----------------------
    #api.release_pokemon(pokemon_id = <your pokemonid>)

    # get download settings call
    # ----------------------
    #api.download_settings(hash="05daf51635c82611d1aac95c0b051d3ec088a930")

    # execute the RPC call
    response_dict = api.call()
    handleMapResp(response_dict["responses"]["GET_MAP_OBJECTS"], pokeOnly)
Ejemplo n.º 38
0
def send_map_request(api, position, args):
    try:
        login_if_necessary(args, position)

        api.set_position(*position)
        api.get_map_objects(latitude=f2i(position[0]),
                            longitude=f2i(position[1]),
                            since_timestamp_ms=TIMESTAMP,
                            cell_id=get_cellid(position[0], position[1]))
        return api.call()
    except Exception:  # make sure we dont crash in the main loop
        log.exception("Uncaught exception when downloading map")
        return False
Ejemplo n.º 39
0
def map_request(api, position):
    try:
        cell_ids = util.get_cell_ids(position[0], position[1])
        timestamps = [
            0,
        ] * len(cell_ids)
        return api.get_map_objects(latitude=f2i(position[0]),
                                   longitude=f2i(position[1]),
                                   since_timestamp_ms=timestamps,
                                   cell_id=cell_ids)
    except Exception as e:
        log.warning('Exception while downloading map: %s', e)
        return False
Ejemplo n.º 40
0
    def get_map_objects(self, lat, lng, timestamp, cellid):
        if time.time() - self.last_time_map_object < self.config.map_object_cache_time:
            return self.last_map_object

        self.last_map_object = self.api.get_map_objects(
            latitude=f2i(lat),
            longitude=f2i(lng),
            since_timestamp_ms=timestamp,
            cell_id=cellid
        )
        self.last_time_map_object = time.time()

        return self.last_map_object
Ejemplo n.º 41
0
    def get_map_objects(self, lat, lng, timestamp, cellid):
        if time.time() - self.last_time_map_object < self.config.map_object_cache_time:
            return self.last_map_object

        self.last_map_object = self.api.get_map_objects(
            latitude=f2i(lat),
            longitude=f2i(lng),
            since_timestamp_ms=timestamp,
            cell_id=cellid
        )
        self.last_time_map_object = time.time()

        return self.last_map_object
Ejemplo n.º 42
0
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)))
Ejemplo n.º 43
0
def gym_request(api, position, gym):
    try:
        log.debug('Getting details for gym @ %f/%f (%fkm away)', gym['latitude'], gym['longitude'], calc_distance(position, [gym['latitude'], gym['longitude']]))
        x = api.get_gym_details(gym_id=gym['gym_id'],
                                player_latitude=f2i(position[0]),
                                player_longitude=f2i(position[1]),
                                gym_latitude=gym['latitude'],
                                gym_longitude=gym['longitude'])

        # print pretty(x)
        return x

    except Exception as e:
        log.warning('Exception while downloading gym details: %s', e)
        return False
def find_poi(api, lat, lng):
    poi = {'pokemons': {}, 'forts': []}
    step_size = 0.0015
    step_limit = 1
    coords = generate_spiral(lat, lng, step_size, step_limit)

    FOUND_POKEMON = []

    for coord in coords:
        lat = coord['lat']
        lng = coord['lng']
        api.set_position(lat, lng, 0)

        #get_cellid was buggy -> replaced through get_cell_ids from pokecli
        #timestamp gets computed a different way:
        cell_ids = util.get_cell_ids(lat, lng)
        timestamps = [
            0,
        ] * len(cell_ids)
        response_dict = api.get_map_objects(latitude=util.f2i(lat),
                                            longitude=util.f2i(lng),
                                            since_timestamp_ms=timestamps,
                                            cell_id=cell_ids)
        if (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']:
                                FOUND_POKEMON.append(
                                    pokemon['pokemon_data']['pokemon_id'])
                                # pokekey = get_key_from_pokemon(pokemon)
                                # pokemon['hides_at'] = time.time() + pokemon['time_till_hidden_ms']/1000
                                # poi['pokemons'][pokekey] = pokemon

        time.sleep(0.51)

    for x in FOUND_POKEMON:
        print("#{} NEARBY, {}!".format(x, POKE_NAMES[x - 1]))
        if (x in COMMON_POKE):
            enable_led(17, True)
        if (x in UNCOMMON_POKE or x in RARE_POKE or x in VERY_RARE_POKE
                or x in EPIC_POKE or x in LEGENDARY_POKE):
            print("RARE POKEMON FOUND!")
            enable_led(27, True)
            enable_led(22, True)
Ejemplo n.º 45
0
 def spin_fort(self, fort):
     fort_id = fort['id']
     latitude = fort['latitude']
     longitude = fort['longitude']
     self.bot.api.fort_search(fort_id=fort_id,
                              fort_latitude=latitude,
                              fort_longitude=longitude,
                              player_latitude=f2i(self.bot.position[0]),
                              player_longitude=f2i(self.bot.position[1]))
     self.emit_event('spun_fort',
                     level='debug',
                     formatted="Spun fort {fort_id}",
                     data={
                         'fort_id': fort_id,
                         'latitude': latitude,
                         'longitude': longitude
                     })
Ejemplo n.º 46
0
def find_poi(api, lat, lng):
    poi = {'pokemons': [], 'forts': []}
    step_size = 0.003
    step_limit = 28
    coords = generate_spiral(lat, lng, step_size, step_limit)
    #timestamp = "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
    pokeCount = 0
    for coord in coords:
        lat = coord['lat']
        lng = coord['lng']
        api.set_position(lat, lng, 0)

        cellid = get_cellid(lat, lng)
        timestamp = [
            0,
        ] * len(cellid)

        response_dict = api.get_map_objects(latitude=f2i(lat),
                                            longitude=f2i(lng),
                                            since_timestamp_ms=timestamp,
                                            cell_id=cellid)
        print response_dict
        if 'status' not in response_dict['responses']['GET_MAP_OBJECTS']:
            raise ValueError("Invalid response: {}".format(
                json.dumps(response_dict, indent=2)))
        if response_dict['responses']['GET_MAP_OBJECTS']['status'] == 1:
            for cell in response_dict['responses']['GET_MAP_OBJECTS'][
                    'map_cells']:
                if 'wild_pokemons' in cell:
                    for wpoke in cell['wild_pokemons']:
                        poke = {
                            "type": wpoke['pokemon_data']['pokemon_id'],
                            "lon": wpoke['longitude'],
                            "lat": wpoke['latitude'],
                            "time_vanish": wpoke['time_till_hidden_ms'] / 1000
                        }
                        poi['pokemons'].append(poke)
                        pokeCount = pokeCount + 1
                #TODO: what about nearby pokemons??

        time.sleep(30)
    print('POI dictionary: \n\r{}'.format(json.dumps(poi, indent=2)))
    print "pokecount: {} pokemons {}".format(pokeCount, len(poi['pokemons']))
    print('Open this in a browser to see the path the spiral search took:')
    print_gmaps_dbug(coords)
Ejemplo n.º 47
0
    def scan_location(self):
        try:
            self.api.set_position(self.latitude, self.longitude,
                                  random.randint(12, 108))
            cell_ids = get_cell_ids(self.latitude, self.longitude)
            timestamps = [
                0,
            ] * len(cell_ids)
            req = self.api.create_request()
            req.get_map_objects(latitude=f2i(self.latitude),
                                longitude=f2i(self.longitude),
                                since_timestamp_ms=timestamps,
                                cell_id=cell_ids)
            response = self.perform_request(req)

            self.wild_pokemon = self.count_pokemon(response)
        except Exception as e:
            pass
Ejemplo n.º 48
0
 def main(self):
     """Heart of the worker - goes over each point and reports sightings"""
     session = db.Session()
     self.seen_per_cycle = 0
     self.step = 0
     for i, point in enumerate(self.points):
         if not self.running:
             return
         logger.info('Visiting point %d (%s %s)', i, point[0], point[1])
         self.api.set_position(point[0], point[1], 0)
         cell_ids = pgoapi_utils.get_cell_ids(point[0], point[1])
         self.api.set_position(point[0], point[1], 100)
         response_dict = self.api.get_map_objects(
             latitude=pgoapi_utils.f2i(point[0]),
             longitude=pgoapi_utils.f2i(point[1]),
             cell_id=cell_ids)
         if response_dict is False:
             raise CannotProcessStep
         now = time.time()
         map_objects = response_dict['responses'].get('GET_MAP_OBJECTS', {})
         pokemons = []
         if map_objects.get('status') == 1:
             for map_cell in map_objects['map_cells']:
                 for pokemon in map_cell.get('wild_pokemons', []):
                     # Care only about 15 min spawns
                     # 30 and 45 min ones will be just put after
                     # time_till_hidden is below 15 min
                     if pokemon['time_till_hidden_ms'] < 0:
                         continue
                     pokemons.append(self.normalize_pokemon(pokemon, now))
         for raw_pokemon in pokemons:
             db.add_sighting(session, raw_pokemon)
             self.seen_per_cycle += 1
             self.total_seen += 1
         logger.info('Point processed, %d Pokemons seen!', len(pokemons))
         session.commit()
         # Clear error code and let know that there are Pokemon
         if self.error_code and self.seen_per_cycle:
             self.error_code = None
         self.step += 1
         time.sleep(random.uniform(5, 7))
     session.close()
     if self.seen_per_cycle == 0:
         self.error_code = 'NO POKEMON'
Ejemplo n.º 49
0
def map_request(api, position, jitter=False):
    # create scan_location to send to the api based off of position, because tuples aren't mutable
    if jitter:
        # jitter it, just a little bit.
        scan_location = jitterLocation(position)
        log.debug('Jittered to: %f/%f/%f', scan_location[0], scan_location[1], scan_location[2])
    else:
        # Just use the original coordinates
        scan_location = position

    try:
        cell_ids = util.get_cell_ids(scan_location[0], scan_location[1])
        timestamps = [0, ] * len(cell_ids)
        return api.get_map_objects(latitude=f2i(scan_location[0]),
                                   longitude=f2i(scan_location[1]),
                                   since_timestamp_ms=timestamps,
                                   cell_id=cell_ids)
    except Exception as e:
        log.warning('Exception while downloading map: %s', e)
        return False
Ejemplo n.º 50
0
def get_map_objects(api, account, position, no_jitter=False):
    # Create scan_location to send to the api based off of position
    # because tuples aren't mutable.
    if no_jitter:
        # Just use the original coordinates.
        scan_location = position
    else:
        # Jitter it, just a little bit.
        scan_location = jitter_location(position)
        log.debug('Jittered to: %f/%f/%f', scan_location[0], scan_location[1],
                  scan_location[2])

    cell_ids = get_cell_ids(scan_location[0], scan_location[1])
    timestamps = [0, ]*len(cell_ids)
    req = api.create_request()
    req.get_map_objects(
        latitude=f2i(scan_location[0]),
        longitude=f2i(scan_location[1]),
        since_timestamp_ms=timestamps,
        cell_id=cell_ids)
    return send_generic_request(req, account)
Ejemplo n.º 51
0
def catchNearby(self, point):

    if self.Grinding:
        d = geography.getDistance(self.lastpt[0], self.lastpt[1], point[0],
                                  point[1])
        if d >= .14:
            self.lastpt = [self.latitude, self.longitude]
            self.plt.pause(1.5)
        else:
            return False
    else:
        return False
    try:
        cell_ids = util.get_cell_ids(self.latitude, self.longitude)
        timestamps = [
            0,
        ] * len(cell_ids)  # for what purpose?
        theMap = self.player.get_map_objects(latitude=util.f2i(self.latitude),
                                             longitude=util.f2i(
                                                 self.longitude),
                                             since_timestamp_ms=timestamps,
                                             cell_id=cell_ids)
    except:
        logging.warn("Unexpexted response from get_map_objects")
        self.relog()
        return False

    try:
        cells = theMap["responses"]["GET_MAP_OBJECTS"]["map_cells"]
    except:
        logging.warn("Unexpexted response from get_map_objects")
        return False
    for i in cells:
        if "catchable_pokemons" in i:
            print("found some pokemon :")
            for j in i["catchable_pokemons"]:
                print(self.data.PokemonNames[j["pokemon_id"]])
                response = catch(self, j["spawn_point_id"], j["encounter_id"])
                if response == False:
                    break
Ejemplo n.º 52
0
def find_poi(api, lat, lng):
    poi = {'pokemons': {}, 'forts': []}
    step_size = 0.0015
    step_limit = 49
    coords = generate_spiral(lat, lng, step_size, step_limit)
    for coord in coords:
        lat = coord['lat']
        lng = coord['lng']
        api.set_position(lat, lng, 0)

        #get_cellid was buggy -> replaced through get_cell_ids from pokecli
        #timestamp gets computed a different way:
        cell_ids = get_cell_ids(lat, lng)
        timestamps = [
            0,
        ] * len(cell_ids)
        response_dict = api.get_map_objects(latitude=util.f2i(lat),
                                            longitude=util.f2i(lng),
                                            since_timestamp_ms=timestamps,
                                            cell_id=cell_ids)
        if (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']:
                                pokekey = get_key_from_pokemon(pokemon)
                                pokemon['hides_at'] = time.time(
                                ) + pokemon['time_till_hidden_ms'] / 1000
                                poi['pokemons'][pokekey] = pokemon

        # time.sleep(0.51)
        # new dict, binary data
        # print('POI dictionary: \n\r{}'.format(json.dumps(poi, indent=2)))
    print('POI dictionary: \n\r{}'.format(
        pprint.PrettyPrinter(indent=4).pformat(poi)))
    print('Open this in a browser to see the path the spiral search took:')
    print_gmaps_dbug(coords)
Ejemplo n.º 53
0
def gym_request(api, position, gym):
    try:
        log.debug('Getting details for gym @ %f/%f (%fkm away)', gym['latitude'], gym['longitude'], calc_distance(position, [gym['latitude'], gym['longitude']]))
        req = api.create_request()
        x = req.get_gym_details(gym_id=gym['gym_id'],
                                player_latitude=f2i(position[0]),
                                player_longitude=f2i(position[1]),
                                gym_latitude=gym['latitude'],
                                gym_longitude=gym['longitude'])
        x = req.check_challenge()
        x = req.get_hatched_eggs()
        x = req.get_inventory()
        x = req.check_awarded_badges()
        x = req.download_settings()
        x = req.get_buddy_walked()
        x = req.call()
        # Print pretty(x).
        return x

    except Exception as e:
        log.warning('Exception while downloading gym details: %s', e)
        return False
Ejemplo n.º 54
0
    def scan(self):
        ScanMetrics.NUM_STEPS = len(self.scan_config.COVER)
        log.info("Starting scan of {} locations".format(ScanMetrics.NUM_STEPS))

        for i, next_pos in enumerate(self.next_position()):
            log.debug('Scanning step {:d} of {:d}.'.format(
                i, ScanMetrics.NUM_STEPS))
            log.debug('Scan location is {:f}, {:f}'.format(
                next_pos[0], next_pos[1]))

            time.sleep(args.delay / 1000.0)

            # TODO: Add error throttle

            cell_ids = get_cell_ids(next_pos[0], next_pos[1], radius=70)
            timestamps = [
                0,
            ] * len(cell_ids)
            self.api.get_map_objects(latitude=f2i(next_pos[0]),
                                     longitude=f2i(next_pos[1]),
                                     cell_id=cell_ids,
                                     since_timestamp_ms=timestamps,
                                     position=next_pos,
                                     callback=Scanner.callback)

            self.api.download_remote_config_version(position=next_pos,
                                                    platform=1,
                                                    app_version=5500,
                                                    callback=Scanner.callback2)

        while not self.api.is_work_queue_empty():
            # Location change
            if self.scan_config.RESTART:
                log.info("Restarting scan")
                self.api.empty_work_queue()
            else:
                time.sleep(2)
Ejemplo n.º 55
0
    def req_get_map_objects(self):
        """Scans current account location."""
        # Make sure that we don't hammer with GMO requests
        diff = self._last_gmo + self.cfg['scan_delay'] - time.time()
        if diff > 0:
            time.sleep(diff)

        # We jitter here because we need the jittered location NOW
        lat, lng = jitter_location(self.latitude, self.longitude)
        self._api.set_position(lat, lng, self.altitude)

        cell_ids = get_cell_ids(lat, lng)
        timestamps = [0, ] * len(cell_ids)
        responses = self.perform_request(
            lambda req: req.get_map_objects(latitude=f2i(lat),
                                            longitude=f2i(lng),
                                            since_timestamp_ms=timestamps,
                                            cell_id=cell_ids),
            get_inbox=True,
            jitter=False # we already jittered
        )
        self._last_gmo = self._last_request
        self._map_cells = responses['GET_MAP_OBJECTS']['map_cells']
        return responses
Ejemplo n.º 56
0
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.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
    # repeated fields (e.g. cell_id and since_timestamp_ms in get_map_objects) can be provided over a list
    # ----------------------
    cell_ids = get_cell_ids(position[0], position[1])
    timestamps = [
        0,
    ] * len(cell_ids)
    api.get_map_objects(latitude=util.f2i(position[0]),
                        longitude=util.f2i(position[1]),
                        since_timestamp_ms=timestamps,
                        cell_id=cell_ids)

    # spin a fort
    # ----------------------
    #fortid = '<your fortid>'
    #lng = <your longitude>
    #lat = <your latitude>
    #api.fort_search(fort_id=fortid, fort_latitude=lat, fort_longitude=lng, player_latitude=f2i(position[0]), player_longitude=f2i(position[1]))

    # release/transfer a pokemon and get candy for it
    # ----------------------
    #api.release_pokemon(pokemon_id = <your pokemonid>)

    # evolve a pokemon if you have enough candies
    # ----------------------
    #api.evolve_pokemon(pokemon_id = <your pokemonid>)

    # get download settings call
    # ----------------------
    #api.download_settings(hash="05daf51635c82611d1aac95c0b051d3ec088a930")

    # execute the RPC call
    response_dict = api.call()
    print(response_dict)
    print("END_OF_RESPONSE")
Ejemplo n.º 57
0
def find_poi(api, lat, lng, pokeOnly):
    poi = {'pokemons': {}, 'forts': {}}
    step_size = 0.0010
    step_limit = 1
    if pokeOnly:
        step_limit = 49
    coords = generate_spiral(lat, lng, step_size, step_limit)
    for coord in coords:
        time.sleep(0.3)
        lat = coord['lat']
        lng = coord['lng']
        api.set_position(lat, lng, 0)

        cellid = get_cellid(lat, lng)
        print("Getting %s %s"% (lat, lng))
        timestamp = [0,] * len(cellid)

        api.get_map_objects(latitude=f2i(lat), longitude=f2i(lng), since_timestamp_ms=timestamp, cell_id=cellid)

        response_dict = api.call()
        if response_dict['responses']['GET_MAP_OBJECTS']['status'] == 1:
            for map_cell in response_dict['responses']['GET_MAP_OBJECTS']['map_cells']:
                if 'forts' in map_cell:
                    for fort in map_cell['forts']:
                        poi["forts"][fort["id"]] = fort
                if 'wild_pokemons' in map_cell:
                    for pokemon in map_cell['wild_pokemons']:
                        poi['pokemons'][pokemon["encounter_id"]] = pokemon

        # time.sleep(0.51)
    bulk=[]
    for fortid in poi["forts"]:
        fort = poi["forts"][fortid]
        props = {
            "id": fort["id"],
            "LastModifiedMs": fort["last_modified_timestamp_ms"]
            }

        p = {"type": "Point", "coordinates": [fort["longitude"],fort["latitude"]]}
        if "type" in fort:
          props["marker-symbol"] = "circle"
          props["title"] = "PokeStop"
          props["type"] = "pokestop"
          props["lure"] = "lure_info" in fort
        else:
          props["marker-symbol"] = "town-hall"
          props["marker-size"] = "large"
          props["type"] = "gym"

        if "owned_by_team" in fort:
           if fort["owned_by_team"] == BLUE:
             props["marker-color"] = "0000FF"
             props["title"] = "Blue Gym"
           elif fort["owned_by_team"] == RED:
             props["marker-color"] = "FF0000"
             props["title"] = "Red Gym"
           elif fort["owned_by_team"] == YELLOW:
             props["marker-color"] = "FF0000"
             props["title"] = "Yellow Gym"
        else:
            if "lure_info" in fort:
                print("This should have lure info")
                print(fort)
                props["lure"] = True
                props["lure_info"] = fort["lure_info"]
                t = createItem(props["type"], fort["id"], p, props)
                print(t)
            props["marker-color"] = "808080"
        if pokeOnly == False:
            bulk.append(createItem(props["type"], fort["id"], p, props))
            print("adding pokestop")
    
    pokemonsJSON = json.load(
        open("pokenames.json"))
    print("made big")
    for encounter in poi["pokemons"]:
        pokemon = poi["pokemons"][encounter]
        pokeid = pokemon["pokemon_data"]["pokemon_id"]
        pokename = pokemonsJSON[str(pokeid)]
        f = {
          "id": "wild%s" % pokemon["encounter_id"],
          "type": "wild",
          "pokemonNumber": pokeid,
          "TimeTillHiddenMs": pokemon["time_till_hidden_ms"],
          "WillDisappear": pokemon["time_till_hidden_ms"] + int(time.time()*1000),
          "title": "Wild %s" %pokename,
          "marker-color": "FF0000"
          }
        p = {"type": "Point", "coordinates": [pokemon["longitude"], pokemon["latitude"]]}

        if pokeOnly:
            bulk.append(createItem("pokemon", pokemon["encounter_id"], p, f))
    print('POI dictionary: \n\r{}'.format(json.dumps(bulk, indent=2)))
    print(time.time())
    dumpToMap(bulk)
    print(time.time())
    print('Open this in a browser to see the path the spiral search took:')
    print_gmaps_dbug(coords)
Ejemplo n.º 58
0
    def work(self):
        forts = self.get_forts_in_range()

        if not self.should_run() or len(forts) == 0:
            return WorkerResult.SUCCESS

        fort = forts[0]

        lat = fort['latitude']
        lng = fort['longitude']

        details = fort_details(self.bot, fort['id'], lat, lng)
        fort_name = details.get('name', 'Unknown')

        response_dict = self.bot.api.fort_search(
            fort_id=fort['id'],
            fort_latitude=lat,
            fort_longitude=lng,
            player_latitude=f2i(self.bot.position[0]),
            player_longitude=f2i(self.bot.position[1]))

        if ('responses' in response_dict) and ('FORT_SEARCH'
                                               in response_dict['responses']):
            spin_details = response_dict['responses']['FORT_SEARCH']
            spin_result = spin_details.get('result', -1)

            if (spin_result == SPIN_REQUEST_RESULT_SUCCESS) or (
                    spin_result == SPIN_REQUEST_RESULT_INVENTORY_FULL):
                self.bot.softban = False
                experience_awarded = spin_details.get('experience_awarded', 0)
                items_awarded = self.get_items_awarded_from_fort_spinned(
                    response_dict)
                egg_awarded = spin_details.get('pokemon_data_egg', None)

                if egg_awarded is not None:
                    items_awarded[u'Egg'] = egg_awarded['egg_km_walked_target']

                if experience_awarded or items_awarded:
                    awards = ', '.join([
                        "{}x {}".format(items_awarded[x], x)
                        for x in items_awarded if x != u'Egg'
                    ])
                    if egg_awarded is not None:
                        awards += u', {} Egg'.format(
                            egg_awarded['egg_km_walked_target'])
                    self.emit_event(
                        'spun_pokestop',
                        formatted=
                        "Spun pokestop {pokestop}. Experience awarded: {exp}. Items awarded: {items}",
                        data={
                            'pokestop': fort_name,
                            'exp': experience_awarded,
                            'items': awards
                        })
                else:
                    self.emit_event(
                        'pokestop_empty',
                        formatted='Found nothing in pokestop {pokestop}.',
                        data={'pokestop': fort_name})
                with self.bot.database as conn:
                    c = conn.cursor()
                    c.execute(
                        "SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name='pokestop_log'"
                    )
                result = c.fetchone()
                c.execute(
                    "SELECT DISTINCT COUNT(pokestop) FROM pokestop_log WHERE dated >= datetime('now','-1 day')"
                )
                if c.fetchone()[0] >= self.config.get('daily_spin_limit',
                                                      2000):
                    self.emit_event(
                        'spin_limit',
                        formatted=
                        'WARNING! You have reached your daily spin limit')
                    sys.exit(2)
                while True:
                    if result[0] == 1:
                        conn.execute(
                            '''INSERT INTO pokestop_log (pokestop, exp, items) VALUES (?, ?, ?)''',
                            (fort_name, str(experience_awarded),
                             str(items_awarded)))
                        break
                    else:
                        self.emit_event(
                            'pokestop_log',
                            sender=self,
                            level='info',
                            formatted=
                            "pokestop_log table not found, skipping log")
                        break
                pokestop_cooldown = spin_details.get(
                    'cooldown_complete_timestamp_ms')
                self.bot.fort_timeouts.update({fort["id"]: pokestop_cooldown})
                self.bot.recent_forts = self.bot.recent_forts[1:] + [
                    fort['id']
                ]
            elif spin_result == SPIN_REQUEST_RESULT_OUT_OF_RANGE:
                self.emit_event('pokestop_out_of_range',
                                formatted="Pokestop {pokestop} out of range.",
                                data={'pokestop': fort_name})
            elif spin_result == SPIN_REQUEST_RESULT_IN_COOLDOWN_PERIOD:
                pokestop_cooldown = spin_details.get(
                    'cooldown_complete_timestamp_ms')
                if pokestop_cooldown:
                    self.bot.fort_timeouts.update(
                        {fort["id"]: pokestop_cooldown})
                    seconds_since_epoch = time.time()
                    minutes_left = format_time((pokestop_cooldown / 1000) -
                                               seconds_since_epoch)
                    self.emit_event(
                        'pokestop_on_cooldown',
                        formatted=
                        "Pokestop {pokestop} on cooldown. Time left: {minutes_left}.",
                        data={
                            'pokestop': fort_name,
                            'minutes_left': minutes_left
                        })
            else:
                self.emit_event('unknown_spin_result',
                                formatted="Unknown spint result {status_code}",
                                data={'status_code': str(spin_result)})
            if 'chain_hack_sequence_number' in response_dict['responses'][
                    'FORT_SEARCH']:
                action_delay(self.spin_wait_min, self.spin_wait_max)
                return response_dict['responses']['FORT_SEARCH'][
                    'chain_hack_sequence_number']
            else:
                self.emit_event(
                    'pokestop_searching_too_often',
                    formatted="Possibly searching too often, take a rest.")
                if spin_result == 1 and not items_awarded and not experience_awarded and not pokestop_cooldown:
                    self.bot.softban = True
                    self.emit_event('softban',
                                    formatted='Probably got softban.')
                    with self.bot.database as conn:
                        c = conn.cursor()
                        c.execute(
                            "SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name='softban_log'"
                        )
                    result = c.fetchone()

                    if result[0] == 1:
                        source = str("PokemonCatchWorker")
                        status = str("Possible Softban")
                        conn.execute(
                            '''INSERT INTO softban_log (status, source) VALUES (?, ?)''',
                            (status, source))
                    else:
                        self.emit_event(
                            'softban_log',
                            sender=self,
                            level='info',
                            formatted=
                            "softban_log table not found, skipping log")

                self.bot.fort_timeouts[fort["id"]] = (
                    time.time() + 300) * 1000  # Don't spin for 5m

                return WorkerResult.ERROR
        action_delay(self.spin_wait_min, self.spin_wait_max)

        if len(forts) > 1:
            return WorkerResult.RUNNING

        return WorkerResult.SUCCESS
Ejemplo n.º 59
0
 def main(self):
     """Heart of the worker - goes over each point and reports sightings"""
     session = db.Session()
     self.seen_per_cycle = 0
     self.step = 0
     for i, point in enumerate(self.points):
         if not self.running:
             return
         logger.info('Visiting point %d (%s %s)', i, point[0], point[1])
         self.api.set_position(point[0], point[1], 0)
         cell_ids = pgoapi_utils.get_cell_ids(point[0], point[1])
         self.api.set_position(point[0], point[1], 100)
         response_dict = self.api.get_map_objects(
             latitude=pgoapi_utils.f2i(point[0]),
             longitude=pgoapi_utils.f2i(point[1]),
             cell_id=cell_ids)
         if not isinstance(response_dict, dict):
             logger.warning('Response: %s', response_dict)
             raise MalformedResponse
         if response_dict['status_code'] == 3:
             logger.warning('Account banned')
             raise BannedAccount
         responses = response_dict.get('responses')
         if not responses:
             logger.warning('Response: %s', response_dict)
             raise MalformedResponse
         map_objects = response_dict['responses'].get('GET_MAP_OBJECTS', {})
         pokemons = []
         forts = []
         if map_objects.get('status') == 1:
             for map_cell in map_objects['map_cells']:
                 for pokemon in map_cell.get('wild_pokemons', []):
                     # Care only about 15 min spawns
                     # 30 and 45 min ones (negative) will be just put after
                     # time_till_hidden is below 15 min
                     # As of 2016.08.14 we don't know what values over
                     # 60 minutes are, so ignore them too
                     invalid_time = (
                         pokemon['time_till_hidden_ms'] < 0
                         or pokemon['time_till_hidden_ms'] > 900000)
                     if invalid_time:
                         continue
                     pokemons.append(
                         self.normalize_pokemon(
                             pokemon, map_cell['current_timestamp_ms']))
                 for fort in map_cell.get('forts', []):
                     if not fort.get('enabled'):
                         continue
                     if fort.get('type') == 1:  # probably pokestops
                         continue
                     forts.append(self.normalize_fort(fort))
         for raw_pokemon in pokemons:
             db.add_sighting(session, raw_pokemon)
             self.seen_per_cycle += 1
             self.total_seen += 1
         session.commit()
         for raw_fort in forts:
             db.add_fort_sighting(session, raw_fort)
         # Commit is not necessary here, it's done by add_fort_sighting
         logger.info(
             'Point processed, %d Pokemons and %d forts seen!',
             len(pokemons),
             len(forts),
         )
         # Clear error code and let know that there are Pokemon
         if self.error_code and self.seen_per_cycle:
             self.error_code = None
         self.step += 1
         time.sleep(random.uniform(config.SCAN_DELAY,
                                   config.SCAN_DELAY + 2))
     session.close()
     if self.seen_per_cycle == 0:
         self.error_code = 'NO POKEMON'
Ejemplo n.º 60
0
    def drop_pokemon_in_gym(self, gym, current_pokemons):
        self.pokemons = inventory.pokemons().all()
        self.fort_pokemons = [p for p in self.pokemons if p.in_fort]
        self.pokemons = [p for p in self.pokemons if not p.in_fort]
        close_gyms = self.get_gyms_in_range()

        empty_gym = False

        for pokemon in self.fort_pokemons:
            if pokemon.fort_id == gym["id"]:
                self.logger.info("We are already in this gym!")
                if pokemon.fort_id not in self.dropped_gyms:
                    self.dropped_gyms.append(pokemon.fort_id)
                self.recent_gyms.append(gym["id"])
                return WorkerResult.SUCCESS

        for g in close_gyms:
            if g["id"] == gym["id"]:
                if 'owned_by_team' in g:
                    self.logger.info(
                        "Expecting team: %s it is: %s" %
                        (self.bot.player_data['team'], g["owned_by_team"]))
                    if g["owned_by_team"] is not self.team:
                        self.logger.info("Can't drop in a enemy gym!")
                        self.recent_gyms.append(gym["id"])
                        return WorkerResult.SUCCESS
                else:
                    #self.logger.info("Empty gym?? %s" % g)
                    gym_details = self.get_gym_details(gym)
                    #self.logger.info("Details: %s" % gym_details)
                    empty_gym = True
                    if not gym_details or gym_details == {}:
                        self.logger.info(
                            "No details for this Gym? Blacklisting!")
                        self.blacklist.append(gym["id"])
                        return WorkerResult.SUCCESS

        # Check for raid
        if 'raid_info' in gym:
            raid_info = gym["raid_info"]
            raid_starts = datetime.fromtimestamp(
                int(raid_info["raid_battle_ms"]) / 1e3)
            raid_ends = datetime.fromtimestamp(
                int(raid_info["raid_end_ms"]) / 1e3)
            self.logger.info("Raid starts: %s" %
                             raid_starts.strftime('%Y-%m-%d %H:%M:%S.%f'))
            self.logger.info("Raid ends: %s" %
                             raid_ends.strftime('%Y-%m-%d %H:%M:%S.%f'))
            t = datetime.today()

            if raid_starts < datetime.now():
                self.logger.info("Active raid?")
                if raid_ends < datetime.now():
                    self.logger.info("No need to wait.")
                elif (raid_ends - t).seconds > 600:
                    self.logger.info(
                        "Need to wait more than 10 minutes, skipping")
                    self.destination = None
                    self.recent_gyms.append(gym["id"])
                    self.raid_gyms[gym["id"]] = raid_ends
                    return WorkerResult.SUCCESS
                else:
                    first_time = False
                    while raid_ends > datetime.now():
                        raid_ending = (raid_ends - datetime.today()).seconds
                        sleep_m, sleep_s = divmod(raid_ending, 60)
                        sleep_h, sleep_m = divmod(sleep_m, 60)
                        sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m,
                                                        sleep_s)
                        if not first_time:
                            # Clear the last log line!
                            stdout.write("\033[1A\033[0K\r")
                            stdout.flush()
                        first_time = True
                        self.logger.info("Waiting for %s for raid to end..." %
                                         sleep_hms)
                        if raid_ending > 20:
                            sleep(20)
                        else:
                            sleep(raid_ending)
                            break
            else:
                self.logger.info("Raid has not begun yet!")

        if 'same_team_deploy_lockout_end_ms' in gym:
            # self.logger.info("%f" % gym["same_team_deploy_lockout_end_ms"])
            org_time = int(gym["same_team_deploy_lockout_end_ms"]) / 1e3
            lockout_time = datetime.fromtimestamp(org_time)
            t = datetime.today()

            if lockout_time > datetime.now():
                self.logger.info("Lockout time: %s" %
                                 lockout_time.strftime('%Y-%m-%d %H:%M:%S.%f'))
                first_time = False
                while lockout_time > datetime.now():
                    lockout_ending = (lockout_time - datetime.today()).seconds
                    sleep_m, sleep_s = divmod(lockout_ending, 60)
                    sleep_h, sleep_m = divmod(sleep_m, 60)
                    sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s)
                    if not first_time:
                        # Clear the last log line!
                        stdout.write("\033[1A\033[0K\r")
                        stdout.flush()
                    first_time = True
                    self.logger.info(
                        "Waiting for %s deployment lockout to end..." %
                        sleep_hms)
                    if lockout_ending > 40:
                        sleep(40)
                        break
                    else:
                        sleep(lockout_ending)
                        break

        #FortDeployPokemon
        # self.logger.info("Trying to deploy Pokemon in gym: %s" % gym)
        gym_details = self.get_gym_details(gym)
        # self.logger.info("Gym details: %s" % gym_details)
        fort_pokemon = self._get_best_pokemon(current_pokemons)
        pokemon_id = fort_pokemon.unique_id
        # self.logger.info("Trying to deploy %s (%s)" % (fort_pokemon, pokemon_id))
        # self.logger.info("Gym in control by %s. I am on team %s" % (gym["owned_by_team"], self.bot.player_data['team']))

        request = self.bot.api.create_request()
        request.gym_deploy(fort_id=gym["id"],
                           pokemon_id=pokemon_id,
                           player_lat_degrees=f2i(self.bot.position[0]),
                           player_lng_degrees=f2i(self.bot.position[1]))
        # self.logger.info("Req: %s" % request)
        response_dict = request.call()
        # self.logger.info("Called deploy pokemon: %s" % response_dict)

        if ('responses' in response_dict) and ('GYM_DEPLOY'
                                               in response_dict['responses']):
            deploy = response_dict['responses']['GYM_DEPLOY']
            result = response_dict.get('status_code', -1)
            self.recent_gyms.append(gym["id"])
            # self.logger.info("Status: %s" % result)
            if result == 1:
                self.dropped_gyms.append(gym["id"])
                self.fort_pokemons.append(fort_pokemon)
                gym_details = self.get_gym_details(gym)
                # SUCCES
                #self.logger.info("We deployed %s (%s CP) in the gym! We now have %s Pokemon in gyms!" % (fort_pokemon.name, fort_pokemon.cp, len(self.dropped_gyms)))
                self.emit_event(
                    'deployed_pokemon',
                    formatted=("We deployed %s (%s CP) in the gym %s!!" %
                               (fort_pokemon.name, fort_pokemon.cp,
                                gym_details["name"])),
                    data={
                        'gym_id': gym['id'],
                        'pokemon_id': pokemon_id
                    })
                return WorkerResult.SUCCESS
            elif result == 2:
                #ERROR_ALREADY_HAS_POKEMON_ON_FORT
                self.logger.info('ERROR_ALREADY_HAS_POKEMON_ON_FORT')
                self.dropped_gyms.append(gym["id"])
                return WorkerResult.ERROR
            elif result == 3:
                #ERROR_OPPOSING_TEAM_OWNS_FORT
                self.logger.info('ERROR_OPPOSING_TEAM_OWNS_FORT')
                return WorkerResult.ERROR
            elif result == 4:
                #ERROR_FORT_IS_FULL
                self.logger.info('ERROR_FORT_IS_FULL')
                return WorkerResult.ERROR
            elif result == 5:
                #ERROR_NOT_IN_RANGE
                self.logger.info('ERROR_NOT_IN_RANGE')
                return WorkerResult.ERROR
            elif result == 6:
                #ERROR_PLAYER_HAS_NO_TEAM
                self.logger.info('ERROR_PLAYER_HAS_NO_TEAM')
                return WorkerResult.ERROR
            elif result == 7:
                #ERROR_POKEMON_NOT_FULL_HP
                self.logger.info('ERROR_POKEMON_NOT_FULL_HP')
                return WorkerResult.ERROR
            elif result == 8:
                #ERROR_PLAYER_BELOW_MINIMUM_LEVEL
                self.logger.info('ERROR_PLAYER_BELOW_MINIMUM_LEVEL')
                return WorkerResult.ERROR
            elif result == 8:
                #ERROR_POKEMON_IS_BUDDY
                self.logger.info('ERROR_POKEMON_IS_BUDDY')
                return WorkerResult.ERROR