コード例 #1
0
ファイル: move_to_fort.py プロジェクト: zoberg/PokemonGo-Bot
    def work(self):
        if not self.should_run():
            return WorkerResult.SUCCESS

        nearest_fort = self.get_nearest_fort()

        if nearest_fort is None:
            return WorkerResult.SUCCESS

        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)
        noised_dist = distance(self.bot.noised_position[0],
                               self.bot.noised_position[1], lat, lng)

        moving = noised_dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE if self.bot.config.replicate_gps_xy_noise else dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE

        if moving:
            fort_event_data = {
                'fort_name': u"{}".format(fort_name),
                'distance': format_dist(dist, unit),
            }

            if self.is_attracted() > 0:
                fort_event_data.update(
                    lure_distance=format_dist(self.lure_distance, unit))
                self.emit_event(
                    'moving_to_lured_fort',
                    formatted=
                    "Moving towards pokestop {fort_name} - {distance} (attraction of lure {lure_distance})",
                    data=fort_event_data)
            else:
                self.emit_event(
                    'moving_to_fort',
                    formatted=
                    "Moving towards pokestop {fort_name} - {distance}",
                    data=fort_event_data)

            step_walker = walker_factory(self.walker, self.bot, lat, lng)

            if not step_walker.step():
                return WorkerResult.RUNNING
        else:
            if nearest_fort.get('active_fort_modifier') and self.wait_at_fort:
                self.emit_event(
                    'arrived_at_fort',
                    formatted='Waiting near fort %s till Lure module expired' %
                    fort_name)
            else:
                self.emit_event('arrived_at_fort',
                                formatted='Arrived at fort.')

        return WorkerResult.SUCCESS
コード例 #2
0
    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
        )
コード例 #3
0
    def _move_to(self, pokemon):
        """Moves trainer towards a Pokemon.

        Args:
            pokemon: Pokemon to move to.

        Returns:
            Walker
        """
        self.emit_event(
            'move_to_map_pokemon_move_towards',
            formatted=('Moving towards {poke_name}, {poke_dist}, left ('
                       '{disappears_in})'),
            data=self._pokemon_event_data(pokemon))
        return walker_factory(self.walker, self.bot, pokemon['latitude'],
                              pokemon['longitude'])
コード例 #4
0
    def _move_to(self, pokemon):
        """Moves trainer towards a Pokemon.

        Args:
            pokemon: Pokemon to move to.

        Returns:
            Walker
        """
        self.emit_event(
            'move_to_map_pokemon_move_towards',
            formatted=('Moving towards {poke_name}, {poke_dist}, left ('
                       '{disappears_in})'),
            data=self._pokemon_event_data(pokemon)
        )
        return walker_factory(self.walker, self.bot, pokemon['latitude'], pokemon['longitude'])
コード例 #5
0
ファイル: move_to_fort.py プロジェクト: dtee/PokemonGo-Bot
    def work(self):
        if not self.should_run():
            return WorkerResult.SUCCESS

        nearest_fort = self.get_nearest_fort()

        if nearest_fort is None:
            return WorkerResult.SUCCESS

        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
        )
        noised_dist = distance(
            self.bot.noised_position[0],
            self.bot.noised_position[1],
            lat,
            lng
        )

        moving = noised_dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE if self.bot.config.replicate_gps_xy_noise else dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE

        if moving:
            self.wait_log_sent = None
            fort_event_data = {
                'fort_name': u"{}".format(fort_name),
                'distance': format_dist(dist, unit),
            }

            if self.is_attracted() > 0:
                fort_event_data.update(lure_distance=format_dist(self.lure_distance, unit))
                self.emit_event(
                    'moving_to_lured_fort',
                    formatted="Moving towards pokestop {fort_name} - {distance} (attraction of lure {lure_distance})",
                    data=fort_event_data
                )
            else:
                self.emit_event(
                    'moving_to_fort',
                    formatted="Moving towards pokestop {fort_name} - {distance}",
                    data=fort_event_data
                )

            step_walker = walker_factory(self.walker,
                self.bot,
                lat,
                lng
            )

            if not step_walker.step():
                return WorkerResult.RUNNING
        else:
            if not self.bot.catch_disabled and nearest_fort.get('active_fort_modifier') and self.wait_at_fort:
                if self.wait_log_sent == None or self.wait_log_sent < datetime.now() - timedelta(seconds=60):
                    self.wait_log_sent = datetime.now()
                    self.emit_event(
                        'arrived_at_fort',
                        formatted='Waiting near fort %s until lure module expires' % fort_name
                    )
            else:
                self.emit_event(
                    'arrived_at_fort',
                    formatted='Arrived at fort.'
                )

        return WorkerResult.RUNNING
コード例 #6
0
    def move_to_destination(self):
        if self.check_interval >= 4:
            self.check_interval = 0
            gyms = self.get_gyms()
            for g in gyms:
                if g["id"] == self.destination["id"]:
                    # self.logger.info("Inspecting target: %s" % g)
                    if "owned_by_team" in g and g[
                            "owned_by_team"] is not self.team:
                        self.logger.info(
                            "Damn! Team %s took gym before we arrived!" %
                            TEAMS[g["owned_by_team"]])
                        self.destination = None
                        return WorkerResult.SUCCESS
                    break
        else:
            self.check_interval += 1

        # Moving to a gym to deploy Pokemon
        unit = self.bot.config.distance_unit  # Unit to use when printing formatted distance
        lat = self.destination["latitude"]
        lng = self.destination["longitude"]
        details = fort_details(self.bot, self.destination["id"], lat, lng)
        gym_name = details.get('name', 'Unknown')

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

        moving = noised_dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE if self.bot.config.replicate_gps_xy_noise else dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE

        if moving:
            fort_event_data = {
                'fort_name': u"{}".format(gym_name),
                'distance': format_dist(dist, unit),
            }
            self.emit_event(
                'moving_to_fort',
                formatted="Moving towards open Gym {fort_name} - {distance}",
                data=fort_event_data)

            step_walker = walker_factory(self.walker, self.bot, lat, lng)

            if not step_walker.step():
                return WorkerResult.RUNNING
            else:
                #Running fails. Let's stop moving to the gym
                return WorkerResult.SUCCESS
        else:
            self.emit_event('arrived_at_fort',
                            formatted=("Arrived at Gym %s." % gym_name))
            gym_details = self.get_gym_details(self.destination)
            current_pokemons = self._get_pokemons_in_gym(gym_details)
            self.drop_pokemon_in_gym(self.destination, current_pokemons)
            self.destination = None
            if len(self.fort_pokemons) >= self.take_at_most:
                self.logger.info("We have a max of %s Pokemon in gyms." %
                                 self.take_at_most)
                return WorkerResult.SUCCESS
            elif self.chain_fill_gyms:
                # Look around if there are more gyms to fill
                self.determin_new_destination()
                # If there is none, we're done, else we go to the next!
                if self.destination is None:
                    return WorkerResult.SUCCESS
                else:
                    return WorkerResult.RUNNING
            else:
                return WorkerResult.SUCCESS
コード例 #7
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
コード例 #8
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
コード例 #9
0
    def work(self):
        if not self.should_run():
            return WorkerResult.SUCCESS

        if hasattr(self.bot, "hunter_locked_target") and self.bot.hunter_locked_target is not None:
            return WorkerResult.SUCCESS

        nearest_fort = self.get_nearest_fort()

        if nearest_fort is None:
            return WorkerResult.SUCCESS

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

        if self.target_id is None:
            self.target_id = fort_name

        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
        )
        noised_dist = distance(
            self.bot.noised_position[0],
            self.bot.noised_position[1],
            lat,
            lng
        )

        moving = noised_dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE if self.bot.config.replicate_gps_xy_noise else dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE

        distance_to_target = int(noised_dist if self.bot.config.replicate_gps_xy_noise else dist)
        if len(self.previous_distance) == 0:
            self.previous_distance.append(distance_to_target)
        elif self.target_id is not fort_name:
            # self.logger.info("Changed target from %s to %s" % (self.target_id, fort_name))
            self.previous_distance = [distance_to_target]
            self.target_id = fort_name
            if self.walker is not self.config.get('walker', 'StepWalker'):
                self.walker = self.config.get('walker', 'StepWalker')
        else:
            # self.logger.info("Previous distances: %s" % self.previous_distance)
            if len(self.previous_distance) > 5:
                self.previous_distance.pop(0)
            error_moving = False
            times_found = 0
            for prev_distance in self.previous_distance:
                if prev_distance == distance_to_target:
                    error_moving = True
                    break

            if error_moving:
                if self.walker == 'StepWalker':
                    self.logger.info("Having difficulty walking to %s" % fort_name)
                    self.bot.recent_forts = self.bot.recent_forts[1:] + [fortID]
                    return WorkerResult.ERROR
                else:
                    self.logger.info("Having difficulty walking to %s. Changing walker." % fort_name)
                    self.walker = 'StepWalker'
                    self.previous_distance = [distance_to_target]
            else:
                self.previous_distance.append(distance_to_target)

        if moving:
            self.wait_log_sent = None
            if "type" in nearest_fort and nearest_fort["type"] == 1:
                # It's a Pokestop
                target_type = "pokestop"
            else:
                # It's a gym
                target_type = "gym"

            fort_event_data = {
                'fort_name': u"{}".format(fort_name),
                'distance': format_dist(dist, unit),
                'target_type': target_type,
            }

            if self.is_attracted() > 0:
                fort_event_data.update(lure_distance=format_dist(self.lure_distance, unit))
                self.emit_event(
                    'moving_to_lured_fort',
                    formatted="Moving towards {target_type} {fort_name} - {distance} (attraction of lure {lure_distance})",
                    data=fort_event_data
                )
            else:
                self.emit_event(
                    'moving_to_fort',
                    formatted="Moving towards {target_type} {fort_name} - {distance}",
                    data=fort_event_data
                )

            step_walker = walker_factory(self.walker,
                self.bot,
                lat,
                lng
            )

            if not step_walker.step():
                return WorkerResult.RUNNING
        else:
            if not self.bot.catch_disabled and nearest_fort.get('active_fort_modifier') and self.wait_at_fort:
                if self.wait_log_sent == None or self.wait_log_sent < datetime.now() - timedelta(seconds=60):
                    self.wait_log_sent = datetime.now()
                    self.emit_event(
                        'arrived_at_fort',
                        formatted='Waiting near fort %s until lure module expires' % fort_name
                    )
            else:
                self.emit_event(
                    'arrived_at_fort',
                    formatted='Arrived at fort %s.' % fort_name
                )

        return WorkerResult.RUNNING
コード例 #10
0
    def move_to_destination(self):
        if self.check_interval >= 4 and not self.found_raid:
            self.check_interval = 0
            gyms = self.get_gyms()
            for g in gyms:
                if g["id"] == self.destination["id"]:
                    # self.logger.info("Inspecting target: %s" % g)
                    if "owned_by_team" in g and g[
                            "owned_by_team"] is not self.team:
                        self.logger.info(
                            "Damn! Team %s took gym before we arrived!" %
                            TEAMS[g["owned_by_team"]])
                        self.destination = None
                        return WorkerResult.SUCCESS
                    break
        elif not self.found_raid:
            self.check_interval += 1

        # Moving to a gym to deploy Pokemon / to start a raid
        unit = self.bot.config.distance_unit  # Unit to use when printing formatted distance
        lat = self.destination["latitude"]
        lng = self.destination["longitude"]
        details = fort_details(self.bot, self.destination["id"], lat, lng)
        gym_name = details.get('name', 'Unknown')

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

        moving = noised_dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE if self.bot.config.replicate_gps_xy_noise else dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE

        if moving:
            fort_event_data = {
                'fort_name': u"{}".format(gym_name),
                'distance': format_dist(dist, unit),
            }
            if not self.found_raid:
                self.emit_event(
                    'moving_to_fort',
                    formatted=
                    "Moving towards open Gym {fort_name} - {distance}",
                    data=fort_event_data)
            else:
                self.emit_event(
                    'moving_to_fort',
                    formatted=
                    "Moving towards raid Gym {fort_name} - {distance}",
                    data=fort_event_data)

            step_walker = walker_factory(self.walker, self.bot, lat, lng)

            if not step_walker.step():
                return WorkerResult.RUNNING
            else:
                #Running fails. Let's stop moving to the gym
                return WorkerResult.SUCCESS
        else:
            self.emit_event('arrived_at_fort',
                            formatted=("Arrived at Gym %s." % gym_name))
            gym_details = self.get_gym_details(self.destination)

            if not self.found_raid:
                current_pokemons = self._get_pokemons_in_gym(gym_details)
                self.drop_pokemon_in_gym(self.destination, current_pokemons)
                self.destination = None
                if len(self.fort_pokemons) >= self.take_at_most:
                    self.logger.info("We have a max of %s Pokemon in gyms." %
                                     self.take_at_most)
                    return WorkerResult.SUCCESS
                elif self.chain_fill_gyms:
                    # Look around if there are more gyms to fill
                    self.determin_new_destination()
                    # If there is none, we're done, else we go to the next!
                    if self.destination is None:
                        return WorkerResult.SUCCESS
                    else:
                        return WorkerResult.RUNNING
                else:
                    return WorkerResult.SUCCESS
            else:
                # we are going to do raid
                # steps: 1. Check if has started. if not started, we wait till start. if started we wait till max number of players in lobby reached.
                # if all conditions met, enter lobby
                # get ready a list of battling pokemons (using type advenage logic)
                # start battle
                # if failed, heal and restart the process
                # successful raid, go to bonus capture
                # reset raid, return success
                gym_info = gym_details.get('gym_status_and_defenders', None)
                if gym_info is not None:
                    pokemon_fort_proto = gym_info.get('pokemon_fort_proto')
                    raid_info = pokemon_fort_proto.get('raid_info')
                    raid_level = raid_info['raid_level']
                    raid_seed = raid_info['raid_seed']
                    raid_end_ms = raid_info['raid_end_ms']
                    raid_battle_ms = raid_info['raid_battle_ms']
                    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'))

                    if raid_starts < datetime.now():
                        timediff = raid_ends - datetime.now()
                        results = divmod(
                            timediff.days * 86400 + timediff.seconds, 60)
                        # No need check what pokemon anymore
                        if results[0] >= self.do_not_raid_last_x_mins:
                            a = 0
                        #
                        #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!")

                self.logger.info("Assume we are done with raid")
                print("id: " + format(gym_info['pokemon_fort_proto']['id']))
                if gym_info['pokemon_fort_proto']['id']:
                    self.raided_gyms.append(
                        gym_info['pokemon_fort_proto']['id']
                    )  #check if this need to be removed after successful implenation of raid feature
                print("dropped_gyms: " + format(self.raided_gyms))
                self.destination = None
                self.found_raid = False
                return WorkerResult.SUCCESS
コード例 #11
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]
コード例 #12
0
ファイル: follow_path.py プロジェクト: uniari/PokemonGo-Bot
    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
コード例 #13
0
    def move_to_destination(self):
        if self.check_interval >= 4 and not self.found_raid:
            self.check_interval = 0
            gyms = self.get_gyms()
            for g in gyms:
                if g["id"] == self.destination["id"]:
                    # self.logger.info("Inspecting target: %s" % g)
                    if "owned_by_team" in g and g["owned_by_team"] is not self.team:
                        self.logger.info("Damn! Team %s took gym before we arrived!" % TEAMS[g["owned_by_team"]])
                        self.destination = None
                        return WorkerResult.SUCCESS
                    break
        elif not self.found_raid:
            self.check_interval += 1

        # Moving to a gym to deploy Pokemon / to start a raid
        unit = self.bot.config.distance_unit  # Unit to use when printing formatted distance
        lat = self.destination["latitude"]
        lng = self.destination["longitude"]
        details = fort_details(self.bot, self.destination["id"], lat, lng)
        gym_name = details.get('name', 'Unknown')

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

        moving = noised_dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE if self.bot.config.replicate_gps_xy_noise else dist > Constants.MAX_DISTANCE_FORT_IS_REACHABLE

        if moving:
            fort_event_data = {
                'fort_name': u"{}".format(gym_name),
                'distance': format_dist(dist, unit),
            }
            if not self.found_raid:
                self.emit_event(
                    'moving_to_fort',
                    formatted="Moving towards open Gym {fort_name} - {distance}",
                    data=fort_event_data
                )
            else:
                self.emit_event(
                    'moving_to_fort',
                    formatted="Moving towards raid Gym {fort_name} - {distance}",
                    data=fort_event_data
                )

            step_walker = walker_factory(self.walker, self.bot, lat, lng)

            if not step_walker.step():
                return WorkerResult.RUNNING
            else:
                #Running fails. Let's stop moving to the gym
                return WorkerResult.SUCCESS
        else:
            self.emit_event(
                'arrived_at_fort',
                formatted=("Arrived at Gym %s." % gym_name)
            )
            gym_details = self.get_gym_details(self.destination)
            
            if not self.found_raid:
                current_pokemons = self._get_pokemons_in_gym(gym_details)
                self.drop_pokemon_in_gym(self.destination, current_pokemons)
                self.destination = None
                if len(self.fort_pokemons) >= self.take_at_most:
                    self.logger.info("We have a max of %s Pokemon in gyms." % self.take_at_most)
                    return WorkerResult.SUCCESS
                elif self.chain_fill_gyms:
                    # Look around if there are more gyms to fill
                    self.determin_new_destination()
                    # If there is none, we're done, else we go to the next!
                    if self.destination is None:
                        return WorkerResult.SUCCESS
                    else:
                        return WorkerResult.RUNNING
                else:
                    return WorkerResult.SUCCESS
            else:
                # we are going to do raid 
                # steps: 1. Check if has started. if not started, we wait till start. if started we wait till max number of players in lobby reached.
                # if all conditions met, enter lobby
                # get ready a list of battling pokemons (using type advenage logic)
                # start battle
                # if failed, heal and restart the process
                # successful raid, go to bonus capture
                # reset raid, return success
                gym_info = gym_details.get('gym_status_and_defenders', None)
                if gym_info is not None:
                    pokemon_fort_proto = gym_info.get('pokemon_fort_proto')
                    raid_info = pokemon_fort_proto.get('raid_info')
                    raid_level = raid_info['raid_level']
                    raid_seed = raid_info['raid_seed']
                    raid_end_ms = raid_info['raid_end_ms']
                    raid_battle_ms = raid_info['raid_battle_ms']
                    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'))
                    
                    if raid_starts < datetime.now():
                        timediff = raid_ends - datetime.now()
                        results = divmod(timediff.days * 86400 + timediff.seconds, 60)
                        # No need check what pokemon anymore
                        if results[0] >= self.do_not_raid_last_x_mins:
                            a=0
                        #
                        #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!")
                    
                self.logger.info("Assume we are done with raid")
                print("id: "+format(gym_info['pokemon_fort_proto']['id']))
                if gym_info['pokemon_fort_proto']['id']:
                    self.raided_gyms.append(gym_info['pokemon_fort_proto']['id'])#check if this need to be removed after successful implenation of raid feature
                print("dropped_gyms: "+format(self.raided_gyms))
                self.destination = None
                self.found_raid = False
                return WorkerResult.SUCCESS