예제 #1
0
    def get_nearest_fort_on_the_way(self, pokemon):
        forts = self.bot.get_forts(order_by_distance=True)

        # Remove stops that are still on timeout
        forts = filter(lambda x: x["id"] not in self.bot.fort_timeouts, forts)
        i = 0
        while i < len(forts):
            ratio = float(self.config.get('max_extra_dist_fort', 20))
            dist_self_to_fort = distance(self.bot.position[0],
                                         self.bot.position[1],
                                         forts[i]['latitude'],
                                         forts[i]['longitude'])
            dist_fort_to_pokemon = distance(pokemon['latitude'],
                                            pokemon['longitude'],
                                            forts[i]['latitude'],
                                            forts[i]['longitude'])
            total_dist = dist_self_to_fort + dist_fort_to_pokemon
            dist_self_to_pokemon = distance(self.bot.position[0],
                                            self.bot.position[1],
                                            pokemon['latitude'],
                                            pokemon['longitude'])
            if total_dist < (1 + (ratio / 100)) * dist_self_to_pokemon:
                i += 1
            else:
                del forts[i]
            # Return nearest fort if there are remaining
        if len(forts):
            return forts[0]
        else:
            return None
예제 #2
0
    def work(self):
        point = self.points[self.ptr]
        self.cnt += 1

        if self.bot.config.walk > 0:
            step_walker = StepWalker(
                self.bot,
                self.bot.config.walk,
                point['lat'],
                point['lng']
            )

            dist = distance(
                self.bot.api._position_lat,
                self.bot.api._position_lng,
                point['lat'],
                point['lng']
            )

            if self.cnt == 1:
                self.emit_event(
                    'position_update',
                    formatted="Walking from {last_position} to {current_position} ({distance} {distance_unit})",
                    data={
                        'last_position': self.bot.position,
                        'current_position': (point['lat'], point['lng'], 0),
                        'distance': dist,
                        'distance_unit': 'm'
                    }
                )

            if step_walker.step():
                step_walker = None
        else:
            self.bot.api.set_position(point['lat'], point['lng'])

        if distance(
                    self.bot.api._position_lat,
                    self.bot.api._position_lng,
                    point['lat'],
                    point['lng']
                ) <= 1 or (self.bot.config.walk > 0 and step_walker == None):
            if self.ptr + self.direction >= len(self.points) or self.ptr + self.direction <= -1:
                self.direction *= -1
            if len(self.points) != 1:
                self.ptr += self.direction
            else:
                self.ptr = 0
            self.cnt = 0

        return [point['lat'], point['lng']]
예제 #3
0
    def work(self):
        if not self.should_run():
            return

        forts = self.bot.get_forts(order_by_distance=True)

        if len(forts) == 0:
            return

        fort_distance = distance(
            self.bot.position[0],
            self.bot.position[1],
            forts[0]['latitude'],
            forts[0]['longitude'],
        )

        if fort_distance > Constants.MAX_DISTANCE_FORT_IS_REACHABLE:
            MoveToFort(self.bot, config=None).work()
            self.bot.recent_forts = self.bot.recent_forts[0:-1]
            if forts[0]['id'] in self.bot.fort_timeouts:
                del self.bot.fort_timeouts[forts[0]['id']]
            return WorkerResult.RUNNING
        else:
            spins = randint(50,60)
            self.emit_event(
                'softban_fix',
                formatted='Fixing softban.'
            )
            for i in xrange(spins):
                self.spin_fort(forts[0])
            self.bot.softban = False
            self.emit_event(
                'softban_fix_done',
                formatted='Softban should be fixed'
            )
예제 #4
0
    def work(self):
        if not self.should_run():
            return

        forts = self.bot.get_forts(order_by_distance=True)

        if len(forts) == 0:
            logger.log('Found no forts to reset softban, skipping...', 'red')
            return
        logger.log('Got softban, fixing...', 'yellow')

        fort_distance = distance(
            self.bot.position[0],
            self.bot.position[1],
            forts[0]['latitude'],
            forts[0]['longitude'],
        )

        if fort_distance > Constants.MAX_DISTANCE_FORT_IS_REACHABLE:
            MoveToFort(self.bot, config=None).work()
            self.bot.recent_forts = self.bot.recent_forts[0:-1]
            if forts[0]['id'] in self.bot.fort_timeouts:
                del self.bot.fort_timeouts[forts[0]['id']]
            return WorkerResult.RUNNING
        else:
            spins = randint(50,60)
            logger.log('Starting %s spins...' % spins)
            for i in xrange(spins):
                if (i + 1) % 10 == 0:
                    logger.log('Spin #{}'.format(str(i+1)))
                self.spin_fort(forts[0])
            self.bot.softban = False
            logger.log('Softban should be fixed.')
    def update_map_location(self):
        if not self.config['update_map']:
            return
        try:
            req = requests.get('{}/loc'.format(self.config['address']))
        except requests.exceptions.ConnectionError:
            logger.log('Could not reach PokemonGo-Map Server', 'red')
            return

        try:
            loc_json = req.json()
        except ValueError:
            return log.logger('Map location data was not valid', 'red')


        dist = distance(
            self.bot.position[0],
            self.bot.position[1],
            loc_json['lat'],
            loc_json['lng']
        )

        # update map when 500m away from center and last update longer than 2 minutes away
        now = int(time.time())
        if dist > 500 and now - self.last_map_update > 2 * 60:
            requests.post('{}/next_loc?lat={}&lon={}'.format(self.config['address'], self.bot.position[0], self.bot.position[1]))
            logger.log('Updated PokemonGo-Map position')
            self.last_map_update = now
예제 #6
0
    def get_cluster(self, forts, circle):
        forts_in_circle = [f for f in forts if self.dist(circle, f) <= circle[2]]
        count = len(forts_in_circle)
        lured = len([f for f in forts_in_circle if "active_fort_modifier" in f])
        dst = distance(self.bot.position[0], self.bot.position[1], circle[0], circle[1])

        return (circle[0], circle[1], lured, count, dst)
예제 #7
0
    def __init__(self, bot, dest_lat, dest_lng):
        self.bot = bot
        self.api = bot.api

        self.initLat, self.initLng = self.bot.position[0:2]

        self.dist = distance(
            self.initLat,
            self.initLng,
            dest_lat,
            dest_lng
        )

        self.alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
        self.speed = uniform(self.bot.config.walk_min, self.bot.config.walk_max)

        self.destLat = dest_lat
        self.destLng = dest_lng
        self.totalDist = max(1, self.dist)

        if self.speed == 0:
            raise Exception("Walking speed cannot be 0, change your walking speed higher than 1!")
        else:
            self.steps = (self.dist + 0.0) / (self.speed + 0.0)

        if self.dist < self.speed or int(self.steps) <= 1:
            self.dLat = 0
            self.dLng = 0
            self.magnitude = 0
        else:
            self.dLat = (dest_lat - self.initLat) / int(self.steps)
            self.dLng = (dest_lng - self.initLng) / int(self.steps)
            self.magnitude = self._pythagorean(self.dLat, self.dLng)
예제 #8
0
    def __init__(self, bot, dest_lat, dest_lng):
        self.bot = bot
        self.api = bot.api

        self.initLat, self.initLng = self.bot.position[0:2]

        self.dist = distance(self.initLat, self.initLng, dest_lat, dest_lng)

        self.alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
        self.speed = uniform(self.bot.config.walk_min,
                             self.bot.config.walk_max)

        self.destLat = dest_lat
        self.destLng = dest_lng
        self.totalDist = max(1, self.dist)

        if self.speed == 0:
            raise Exception(
                "Walking speed cannot be 0, change your walking speed higher than 1!"
            )
        else:
            self.steps = (self.dist + 0.0) / (self.speed + 0.0)

        if self.dist < self.speed or int(self.steps) <= 1:
            self.dLat = 0
            self.dLng = 0
            self.magnitude = 0
        else:
            self.dLat = (dest_lat - self.initLat) / int(self.steps)
            self.dLng = (dest_lng - self.initLng) / int(self.steps)
            self.magnitude = self._pythagorean(self.dLat, self.dLng)
예제 #9
0
    def work(self):
        point = self.points[self.ptr]
        lat = float(point['lat'])
        lng = float(point['lng'])

        if self.bot.config.walk > 0:
            step_walker = StepWalker(self.bot, self.bot.config.walk, lat, lng)

            is_at_destination = False
            if step_walker.step():
                is_at_destination = True

        else:
            self.bot.api.set_position(lat, lng)

        dist = distance(self.bot.api._position_lat, self.bot.api._position_lng,
                        lat, lng)

        if dist <= 1 or (self.bot.config.walk > 0 and is_at_destination):
            if (self.ptr + 1) == len(self.points):
                self.ptr = 0
                if self.path_mode == 'linear':
                    self.points = list(reversed(self.points))
            else:
                self.ptr += 1

        return [lat, lng]
예제 #10
0
    def __init__(self, bot, dest_lat, dest_lng):
        super(PolylineWalker, self).__init__(bot, dest_lat, dest_lng)

        self.actual_pos = tuple(self.api.get_position()[:2])

        self.dist = distance(self.bot.position[0], self.bot.position[1],
                             dest_lat, dest_lng)
예제 #11
0
    def work(self):
        if not self.should_run():
            return

        forts = self.bot.get_forts(order_by_distance=True)

        if len(forts) == 0:
            return

        fort_distance = distance(
            self.bot.position[0],
            self.bot.position[1],
            forts[0]['latitude'],
            forts[0]['longitude'],
        )

        if fort_distance > Constants.MAX_DISTANCE_FORT_IS_REACHABLE:
            MoveToFort(self.bot, config=None).work()
            self.bot.recent_forts = self.bot.recent_forts[0:-1]
            if forts[0]['id'] in self.bot.fort_timeouts:
                del self.bot.fort_timeouts[forts[0]['id']]
            return WorkerResult.RUNNING
        else:
            spins = randint(50, 60)
            self.emit_event('softban_fix', formatted='Fixing softban.')
            for i in xrange(spins):
                self.spin_fort(forts[0])
            self.bot.softban = False
            self.emit_event('softban_fix_done',
                            formatted='Softban should be fixed')
예제 #12
0
    def update_map_location(self):
        if not self.config['update_map']:
            return
        try:
            req = requests.get('{}/loc'.format(self.config['address']))
        except requests.exceptions.ConnectionError:
            self._emit_failure('Could not update trainer location '
                               'PokemonGo-Map: {}. Is it running?'.format(
                                   self.config['address']))
            return

        try:
            loc_json = req.json()
        except ValueError:
            err = 'Map location data was not valid'
            self._emit_failure(err)
            return log.logger(err, 'red')

        dist = distance(self.bot.position[0], self.bot.position[1],
                        loc_json['lat'], loc_json['lng'])

        # update map when 500m away from center and last update longer than 2 minutes away
        now = int(time.time())
        if (dist > UPDATE_MAP_MIN_DISTANCE_METERS
                and now - self.last_map_update > UPDATE_MAP_MIN_TIME_SEC):
            requests.post('{}/next_loc?lat={}&lon={}'.format(
                self.config['address'], self.bot.position[0],
                self.bot.position[1]))
            self.emit_event('move_to_map_pokemon_updated_map',
                            formatted='Updated PokemonGo-Map to {lat}, {lon}',
                            data={
                                'lat': self.bot.position[0],
                                'lon': self.bot.position[1]
                            })
            self.last_map_update = now
예제 #13
0
    def get_pokemon_from_map(self):
        try:
            req = requests.get('{}/raw_data?gyms=false&scanned=false'.format(
                self.config['address']))
        except requests.exceptions.ConnectionError:
            self._emit_failure(
                'Could not get Pokemon data from PokemonGo-Map: '
                '{}. Is it running?'.format(self.config['address']))
            return []

        try:
            raw_data = req.json()
        except ValueError:
            self._emit_failure('Map data was not valid')
            return []

        pokemon_list = []
        now = int(time.time())

        for pokemon in raw_data['pokemons']:
            try:
                pokemon['encounter_id'] = long(
                    base64.b64decode(pokemon['encounter_id']))
            except TypeError:
                self._emit_failure('base64 error: {}'.format(
                    pokemon['encounter_id']))
                continue
            pokemon['spawn_point_id'] = pokemon['spawnpoint_id']
            pokemon['disappear_time'] = int(pokemon['disappear_time'] / 1000)
            pokemon['name'] = self.pokemon_data[pokemon['pokemon_id'] -
                                                1]['Name']
            pokemon['is_vip'] = pokemon['name'] in self.bot.config.vips

            if pokemon['name'] not in self.config[
                    'catch'] and not pokemon['is_vip']:
                continue

            if pokemon['disappear_time'] < (now + self.config['min_time']):
                continue

            if self.was_caught(pokemon):
                continue

            pokemon['priority'] = self.config['catch'].get(pokemon['name'], 0)

            pokemon['dist'] = distance(
                self.bot.position[0],
                self.bot.position[1],
                pokemon['latitude'],
                pokemon['longitude'],
            )

            if pokemon['dist'] > self.config[
                    'max_distance'] and not self.config['snipe']:
                continue

            pokemon_list.append(pokemon)

        return pokemon_list
예제 #14
0
    def __init__(self, bot, dest_lat, dest_lng):
        super(PolylineWalker, self).__init__(bot, dest_lat, dest_lng)
        self.polyline_walker = PolylineObjectHandler.cached_polyline(
            tuple(self.api.get_position()[:2]), (self.destLat, self.destLng),
            self.speed)

        self.dist = distance(self.bot.position[0], self.bot.position[1],
                             dest_lat, dest_lng)
예제 #15
0
    def work(self):
        last_lat, last_lng, last_alt = self.bot.api.get_position()

        point = self.points[self.ptr]
        self.cnt += 1

        dist = distance(
            last_lat,
            last_lng,
            point['lat'],
            point['lng']
        )

        alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
        if self.bot.config.walk_max > 0:
            step_walker = StepWalker(
                self.bot,
                point['lat'],
                point['lng']
            )

            if self.cnt == 1:
                self.emit_event(
                    'position_update',
                    formatted="Walking from {last_position} to {current_position} ({distance} {distance_unit})",
                    data={
                        'last_position': (last_lat, last_lng, last_alt),
                        'current_position': (point['lat'], point['lng'], alt),
                        'distance': dist,
                        'distance_unit': 'm'
                    }
                )

            if step_walker.step():
                step_walker = None
        else:
            self.bot.api.set_position(point['lat'], point['lng'], alt)
            self.emit_event(
                'position_update',
                formatted="Teleported from {last_position} to {current_position} ({distance} {distance_unit})",
                data={
                    'last_position': (last_lat, last_lng, last_alt),
                    'current_position': (point['lat'], point['lng'], alt),
                    'distance': dist,
                    'distance_unit': 'm'
                }
            )

        if dist <= 1 or (self.bot.config.walk_min > 0 and step_walker == None):
            if self.ptr + self.direction >= len(self.points) or self.ptr + self.direction <= -1:
                self.direction *= -1
            if len(self.points) != 1:
                self.ptr += self.direction
            else:
                self.ptr = 0
            self.cnt = 0

        return [point['lat'], point['lng']]
예제 #16
0
    def get_pokemon_from_map(self):
        try:
            req = requests.get('{}/{}?gyms=false&scanned=false'.format(self.config['address'], self.map_path))
        except requests.exceptions.ConnectionError:
            self._emit_failure('Could not get Pokemon data from PokemonGo-Map: '
                               '{}. Is it running?'.format(
                                   self.config['address']))
            return []

        try:
            raw_data = req.json()
        except ValueError:
            self._emit_failure('Map data was not valid')
            return []

        pokemon_list = []
        now = int(time.time())

        for pokemon in raw_data['pokemons']:
            try:
                pokemon['encounter_id'] = long(base64.b64decode(pokemon['encounter_id']))
            except:
                self._emit_failure('base64 error: {}'.format(pokemon['encounter_id']))
                continue
            pokemon['spawn_point_id'] = pokemon['spawnpoint_id']
            pokemon['disappear_time'] = int(pokemon['disappear_time'] / 1000)
            pokemon['name'] = self.pokemon_data[pokemon['pokemon_id'] - 1]['Name']
            pokemon['is_vip'] = pokemon['name'] in self.bot.config.vips

            if pokemon['name'] not in self.config['catch'] and not pokemon['is_vip']:
                continue

            if self.was_caught(pokemon):
                continue

            pokemon['priority'] = self.config['catch'].get(pokemon['name'], 0)

            pokemon['dist'] = distance(
                self.bot.position[0],
                self.bot.position[1],
                pokemon['latitude'],
                pokemon['longitude'],
            )

            if pokemon['dist'] > self.config['max_sniping_distance'] and self.config['snipe']:
                continue

            if pokemon['dist'] > self.config['max_walking_distance'] and not self.config['snipe']:
                continue

            # pokemon not reachable with mean walking speed (by config)
            mean_walk_speed = (self.bot.config.walk_max + self.bot.config.walk_min) / 2
            if pokemon['dist'] > ((pokemon['disappear_time'] - now) * mean_walk_speed) and not self.config['snipe']:
                continue

            pokemon_list.append(pokemon)

        return pokemon_list
예제 #17
0
    def work(self):
        point = self.points[self.ptr]
        self.cnt += 1

        if self.bot.config.walk > 0:
            step_walker = StepWalker(
                self.bot,
                self.bot.config.walk,
                point['lat'],
                point['lng']
            )

            dist = distance(
                self.bot.api._position_lat,
                self.bot.api._position_lng,
                point['lat'],
                point['lng']
            )

            if self.cnt == 1:
                logger.log(
                    'Walking from ' + str((self.bot.api._position_lat,
                    self.bot.api._position_lng)) + " to " + str([point['lat'], point['lng']]) + " " + format_dist(dist,
                                                                                                   self.bot.config.distance_unit))

            if step_walker.step():
                step_walker = None
        else:
            self.bot.api.set_position(point['lat'], point['lng'])

        if distance(
                    self.bot.api._position_lat,
                    self.bot.api._position_lng,
                    point['lat'],
                    point['lng']
                ) <= 1 or (self.bot.config.walk > 0 and step_walker == None):
            if self.ptr + self.direction >= len(self.points) or self.ptr + self.direction <= -1:
                self.direction *= -1
            if len(self.points) != 1:
                self.ptr += self.direction
            else:
                self.ptr = 0
            self.cnt = 0

        return [point['lat'], point['lng']]
    def pokemons_parser(self, pokemon_list):
        pokemons = []
        if not pokemon_list:
            return pokemons

        now = int(time.time())

        for pokemon in pokemon_list:
            try:
                disappear = int(pokemon.get('expiration_timestamp_ms', 0) / 1000) or int(pokemon.get('disappear_time', 0) / 1000)

                pokemon['encounter_id'] = pokemon.get('encounter_id', '')
                pokemon['spawn_point_id'] = pokemon.get('spawn_point_id', '') or pokemon.get('spawnpoint_id', '')
                pokemon['iv'] = pokemon.get('iv', 0)
                pokemon['disappear_time'] = disappear
                pokemon['name'] = self.pokemon_data[pokemon['pokemon_id'] - 1]['Name']
                pokemon['is_vip'] = pokemon['name'] in self.bot.config.vips
            except TypeError:
                continue
            except KeyError:
                continue
            if now > pokemon['disappear_time']:
                continue

            if pokemon['name'] not in self.config['catch'] and not pokemon['is_vip']:
                if self.debug:
                    self._emit_failure("Not catching {}".format(pokemon['name']))
                continue

            if self.is_inspected(pokemon):
                if self.debug:
                    self._emit_log('Skipped {} because it was already catch or does not exist'.format(pokemon['name']))
                continue

            pokemon['priority'] = self.config['catch'].get(pokemon['name'], 0)
            pokemon['dist'] = distance(
                self.bot.position[0],
                self.bot.position[1],
                pokemon['latitude'],
                pokemon['longitude']
            )

            # If distance to pokemon greater than the max_sniping_distance, then ignore regardless of "snipe" setting
            if pokemon['dist'] > self.config.get('max_sniping_distance', 10000):
                continue

            # If distance bigger than walking distance, ignore if sniping is not active
            if pokemon['dist'] > self.config.get('max_walking_distance', 1000) and not self.snip_enabled:
                continue

            # if pokemon not reachable with mean walking speed (by config)
            mean_walk_speed = (self.bot.config.walk_max + self.bot.config.walk_min) / 2
            if pokemon['dist'] > ((pokemon['disappear_time'] - now) * mean_walk_speed) and not self.snip_enabled:
                continue
            pokemons.append(pokemon)

        return pokemons
예제 #19
0
    def work(self):
        last_lat = self.bot.api._position_lat
        last_lng = self.bot.api._position_lng
        last_alt = self.bot.api._position_alt

        point = self.points[self.ptr]
        lat = float(point['lat'])
        lng = float(point['lng'])
        alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
        if 'alt' in point:
            alt = float(point['alt'])

        if self.bot.config.walk_max > 0:
            step_walker = StepWalker(self.bot, lat, lng)

            is_at_destination = False
            if step_walker.step():
                is_at_destination = True

        else:
            self.bot.api.set_position(lat, lng, alt)

        dist = distance(last_lat, last_lng, lat, lng)

        self.emit_event(
            'position_update',
            formatted=
            "Walking from {last_position} to {current_position}, distance left: ({distance} {distance_unit}) ..",
            data={
                'last_position': (last_lat, last_lng, last_alt),
                'current_position': (lat, lng, alt),
                'distance': dist,
                'distance_unit': 'm'
            })

        if dist <= 1 or (self.bot.config.walk_min > 0 and is_at_destination):
            if (self.ptr + 1) == len(self.points):
                self.ptr = 0
                if self.path_mode == 'linear':
                    self.points = list(reversed(self.points))
                if self.number_lap_max >= 0:
                    self.number_lap += 1
                    self.emit_event(
                        'path_lap_update',
                        formatted=
                        "number lap : {number_lap} / {number_lap_max}",
                        data={
                            'number_lap': str(self.number_lap),
                            'number_lap_max': str(self.number_lap_max)
                        })
                    if self.number_lap >= self.number_lap_max:
                        self.endLaps()
            else:
                self.ptr += 1

        return [lat, lng]
예제 #20
0
    def work(self):
        if not self.enabled:
            return WorkerResult.SUCCESS

        now = time.time()

        if now < self.move_until:
            return WorkerResult.SUCCESS

        if 0 < self.stay_until < now:
            self.destination = None
            self.stay_until = 0
            self.move_until = now + self.config_moving_time

            if self.config_moving_time > 0:
                return WorkerResult.SUCCESS

        if self.destination is None:
            forts = self.get_forts()
            forts_clusters = self.get_forts_clusters(forts)

            if len(forts_clusters) > 0:
                self.destination = forts_clusters[0]
                self.logger.info("New destination at %s meters: %s forts, %s lured.", int(self.destination[4]), self.destination[3], self.destination[2])
            else:
                # forts = [f for f in forts if f.get("cooldown_complete_timestamp_ms", 0) < now * 1000]
                # fort = min(forts, key=lambda f: self.dist(self.bot.position, f))
                # self.destination = (fort["latitude"], fort["longitude"])
                return WorkerResult.SUCCESS

        if (now - self.last_position_update) < 1:
            return WorkerResult.RUNNING
        else:
            self.last_position_update = now

        if self.stay_until >= now:
            lat = self.destination[0] + random_lat_long_delta() / 5
            lon = self.destination[1] + random_lat_long_delta() / 5
            alt = self.walker.pol_alt + random_alt_delta() / 2
            self.bot.api.set_position(lat, lon, alt)
        else:
            self.walker = PolylineWalker(self.bot, self.destination[0], self.destination[1])
            self.walker.step()

            dst = distance(self.bot.position[0], self.bot.position[1], self.destination[0], self.destination[1])

            if dst < 1:
                forts = self.get_forts()
                circle = (self.destination[0], self.destination[1], Constants.MAX_DISTANCE_FORT_IS_REACHABLE)
                cluster = self.get_cluster(forts, circle)

                self.logger.info("Arrived at destination: %s forts, %s lured.", cluster[3], cluster[2])
                self.stay_until = now + self.config_camping_time

        return WorkerResult.RUNNING
예제 #21
0
 def request_snipe_time(self, update, location):
     last_position = self.bot.position[0:2]
     loc_list = location.split(',')
     snipe_distance = convert(distance(last_position[0],last_position[1],float(loc_list[0].strip()),float(loc_list[1].strip())),"m","km")
     time_to_snipe = wait_time_sec(snipe_distance)
     time_to_snipe_str_min = time.strftime("%M:%S", time.gmtime(time_to_snipe))
     if time_to_snipe <= 900:
         outMsg = "Estimated Time to Snipe: " + time_to_snipe_str_min + " Distance: " + "{0:.2f}".format(snipe_distance) + "KM"
         self.sendMessage(chat_id=update.message.chat_id, parse_mode='Markdown', text="".join(outMsg))
     else:
         self.sendMessage(chat_id=update.message.chat_id, parse_mode='Markdown', text="Sniping distance is more than supported distance")
예제 #22
0
    def __init__(self, bot, dest_lat, dest_lng):
        super(PolylineWalker, self).__init__(bot, dest_lat, dest_lng)
        self.polyline_walker = PolylineObjectHandler.cached_polyline(tuple(self.api.get_position()[:2]),
                                        (self.destLat, self.destLng), self.speed)

        self.dist = distance(
            self.bot.position[0],
            self.bot.position[1],
            dest_lat,
            dest_lng
        )
예제 #23
0
    def get_pokemon_from_social(self):
        if not hasattr(self.bot, 'mqtt_pokemon_list'):
            return []
        if not self.bot.mqtt_pokemon_list or len(self.bot.mqtt_pokemon_list) <= 0:
            return []

        pokemon_list = []
        now = int(time.time())
        tmp_pokemon_list = self.bot.mqtt_pokemon_list
        self.bot.mqtt_pokemon_list = []

        for pokemon in tmp_pokemon_list:
            pokemon['encounter_id'] = pokemon['encounter_id']
            pokemon['spawn_point_id'] = pokemon['spawn_point_id']
            pokemon['disappear_time'] = int(pokemon['expiration_timestamp_ms'] / 1000)
            pokemon['name'] = self.pokemon_data[pokemon['pokemon_id'] - 1]['Name']
            pokemon['is_vip'] = pokemon['name'] in self.bot.config.vips

            if pokemon['name'] not in self.config['catch']:
                if self.config.get('debug', False):
                    self._emit_failure("Not catching {}".format(pokemon['name']))
                continue
            else:
                if self.config.get('debug', False):
                    self._emit_log("Catching {}".format(pokemon['name']))


            if self.was_caught(pokemon):
                continue

            pokemon['priority'] = self.config['catch'].get(pokemon['name'], 0)

            pokemon['dist'] = distance(
                self.bot.position[0],
                self.bot.position[1],
                pokemon['latitude'],
                pokemon['longitude'],
            )

            # If distance to pokemon greater than the max_sniping_distance, then ignore regardless of "snipe" setting
            if pokemon['dist'] > self.config.get('max_sniping_distance', 10000):
                continue
            
            # If distance bigger than walking distance, ignore if sniping is not active
            if pokemon['dist'] > self.config.get('max_walking_distance', 1000) and not self.config.get('snipe', False):
                continue

            # if pokemon not reachable with mean walking speed (by config)
            mean_walk_speed = (self.bot.config.walk_max + self.bot.config.walk_min) / 2
            if pokemon['dist'] > ((pokemon['disappear_time'] - now) * mean_walk_speed) and not self.config['snipe']:
                continue
            pokemon_list.append(pokemon)
        return pokemon_list
예제 #24
0
    def work(self):
        forts = self.bot.get_forts()
        log_lure_avail_str = ''
        log_lured_str = ''
        if self.lured:
            log_lured_str = 'lured '
            lured_forts = [x for x in forts if 'lure_info' in x]
            if len(lured_forts) > 0:
                self.dest = find_biggest_cluster(self.radius, lured_forts, 'lure_info')
            else:
                log_lure_avail_str = 'No lured pokestops in vicinity. Search for normal ones instead. '
                self.dest = find_biggest_cluster(self.radius, forts)
        else:
            self.dest = find_biggest_cluster(self.radius, forts)

        if self.dest is not None:

            lat = self.dest['latitude']
            lng = self.dest['longitude']
            cnt = self.dest['num_points']

            if not self.is_at_destination:

                log_str = log_lure_avail_str + 'Move to destiny. ' + str(cnt) + ' ' + log_lured_str + \
                          'pokestops will be in range of ' + str(self.radius) + 'm. Arrive in ' \
                          + str(distance(self.bot.position[0], self.bot.position[1], lat, lng)) + 'm.'
                logger.log(log_str)
                self.announced = False

                if self.bot.config.walk > 0:
                    step_walker = StepWalker(
                        self.bot,
                        self.bot.config.walk,
                        lat,
                        lng
                    )

                    self.is_at_destination = False
                    if step_walker.step():
                        self.is_at_destination = True
                else:
                    self.bot.api.set_position(lat, lng)

            elif not self.announced:
                log_str = 'Arrived at destiny. ' + str(cnt) + ' pokestops are in range of ' \
                         + str(self.radius) + 'm.'
                logger.log(log_str)
                self.announced = True
        else:
            lat = self.bot.position[0]
            lng = self.bot.position[1]

        return [lat, lng]
예제 #25
0
    def get_nearest_fort_on_the_way(self, pokemon):
        forts = self.bot.get_forts(order_by_distance=True)

        # Remove stops that are still on timeout
        forts = filter(lambda x: x["id"] not in self.bot.fort_timeouts, forts)
        i=0
        while i < len(forts) :
            ratio = float(self.config.get('max_extra_dist_fort', 20))
            dist_self_to_fort = distance (self.bot.position[0], self.bot.position[1], forts[i]['latitude'], forts [i]['longitude'])
            dist_fort_to_pokemon = distance (pokemon['latitude'], pokemon['longitude'], forts[i]['latitude'], forts [i]['longitude'])
            total_dist = dist_self_to_fort + dist_fort_to_pokemon
            dist_self_to_pokemon = distance (self.bot.position[0], self.bot.position[1], pokemon['latitude'], pokemon['longitude'])
            if total_dist < (1 + (ratio / 100))* dist_self_to_pokemon:
                i = i + 1
            else :
                del forts[i]
		#Return nearest fort if there are remaining
        if len(forts)> 0 :
            return forts[0]
        else :
            return None
예제 #26
0
    def __init__(self,
                 bot,
                 dest_lat,
                 dest_lng,
                 dest_alt=None,
                 fixed_speed=None,
                 precision=50):
        self.bot = bot
        self.api = bot.api
        self.precision = precision

        self.initLat, self.initLng = self.bot.position[0:2]

        self.dist = distance(self.initLat, self.initLng, dest_lat, dest_lng)

        if dest_alt == None:
            self.alt = uniform(self.bot.config.alt_min,
                               self.bot.config.alt_max)
        else:
            self.alt = dest_alt

        if fixed_speed != None:
            # PolylineWalker uses a fixed speed!
            self.speed = fixed_speed
        else:
            self.speed = uniform(self.bot.config.walk_min,
                                 self.bot.config.walk_max)

        if len(self.bot.position) == 3:
            self.initAlt = self.bot.position[2]
        else:
            self.initAlt = self.alt

        self.destLat = dest_lat
        self.destLng = dest_lng

        if self.speed == 0:
            raise Exception(
                "Walking speed cannot be 0, change your walking speed higher than 1!"
            )
        else:
            self.steps = (self.dist + 0.0) / (self.speed + 0.0)

        if self.dist < self.speed or int(self.steps) <= 1:
            self.dLat = 0
            self.dLng = 0
        else:
            self.dLat = (dest_lat - self.initLat) / int(self.steps)
            self.dLng = (dest_lng - self.initLng) / int(self.steps)

        self.bearing = self._calc_bearing(self.initLat, self.initLng,
                                          self.destLat, self.destLng)
예제 #27
0
    def get_pokemon_from_map(self):
        try:
            req = requests.get('{}/raw_data?gyms=false&scanned=false'.format(self.config['address']))
        except requests.exceptions.ConnectionError:
            logger.log('Could not reach PokemonGo-Map Server', 'red')
            return []

        try:
            raw_data = req.json()
        except ValueError:
            logger.log('Map data was not valid', 'red')
            return []

        pokemon_list = []
        now = int(time.time())

        for pokemon in raw_data['pokemons']:
            try:
                pokemon['encounter_id'] = long(base64.b64decode(pokemon['encounter_id']))
            except TypeError:
                log.logger('base64 error: {}'.format(pokemon['encounter_id']), 'red')
                continue
            pokemon['spawn_point_id'] = pokemon['spawnpoint_id']
            pokemon['disappear_time'] = int(pokemon['disappear_time'] / 1000)
            pokemon['name'] = self.pokemon_data[pokemon['pokemon_id'] - 1]['Name']
            pokemon['is_vip'] = pokemon['name'] in self.bot.config.vips

            if pokemon['name'] not in self.config['catch'] and not pokemon['is_vip']:
                continue

            if pokemon['disappear_time'] < (now + self.config['min_time']):
                continue

            if self.was_caught(pokemon):
                continue

            pokemon['priority'] = self.config['catch'].get(pokemon['name'], 0)

            pokemon['dist'] = distance(
                self.bot.position[0],
                self.bot.position[1],
                pokemon['latitude'],
                pokemon['longitude'],
            )

            if pokemon['dist'] > self.config['max_distance'] and not self.config['snipe']:
                continue

            pokemon_list.append(pokemon)

        return pokemon_list
    def _move_to_pokemon_througt_fort(self, fort, pokemon):
        """Moves trainer towards a fort before a Pokemon.

        Args:
            fort

        Returns:
            StepWalker
        """

        nearest_fort = fort

        lat = nearest_fort['latitude']
        lng = nearest_fort['longitude']
        fortID = nearest_fort['id']
        details = fort_details(self.bot, fortID, lat, lng)
        fort_name = details.get('name', 'Unknown')

        unit = self.bot.config.distance_unit  # Unit to use when printing formatted distance

        dist = distance(
            self.bot.position[0],
            self.bot.position[1],
            lat,
            lng
        )

        if dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE:
            pokemon_throught_fort_event_data = {
                'fort_name': u"{}".format(fort_name),
                'distance': format_dist(dist, unit),
                'poke_name': pokemon['name'],
                'poke_dist': (format_dist(pokemon['dist'], self.unit))
            }

            self.emit_event(
                'moving_to_pokemon_throught_fort',
                formatted="Moving towards {poke_name} - {poke_dist}  through pokestop  {fort_name} - {distance}",
                data= pokemon_throught_fort_event_data
            )
        else:
            self.emit_event(
                'arrived_at_fort',
                formatted='Arrived at fort.'
            )

	return walker_factory(self.walker,
            self.bot,
            lat,
            lng
        )
예제 #29
0
    def work(self):
        last_lat, last_lng, last_alt = self.bot.api.get_position()

        point = self.points[self.ptr]
        self.cnt += 1

        dist = distance(last_lat, last_lng, point['lat'], point['lng'])

        alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
        if self.bot.config.walk_max > 0:
            step_walker = StepWalker(self.bot, point['lat'], point['lng'])

            if self.cnt == 1:
                self.emit_event(
                    'position_update',
                    formatted=
                    "Walking from {last_position} to {current_position} ({distance} {distance_unit})",
                    data={
                        'last_position': (last_lat, last_lng, last_alt),
                        'current_position': (point['lat'], point['lng'], alt),
                        'distance': dist,
                        'distance_unit': 'm'
                    })

            if step_walker.step():
                step_walker = None
        else:
            self.bot.api.set_position(point['lat'], point['lng'], alt)
            self.emit_event(
                'position_update',
                formatted=
                "Teleported from {last_position} to {current_position} ({distance} {distance_unit})",
                data={
                    'last_position': (last_lat, last_lng, last_alt),
                    'current_position': (point['lat'], point['lng'], alt),
                    'distance': dist,
                    'distance_unit': 'm'
                })

        if dist <= 1 or (self.bot.config.walk_min > 0 and step_walker == None):
            if self.ptr + self.direction >= len(
                    self.points) or self.ptr + self.direction <= -1:
                self.direction *= -1
            if len(self.points) != 1:
                self.ptr += self.direction
            else:
                self.ptr = 0
            self.cnt = 0

        return [point['lat'], point['lng']]
예제 #30
0
    def get_pokemon_from_social(self):
        if not hasattr(self.bot, 'mqtt_pokemon_list'):
            return []
        if not self.bot.mqtt_pokemon_list or len(
                self.bot.mqtt_pokemon_list) <= 0:
            return []

        pokemon_list = []
        now = int(time.time())
        tmp_pokemon_list = self.bot.mqtt_pokemon_list
        self.bot.mqtt_pokemon_list = []

        for pokemon in tmp_pokemon_list:
            pokemon['encounter_id'] = pokemon['encounter_id']
            pokemon['spawn_point_id'] = pokemon['spawn_point_id']
            pokemon['disappear_time'] = int(
                pokemon['expiration_timestamp_ms'] / 1000)
            pokemon['name'] = self.pokemon_data[pokemon['pokemon_id'] -
                                                1]['Name']
            pokemon['is_vip'] = pokemon['name'] in self.bot.config.vips

            if pokemon['name'] not in self.config['catch']:
                continue

            if self.was_caught(pokemon):
                continue

            pokemon['priority'] = self.config['catch'].get(pokemon['name'], 0)

            pokemon['dist'] = distance(
                self.bot.position[0],
                self.bot.position[1],
                pokemon['latitude'],
                pokemon['longitude'],
            )

            if pokemon['dist'] > self.config[
                    'max_distance'] or not self.config['snipe']:
                continue

            # pokemon not reachable with mean walking speed (by config)
            mean_walk_speed = (self.bot.config.walk_max +
                               self.bot.config.walk_min) / 2
            if pokemon['dist'] > (
                (pokemon['disappear_time'] - now) *
                    mean_walk_speed) and not self.config['snipe']:
                continue
            pokemon_list.append(pokemon)
        return pokemon_list
예제 #31
0
    def work(self):
        last_lat = self.bot.api._position_lat
        last_lng = self.bot.api._position_lng

        point = self.points[self.ptr]
        lat = float(point['lat'])
        lng = float(point['lng'])

        if self.bot.config.walk_max > 0:
            step_walker = StepWalker(
                self.bot,
                lat,
                lng
            )

            is_at_destination = False
            if step_walker.step():
                is_at_destination = True

        else:
            self.bot.api.set_position(lat, lng, 0)

        dist = distance(
            last_lat,
            last_lng,
            lat,
            lng
        )

        if dist <= 1 or (self.bot.config.walk_min > 0 and is_at_destination):
            if (self.ptr + 1) == len(self.points):
                self.ptr = 0
                if self.path_mode == 'linear':
                    self.points = list(reversed(self.points))
            else:
                self.ptr += 1

        self.emit_event(
            'position_update',
            formatted="Walking from {last_position} to {current_position} ({distance} {distance_unit})",
            data={
                'last_position': (last_lat, last_lng, 0),
                'current_position': (lat, lng, 0),
                'distance': dist,
                'distance_unit': 'm'
            }
        )
        return [lat, lng]
예제 #32
0
    def __init__(self, bot, dest_lat, dest_lng, dest_alt=None, fixed_speed=None, precision=50):
        self.bot = bot
        self.api = bot.api
        self.precision = precision

        self.initLat, self.initLng = self.bot.position[0:2]

        self.dist = distance(
            self.initLat,
            self.initLng,
            dest_lat,
            dest_lng
        )
        
        if dest_alt == None:
            self.alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)
        else:
            self.alt = dest_alt
            
        if fixed_speed != None:
            # PolylineWalker uses a fixed speed!
            self.speed = fixed_speed
        else:
            self.speed = uniform(self.bot.config.walk_min, self.bot.config.walk_max)

        if len(self.bot.position) == 3:
            self.initAlt = self.bot.position[2]
        else:
            self.initAlt = self.alt

        self.destLat = dest_lat
        self.destLng = dest_lng

        if self.speed == 0:
            raise Exception("Walking speed cannot be 0, change your walking speed higher than 1!")
        else:
            self.steps = (self.dist + 0.0) / (self.speed + 0.0)

        if self.dist < self.speed or int(self.steps) <= 1:
            self.dLat = 0
            self.dLng = 0
        else:
            self.dLat = (dest_lat - self.initLat) / int(self.steps)
            self.dLng = (dest_lng - self.initLng) / int(self.steps)
            
        self.bearing = self._calc_bearing(self.initLat, self.initLng, self.destLat, self.destLng)
예제 #33
0
    def find_closest_point_idx(self, points):
        return_idx = 0
        min_distance = float("inf")

        for index in range(len(points)):
            point = points[index]
            lat = point['lat']
            lng = point['lng']

            dist = distance(self.bot.position[0], self.bot.position[1], lat,
                            lng)

            if dist < min_distance:
                min_distance = dist
                return_idx = index

        return return_idx
예제 #34
0
    def find_closest_point_idx(self, points):
        return_idx = 0
        min_distance = float("inf")

        for index in range(len(points)):
            point = points[index]
            botlat, botlng, _ = self.bot.api.get_position()
            lat = point['lat']
            lng = point['lng']

            dist = distance(botlat, botlng, lat, lng)

            if dist < min_distance:
                min_distance = dist
                return_idx = index

        return return_idx
예제 #35
0
 def request_snipe_time(self, update, lat, lng):
     last_position = self.bot.position[0:2]
     snipe_distance = convert(
         distance(last_position[0], last_position[1], float(lat),
                  float(lng)), "m", "km")
     time_to_snipe = wait_time_sec(snipe_distance) / 60
     if time_to_snipe <= 900:
         outMsg = "Estimate Time to Snipe: " + "{0:.2f}".format(
             time_to_snipe) + " Mins. Distance: " + "{0:.2f}".format(
                 snipe_distance) + "KM"
         self.sendMessage(chat_id=update.message.chat_id,
                          parse_mode='Markdown',
                          text="".join(outMsg))
     else:
         self.sendMessage(
             chat_id=update.message.chat_id,
             parse_mode='Markdown',
             text="Sniping distance is more than supported distance")
예제 #36
0
    def get_pokemon(self, pokemon):
        if 'pokemon_id' not in pokemon:
            pokemon['pokemon_id'] = pokemon['pokemon_data']['pokemon_id']

        if 'time_till_hidden_ms' not in pokemon:
            pokemon['time_till_hidden_ms'] = pokemon['expiration_timestamp_ms']

        pokemon['disappear_time'] = int(pokemon['time_till_hidden_ms'] / 1000)
        pokemon['name'] = self.pokemon_data[pokemon['pokemon_id'] - 1]['Name']
        pokemon['is_vip'] = pokemon['name'] in self.bot.config.vips
        pokemon['dist'] = distance(
            self.bot.position[0],
            self.bot.position[1],
            pokemon['latitude'],
            pokemon['longitude'],
        )

        return pokemon
예제 #37
0
    def get_lured_pokemon(self):
        forts_in_range = []
        pokemon_to_catch = []
        forts = self.bot.get_forts(order_by_distance=True)

        if len(forts) == 0:
            return []

        for fort in forts:
            distance_to_fort = distance(
                self.bot.position[0],
                self.bot.position[1],
                fort['latitude'],
                fort['longitude']
            )

            encounter_id = fort.get('lure_info', {}).get('encounter_id', None)
            if distance_to_fort < Constants.MAX_DISTANCE_FORT_IS_REACHABLE and encounter_id:
                forts_in_range.append(fort)


        for fort in forts_in_range:
            details = fort_details(self.bot, fort_id=fort['id'],
                                  latitude=fort['latitude'],
                                  longitude=fort['longitude'])
            fort_name = details.get('name', 'Unknown')
            encounter_id = fort['lure_info']['encounter_id']

            result = {
                'encounter_id': encounter_id,
                'fort_id': fort['id'],
                'fort_name': u"{}".format(fort_name),
                'latitude': fort['latitude'],
                'longitude': fort['longitude']
            }
            pokemon_to_catch.append(result)

            self.emit_event(
                'lured_pokemon_found',
                level='info',
                formatted='Lured pokemon at fort {fort_name} ({fort_id})',
                data=result
            )
        return pokemon_to_catch
예제 #38
0
    def get_lured_pokemon(self):
        forts_in_range = []
        pokemon_to_catch = []
        forts = self.bot.get_forts(order_by_distance=True)

        if len(forts) == 0:
            return []

        for fort in forts:
            distance_to_fort = distance(
                self.bot.position[0],
                self.bot.position[1],
                fort['latitude'],
                fort['longitude']
            )

            encounter_id = fort.get('lure_info', {}).get('encounter_id', None)
            if distance_to_fort < Constants.MAX_DISTANCE_FORT_IS_REACHABLE and encounter_id:
                forts_in_range.append(fort)


        for fort in forts_in_range:
            details = fort_details(self.bot, fort_id=fort['id'],
                                  latitude=fort['latitude'],
                                  longitude=fort['longitude'])
            fort_name = details.get('name', 'Unknown')
            encounter_id = fort['lure_info']['encounter_id']

            result = {
                'encounter_id': encounter_id,
                'fort_id': fort['id'],
                'fort_name': u"{}".format(fort_name),
                'latitude': fort['latitude'],
                'longitude': fort['longitude']
            }
            pokemon_to_catch.append(result)

            self.emit_event(
                'lured_pokemon_found',
                level='info',
                formatted='Lured pokemon at fort {fort_name} ({fort_id})',
                data=result
            )
        return pokemon_to_catch
예제 #39
0
    def update_map_location(self):
        if not self.config['update_map']:
            return
        try:
            req = requests.get('{}/loc'.format(self.config['address']))
        except requests.exceptions.ConnectionError:
            self._emit_failure('Could not update trainer location '
                               'PokemonGo-Map: {}. Is it running?'.format(
                                   self.config['address']))
            return

        try:
            loc_json = req.json()
        except ValueError:
            err = 'Map location data was not valid'
            self._emit_failure(err)
            return log.logger(err, 'red')

        dist = distance(
            self.bot.position[0],
            self.bot.position[1],
            loc_json['lat'],
            loc_json['lng']
        )

        # update map when 500m away from center and last update longer than 2 minutes away
        now = int(time.time())
        if (dist > UPDATE_MAP_MIN_DISTANCE_METERS and
            now - self.last_map_update > UPDATE_MAP_MIN_TIME_SEC):
            requests.post(
                '{}/next_loc?lat={}&lon={}'.format(self.config['address'],
                                                   self.bot.position[0],
                                                   self.bot.position[1]))
            self.emit_event(
                'move_to_map_pokemon_updated_map',
                formatted='Updated PokemonGo-Map to {lat}, {lon}',
                data={
                    'lat': self.bot.position[0],
                    'lon': self.bot.position[1]
                }
            )
            self.last_map_update = now
예제 #40
0
    def get_pokemon_from_social(self):
    	if not hasattr(self.bot, 'mqtt_pokemon_list'):
            return []
        if not self.bot.mqtt_pokemon_list or len(self.bot.mqtt_pokemon_list) <= 0:
            return []

        pokemon_list = []
        now = int(time.time())
        tmp_pokemon_list = self.bot.mqtt_pokemon_list
        self.bot.mqtt_pokemon_list = []

        for pokemon in tmp_pokemon_list:
            pokemon['encounter_id'] = pokemon['encounter_id']
            pokemon['spawn_point_id'] = pokemon['spawn_point_id']
            pokemon['disappear_time'] = int(pokemon['expiration_timestamp_ms'] / 1000)
            pokemon['name'] = self.pokemon_data[pokemon['pokemon_id'] - 1]['Name']
            pokemon['is_vip'] = pokemon['name'] in self.bot.config.vips

            if pokemon['name'] not in self.config['catch']:
                continue

            if self.was_caught(pokemon):
                continue

            pokemon['priority'] = self.config['catch'].get(pokemon['name'], 0)

            pokemon['dist'] = distance(
                self.bot.position[0],
                self.bot.position[1],
                pokemon['latitude'],
                pokemon['longitude'],
            )

            if pokemon['dist'] > self.config['max_distance'] or not self.config['snipe']:
                continue

            # pokemon not reachable with mean walking speed (by config)
            mean_walk_speed = (self.bot.config.walk_max + self.bot.config.walk_min) / 2
            if pokemon['dist'] > ((pokemon['disappear_time'] - now) * mean_walk_speed) and not self.config['snipe']:
                continue
            pokemon_list.append(pokemon)
        return pokemon_list
예제 #41
0
    def find_closest_point_idx(self, points):
        return_idx = 0
        min_distance = float("inf");
        
        for index in range(len(points)):
            point = points[index]
            lat = point['lat']
            lng = point['lng']

            dist = distance(
                self.bot.position[0],
                self.bot.position[1],
                lat,
                lng
            )

            if dist < min_distance:
                min_distance = dist
                return_idx = index

        return return_idx
예제 #42
0
 def request_snipe_time(self, update, location):
     last_position = self.bot.position[0:2]
     loc_list = location.split(',')
     snipe_distance = convert(
         distance(last_position[0], last_position[1],
                  float(loc_list[0].strip()), float(loc_list[1].strip())),
         "m", "km")
     time_to_snipe = wait_time_sec(snipe_distance)
     time_to_snipe_str_min = time.strftime("%M:%S",
                                           time.gmtime(time_to_snipe))
     if time_to_snipe <= 900:
         outMsg = "Estimated Time to Snipe: " + time_to_snipe_str_min + " Distance: " + "{0:.2f}".format(
             snipe_distance) + "KM"
         self.sendMessage(chat_id=update.message.chat_id,
                          parse_mode='Markdown',
                          text="".join(outMsg))
     else:
         self.sendMessage(
             chat_id=update.message.chat_id,
             parse_mode='Markdown',
             text="Sniping distance is more than supported distance")
예제 #43
0
    def work(self):
        last_lat = self.bot.api._position_lat
        last_lng = self.bot.api._position_lng

        point = self.points[self.ptr]
        lat = float(point['lat'])
        lng = float(point['lng'])

        if self.bot.config.walk_max > 0:
            step_walker = StepWalker(self.bot, lat, lng)

            is_at_destination = False
            if step_walker.step():
                is_at_destination = True

        else:
            self.bot.api.set_position(lat, lng, 0)

        dist = distance(last_lat, last_lng, lat, lng)

        if dist <= 1 or (self.bot.config.walk_min > 0 and is_at_destination):
            if (self.ptr + 1) == len(self.points):
                self.ptr = 0
                if self.path_mode == 'linear':
                    self.points = list(reversed(self.points))
            else:
                self.ptr += 1

        self.emit_event(
            'position_update',
            formatted=
            "Walk to {last_position} now at {current_position}, distance left: ({distance} {distance_unit}) ..",
            data={
                'last_position': (lat, lng, 0),
                'current_position': (last_lat, last_lng, 0),
                'distance': dist,
                'distance_unit': 'm'
            })
        return [lat, lng]
예제 #44
0
    def find_closest_point_idx(self, points):
        return_idx = 0
        min_distance = float("inf");
        for index in range(len(points)):
            point = points[index]
            botlat = self.bot.api._position_lat
            botlng = self.bot.api._position_lng
            lat = point['lat']
            lng = point['lng']

            dist = distance(
                botlat,
                botlng,
                lat,
                lng
            )

            if dist < min_distance:
                min_distance = dist
                return_idx = index

        return return_idx
예제 #45
0
    def work(self):
        point = self.points[self.ptr]
        lat = float(point['lat'])
        lng = float(point['lng'])

        if self.bot.config.walk > 0:
            step_walker = StepWalker(
                self.bot,
                self.bot.config.walk,
                lat,
                lng
            )

            is_at_destination = False
            if step_walker.step():
                is_at_destination = True

        else:
            self.bot.api.set_position(lat, lng)

        dist = distance(
            self.bot.api._position_lat,
            self.bot.api._position_lng,
            lat,
            lng
        )

        if dist <= 1 or (self.bot.config.walk > 0 and is_at_destination):
            if (self.ptr + 1) == len(self.points):
                self.ptr = 0
                if self.path_mode == 'linear':
                    self.points = list(reversed(self.points))
            else:
                self.ptr += 1

        return [lat, lng]
예제 #46
0
    def snipe(self, pokemon):
        success = False
        

        # Apply snipping business rules and snipe if its good
        if not self.is_snipeable(pokemon) and not self.mode == SniperMode.TELEGRAM:
            self._trace('{} is not snipeable! Skipping...'.format(pokemon['pokemon_name']))
        else:
            # Have we already tried this pokemon?
            if not hasattr(self.bot,'sniper_unique_pokemon'):
                self.bot.sniper_unique_pokemon = []

            # Check if already in list of pokemon we've tried
            uniqueid = self._build_unique_id(pokemon)
            if self._is_cached(uniqueid):
                # Do nothing. Either we already got this, or it doesn't really exist
                self._trace('{} was already handled! Skipping...'.format(pokemon['pokemon_name']))
            else:
                # Backup position before anything
                last_position = self.bot.position[0:2]
                teleport_position = [pokemon['latitude'], pokemon['longitude']]
                #teleport_distance = self._get_distance(last_position, teleport_position)
                teleport_distance = convert(distance(last_position[0],last_position[1],float(pokemon['latitude']),float(pokemon['longitude'])),"m","km")
                #sleep_time = self._get_sleep_sec(teleport_distance)
                sleep_time = wait_time_sec(teleport_distance)
                
                if sleep_time > 900:
                    success = False
                    exists = False
                    self._log('Sniping distance is more than supported distance, abort sniping')
                else:
                    self._log('Base on distance, pausing for {0:.2f} Mins'.format(sleep_time/60))

                    # Teleport, so that we can see nearby stuff
                    self.bot.hb_locked = True
                    time.sleep(sleep_time)
                    self._teleport_to(pokemon)


                    # If social is enabled and if no verification is needed, trust it. Otherwise, update IDs!
                    verify = not pokemon.get('encounter_id') or not pokemon.get('spawn_point_id')
                    exists = not verify or self.mode == SniperMode.SOCIAL
                    success = exists

                    # Always verify if it's from telegram
                    if TelegramSnipe.ENABLED == True:
                        verify = True

                    # If information verification have to be done, do so
                    if verify:
                        seconds_since_last_check = time.time() - self.last_cell_check_time

                        # Wait a maximum of MIN_SECONDS_ALLOWED_FOR_CELL_CHECK seconds before requesting nearby cells
                        self._log('Pausing for {} secs before checking for Pokemons'.format(self.MIN_SECONDS_ALLOWED_FOR_CELL_CHECK))

                        #recode it to check every 5 secs, first check for wild then catchable
                        nearby_pokemons = []
                        nearby_stuff = []
                        num = 0
                        for num in range(0,self.MIN_SECONDS_ALLOWED_FOR_CELL_CHECK):
                            if num%5 == 0:
                                nearby_stuff = self.bot.get_meta_cell()
                                self.last_cell_check_time = time.time()

                                # Retrieve nearby pokemons for validation
                                nearby_pokemons.extend(nearby_stuff.get('wild_pokemons', []))
                                if nearby_pokemons:
                                    break

                            time.sleep(1)
                            num += 1

                        num = 0
                        for num in range(0,self.MIN_SECONDS_ALLOWED_FOR_CELL_CHECK):
                            if num%5 == 0:
                                nearby_stuff = self.bot.get_meta_cell()
                                self.last_cell_check_time = time.time()

                                # Retrieve nearby pokemons for validation
                                nearby_pokemons.extend(nearby_stuff.get('catchable_pokemons', []))
                                if nearby_pokemons:
                                    break

                            time.sleep(1)
                            num += 1

                        self._trace('Pokemon Nearby: {}'.format(nearby_pokemons))

                        # Make sure the target really/still exists (nearby_pokemon key names are game-bound!)
                        for nearby_pokemon in nearby_pokemons:
                            nearby_pokemon_id = nearby_pokemon.get('pokemon_data', {}).get('pokemon_id') or nearby_pokemon.get('pokemon_id')

                            # If we found the target, it exists and will very likely be encountered/caught (success)
                            if nearby_pokemon_id == pokemon.get('pokemon_id', 0):
                                exists = True
                                success = True

                                # Also, if the IDs arent valid, override them (nearby_pokemon key names are game-bound!) with game values
                                if not pokemon.get('encounter_id') or not pokemon.get('spawn_point_id'):
                                    pokemon['encounter_id'] = nearby_pokemon['encounter_id']
                                    pokemon['spawn_point_id'] = nearby_pokemon['spawn_point_id']
                                break

                    # If target exists, catch it, otherwise ignore
                    if exists:
                        self._log('Yay! There really is a wild {} nearby!'.format(pokemon.get('pokemon_name')))
                        self._catch(pokemon)
                        if self.teleport_back_to_last_location:
                            self._log('You have set to return to previous location, pause for {} sec before returning'.format(sleep_time))
                            time.sleep(sleep_time)
                            self._teleport_back(last_position)
                            #self._teleport_back_and_catch(last_position, pokemon)
                    else:
                        self._error('Damn! Its not here. Reasons: too far, caught, expired or fake data. Skipping...')
                        if self.teleport_back_to_last_location:
                            self._log('You have set to return to previous location, pause for {} sec before returning'.format(sleep_time))
                            time.sleep(sleep_time)
                            self._teleport_back(last_position)
                        else:
                            self._log('Bot will now continue from new position')
                            #self._teleport_back(last_position)

                    #Set always to false to re-enable sniper to check for telegram data
                    TelegramSnipe.ENABLED = False

                    # Save target and unlock heartbeat calls
                    self._cache(uniqueid)
                    self.bot.hb_locked = False

            return success
예제 #47
0
    def work(self):
        last_lat = self.bot.api._position_lat
        last_lng = self.bot.api._position_lng
        last_alt = self.bot.api._position_alt

        point = self.points[self.ptr]
        lat = float(point['lat'])
        lng = float(point['lng'])

        if 'alt' in point:
            alt = float(point['alt'])
        else:
            alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)

        if self.bot.config.walk_max > 0:
            step_walker = walker_factory(self.walker,
                self.bot,
                lat,
                lng,
                alt
            )

            is_at_destination = False
            if step_walker.step():
                is_at_destination = True

        else:
            self.bot.api.set_position(lat, lng, alt)

        dist = distance(
            last_lat,
            last_lng,
            lat,
            lng
        )

        self.emit_event(
            'position_update',
            formatted="Walking from {last_position} to {current_position}, distance left: ({distance} {distance_unit}) ..",
            data={
                'last_position': (last_lat, last_lng, last_alt),
                'current_position': (lat, lng, alt),
                'distance': dist,
                'distance_unit': 'm'
            }
        )
        
        if dist <= 1 or (self.bot.config.walk_min > 0 and is_at_destination):
            if (self.ptr + 1) == len(self.points):
                self.ptr = 0
                if self.path_mode == 'linear':
                    self.points = list(reversed(self.points))
                if self.number_lap_max >= 0:
                    self.number_lap+=1
                    self.emit_event(
                        'path_lap_update',
                        formatted="number lap : {number_lap} / {number_lap_max}",
                        data={
                            'number_lap': str(self.number_lap),
                            'number_lap_max': str(self.number_lap_max)
                        }
                    )
                    if self.number_lap >= self.number_lap_max:
                        self.endLaps()
            else:
                self.ptr += 1
        
        return [lat, lng]
예제 #48
0
 def step(self):
     step = super(PolylineWalker, self).step()
     if not (distance(self.pol_lat, self.pol_lon, self.dest_lat, self.dest_lng) > 10 and step):
         return False
     else:
         return True
예제 #49
0
    def work(self):
        # If done or wandering allow the next task to run
        if self.status == STATUS_FINISHED:
            return WorkerResult.SUCCESS

        if self.disable_while_hunting and hasattr(self.bot,
                                                  "hunter_locked_target"):
            if self.bot.hunter_locked_target != None:
                return WorkerResult.SUCCESS

        if time.time() < self.waiting_end_time:
            if self.status == STATUS_WANDERING:
                return WorkerResult.SUCCESS
            elif self.status == STATUS_LOITERING:
                return WorkerResult.RUNNING

        last_lat, last_lng, last_alt = self.bot.position

        point = self.points[self.ptr]
        lat = point['lat']
        lng = point['lng']

        if 'alt' in point:
            alt = float(point['alt'])
        else:
            alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)

        if self.bot.config.walk_max > 0:
            step_walker = walker_factory(self.walker, self.bot, lat, lng, alt)

            is_at_destination = False
            if step_walker.step():
                is_at_destination = True

        else:
            self.bot.api.set_position(lat, lng, alt)

        dist = distance(last_lat, last_lng, lat, lng)

        if not self.disable_location_output:
            self.emit_event(
                'position_update',
                formatted=
                "Walking from {last_position} to {current_position}, distance left: ({distance} {distance_unit}) ..",
                data={
                    'last_position': (last_lat, last_lng, last_alt),
                    'current_position':
                    point["location"],
                    'distance':
                    format_dist(dist, self.distance_unit, self.append_unit),
                    'distance_unit':
                    self.distance_unit
                })

        if (self.bot.config.walk_min > 0 and is_at_destination) or (
                self.status in [STATUS_WANDERING, STATUS_LOITERING]
                and time.time() >= self.waiting_end_time):
            if "loiter" in point and self.status != STATUS_LOITERING:
                self.logger.info("Loitering for {} seconds...".format(
                    point["loiter"]))
                self.status = STATUS_LOITERING
                self.waiting_end_time = time.time() + point["loiter"]
                return WorkerResult.RUNNING
            if "wander" in point and self.status != STATUS_WANDERING:
                self.logger.info("Wandering for {} seconds...".format(
                    point["wander"]))
                self.status = STATUS_WANDERING
                self.waiting_end_time = time.time() + point["wander"]
                return WorkerResult.SUCCESS
            if (self.ptr + 1) == len(self.points):
                if self.path_mode == 'single':
                    self.status = STATUS_FINISHED
                    return WorkerResult.SUCCESS
                self.ptr = 0
                if self.path_mode == 'linear':
                    self.points = list(reversed(self.points))
                if self.number_lap_max >= 0:
                    self.number_lap += 1
                    self.emit_event(
                        'path_lap_update',
                        formatted=
                        "number lap : {number_lap} / {number_lap_max}",
                        data={
                            'number_lap': str(self.number_lap),
                            'number_lap_max': str(self.number_lap_max)
                        })
                    if self.number_lap >= self.number_lap_max:
                        self.endLaps()
            else:
                self.ptr += 1

        self.status = STATUS_MOVING
        return WorkerResult.RUNNING
예제 #50
0
    def work(self):
        # If done or loitering allow the next task to run
        if self.status == STATUS_FINISHED:
            return WorkerResult.SUCCESS

        if self.status == STATUS_LOITERING and time.time() < self.loiter_end_time:
            return WorkerResult.SUCCESS

        last_lat, last_lng, last_alt = self.bot.position

        point = self.points[self.ptr]
        lat = point['lat']
        lng = point['lng']

        if 'alt' in point:
            alt = float(point['alt'])
        else:
            alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)

        if self.bot.config.walk_max > 0:
            step_walker = walker_factory(self.walker,
                self.bot,
                lat,
                lng,
                alt
            )

            is_at_destination = False
            if step_walker.step():
                is_at_destination = True

        else:
            self.bot.api.set_position(lat, lng, alt)

        dist = distance(
            last_lat,
            last_lng,
            lat,
            lng
        )

        self.emit_event(
            'position_update',
            formatted="Walking from {last_position} to {current_position}, distance left: ({distance} {distance_unit}) ..",
            data={
                'last_position': (last_lat, last_lng, last_alt),
                'current_position': (lat, lng, alt),
                'distance': format_dist(dist,self.distance_unit,self.append_unit),
                'distance_unit': self.distance_unit
            }
        )
        
        if dist <= 1 or (self.bot.config.walk_min > 0 and is_at_destination) or (self.status == STATUS_LOITERING and time.time() >= self.loiter_end_time):
            if "loiter" in point and self.status != STATUS_LOITERING:
                self.logger.info("Loitering for {} seconds...".format(point["loiter"]))
                self.status = STATUS_LOITERING
                self.loiter_end_time = time.time() + point["loiter"]
                return WorkerResult.SUCCESS
            if (self.ptr + 1) == len(self.points):
                if self.path_mode == 'single':
                    self.status = STATUS_FINISHED
                    return WorkerResult.SUCCESS
                self.ptr = 0
                if self.path_mode == 'linear':
                    self.points = list(reversed(self.points))
                if self.number_lap_max >= 0:
                    self.number_lap+=1
                    self.emit_event(
                        'path_lap_update',
                        formatted="number lap : {number_lap} / {number_lap_max}",
                        data={
                            'number_lap': str(self.number_lap),
                            'number_lap_max': str(self.number_lap_max)
                        }
                    )
                    if self.number_lap >= self.number_lap_max:
                        self.endLaps()
            else:
                self.ptr += 1
        
        self.status = STATUS_MOVING
        return WorkerResult.RUNNING
예제 #51
0
    def pokemons_parser(self, pokemon_list):
        pokemons = []
        if not pokemon_list:
            return pokemons

        now = int(time.time())

        for pokemon in pokemon_list:
            try:
                disappear = int(
                    pokemon.get('expiration_timestamp_ms', 0) / 1000) or int(
                        pokemon.get('disappear_time', 0) / 1000)

                pokemon['encounter_id'] = pokemon.get('encounter_id', '')
                pokemon['spawn_point_id'] = pokemon.get(
                    'spawn_point_id', '') or pokemon.get('spawnpoint_id', '')
                pokemon['iv'] = pokemon.get('iv', 0)
                pokemon['disappear_time'] = disappear
                pokemon['name'] = self.pokemon_data[pokemon['pokemon_id'] -
                                                    1]['Name']
                pokemon['is_vip'] = pokemon['name'] in self.bot.config.vips
            except TypeError:
                continue
            except KeyError:
                continue
            if now > pokemon['disappear_time']:
                continue

            if pokemon['name'] not in self.config[
                    'catch'] and not pokemon['is_vip']:
                if self.debug:
                    self._emit_failure("Not catching {}".format(
                        pokemon['name']))
                continue

            if self.is_inspected(pokemon):
                if self.debug:
                    self._emit_log(
                        'Skipped {} because it was already catch or does not exist'
                        .format(pokemon['name']))
                continue

            pokemon['priority'] = self.config['catch'].get(pokemon['name'], 0)
            pokemon['dist'] = distance(self.bot.position[0],
                                       self.bot.position[1],
                                       pokemon['latitude'],
                                       pokemon['longitude'])

            # If distance to pokemon greater than the max_sniping_distance, then ignore regardless of "snipe" setting
            if pokemon['dist'] > self.config.get('max_sniping_distance',
                                                 10000):
                continue

            # If distance bigger than walking distance, ignore if sniping is not active
            if pokemon['dist'] > self.config.get(
                    'max_walking_distance', 1000) and not self.snip_enabled:
                continue

            # if pokemon not reachable with mean walking speed (by config)
            mean_walk_speed = (self.bot.config.walk_max +
                               self.bot.config.walk_min) / 2
            if pokemon['dist'] > ((pokemon['disappear_time'] - now) *
                                  mean_walk_speed) and not self.snip_enabled:
                continue
            pokemons.append(pokemon)

        return pokemons
예제 #52
0
    def work(self):
        # If done or loitering allow the next task to run
        if self.status == STATUS_FINISHED:
            return WorkerResult.SUCCESS

        if self.status == STATUS_LOITERING and time.time() < self.loiter_end_time:
            return WorkerResult.SUCCESS

        last_lat = self.bot.api._position_lat
        last_lng = self.bot.api._position_lng
        last_alt = self.bot.api._position_alt

        point = self.points[self.ptr]
        lat = point['lat']
        lng = point['lng']

        if 'alt' in point:
            alt = float(point['alt'])
        else:
            alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max)

        if self.bot.config.walk_max > 0:
            step_walker = walker_factory(self.walker,
                self.bot,
                lat,
                lng,
                alt
            )

            is_at_destination = False
            if step_walker.step():
                is_at_destination = True

        else:
            self.bot.api.set_position(lat, lng, alt)

        dist = distance(
            last_lat,
            last_lng,
            lat,
            lng
        )

        self.emit_event(
            'position_update',
            formatted="Walking from {last_position} to {current_position}, distance left: ({distance} {distance_unit}) ..",
            data={
                'last_position': (last_lat, last_lng, last_alt),
                'current_position': (lat, lng, alt),
                'distance': dist,
                'distance_unit': 'm'
            }
        )
        
        if dist <= 1 or (self.bot.config.walk_min > 0 and is_at_destination) or (self.status == STATUS_LOITERING and time.time() >= self.loiter_end_time):
            if "loiter" in point and self.status != STATUS_LOITERING: 
                print("Loitering {} seconds".format(point["loiter"]))
                self.status = STATUS_LOITERING
                self.loiter_end_time = time.time() + point["loiter"]
                return WorkerResult.SUCCESS
            if (self.ptr + 1) == len(self.points):
                if self.path_mode == 'single':
                    self.status = STATUS_FINISHED
                    return WorkerResult.SUCCESS
                self.ptr = 0
                if self.path_mode == 'linear':
                    self.points = list(reversed(self.points))
                if self.number_lap_max >= 0:
                    self.number_lap+=1
                    self.emit_event(
                        'path_lap_update',
                        formatted="number lap : {number_lap} / {number_lap_max}",
                        data={
                            'number_lap': str(self.number_lap),
                            'number_lap_max': str(self.number_lap_max)
                        }
                    )
                    if self.number_lap >= self.number_lap_max:
                        self.endLaps()
            else:
                self.ptr += 1
        
        self.status = STATUS_MOVING
        return WorkerResult.RUNNING
예제 #53
0
    def work(self):
        forts = self.bot.get_forts()
        log_lure_avail_str = ''
        log_lured_str = ''
        if self.lured:
            log_lured_str = 'lured '
            lured_forts = [x for x in forts if 'lure_info' in x]
            if len(lured_forts) > 0:
                self.dest = find_biggest_cluster(self.radius, lured_forts, 'lure_info')
            else:
                log_lure_avail_str = 'No lured pokestops in vicinity. Search for normal ones instead. '
                self.dest = find_biggest_cluster(self.radius, forts)
        else:
            self.dest = find_biggest_cluster(self.radius, forts)

        if self.dest is not None:

            lat = self.dest['latitude']
            lng = self.dest['longitude']
            cnt = self.dest['num_points']

            if not self.is_at_destination:
                msg = log_lure_avail_str + (
                    "Move to destiny {num_points}. {forts} "
                    "pokestops will be in range of {radius}. Walking {distance}m."
                )
                self.emit_event(
                    'found_cluster',
                    formatted=msg,
                    data={
                        'num_points': cnt,
                        'forts': log_lured_str,
                        'radius': str(self.radius),
                        'distance': str(distance(self.bot.position[0], self.bot.position[1], lat, lng))
                    }
                )

                self.announced = False

                if self.bot.config.walk_max > 0:
                    step_walker = StepWalker(
                        self.bot,
                        lat,
                        lng
                    )

                    self.is_at_destination = False
                    if step_walker.step():
                        self.is_at_destination = True
                else:
                    self.bot.api.set_position(lat, lng)

            elif not self.announced:
                self.emit_event(
                    'arrived_at_cluster',
                    formatted="Arrived at cluster. {forts} are in a range of {radius}m radius.",
                    data={
                        'forts': str(cnt),
                        'radius': self.radius
                    }
                )
                self.announced = True
        else:
            lat = self.bot.position[0]
            lng = self.bot.position[1]

        return [lat, lng]
예제 #54
0
    def work(self):
        forts = self.bot.get_forts()
        log_lure_avail_str = ''
        log_lured_str = ''
        if self.lured:
            lured_forts = [x for x in forts if 'active_fort_modifier' in x]
            if len(lured_forts) > 0:
                log_lured_str = 'lured '
                self.dest = find_biggest_cluster(self.radius, lured_forts,
                                                 '9QM=')
            else:
                log_lure_avail_str = 'No lured pokestops in vicinity. Search for normal ones instead. '
                self.dest = find_biggest_cluster(self.radius, forts)
        else:
            self.dest = find_biggest_cluster(self.radius, forts)

        if self.dest is not None:
            lat = self.dest['latitude']
            lng = self.dest['longitude']
            cnt = self.dest['num_points']

            if not self.is_at_destination:
                msg = log_lure_avail_str + (
                    "Move to cluster: {num_points} {forts} "
                    "pokestops will be in range of {radius}. Walking {distance}m."
                )
                self.emit_event('found_cluster',
                                formatted=msg,
                                data={
                                    'num_points':
                                    cnt,
                                    'forts':
                                    log_lured_str,
                                    'radius':
                                    str(self.radius),
                                    'distance':
                                    str(
                                        round(
                                            distance(self.bot.position[0],
                                                     self.bot.position[1], lat,
                                                     lng), 2))
                                })

                self.announced = False

                step_walker = StepWalker(self.bot, lat, lng)

                self.is_at_destination = False
                if step_walker.step():
                    self.is_at_destination = True
            elif not self.announced:
                self.emit_event(
                    'arrived_at_cluster',
                    formatted=
                    "Arrived at cluster. {num_points} {forts} pokestops are in a range of {radius}m radius.",
                    data={
                        'num_points': cnt,
                        'forts': log_lured_str,
                        'radius': self.radius
                    })
                self.announced = True
        else:
            lat = self.bot.position[0]
            lng = self.bot.position[1]

        return [lat, lng]