Skip to content

Commit

Permalink
Removed the old inventory / only one call to the api (#3948)
Browse files Browse the repository at this point in the history
* Removed every call to the old inventory
Added some messages to monitor item inventory
Added some methods needed on the new inventory

* Removed print

* Removed print

* Keeps track of candy on pokemon catch

* Dynamically count candy gained

* Rename pokemon id in pokemon unique id

* Fixed typo
Some clean up

* Renamed pokemon id in unique_id

* Now display again stats on start

* Now use ultraball on non vip too

* Merge branch 'dev' of https://github.com/PokemonGoF/PokemonGo-Bot into remove-old-inventory

# Conflicts:
#	pokemongo_bot/__init__.py

Now move to map use cached inventory
Removed log.logger()
  • Loading branch information
BriceSD authored and solderzzc committed Aug 18, 2016
1 parent 660bb62 commit 91ad8df
Show file tree
Hide file tree
Showing 11 changed files with 167 additions and 243 deletions.
1 change: 1 addition & 0 deletions pokecli.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from pgoapi.exceptions import NotLoggedInException, ServerSideRequestThrottlingException, ServerBusyOrOfflineException
from geopy.exc import GeocoderQuotaExceeded

from pokemongo_bot import inventory
from pokemongo_bot import PokemonGoBot, TreeConfigBuilder
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.health_record import BotEvent
Expand Down
225 changes: 59 additions & 166 deletions pokemongo_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,11 @@ def start(self):
self._setup_logging()
self._setup_api()
self._load_recent_forts()
init_inventory(self)
self.display_player_info()
self._print_character_info()
if self.config.pokemon_bag_show_at_start and self.config.pokemon_bag_pokemon_info:
self._print_list_pokemon()

random.seed()

Expand Down Expand Up @@ -753,12 +758,8 @@ def _setup_api(self):
self.login()
# chain subrequests (methods) into one RPC call

self._print_character_info()
if self.config.pokemon_bag_show_at_start and self.config.pokemon_bag_pokemon_info:
self._print_list_pokemon()
self.api.activate_signature(self.get_encryption_lib())
self.logger.info('')
self.update_inventory()
# send empty map_cells and then our position
self.update_web_location()

Expand Down Expand Up @@ -788,25 +789,25 @@ def _print_character_info(self):

pokecoins = '0'
stardust = '0'
items_stock = self.current_inventory()
items_inventory = inventory.items()

if 'amount' in player['currencies'][0]:
pokecoins = player['currencies'][0]['amount']
if 'amount' in player['currencies'][1]:
stardust = player['currencies'][1]['amount']
self.logger.info('')
self.logger.info('--- {username} ---'.format(**player))
self.get_player_info()

self.logger.info(
'Pokemon Bag: {}/{}'.format(
self.get_inventory_count('pokemon'),
player['max_pokemon_storage']
inventory.Pokemons.get_space_used(),
inventory.get_pokemon_inventory_size()
)
)
self.logger.info(
'Items: {}/{}'.format(
self.get_inventory_count('item'),
player['max_item_storage']
inventory.Items.get_space_used(),
inventory.get_item_inventory_size()
)
)
self.logger.info(
Expand All @@ -815,41 +816,39 @@ def _print_character_info(self):
)
# Items Output
self.logger.info(
'PokeBalls: ' + str(items_stock[1]) +
' | GreatBalls: ' + str(items_stock[2]) +
' | UltraBalls: ' + str(items_stock[3]) +
' | MasterBalls: ' + str(items_stock[4]))
'PokeBalls: ' + str(items_inventory.get(1).count) +
' | GreatBalls: ' + str(items_inventory.get(2).count) +
' | UltraBalls: ' + str(items_inventory.get(3).count) +
' | MasterBalls: ' + str(items_inventory.get(4).count))

self.logger.info(
'RazzBerries: ' + str(items_stock[701]) +
' | BlukBerries: ' + str(items_stock[702]) +
' | NanabBerries: ' + str(items_stock[703]))
'RazzBerries: ' + str(items_inventory.get(701).count) +
' | BlukBerries: ' + str(items_inventory.get(702).count) +
' | NanabBerries: ' + str(items_inventory.get(703).count))

self.logger.info(
'LuckyEgg: ' + str(items_stock[301]) +
' | Incubator: ' + str(items_stock[902]) +
' | TroyDisk: ' + str(items_stock[501]))
'LuckyEgg: ' + str(items_inventory.get(301).count) +
' | Incubator: ' + str(items_inventory.get(902).count) +
' | TroyDisk: ' + str(items_inventory.get(501).count))

self.logger.info(
'Potion: ' + str(items_stock[101]) +
' | SuperPotion: ' + str(items_stock[102]) +
' | HyperPotion: ' + str(items_stock[103]) +
' | MaxPotion: ' + str(items_stock[104]))
'Potion: ' + str(items_inventory.get(101).count) +
' | SuperPotion: ' + str(items_inventory.get(102).count) +
' | HyperPotion: ' + str(items_inventory.get(103).count) +
' | MaxPotion: ' + str(items_inventory.get(104).count))

self.logger.info(
'Incense: ' + str(items_stock[401]) +
' | IncenseSpicy: ' + str(items_stock[402]) +
' | IncenseCool: ' + str(items_stock[403]))
'Incense: ' + str(items_inventory.get(401).count) +
' | IncenseSpicy: ' + str(items_inventory.get(402).count) +
' | IncenseCool: ' + str(items_inventory.get(403).count))

self.logger.info(
'Revive: ' + str(items_stock[201]) +
' | MaxRevive: ' + str(items_stock[202]))
'Revive: ' + str(items_inventory.get(201).count) +
' | MaxRevive: ' + str(items_inventory.get(202).count))

self.logger.info('')

def _print_list_pokemon(self):
init_inventory(self)

# get pokemon list
pokemon_list = inventory.pokemons().all()
pokemon_list = sorted(pokemon_list, key=lambda k: k.pokemon_id)
Expand Down Expand Up @@ -898,84 +897,6 @@ def get_poke_info(info, pokemon):
def use_lucky_egg(self):
return self.api.use_item_xp_boost(item_id=301)

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

def update_inventory(self):
# TODO: transition to using this inventory class everywhere
init_inventory(self)
response = self.get_inventory()
self.inventory = list()
inventory_items = response.get('responses', {}).get('GET_INVENTORY', {}).get(
'inventory_delta', {}).get('inventory_items', {})
if inventory_items:
for item in inventory_items:
item_info = item.get('inventory_item_data', {}).get('item', {})
if {"item_id", "count"}.issubset(set(item_info.keys())):
self.inventory.append(item['inventory_item_data']['item'])

def current_inventory(self):
inventory_req = self.get_inventory()
inventory_dict = inventory_req['responses']['GET_INVENTORY'][
'inventory_delta']['inventory_items']

user_web_inventory = os.path.join(_base_dir, 'web', 'inventory-%s.json' % self.config.username)

try:
with open(user_web_inventory, 'w') as outfile:
json.dump(inventory_dict, outfile)
except IOError as e:
self.logger.info('[x] Error while opening location file: %s' % e)

# get player items stock
# ----------------------
items_stock = {x.value: 0 for x in list(Item)}

for item in inventory_dict:
item_dict = item.get('inventory_item_data', {}).get('item', {})
item_count = item_dict.get('count')
item_id = item_dict.get('item_id')

if item_count and item_id:
if item_id in items_stock:
items_stock[item_id] = item_count
return items_stock

def item_inventory_count(self, id):
inventory_req = self.get_inventory()
inventory_dict = inventory_req['responses'][
'GET_INVENTORY']['inventory_delta']['inventory_items']

if id == 'all':
return self._all_items_inventory_count(inventory_dict)
else:
return self._item_inventory_count_per_id(id, inventory_dict)

def _item_inventory_count_per_id(self, id, inventory_dict):
item_count = 0

for item in inventory_dict:
item_dict = item.get('inventory_item_data', {}).get('item', {})
item_id = item_dict.get('item_id', False)
item_count = item_dict.get('count', False)
if item_id == int(id) and item_count:
return item_count
return 0

def _all_items_inventory_count(self, inventory_dict):
item_count_dict = {}

for item in inventory_dict:
item_dict = item.get('inventory_item_data', {}).get('item', {})
item_id = item_dict.get('item_id', False)
item_count = item_dict.get('count', False)
if item_id and item_count:
item_count_dict[item_id] = item_count

return item_count_dict

def _set_starting_position(self):

self.event_manager.emit(
Expand Down Expand Up @@ -1129,63 +1050,35 @@ def update_web_location_worker(self):
self.web_update_queue.get()
self.update_web_location()

def get_inventory_count(self, what):
response_dict = self.get_inventory()
inventory_items = response_dict.get('responses', {}).get('GET_INVENTORY', {}).get(
'inventory_delta', {}).get('inventory_items', {})
if inventory_items:
pokecount = 0
itemcount = 1
for item in inventory_items:
if 'inventory_item_data' in item:
if 'pokemon_data' in item['inventory_item_data']:
pokecount += 1
itemcount += item['inventory_item_data'].get('item', {}).get('count', 0)
if 'pokemon' in what:
return pokecount
if 'item' in what:
return itemcount
return '0'

def get_player_info(self):
response_dict = self.get_inventory()
inventory_items = response_dict.get('responses', {}).get('GET_INVENTORY', {}).get(
'inventory_delta', {}).get('inventory_items', {})
if inventory_items:
pokecount = 0
itemcount = 1
for item in inventory_items:
# print('item {}'.format(item))
playerdata = item.get('inventory_item_data', {}).get('player_stats')
if playerdata:
nextlvlxp = (int(playerdata.get('next_level_xp', 0)) - int(playerdata.get('experience', 0)))

if 'level' in playerdata and 'experience' in playerdata:
self.logger.info(
'Level: {level}'.format(
**playerdata) +
' (Next Level: {} XP)'.format(
nextlvlxp) +
' (Total: {experience} XP)'
''.format(**playerdata))

if 'pokemons_captured' in playerdata and 'poke_stop_visits' in playerdata:
self.logger.info(
'Pokemon Captured: '
'{pokemons_captured}'.format(
**playerdata) +
' | Pokestops Visited: '
'{poke_stop_visits}'.format(
**playerdata))

def has_space_for_loot(self):
number_of_things_gained_by_stop = 5
enough_space = (
self.get_inventory_count('item') <
self._player['max_item_storage'] - number_of_things_gained_by_stop
)

return enough_space
def display_player_info(self):
inventory_items = self.api.get_inventory()
inventory_items = inventory_items['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']
player_stats = next((x["inventory_item_data"]["player_stats"]
for x in inventory_items
if x.get("inventory_item_data", {}).get("player_stats", {})),
None)

if player_stats:

nextlvlxp = (int(player_stats.get('next_level_xp', 0)) - int(player_stats.get('experience', 0)))

if 'level' in player_stats and 'experience' in player_stats:
self.logger.info(
'Level: {level}'.format(
**player_stats) +
' (Next Level: {} XP)'.format(
nextlvlxp) +
' (Total: {experience} XP)'
''.format(**player_stats))

if 'pokemons_captured' in player_stats and 'poke_stop_visits' in player_stats:
self.logger.info(
'Pokemon Captured: '
'{pokemons_captured}'.format(
**player_stats) +
' | Pokestops Visited: '
'{poke_stop_visits}'.format(
**player_stats))

def get_forts(self, order_by_distance=False):
forts = [fort
Expand Down
7 changes: 7 additions & 0 deletions pokemongo_bot/base_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ class BaseTask(object):
TASK_API_VERSION = 1

def __init__(self, bot, config):
"""
:param bot:
:type bot: pokemongo_bot.PokemonGoBot
:param config:
:return:
"""
self.bot = bot
self.config = config
self._validate_work_exists()
Expand Down
6 changes: 3 additions & 3 deletions pokemongo_bot/cell_workers/evolve_pokemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def _sort_and_filter(self):
}

for pokemon in inventory.pokemons().all():
if pokemon.id > 0 and pokemon.has_next_evolution() and (logic_to_function[self.cp_iv_logic](pokemon)):
if pokemon.unique_id > 0 and pokemon.has_next_evolution() and (logic_to_function[self.cp_iv_logic](pokemon)):
pokemons.append(pokemon)

if self.first_evolve_by == "cp":
Expand All @@ -99,7 +99,7 @@ def _execute_pokemon_evolve(self, pokemon, cache):
if pokemon.name in cache:
return False

response_dict = self.api.evolve_pokemon(pokemon_id=pokemon.id)
response_dict = self.api.evolve_pokemon(pokemon_id=pokemon.unique_id)
if response_dict.get('responses', {}).get('EVOLVE_POKEMON', {}).get('result', 0) == 1:
self.emit_event(
'pokemon_evolved',
Expand All @@ -115,7 +115,7 @@ def _execute_pokemon_evolve(self, pokemon, cache):
)
awarded_candies = response_dict.get('responses', {}).get('EVOLVE_POKEMON', {}).get('candy_awarded', 0)
inventory.candies().get(pokemon.pokemon_id).consume(pokemon.evolution_cost - awarded_candies)
inventory.pokemons().remove(pokemon.id)
inventory.pokemons().remove(pokemon.unique_id)
pokemon = Pokemon(response_dict.get('responses', {}).get('EVOLVE_POKEMON', {}).get('evolved_pokemon_data', {}))
inventory.pokemons().add(pokemon)
sleep(self.evolve_speed)
Expand Down
Loading

2 comments on commit 91ad8df

@DeXtroTip
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems that two changes are missing.
In collect_level_up_reward.py at line 59:
response_dict = self.bot.get_inventory()
should be
response_dict = self.bot.api.get_inventory()

In nickname_pokemon.py at line 25:
instance_id = pokemon.id
should be
instance_id = pokemon.unique_id

@cmezh
Copy link
Contributor

@cmezh cmezh commented on 91ad8df Aug 18, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, something is wrong.

Traceback (most recent call last):
  File "pokecli.py", line 595, in <module>
    main()
  File "pokecli.py", line 92, in main
    tree = TreeConfigBuilder(bot, config.raw_tasks).build()
  File "/home/cmezh/pogocmezh/pokemongo_bot/tree_config_builder.py", line 74, in build
    instance = worker(self.bot, task_config)
  File "/home/cmezh/pogocmezh/pokemongo_bot/base_task.py", line 20, in __init__
    self.initialize()
  File "/home/cmezh/pogocmezh/pokemongo_bot/cell_workers/collect_level_up_reward.py", line 11, in initialize
    self.current_level = self._get_current_level()
  File "/home/cmezh/pogocmezh/pokemongo_bot/cell_workers/collect_level_up_reward.py", line 59, in _get_current_level
    response_dict = self.bot.get_inventory()
AttributeError: 'PokemonGoBot' object has no attribute 'get_inventory'

Please sign in to comment.