Пример #1
0
def is_ditto(args, api, p, account):
    pokemon_id = p['pokemon_data']['pokemon_id']
    pokemon_name = get_pokemon_name(pokemon_id)
    captured_pokemon_name = pokemon_name
    log.info(
        u'{} may be a Ditto. Triggering catch logic!'.format(pokemon_name))

    # Encounter Pokemon.
    time.sleep(args.encounter_delay)
    encounter_pokemon_request(api, account, p['encounter_id'],
                              p['spawn_point_id'],
                              [p['latitude'], p['longitude']])

    # Now try to catch it.
    got_ditto = False
    catch_result = catch(api, p['encounter_id'], p['spawn_point_id'], account)
    if catch_result['catch_status'] == 'success':
        if int(catch_result['pid']) == DITTO_POKEDEX_ID:
            logmsg = u'Successfully caught a Ditto disguised as {}! Needed {} attempts.'
            captured_pokemon_name = get_pokemon_name(DITTO_POKEDEX_ID)
            got_ditto = True
        else:
            logmsg = u'Successfully caught a regular {} after {} attempts.'
        log.info(logmsg.format(pokemon_name, catch_result['attempts']))
        # Release the Pokemon in any case
        time.sleep(random.uniform(7, 10))
        if release(api, catch_result['capture_id'], account):
            log.info(
                u'Successfully released {}.'.format(captured_pokemon_name))
    else:
        log.info("Failed catching {}: {} Attempts: {}".format(
            pokemon_name, catch_result['reason'], catch_result['attempts']))
    return got_ditto
Пример #2
0
def is_ditto(args, pgacc, p):
    pokemon_id = p.pokemon_data.pokemon_id
    pokemon_name = get_pokemon_name(pokemon_id)
    log.info(
        u'{} may be a Ditto. Triggering catch logic!'.format(pokemon_name))

    # Encounter Pokemon.
    time.sleep(args.encounter_delay)
    encounter_pokemon_request(pgacc, p.encounter_id, p.spawn_point_id,
                              [p.latitude, p.longitude])

    # Now try to catch it.
    got_ditto = False
    catch_result = catch(pgacc, p.encounter_id, p.spawn_point_id)
    if catch_result['catch_status'] == 'success':
        if int(catch_result['pid']) == DITTO_POKEDEX_ID:
            logmsg = u'GXP: Successfully caught a Ditto disguised as {}! Needed {} attempts.'
            captured_pokemon_name = get_pokemon_name(DITTO_POKEDEX_ID)
            got_ditto = True
        else:
            logmsg = u'GXP: Successfully caught a regular {} after {} attempts.'
        log.info(logmsg.format(pokemon_name, catch_result['attempts']))
    else:
        log.info("GXP: Failed catching {}: {} Attempts: {}".format(
            pokemon_name, catch_result['reason'], catch_result['attempts']))
    return got_ditto
Пример #3
0
 def scout_pokemon(self):
     args = get_args()
     if args.pgscout_url:
         encounterId = request.args.get('encounter_id')
         p = Pokemon.get(Pokemon.encounter_id == encounterId)
         pokemon_name = get_pokemon_name(p.pokemon_id)
         save_encounter_id = p.encounter_id
         save_spawnpoint_id = p.spawnpoint_id
         p.encounter_id = b64encode(str(p.encounter_id))
         p.spawnpoint_id = format(p.spawnpoint_id, 'x')
         log.info(
             u"On demand PGScouting a {} at {}, {} with ID {} and spawn {}.".format(pokemon_name,
                                                           p.latitude,
                                                           p.longitude, encounterId, p.spawnpoint_id))
         scout_result = pgscout_encounter(p, 1)
         if scout_result['success']:
             p.encounter_id  = save_encounter_id
             p.spawnpoint_id = save_spawnpoint_id
             
             self.update_scouted_pokemon(p, scout_result)
             log.info(
                 u"Successfully PGScouted a {:.1f}% lvl {} {} with {} CP"
                 u" (scout level {}).".format(
                     scout_result['iv_percent'], scout_result['level'],
                     pokemon_name, scout_result['cp'],
                     scout_result['scout_level']))
         else:
             log.warning(u"Failed PGScouting {}: {}".format(pokemon_name,
                                                            scout_result[
                                                                'error']))
     else:
         scout_result = scout_error("Check IV URL not configured.")
     return jsonify(scout_result)
Пример #4
0
 def scout_pokemon(self):
     args = get_args()
     if args.pgscout_url:
         encounterId = request.args.get('encounter_id')
         p = Pokemon.get(Pokemon.encounter_id == encounterId)
         pokemon_name = get_pokemon_name(p.pokemon_id)
         log.info(
             u"On demand PGScouting a {} at {}, {}.".format(pokemon_name,
                                                           p.latitude,
                                                           p.longitude))
         scout_result = pgscout_encounter(p, forced=1)
         if scout_result['success']:
             self.update_scouted_pokemon(p, scout_result)
             if scout_result['weather_id'] == None:
                 scout_result['weather_id'] = 0
             log.info(
                 u"Successfully PGScouted a {:.1f}% lvl {} {} with {} CP {} Bonus"
                 u" (scout level {}).".format(
                     scout_result['iv_percent'], scout_result['level'],
                     pokemon_name, scout_result['cp'],
                     GameplayWeather.WeatherCondition.Name(scout_result['weather_id']),
                     scout_result['scout_level']))
         else:
             log.warning(u"Failed PGScouting {}: {}".format(pokemon_name,
                                                            scout_result[
                                                                'error']))
     else:
         scout_result = scout_error("PGScout URL not configured.")
     return jsonify(scout_result)
Пример #5
0
def perform_scout(p):
    global api, last_scout_timestamp, encounter_cache

    if not args.scout_account_username:
        return { "msg": "No scout account configured." }

    pokemon_name = get_pokemon_name(p.pokemon_id)

    # Check cache once in a non-blocking way
    if p.encounter_id in encounter_cache:
        result = encounter_cache[p.encounter_id]
        log.info(u"Cached scout-result: level {} {} with CP {}.".format(result["level"], pokemon_name, result["cp"]))
        return result

    scoutLock.acquire()
    try:
        # Check cache again after mutually exclusive access
        if p.encounter_id in encounter_cache:
            result = encounter_cache[p.encounter_id]
            log.info(u"Cached scout-result: level {} {} with CP {}.".format(result["level"], pokemon_name, result["cp"]))
            return result

        # Delay scouting
        now = time.time()
        if last_scout_timestamp is not None and now < last_scout_timestamp + scout_delay_seconds:
            wait_secs = last_scout_timestamp + scout_delay_seconds - now
            log.info("Waiting {} more seconds before next scout use.".format(wait_secs))
            time.sleep(wait_secs)

        log.info(u"Scouting a {} at {}, {}".format(pokemon_name, p.latitude, p.longitude))
        step_location = jitterLocation([p.latitude, p.longitude, 42])

        if api is None:
            # instantiate pgoapi
            api = PGoApi()

        api.set_position(*step_location)
        api.set_proxy({'http': args.scout_account_proxy, 'https': args.scout_account_proxy})
        account = {
            "auth_service": args.scout_account_auth,
            "username": args.scout_account_username,
            "password": args.scout_account_password,
        }
        check_login(args, account, api, None, False)

        if args.hash_key:
            key = key_scheduler.next()
            log.debug('Using key {} for this scout use.'.format(key))
            api.activate_hash_server(key)

        request_result = encounter_request(long(b64decode(p.encounter_id)), p.spawnpoint_id, p.latitude, p.longitude)

        # Update last timestamp
        last_scout_timestamp = time.time()
    finally:
        scoutLock.release()

    return parse_scout_result(request_result, p.encounter_id, pokemon_name)
Пример #6
0
def convert_pokemon_list(pokemon):
    args = get_args()
    # Performance:  disable the garbage collector prior to creating a
    # (potentially) large dict with append().
    gc.disable()

    pokemon_result = []
    for p in pokemon:
        p['pokemon_name'] = get_pokemon_name(p['pokemon_id'])
        p['pokemon_types'] = get_pokemon_types(p['pokemon_id'])
        p['encounter_id'] = str(p['encounter_id'])
        if args.china:
            p['latitude'], p['longitude'] = \
                transform_from_wgs_to_gcj(p['latitude'], p['longitude'])
        pokemon_result.append(p)

    # Re-enable the GC.
    gc.enable()
    return pokemon
Пример #7
0
def perform_scout(p):
    global api, last_scout_timestamp, encounter_cache

    if not args.scout:
        return {"msg": "Scouting disabled"}

    if len(accounts) == 0:
        return {"msg": "No scout account configured."}

    pokemon_name = get_pokemon_name(p.pokemon_id)

    # Check cache once in a non-blocking way
    if p.encounter_id in encounter_cache:
        result = encounter_cache[p.encounter_id]
        log.info(u"Cached scout-result: level {} {} with CP {}.".format(
            result["level"], pokemon_name, result["cp"]))
        return result

    step_location = []
    scoutLock.acquire()
    try:
        now = time.time()
        account = None
        wait_secs = args.scout_cooldown_delay
        for acc in accounts:
            if account is None:
                last_scout_timestamp = acc["last_used"]
                if acc['in_use']:
                    continue
                elif last_scout_timestamp is not None \
                    and now < last_scout_timestamp + args.scout_cooldown_delay:
                    wait_secs = min(
                        last_scout_timestamp + args.scout_cooldown_delay - now,
                        wait_secs)
                else:
                    account = acc
                    account["last_used"] = now
                    acc['in_use'] = True
    finally:
        scoutLock.release()

    if account is None:
        log.info(
            "Waiting {} more seconds before next scout use.".format(wait_secs))
        # time.sleep(wait_secs)
        request_result = {}
        request_result["wait"] = wait_secs
    else:
        # Check cache again after mutually exclusive access
        if p.encounter_id in encounter_cache:
            result = encounter_cache[p.encounter_id]
            log.info(u"Cached scout-result: level {} {} with CP {}.".format(
                result["level"], pokemon_name, result["cp"]))
            return result

        # Delay scouting

        if last_scout_timestamp is not None and now < last_scout_timestamp + args.scout_cooldown_delay:
            wait_secs = last_scout_timestamp + args.scout_cooldown_delay - now
            log.info("Waiting {} more seconds before next scout use.".format(
                wait_secs))
            # time.sleep(wait_secs)
            request_result = {}
            request_result["wait"] = wait_secs
        else:
            log.info(u"Scouting a {} at {}, {}".format(pokemon_name,
                                                       p.latitude,
                                                       p.longitude))
            step_location = jitter_location([p.latitude, p.longitude, 42])

            if api is None:
                # instantiate pgoapi
                api = PGoApi()

            api.set_position(*step_location)

            proxy_url = False
            if args.proxy is not None and len(args.proxy) > 0:
                proxy_num, proxy_url = get_new_proxy(args)
                if proxy_url:
                    log.debug('Using proxy %s', proxy_url)
                    api.set_proxy({'http': proxy_url, 'https': proxy_url})

            try:
                check_login(args, account, api, None, proxy_url)
                if args.hash_key:
                    key = key_scheduler.next()
                    log.debug('Using key {} for this scout use.'.format(key))
                    api.activate_hash_server(key)

                request_result = encounter_request(
                    long(b64decode(p.encounter_id)), p.spawnpoint_id,
                    p.latitude, p.longitude)

                # Update last timestamp
                account['last_used'] = time.time()
            except TooManyLoginAttempts:
                log.error("{} failed to login, going to sleep for 600 seconds".
                          format(account['username']))
                account['last_used'] = time.mktime(
                    (datetime.datetime.now() +
                     datetime.timedelta(seconds=600)).timetuple())
                account['in_use'] = False
                return {"msg": "Scout can't login"}
            finally:
                account['in_use'] = False

    return parse_scout_result(request_result, p.encounter_id, pokemon_name,
                              step_location, account)
Пример #8
0
    def test_get_pokemon_name(self):
        self.assertEqual("Bulbasaur", utils.get_pokemon_name(1))
        self.assertEqual("Dragonite", utils.get_pokemon_name(149))

        # Unknown ID raises KeyError
        self.assertRaises(KeyError, utils.get_pokemon_name, 12367)
Пример #9
0
def add_fake_pokemon(args, db_updates_queue, wh_update_queue,
                     fake_pokemon_objects):
    if not type(fake_pokemon_objects) is list:
        print 'Fake Script: add_fake_pokemon() expects a list'
        print 'instead, got ' + str(fake_pokemon_objects)
        return
    now_date = datetime.utcnow()
    pokemons = {}
    for obj in fake_pokemon_objects:
        error = False
        for key in ['pokemon_id', 'latitude', 'longitude', 'disappear_time']:
            if key not in obj.keys():
                print('fake_pokemon missing "' + key + '"')
                error = True
        if error:
            continue

        fakeid = random.getrandbits(64)
        fakeidstr = str(fakeid).decode('UTF-8')

        time_left_in_seconds = (obj['disappear_time']
                                - now_date).total_seconds()
        message = (utils.get_pokemon_name(obj['pokemon_id']) + ' expires in '
                   + str(time_left_in_seconds/60.) + ' minutes')
        skip_it = time_left_in_seconds <= 0 or time_left_in_seconds > 3600
        if skip_it:
            message += ' (skipping)'
        print(message)
        if skip_it:
            continue

        pokemon = {
            'encounter_id': b64encode(str(fakeid)),
            'spawnpoint_id': fakeidstr,
            'pokemon_id': None,
            'latitude': None,
            'longitude': None,
            'disappear_time': None,
            'individual_attack': None,
            'individual_defense': None,
            'individual_stamina': None,
            'move_1': None,
            'move_2': None,
            'cp': None,
            'height': None,
            'weight': None,
            'gender': None,
            'form': None,
            'cp_multiplier': None,
            }

        for key, value in obj.items():
            if key in pokemon:
                pokemon[key] = value
            else:
                print('got unknown fake-pokemon attribute: ' + key)

        pokemons[pokemon['encounter_id']] = pokemon

        if 'pokemon' in args.wh_types:
            pokemon_id = pokemon['pokemon_id']
            disappear_time = pokemon['disappear_time']
            if (not args.webhook_whitelist
                    or pokemon_id in args.webhook_whitelist):
                wh_poke = pokemons[pokemon['encounter_id']].copy()
                wh_poke.update({
                    'disappear_time': calendar.timegm(
                          disappear_time.timetuple()),
                    'last_modified_time': None, # todo
                    'time_until_hidden_ms': time_left_in_seconds*1000,
                    'verified': True, # todo?
                    'seconds_until_despawn': time_left_in_seconds,
                    'spawn_start': 777, # todo
                    'spawn_end': 888, # todo
                    'player_level': 17 # todo
                })
                if wh_poke['cp_multiplier'] is not None:
                    wh_poke.update({
                        'pokemon_level': calc_pokemon_level(
                            wh_poke['cp_multiplier'])
                    })
                wh_update_queue.put(('pokemon', wh_poke))

    if pokemons:
        db_updates_queue.put((Pokemon, pokemons))