Skip to content

Commit

Permalink
Fixed seperate transfer bug in worker (#1286)
Browse files Browse the repository at this point in the history
* seperate worker for transfering pokemons to professor

pulled out initial transfer and transfer on catched pokemon to seperate
worker

* Fixed bug where config parameters wasnt checked

* Initial_transfer renamed to release_pokemons

Also updated the configuration argument

function to release pokemon runs on tick method which is called after
everyt small step the bot takes

* added back exception which was missing

* Default conf value and fixed typo

* fixed typo for pokemon and updated config
* added default value if its missing from conf

NOTE: transfer conditions are set by "release" parameters in config,
however we keep the highest CP of each pokemon, just to be sure we don't
empty the bag.

* Capital leter

* missed to rename on some places

Also enabled loggning to easier see why a certain pokemon may not be
transfered to professor for candy

* Log format update

* moved runtime error to evolved_capture statement

workaround if anyone should get it...

fixing it in future
  • Loading branch information
fredrik-hellmangroup authored and douglascamata committed Jul 28, 2016
1 parent 5c3b108 commit 63b4387
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 133 deletions.
2 changes: 1 addition & 1 deletion configs/config.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"action_wait_max": 4,
"debug": false,
"test": false,
"initial_transfer": false,
"location_cache": true,
"distance_unit": "km",
"reconnecting_timeout": 15,
Expand All @@ -28,6 +27,7 @@
"cp_min": 300,
"use_lucky_egg": false,
"evolve_captured": false,
"release_pokemon": true,
"catch": {
"any": {"catch_above_cp": 0, "catch_above_iv": 0, "logic": "or"},
"// Example of always catching Rattata:": {},
Expand Down
14 changes: 9 additions & 5 deletions configs/config.json.pokemons.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,27 @@
"max_steps": 5,
"mode": "all",
"walk": 4.16,
"action_wait_min": 1,
"action_wait_max": 4,
"debug": false,
"test": false,
"initial_transfer": false,
"location_cache": true,
"distance_unit": "km",
"item_filter": {
"1": { "keep" : 100 },
"1": { "keep" : 50 },
"2": { "keep" : 50 },
"3": { "keep" : 50 },
"101": { "keep" : 10 },
"102": { "keep" : 30 },
"103": { "keep" : 30 },
"201": { "keep" : 30 },
"102": { "keep" : 25 },
"103": { "keep" : 25 },
"201": { "keep" : 25 },
"701": { "keep" : 100 }
},
"evolve_all": "NONE",
"evolve_speed": 20,
"use_lucky_egg": false,
"evolve_captured": false,
"release_pokemon": true,
"catch": {
"any": {"catch_above_cp": 0, "catch_above_iv": 0, "logic": "or" },

Expand Down
10 changes: 5 additions & 5 deletions pokecli.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ def init_config():
default=50
)
parser.add_argument(
"-it",
"--initial_transfer",
help="Transfer all duplicate pokemon with same ID on bot start, except pokemon with highest CP. Accepts a number to prevent transferring pokemon with a CP above the provided value. Default is 0 (aka transfer none).",
type=int,
default=0
"-rp",
"--release_pokemon",
help="Allow transfer pokemon to professor based on release configuration. Default is false",
type=bool,
default=False
)
parser.add_argument(
"-d",
Expand Down
4 changes: 2 additions & 2 deletions pokemongo_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from pgoapi.utilities import f2i

import logger
from cell_workers import CatchVisiblePokemonWorker, PokemonCatchWorker, SeenFortWorker, MoveToFortWorker, InitialTransferWorker, EvolveAllWorker, RecycleItemsWorker
from cell_workers import CatchVisiblePokemonWorker, PokemonCatchWorker, SeenFortWorker, MoveToFortWorker, PokemonTransferWorker, EvolveAllWorker, RecycleItemsWorker
from cell_workers.utils import distance, get_cellid, encode, i2f
from human_behaviour import sleep
from item_list import Item
Expand Down Expand Up @@ -160,7 +160,7 @@ def work_on_cell(self, cell, position):
# Check if session token has expired
self.check_session(position)

worker = InitialTransferWorker(self)
worker = PokemonTransferWorker(self)
if worker.work() == WorkerResult.RUNNING:
return

Expand Down
2 changes: 1 addition & 1 deletion pokemongo_bot/cell_workers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pokemon_catch_worker import PokemonCatchWorker
from seen_fort_worker import SeenFortWorker
from move_to_fort_worker import MoveToFortWorker
from initial_transfer_worker import InitialTransferWorker
from pokemon_transfer_worker import PokemonTransferWorker
from evolve_all_worker import EvolveAllWorker
from catch_visible_pokmeon_worker import CatchVisiblePokemonWorker
from recycle_items_worker import RecycleItemsWorker
108 changes: 13 additions & 95 deletions pokemongo_bot/cell_workers/pokemon_catch_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
from sets import Set

from pokemongo_bot import logger
from pokemongo_bot.human_behaviour import sleep, action_delay

from pokemongo_bot.human_behaviour import sleep
from pokemon_transfer_worker import PokemonTransferWorker

class PokemonCatchWorker(object):
BAG_FULL = 'bag_full'
Expand Down Expand Up @@ -34,9 +34,11 @@ def work(self):
if self.response_key in response_dict['responses']:
if self.response_status_key in response_dict['responses'][self.response_key]:
if response_dict['responses'][self.response_key][self.response_status_key] is 7:
if self.config.initial_transfer:
if self.config.release_pokemon:
logger.log('Pokemon Bag is full!', 'red')
return PokemonCatchWorker.BAG_FULL
worker = PokemonTransferWorker(self)
worker.work()

else:
raise RuntimeError('Pokemon Bag is full!')

Expand Down Expand Up @@ -191,8 +193,6 @@ def work(self):
'Oh no! {} vanished! :('.format(pokemon_name), 'red')
if status is 1:

id_list2 = self.count_pokemon_inventory()

self.bot.metrics.captured_pokemon(pokemon_name, cp, iv_display, pokemon_potential)

logger.log('Captured {}! [CP {}] [{}]'.format(
Expand All @@ -202,8 +202,14 @@ def work(self):
), 'blue')

if self.config.evolve_captured:
pokemon_to_transfer = list(Set(id_list2) - Set(id_list1))
# No need to capture this even for metrics, player stats includes it.
id_list2 = self.count_pokemon_inventory()
pokemon_to_transfer = list(Set(id_list2) - Set(id_list1))

# TODO dont throw RuntimeError, do something better
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()
status = response_dict['responses']['EVOLVE_POKEMON']['result']
Expand All @@ -214,55 +220,8 @@ def work(self):
logger.log(
'Failed to evolve {}!'.format(pokemon_name))

if self.should_release_pokemon(pokemon_name, cp, pokemon_potential, response_dict):
# Transfering Pokemon
pokemon_to_transfer = list(
Set(id_list2) - Set(id_list1))
if len(pokemon_to_transfer) == 0:
raise RuntimeError(
'Trying to transfer 0 pokemons!')
# Add slight delay between capture & candy transfer #774
logger.log("Waiting briefly before transferring pokemon")
action_delay(self.config.action_wait_min, self.config.action_wait_max)
self.transfer_pokemon(pokemon_to_transfer[0])
self.bot.metrics.released_pokemon()
logger.log(
'{} has been exchanged for candy!'.format(pokemon_name), 'green')

break
time.sleep(5)

def _transfer_low_cp_pokemon(self, value):
response_dict = self.bot.get_inventory()
self._transfer_all_low_cp_pokemon(value, response_dict)

def _transfer_all_low_cp_pokemon(self, value, response_dict):
try:
reduce(dict.__getitem__, [
"responses", "GET_INVENTORY", "inventory_delta", "inventory_items"], response_dict)
except KeyError:
pass
else:
for item in response_dict['responses']['GET_INVENTORY']['inventory_delta']['inventory_items']:
try:
reduce(dict.__getitem__, [
"inventory_item_data", "pokemon"], item)
except KeyError:
pass
else:
pokemon = item['inventory_item_data']['pokemon']
self._execute_pokemon_transfer(value, pokemon)
time.sleep(1.2)

def _execute_pokemon_transfer(self, value, pokemon):
if 'cp' in pokemon and pokemon['cp'] < value:
self.api.release_pokemon(pokemon_id=pokemon['id'])
response_dict = self.api.call()

def transfer_pokemon(self, pid):
self.api.release_pokemon(pokemon_id=pid)
response_dict = self.api.call()

def count_pokemon_inventory(self):
self.bot.latest_inventory = None # Need accurate count of balls/berries/pokemons
response_dict = self.bot.get_inventory()
Expand Down Expand Up @@ -337,47 +296,6 @@ def _get_catch_config_for(self, pokemon):
catch_config = self.config.catch.get('any')
return catch_config

def should_release_pokemon(self, pokemon_name, cp, iv, response_dict):
release_config = self._get_release_config_for(pokemon_name)
cp_iv_logic = release_config.get('logic')
if not cp_iv_logic:
cp_iv_logic = self._get_release_config_for('any').get('logic', 'and')

release_results = {
'cp': False,
'iv': False,
}

if release_config.get('never_release', False):
return False

if release_config.get('always_release', False):
return True

release_cp = release_config.get('release_below_cp', 0)
if cp < release_cp:
release_results['cp'] = True

release_iv = release_config.get('release_below_iv', 0)
if iv < release_iv:
release_results['iv'] = True

logic_to_function = {
'or': lambda x, y: x or y,
'and': lambda x, y: x and y
}

#logger.log(
# "Release config for {}: CP {} {} IV {}".format(
# pokemon_name,
# min_cp,
# cp_iv_logic,
# min_iv
# ), 'yellow'
#)

return logic_to_function[cp_iv_logic](*release_results.values())

def _get_release_config_for(self, pokemon):
release_config = self.config.release.get(pokemon)
if not release_config:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
import json

from pokemongo_bot.human_behaviour import sleep
from pokemongo_bot.human_behaviour import sleep, action_delay
from pokemongo_bot import logger

class InitialTransferWorker(object):
class PokemonTransferWorker(object):
def __init__(self, bot):
self.config = bot.config
self.pokemon_list = bot.pokemon_list
self.api = bot.api

def work(self):
if not self.config.initial_transfer:
if not self.config.release_pokemon:
return

pokemon_groups = self._initial_transfer_get_groups()

pokemon_groups = self._release_pokemon_get_groups()
for id in pokemon_groups:

group_cp = pokemon_groups[id].keys()

if len(group_cp) > 1:
Expand All @@ -28,19 +26,15 @@ def work(self):
pokemon_cp = group_cp[x]
pokemon_data = pokemon_groups[id][pokemon_cp]
pokemon_potential = self.get_pokemon_potential(pokemon_data)
#logger.log('Checking {} [CP {}] [Potential {}] for release!'.format(pokemon_name, pokemon_cp, pokemon_potential))
if self.should_release_pokemon(pokemon_name, pokemon_cp, pokemon_potential):
message = 'Exchanging {} [CP {}] [Potential {}]'.format(
pokemon_name,
pokemon_cp,
pokemon_potential
)
logger.log(message, 'red')
self.api.release_pokemon(
pokemon_id=pokemon_data['id'])
logger.log('Exchanging {} for candy!'.format(
pokemon_name), 'green')
self.api.release_pokemon(pokemon_id=pokemon_data['id'])
response_dict = self.api.call()
sleep(2)
action_delay(self.config.action_wait_min, self.config.action_wait_max)

def _initial_transfer_get_groups(self):
def _release_pokemon_get_groups(self):
pokemon_groups = {}
self.api.get_player().get_inventory()
inventory_req = self.api.call()
Expand Down Expand Up @@ -109,14 +103,17 @@ def should_release_pokemon(self, pokemon_name, cp, iv):
'and': lambda x, y: x and y
}

#logger.log(
# "Release config for {}: CP {} {} IV {}".format(
# pokemon_name,
# min_cp,
# cp_iv_logic,
# min_iv
# ), 'yellow'
#)
if logic_to_function[cp_iv_logic](*release_results.values()):
logger.log(
"Release config for {}: Conf, CP {} {} IV {} - Poke, CP {} IV {}".format(
pokemon_name,
release_cp,
cp_iv_logic,
release_iv,
cp,
iv
), 'yellow'
)

return logic_to_function[cp_iv_logic](*release_results.values())

Expand Down

0 comments on commit 63b4387

Please sign in to comment.