Skip to content

Commit

Permalink
add tests, and modify calls to api accordingly
Browse files Browse the repository at this point in the history
  • Loading branch information
DayBr3ak committed Aug 2, 2016
1 parent 61d0449 commit 26f6087
Show file tree
Hide file tree
Showing 14 changed files with 94 additions and 81 deletions.
29 changes: 11 additions & 18 deletions pokemongo_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,12 @@ def update_web_location(self, cells=[], lat=None, lng=None, alt=None):
if cells == []:
cellid = get_cell_ids(lat, lng)
timestamp = [0, ] * len(cellid)
self.api.get_map_objects(
response_dict = self.api.get_map_objects(
latitude=f2i(lat),
longitude=f2i(lng),
since_timestamp_ms=timestamp,
cell_id=cellid
)
response_dict = self.api.call()
map_objects = response_dict.get(
'responses', {}
).get('GET_MAP_OBJECTS', {})
Expand All @@ -139,14 +138,13 @@ def update_web_location(self, cells=[], lat=None, lng=None, alt=None):
if 'forts' in cell:
for fort in cell['forts']:
if fort.get('type') != 1:
self.api.get_gym_details(
response_gym_details = self.api.get_gym_details(
gym_id=fort.get('id'),
player_latitude=lng,
player_longitude=lat,
gym_latitude=fort.get('latitude'),
gym_longitude=fort.get('longitude')
)
response_gym_details = self.api.call()
fort['gym_details'] = response_gym_details.get(
'responses', {}
).get('GET_GYM_DETAILS', None)
Expand Down Expand Up @@ -183,13 +181,12 @@ def find_close_cells(self, lat, lng):
cellid = get_cell_ids(lat, lng)
timestamp = [0, ] * len(cellid)

self.api.get_map_objects(
response_dict = self.api.get_map_objects(
latitude=f2i(lat),
longitude=f2i(lng),
since_timestamp_ms=timestamp,
cell_id=cellid
)
response_dict = self.api.call()
map_objects = response_dict.get(
'responses', {}
).get('GET_MAP_OBJECTS', {})
Expand Down Expand Up @@ -275,7 +272,7 @@ def login(self):

def _setup_api(self):
# instantiate pgoapi
self.api = ApiWrapper(PGoApi())
self.api = ApiWrapper()

# provide player position on the earth
self._set_starting_position()
Expand All @@ -294,8 +291,7 @@ def _setup_api(self):
def _print_character_info(self):
# get player profile call
# ----------------------
self.api.get_player()
response_dict = self.api.call()
response_dict = self.api.get_player()
# print('Response dictionary: \n\r{}'.format(json.dumps(response_dict, indent=2)))
currency_1 = "0"
currency_2 = "0"
Expand Down Expand Up @@ -376,15 +372,11 @@ def _print_character_info(self):
logger.log('')

def use_lucky_egg(self):
self.api.use_item_xp_boost(item_id=301)
inventory_req = self.api.call()
return inventory_req
return self.api.use_item_xp_boost(item_id=301)

def get_inventory(self):
if self.latest_inventory is None:
self.api.get_inventory()
response = self.api.call()
self.latest_inventory = response
self.latest_inventory = self.api.get_inventory()
return self.latest_inventory

def update_inventory(self):
Expand Down Expand Up @@ -548,9 +540,10 @@ def heartbeat(self):
self.fort_timeouts = {id: timeout for id, timeout
in self.fort_timeouts.iteritems()
if timeout >= time.time() * 1000}
self.api.get_player()
self.api.check_awarded_badges()
self.api.call()
request = self.api.create_request()
request.get_player()
request.check_awarded_badges()
request.call()
self.update_web_location() # updates every tick

def get_inventory_count(self, what):
Expand Down
3 changes: 1 addition & 2 deletions pokemongo_bot/cell_workers/collect_level_up_reward.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ def work(self):
self.previous_level = self.current_level

def _collect_level_reward(self):
self.bot.api.level_up_rewards(level=self.current_level)
response_dict = self.bot.api.call()
response_dict = self.bot.api.level_up_rewards(level=self.current_level)
if 'status_code' in response_dict and response_dict['status_code'] == 1:
data = (response_dict
.get('responses', {})
Expand Down
6 changes: 2 additions & 4 deletions pokemongo_bot/cell_workers/evolve_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,7 @@ def _execute_pokemon_evolve(self, pokemon, cache):
if pokemon_name in cache:
return

self.bot.api.evolve_pokemon(pokemon_id=pokemon_id)
response_dict = self.bot.api.call()
response_dict = self.bot.api.evolve_pokemon(pokemon_id=pokemon_id)
status = response_dict['responses']['EVOLVE_POKEMON']['result']
if status == 1:
logger.log('[#] Successfully evolved {} with {} CP and {} IV!'.format(
Expand All @@ -173,8 +172,7 @@ def _execute_pokemon_evolve(self, pokemon, cache):

# TODO: move to utils. These methods are shared with other workers.
def transfer_pokemon(self, pid):
self.bot.api.release_pokemon(pokemon_id=pid)
response_dict = self.bot.api.call()
response_dict = self.bot.api.release_pokemon(pokemon_id=pid)

def count_pokemon_inventory(self):
response_dict = self.bot.get_inventory()
Expand Down
1 change: 0 additions & 1 deletion pokemongo_bot/cell_workers/handle_soft_ban.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ def spin_fort(self, fort):
player_latitude=f2i(self.bot.position[0]),
player_longitude=f2i(self.bot.position[1])
)
self.bot.api.call()

def should_run(self):
return self.bot.softban
9 changes: 5 additions & 4 deletions pokemongo_bot/cell_workers/incubate_eggs.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ def _apply_incubators(self):
continue
if self.bot.config.debug:
logger.log('[x] Attempting to apply incubator {} to egg {}'.format(incubator['id'], egg['id']))
self.bot.api.use_item_egg_incubator(item_id=incubator["id"], pokemon_id=egg["id"])
ret = self.bot.api.call()
ret = self.bot.api.use_item_egg_incubator(
item_id=incubator["id"],
pokemon_id=egg["id"]
)
if ret:
code = ret.get("responses", {}).get("USE_ITEM_EGG_INCUBATOR", {}).get("result", 0)
if code == 1:
Expand Down Expand Up @@ -125,8 +127,7 @@ def _check_inventory(self, lookup_ids=[]):
return matched_pokemon

def _hatch_eggs(self):
self.bot.api.get_hatched_eggs()
response_dict = self.bot.api.call()
response_dict = self.bot.api.get_hatched_eggs()
log_color = 'green'
try:
result = reduce(dict.__getitem__, ["responses", "GET_HATCHED_EGGS"], response_dict)
Expand Down
13 changes: 6 additions & 7 deletions pokemongo_bot/cell_workers/nickname_pokemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def initialize(self):
self.template = self.config.get('nickname_template','').lower().strip()
if self.template == "{name}":
self.template = ""

def work(self):
try:
inventory = reduce(dict.__getitem__, ["responses", "GET_INVENTORY", "inventory_delta", "inventory_items"], self.bot.get_inventory())
Expand All @@ -16,8 +16,8 @@ def work(self):
else:
pokemon_data = self._get_inventory_pokemon(inventory)
for pokemon in pokemon_data:
self._nickname_pokemon(pokemon)
self._nickname_pokemon(pokemon)

def _get_inventory_pokemon(self,inventory_dict):
pokemon_data = []
for inv_data in inventory_dict:
Expand All @@ -29,7 +29,7 @@ def _get_inventory_pokemon(self,inventory_dict):
if not pokemon.get('is_egg',False):
pokemon_data.append(pokemon)
return pokemon_data

def _nickname_pokemon(self,pokemon):
"""This requies a pokemon object containing all the standard fields: id, ivs, cp, etc"""
new_name = ""
Expand Down Expand Up @@ -62,10 +62,9 @@ def _nickname_pokemon(self,pokemon):
logger.log("Unable to nickname {} due to bad template ({})".format(name,bad_key),log_color)
if pokemon.get('nickname', "") == new_name:
return
self.bot.api.nickname_pokemon(pokemon_id=instance_id,nickname=new_name)
response = self.bot.api.call()
response = self.bot.api.nickname_pokemon(pokemon_id=instance_id,nickname=new_name)
sleep(1.2)
try:
try:
result = reduce(dict.__getitem__, ["responses", "NICKNAME_POKEMON"], response)
except KeyError:
logger.log("Attempt to nickname received bad response from server.",log_color)
Expand Down
62 changes: 38 additions & 24 deletions pokemongo_bot/cell_workers/pokemon_catch_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,11 @@ def work(self):
break

# Use the berry to catch
self.api.use_item_capture(item_id = berry_id,encounter_id = encounter_id,spawn_point_id = self.spawn_point_guid)
response_dict = self.api.call()
response_dict = self.api.use_item_capture(
item_id=berry_id,
encounter_id=encounter_id,
spawn_point_id=self.spawn_point_guid
)
if response_dict and response_dict['status_code'] is 1 and 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']:
for i in range(len(catch_rate)):
if 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']:
Expand Down Expand Up @@ -126,8 +129,10 @@ def work(self):

success_percentage = '{0:.2f}'.format(catch_rate[pokeball-1]*100)
logger.log('Catch Rate with normal Pokeball is low ({}%). Thinking to throw a {}... ({} left!)'.format(success_percentage,self.item_list[str(berry_id)],berries_count-1))
self.api.use_item_capture(item_id = berry_id,encounter_id = encounter_id,spawn_point_id = self.spawn_point_guid)
response_dict = self.api.call()
response_dict = self.api.use_item_capture(item_id=berry_id,
encounter_id=encounter_id,
spawn_point_id=self.spawn_point_guid
)
if response_dict and response_dict['status_code'] is 1 and 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']:
for i in range(len(catch_rate)):
if 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']:
Expand Down Expand Up @@ -159,8 +164,10 @@ def work(self):

success_percentage = '{0:.2f}'.format(catch_rate[pokeball-1]*100)
logger.log('Catch Rate with normal Pokeball is low ({}%). Thinking to throw a {}... ({} left!)'.format(success_percentage,self.item_list[str(berry_id)],berries_count-1))
self.api.use_item_capture(item_id = berry_id,encounter_id = encounter_id,spawn_point_id = self.spawn_point_guid)
response_dict = self.api.call()
response_dict = self.api.use_item_capture(item_id=berry_id,
encounter_id=encounter_id,
spawn_point_id=self.spawn_point_guid
)
if response_dict and response_dict['status_code'] is 1 and 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']:
for i in range(len(catch_rate)):
if 'item_capture_mult' in response_dict['responses']['USE_ITEM_CAPTURE']:
Expand Down Expand Up @@ -205,14 +212,15 @@ def work(self):
reticle_size_parameter = normalized_reticle_size(self.config.catch_randomize_reticle_factor)
spin_modifier_parameter = spin_modifier(self.config.catch_randomize_spin_factor)

self.api.catch_pokemon(encounter_id=encounter_id,
pokeball=pokeball,
normalized_reticle_size=reticle_size_parameter,
spawn_point_id=self.spawn_point_guid,
hit_pokemon=1,
spin_modifier=spin_modifier_parameter,
normalized_hit_position=1)
response_dict = self.api.call()
response_dict = self.api.catch_pokemon(
encounter_id=encounter_id,
pokeball=pokeball,
normalized_reticle_size=reticle_size_parameter,
spawn_point_id=self.spawn_point_guid,
hit_pokemon=1,
spin_modifier=spin_modifier_parameter,
normalized_hit_position=1
)

if response_dict and \
'responses' in response_dict and \
Expand Down Expand Up @@ -254,8 +262,7 @@ def work(self):
if len(pokemon_to_transfer) == 0:
raise RuntimeError(
'Trying to evolve 0 pokemons!')
self.api.evolve_pokemon(pokemon_id=pokemon_to_transfer[0])
response_dict = self.api.call()
response_dict = self.api.evolve_pokemon(pokemon_id=pokemon_to_transfer[0])
status = response_dict['responses']['EVOLVE_POKEMON']['result']
if status == 1:
logger.log(
Expand All @@ -269,8 +276,7 @@ def work(self):
def count_pokemon_inventory(self):
# don't use cached bot.get_inventory() here
# because we need to have actual information in capture logic
self.api.get_inventory()
response_dict = self.api.call()
response_dict = self.api.get_inventory()

id_list = []
callback = lambda pokemon: id_list.append(pokemon['id'])
Expand Down Expand Up @@ -360,22 +366,30 @@ def create_encounter_api_call(self):
player_latitude = self.pokemon['latitude']
player_longitude = self.pokemon['longitude']

request = self.api.create_request()
if 'spawn_point_id' in self.pokemon:
spawn_point_id = self.pokemon['spawn_point_id']
self.spawn_point_guid = spawn_point_id
self.response_key = 'ENCOUNTER'
self.response_status_key = 'status'
self.api.encounter(encounter_id=encounter_id, spawn_point_id=spawn_point_id,
player_latitude=player_latitude, player_longitude=player_longitude)
request.encounter(
encounter_id=encounter_id,
spawn_point_id=spawn_point_id,
player_latitude=player_latitude,
player_longitude=player_longitude
)
else:
fort_id = self.pokemon['fort_id']
self.spawn_point_guid = fort_id
self.response_key = 'DISK_ENCOUNTER'
self.response_status_key = 'result'
self.api.disk_encounter(encounter_id=encounter_id, fort_id=fort_id,
player_latitude=player_latitude, player_longitude=player_longitude)

return self.api.call()
request.disk_encounter(
encounter_id=encounter_id,
fort_id=fort_id,
player_latitude=player_latitude,
player_longitude=player_longitude
)
return request.call()

def check_vip_pokemon(self,pokemon, cp, iv):

Expand Down
8 changes: 4 additions & 4 deletions pokemongo_bot/cell_workers/recycle_items.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ def work(self):
logger.log("-- Failed to discard " + item_name, 'red')

def send_recycle_item_request(self, item_id, count):
self.bot.api.recycle_inventory_item(item_id=item_id, count=count)
inventory_req = self.bot.api.call()

# Example of good request response
#{'responses': {'RECYCLE_INVENTORY_ITEM': {'result': 1, 'new_count': 46}}, 'status_code': 1, 'auth_ticket': {'expire_timestamp_ms': 1469306228058L, 'start': '/HycFyfrT4t2yB2Ij+yoi+on778aymMgxY6RQgvrGAfQlNzRuIjpcnDd5dAxmfoTqDQrbz1m2dGqAIhJ+eFapg==', 'end': 'f5NOZ95a843tgzprJo4W7Q=='}, 'request_id': 8145806132888207460L}
return inventory_req
return self.bot.api.recycle_inventory_item(
item_id=item_id,
count=count
)
13 changes: 7 additions & 6 deletions pokemongo_bot/cell_workers/spin_fort.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@ def work(self):
logger.log('Now at Pokestop: {0}'.format(fort_name), 'cyan')
logger.log('Spinning ...', 'cyan')

self.bot.api.fort_search(fort_id=fort['id'],
fort_latitude=lat,
fort_longitude=lng,
player_latitude=f2i(self.bot.position[0]),
player_longitude=f2i(self.bot.position[1]))
response_dict = self.bot.api.call()
response_dict = self.bot.api.fort_search(
fort_id=fort['id'],
fort_latitude=lat,
fort_longitude=lng,
player_latitude=f2i(self.bot.position[0]),
player_longitude=f2i(self.bot.position[1])
)
if 'responses' in response_dict and \
'FORT_SEARCH' in response_dict['responses']:

Expand Down
9 changes: 5 additions & 4 deletions pokemongo_bot/cell_workers/transfer_pokemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,10 @@ def work(self):

def _release_pokemon_get_groups(self):
pokemon_groups = {}
self.bot.api.get_player().get_inventory()
inventory_req = self.bot.api.call()
request = self.bot.api.create_request()
request.get_player()
request.get_inventory()
inventory_req = request.call()

if inventory_req.get('responses', False) is False:
return pokemon_groups
Expand Down Expand Up @@ -173,8 +175,7 @@ def release_pokemon(self, pokemon_name, cp, iv, pokemon_id):
logger.log('Exchanging {} [CP {}] [Potential {}] for candy!'.format(pokemon_name,
cp,
iv), 'green')
self.bot.api.release_pokemon(pokemon_id=pokemon_id)
response_dict = self.bot.api.call()
response_dict = self.bot.api.release_pokemon(pokemon_id=pokemon_id)
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)

def _get_release_config_for(self, pokemon):
Expand Down
6 changes: 3 additions & 3 deletions pokemongo_bot/cell_workers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ def fort_details(bot, fort_id, latitude, longitude):
"""
Lookup the fort details and cache the response for future use.
"""
bot.api.fort_details(fort_id=fort_id, latitude=latitude, longitude=longitude)

request = bot.api.create_request()
request.fort_details(fort_id=fort_id, latitude=latitude, longitude=longitude)
try:
response_dict = bot.api.call()
response_dict = request.call()
FORT_CACHE[fort_id] = response_dict['responses']['FORT_DETAILS']
except Exception:
pass
Expand Down
Loading

0 comments on commit 26f6087

Please sign in to comment.