Repository: PokemonGoF/PokemonGo-Bot

Issue:
pgoapi  code change is in conflict with bot and virtuaenv
This issue affects the combination of bot+virtualenv+latets pogoapi from dev. 
I've have checked PokemonGo-Map with latest pogoapi (I've changed their requirementst.txt) and with virtualenv and map works.

In this commit https://github.com/pogodevorg/pgoapi/commit/d5f846aaee84b10dd43c184fd191c3fc02244bed, they changed support for protobuf3-to-dict:
*  They require version higher or equal to >=0.1.4  and they did some code change, 
*  They have removed protobuf_to_dict.py file and switched to the one from requirements
*  They have changed rpc_api.py from: 
```
[auth_ticket['expire_timestamp_ms'], base64.standard_b64decode(auth_ticket['start']), base64.standard_b64decode(auth_ticket['end'])])  
```
to:
```
[auth_ticket['expire_timestamp_ms'], auth_ticket['start'], auth_ticket['end']]) 
```
This breaks the bot ability to login while running under virtualenv. 

However I don't know how to fix it. 

Stardust count error on new account
### Expected Behavior
No crash, just set it to 0 and continue


### Actual Behavior
```
Traceback (most recent call last):
  File "pokecli.py", line 865, in <module>
    main()
  File "pokecli.py", line 206, in main
    bot.tick()
  File "/home/david/Broncode/personal/PokemonGo-Bot/pokemongo_bot/__init__.py", line 770, in tick
    if worker.work() == WorkerResult.RUNNING:
  File "/home/david/Broncode/personal/PokemonGo-Bot/pokemongo_bot/cell_workers/pokemon_optimizer.py", line 127, in work
    self.open_inventory()
  File "/home/david/Broncode/personal/PokemonGo-Bot/pokemongo_bot/cell_workers/pokemon_optimizer.py", line 294, in open_inventory
    self.ongoing_stardust_count = self.bot.stardust
  File "/home/david/Broncode/personal/PokemonGo-Bot/pokemongo_bot/__init__.py", line 75, in stardust
    return filter(lambda y: y['name'] == 'STARDUST', self._player['currencies'])[0]['amount']
KeyError: u'amount'
```
This happens on a fresh new account.

### Output when issue occurred
Se above


### Steps to Reproduce
Create a new account, run the bot from master.


### Other Information
OS:  Ubuntu
Branch: master 
Git Commit:  ce549716d20b5a512a65cfa9de93e808218cfb9e




Discussion:
Waiting for someone from @PokemonGoF/pokemongo-bot-team to check this. 
Check this patch: https://github.com/pogodevorg/pgoapi/pull/178/commits/bd87ce2761dc07dfdc7cf003caa771afc2dc4f64



Resolving patch:
diff --git a/pokemongo_bot/__init__.py b/pokemongo_bot/__init__.py
--- a/pokemongo_bot/__init__.py
+++ b/pokemongo_bot/__init__.py
@@ -72,11 +72,17 @@ def player_data(self):
 
     @property
     def stardust(self):
-        return filter(lambda y: y['name'] == 'STARDUST', self._player['currencies'])[0]['amount']
+        dust = filter(lambda y: y['name'] == 'STARDUST', self._player['currencies'])[0]
+        if 'amount' in dust:
+            return dust['amount']
+        else:
+            return 0
 
     @stardust.setter
     def stardust(self, value):
-        filter(lambda y: y['name'] == 'STARDUST', self._player['currencies'])[0]['amount'] = value
+        dust = filter(lambda y: y['name'] == 'STARDUST', self._player['currencies'])[0]
+        if 'amount' in dust:
+            dust['amount'] = value
 
     def __init__(self, db, config):
 
diff --git a/pokemongo_bot/cell_workers/pokemon_optimizer.py b/pokemongo_bot/cell_workers/pokemon_optimizer.py
--- a/pokemongo_bot/cell_workers/pokemon_optimizer.py
+++ b/pokemongo_bot/cell_workers/pokemon_optimizer.py
@@ -7,6 +7,7 @@
 import math
 import os
 import time
+import datetime
 
 from pokemongo_bot import inventory
 from pokemongo_bot.base_dir import _base_dir
@@ -32,6 +33,7 @@ def initialize(self):
         self.last_pokemon_count = 0
         self.pokemon_names = [p.name for p in inventory.pokemons().STATIC_DATA]
         self.evolution_map = {}
+        self.debug = self.config.get('debug', False)
         self.ongoing_stardust_count = 0
         self.buddy = None
         self.buddyid = 0
@@ -46,13 +48,14 @@ def initialize(self):
         if self.config.get("keep", None) is not None:
             raise ConfigException("Pokemon Optimizer configuration has changed. See docs/pokemon_optimized.md or configs/config.json.optimizer.example")
 
-#         log_file_path = os.path.join(_base_dir, "data", "pokemon-optimizer-%s.log" % self.bot.config.username)
-#
-#         with open(log_file_path, "a") as _:
-#             pass
-#
-#         self.log_file = open(log_file_path, "r+")
-#         self.log_file.seek(0, 2)
+        if self.debug:
+            log_file_path = os.path.join(_base_dir, "data", "pokemon-optimizer-%s.log" % self.bot.config.username)
+
+            with open(log_file_path, "a") as _:
+                pass
+
+            self.log_file = open(log_file_path, "r+")
+            self.log_file.seek(0, 2)
 
         self.config_min_slots_left = self.config.get("min_slots_left", 5)
         self.config_action_wait_min = self.config.get("action_wait_min", 3)
@@ -98,12 +101,12 @@ def initialize(self):
             if pokemon.prev_evolutions_all:
                 self.config_groups["with_previous_evolution"].append(pokemon.name)
 
-#     def log(self, txt):
-#         if self.log_file.tell() >= 1024 * 1024:
-#             self.log_file.seek(0, 0)
-#
-#         self.log_file.write("[%s] %s\n" % (datetime.datetime.now().isoformat(str(" ")), txt))
-#         self.log_file.flush()
+    def log(self, txt):
+        if self.log_file.tell() >= 1024 * 1024:
+             self.log_file.seek(0, 0)
+
+        self.log_file.write("[%s] %s\n" % (datetime.datetime.now().isoformat(str(" ")), txt))
+        self.log_file.flush()
 
     def get_pokemon_slot_left(self):
         pokemon_count = inventory.Pokemons.get_space_used()
@@ -364,8 +367,9 @@ def get_family_id(self, pokemon):
     def score_and_sort(self, pokemon_list, rule):
         pokemon_list = list(pokemon_list)
 
-#         self.log("Pokemon %s" % pokemon_list)
-#         self.log("Rule %s" % rule)
+        if self.debug:
+            self.log("Pokemon %s" % pokemon_list)
+            self.log("Rule %s" % rule)
 
         for pokemon in pokemon_list:
             setattr(pokemon, "__score__", self.get_score(pokemon, rule))
@@ -405,7 +409,8 @@ def get_score(self, pokemon, rule):
         may_buddy &= pokemon.in_fort is False
         may_buddy &= self.satisfy_requirements(pokemon, may_buddy)
 
-#         self.log("%s %s %s %s %s %s" % (pokemon, tuple(score), keep, may_try_evolve, may_try_upgrade, may_buddy))
+        if self.debug:
+            self.log("%s %s %s %s %s %s" % (pokemon, tuple(score), keep, may_try_evolve, may_try_upgrade, may_buddy))
 
         return tuple(score), keep, may_try_evolve, may_try_upgrade, may_buddy
 
diff --git a/pokemongo_bot/cell_workers/update_live_stats.py b/pokemongo_bot/cell_workers/update_live_stats.py
--- a/pokemongo_bot/cell_workers/update_live_stats.py
+++ b/pokemongo_bot/cell_workers/update_live_stats.py
@@ -61,6 +61,7 @@ class UpdateLiveStats(BaseTask):
     - pokeballs_thrown : The number of thrown pokeballs.
     - stardust_earned : The number of earned stardust since the bot started.
     - stardust_per_hour : The estimated gain of stardust per hour
+    - total_stardust : The stardust in possesion of Trainer
     - highest_cp_pokemon : The caught pokemon with the highest CP since the bot started.
     - most_perfect_pokemon : The most perfect caught pokemon since the bot started.
     - location : The location where the player is located.
@@ -267,6 +268,7 @@ def _get_stats(self, player_stats):
         pokemon_unseen = metrics.num_new_mons()
         pokeballs_thrown = metrics.num_throws()
         dust_per_hour = int(metrics.stardust_per_hour())
+        total_stardust = int(metrics.total_stardust())
         stardust_earned = metrics.earned_dust()
         highest_cp_pokemon = metrics.highest_cp['desc']
         if not highest_cp_pokemon:
@@ -300,6 +302,7 @@ def _get_stats(self, player_stats):
             'pokeballs_thrown': pokeballs_thrown,
             'stardust_earned': stardust_earned,
             'stardust_per_hour': dust_per_hour,
+            'total_stardust' : total_stardust,
             'highest_cp_pokemon': highest_cp_pokemon,
             'most_perfect_pokemon': most_perfect_pokemon,
             'location': [self.bot.position[0], self.bot.position[1]],
@@ -348,6 +351,7 @@ def _get_stats_line(self, player_stats):
             'pokeballs_thrown': 'Threw {:,} pokeballs'.format(player_stats['pokeballs_thrown']),
             'stardust_earned': 'Earned {:,} Stardust'.format(player_stats['stardust_earned']),
             'stardust_per_hour': '{:,} Stardust/h'.format(player_stats['stardust_per_hour']),
+            'total_stardust': 'Total Stardust: {}'.format(player_stats['total_stardust']),
             'highest_cp_pokemon': 'Highest CP pokemon : {}'.format(player_stats['highest_cp_pokemon']),
             'most_perfect_pokemon': 'Most perfect pokemon : {}'.format(player_stats['most_perfect_pokemon']),
             'location': 'Location : ({}, {})'.format(*player_stats['location']),


Test patch:
diff --git a/tests/update_live_stats_test.py b/tests/update_live_stats_test.py
--- a/tests/update_live_stats_test.py
+++ b/tests/update_live_stats_test.py
@@ -13,7 +13,7 @@ class UpdateLiveStatsTestCase(unittest.TestCase):
                   'pokemon_caught', 'stops_visited', 'km_walked', 'level', 'stardust_earned',
                   'level_completion', 'xp_per_hour', 'pokeballs_thrown', 'highest_cp_pokemon',
                   'level_stats', 'xp_earned', 'pokemon_unseen', 'most_perfect_pokemon',
-                  'pokemon_stats', 'pokemon_released', 'captures_per_hour'],
+                  'pokemon_stats', 'pokemon_released', 'captures_per_hour','total_stardust'],
         'terminal_log': True,
         'terminal_title': False
     }
@@ -183,6 +183,6 @@ def test_get_stats_line(self):
                    '+424,242 XP | Encountered 3 new pokemon | ' \
                    'Most perfect pokemon : most_perfect | ' \
                    'Encountered 130 pokemon, 120 caught, 30 released, 12 evolved, ' \
-                   '3 never seen before | Released 30 pokemon | 75 pokemon/h'
+                   '3 never seen before | Released 30 pokemon | 75 pokemon/h | Total Stardust: 1'
 
         self.assertEqual(line, expected)