Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IncubateEggs update #5125

Merged
merged 27 commits into from
Sep 4, 2016
Merged
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
685a151
Little code updates
DeXtroTip Aug 31, 2016
c7fa226
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Aug 31, 2016
edbff84
Fix merge conflicts
DeXtroTip Sep 1, 2016
1e85c38
Fix iv_ads display
DeXtroTip Sep 1, 2016
3d1a2cc
Fixed iv_ads display
DeXtroTip Sep 1, 2016
1010a5c
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 1, 2016
de6a50c
Removed test prints
DeXtroTip Sep 1, 2016
56251a7
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 1, 2016
d6e4375
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 1, 2016
26ff395
Updated iv_ads
DeXtroTip Sep 1, 2016
7711b44
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 2, 2016
1ec3e3e
Fix
DeXtroTip Sep 2, 2016
2a9d19f
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 2, 2016
6018876
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 2, 2016
8c36dfb
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 2, 2016
03e0ea0
Add eggs hatched to db
DeXtroTip Sep 2, 2016
37b1e98
Fix merge conflicts
DeXtroTip Sep 2, 2016
5695d12
Added missing import
DeXtroTip Sep 2, 2016
7f66164
Fixed creation of table in db
DeXtroTip Sep 2, 2016
ff98160
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 2, 2016
15bb769
Added eggs_hatched_log.py
DeXtroTip Sep 2, 2016
281afd4
Fixed wrong color log
DeXtroTip Sep 2, 2016
e039d79
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 3, 2016
121cbd9
Added different event when egg hatchs fails
DeXtroTip Sep 3, 2016
299ac6b
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 3, 2016
3d714e3
Updated for database changes
DeXtroTip Sep 3, 2016
accc804
Merge remote-tracking branch 'upstream/dev' into incubate_eggs_update
DeXtroTip Sep 3, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions pokemongo_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,10 +501,10 @@ def _register_events(self):
self.event_manager.register_event(
'egg_hatched',
parameters=(
'pokemon',
'cp', 'iv', 'exp', 'stardust', 'candy'
'name', 'cp', 'ncp', 'iv_ads', 'iv_pct', 'exp', 'stardust', 'candy'
)
)
self.event_manager.register_event('egg_hatched_fail')

# discard item
self.event_manager.register_event(
Expand Down Expand Up @@ -632,6 +632,7 @@ def _register_events(self):
self.event_manager.register_event('transfer_log')
self.event_manager.register_event('pokestop_log')
self.event_manager.register_event('softban_log')
self.event_manager.register_event('eggs_hatched_log')

self.event_manager.register_event(
'badges',
Expand Down
130 changes: 66 additions & 64 deletions pokemongo_bot/cell_workers/incubate_eggs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@
from pokemongo_bot import inventory
from pokemongo_bot.human_behaviour import sleep
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.datastore import Datastore
from pokemongo_bot.worker_result import WorkerResult


class IncubateEggs(BaseTask):
class IncubateEggs(Datastore, BaseTask):
Copy link
Contributor

Choose a reason for hiding this comment

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

remove Datastore

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, I was waiting your PR to be merge, already had changes made. 👍

SUPPORTED_TASK_API_VERSION = 1

last_km_walked = 0

def __init__(self, bot, config):
super(IncubateEggs, self).__init__(bot, config)

def initialize(self):
self.next_update = None
self.ready_breakable_incubators = []
Expand All @@ -18,36 +23,31 @@ def initialize(self):
self.eggs = []
self.km_walked = 0
self.hatching_animation_delay = 4.20
self.max_iv = 45.0

self._process_config()

def _process_config(self):
self.infinite_longer_eggs_first = self.config.get("infinite_longer_eggs_first", False)
self.breakable_longer_eggs_first = self.config.get("breakable_longer_eggs_first", True)
self.min_interval = self.config.get('min_interval', 120)

self.breakable_incubator = self.config.get("breakable", [2,5,10])
self.infinite_incubator = self.config.get("infinite", [2,5,10])

def work(self):
try:
self._check_inventory()
except:
return

should_print = self._should_print()
return WorkerResult.ERROR

if self.used_incubators and IncubateEggs.last_km_walked != self.km_walked:
self.used_incubators.sort(key=lambda x: x.get("km"))
km_left = self.used_incubators[0]['km']-self.km_walked
if km_left <= 0:
self._hatch_eggs()
should_print = False
if not self._hatch_eggs():
return WorkerResult.ERROR
else:
self.bot.metrics.next_hatching_km(km_left)

if should_print:
if self._should_print():
self._print_eggs()
self._compute_next_update()

Expand All @@ -59,13 +59,14 @@ def work(self):
eggs = self._filter_sort_eggs(self.infinite_incubator,
self.infinite_longer_eggs_first)
self._apply_incubators(eggs, self.ready_infinite_incubators)

if self.ready_breakable_incubators:
# get available eggs
eggs = self._filter_sort_eggs(self.breakable_incubator,
self.breakable_longer_eggs_first)
self._apply_incubators(eggs, self.ready_breakable_incubators)

return WorkerResult.SUCCESS


def _filter_sort_eggs(self, allowed, sorting):
eligible_eggs = filter(lambda egg: int(egg["km"]) in allowed, self.eggs)
Expand All @@ -75,7 +76,6 @@ def _filter_sort_eggs(self, allowed, sorting):


def _apply_incubators(self, available_eggs, available_incubators):

for incubator in available_incubators:
for egg in available_eggs:
if egg["used"] or egg["km"] == -1:
Expand Down Expand Up @@ -166,100 +166,102 @@ def _check_inventory(self, lookup_ids=[]):
"used": False
})
elif 'is_egg' not in pokemon and pokemon['id'] in lookup_ids:
pokemon.update({
"iv": [
pokemon.get('individual_attack', 0),
pokemon.get('individual_defense', 0),
pokemon.get('individual_stamina', 0)
]})
matched_pokemon.append(pokemon)
continue
if "player_stats" in inv_data:
self.km_walked = inv_data.get("player_stats", {}).get("km_walked", 0)

self.used_incubators = temp_used_incubators
if self.used_incubators:
self.used_incubators.sort(key=lambda x: x.get("km"))
self.ready_breakable_incubators = temp_ready_breakable_incubators
self.ready_infinite_incubators = temp_ready_infinite_incubators
self.eggs = temp_eggs
return matched_pokemon

def _hatch_eggs(self):
response_dict = self.bot.api.get_hatched_eggs()
log_color = 'green'
try:
result = reduce(dict.__getitem__, ["responses", "GET_HATCHED_EGGS"], response_dict)
except KeyError:
return
return WorkerResult.ERROR
pokemon_ids = []
if 'pokemon_id' in result:
pokemon_ids = [id for id in result['pokemon_id']]
stardust = result.get('stardust_awarded', "error")
candy = result.get('candy_awarded', "error")
xp = result.get('experience_awarded', "error")
stardust = result.get('stardust_awarded', [])
candy = result.get('candy_awarded', [])
xp = result.get('experience_awarded', [])
sleep(self.hatching_animation_delay)
try:
pokemon_data = self._check_inventory(pokemon_ids)
for pokemon in pokemon_data:
# pokemon ids seem to be offset by one
if pokemon['pokemon_id']!=-1:
pokemon['name'] = self.bot.pokemon_list[(pokemon.get('pokemon_id')-1)]['Name']
#remove as egg and add as pokemon
inventory.pokemons().remove(pokemon['id'])
inventory.pokemons().add(inventory.Pokemon(pokemon))
else:
pokemon['name'] = "error"
pokemon_list = [inventory.Pokemon(p) for p in pokemon_data]
for pokemon in pokemon_list:
inventory.pokemons().remove(pokemon.unique_id)
inventory.pokemons().add(pokemon)
except:
pokemon_data = [{"name":"error", "cp":"error", "iv":"error"}]
if not pokemon_ids or not pokemon_data or pokemon_data[0]['name'] == "error":
pokemon_data = []
if not pokemon_ids or not pokemon_data:
self.emit_event(
'egg_hatched',
data={
'pokemon': 'error',
'cp': 'error',
'iv': 'error',
'exp': 'error',
'stardust': 'error',
'candy': 'error',
}
'egg_hatched_fail',
formatted= "Error trying to hatch egg."
)
return
for i in range(len(pokemon_data)):
msg = "Egg hatched with a {pokemon} (CP {cp} - IV {iv}), {exp} exp, {stardust} stardust and {candy} candies."
self.bot.metrics.hatched_eggs(1)
return False

for i in range(len(pokemon_list)):
pokemon = pokemon_list[i]
msg = "Egg hatched with a {name} (CP {cp} - NCP {ncp} - IV {iv_ads} {iv_pct}), {exp} exp, {stardust} stardust and {candy} candies."
self.emit_event(
'egg_hatched',
formatted=msg,
data={
'pokemon': pokemon_data[i]['name'],
'cp': pokemon_data[i]['cp'],
'iv': "{} {}".format(
"/".join(map(str, pokemon_data[i]['iv'])),
round(sum(pokemon_data[i]['iv'])/self.max_iv, 2)
),
'name': pokemon.name,
'cp': pokemon.cp,
'ncp': round(pokemon.cp_percent, 2),
'iv_ads': pokemon.iv_display,
'iv_pct': pokemon.iv,
'exp': xp[i],
'stardust': stardust[i],
'candy': candy[i],
'candy': candy[i]
}
)
# hatching egg gets exp too!
inventory.player().exp += xp[i]

with self.bot.database as conn:
c = conn.cursor()
c.execute("SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name='eggs_hatched_log'")
result = c.fetchone()
while True:
if result[0] == 1:
conn.execute('''INSERT INTO eggs_hatched_log (pokemon, cp, iv, pokemon_id) VALUES (?, ?, ?, ?)''', (pokemon.name, pokemon.cp, pokemon.iv, pokemon.pokemon_id))
break
else:
self.emit_event(
'eggs_hatched_log',
sender=self,
level='info',
formatted="eggs_hatched_log table not found, skipping log"
)
break

self.bot.metrics.hatched_eggs(len(pokemon_list))
return True

def _print_eggs(self):
if not self.used_incubators:
return

self.used_incubators.sort(key=lambda x: x.get("km"))

eggs = ['{:.2f}/{} km'.format(e['km_needed']-e['km']+self.km_walked, e['km_needed']) for e in self.used_incubators]

self.emit_event(
'next_egg_incubates',
formatted='Eggs incubating: [{eggs}] (Eggs left: {eggs_left}, Incubating: {eggs_inc})',
data={
'eggs_left': len(self.eggs),
'eggs_inc': len(self.used_incubators),
'eggs': ', '.join(eggs)
}
)
'next_egg_incubates',
formatted='Eggs incubating: [{eggs}] (Eggs left: {eggs_left}, Incubating: {eggs_inc})',
data={
'eggs_left': len(self.eggs),
'eggs_inc': len(self.used_incubators),
'eggs': ', '.join(eggs)
}
)

def _should_print(self):
"""
Expand Down
5 changes: 5 additions & 0 deletions pokemongo_bot/cell_workers/migrations/eggs_hatched_log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from yoyo import step

step(
"CREATE TABLE IF NOT EXISTS eggs_hatched_log (pokemon text, cp real, iv real, pokemon_id real, dated datetime DEFAULT CURRENT_TIMESTAMP)"
)
4 changes: 2 additions & 2 deletions pokemongo_bot/event_handlers/colored_logging_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ class ColoredLoggingHandler(EventHandler):
'config_error': 'red',
'egg_already_incubating': 'yellow',
'egg_hatched': 'green',
'egg_hatched_fail': 'red',
'eggs_hatched_log': 'magenta',
'evolve_log': 'magenta',
'future_pokemon_release': 'yellow',
'incubate': 'green',
Expand Down Expand Up @@ -126,8 +128,6 @@ def handle_event(self, event, sender, level, formatted_msg, data):

if event in self.EVENT_COLOR_MAP:
color = self.COLOR_CODE[self.EVENT_COLOR_MAP[event]]
if event == 'egg_hatched' and data.get('pokemon', 'error') == 'error':
color = self.COLOR_CODE['red']
formatted_msg = '{}{}{}'.format(color, formatted_msg, self.COLOR_CODE['none'])

if self.bot.config.debug or not self.bot.config.logging_clean:
Expand Down