Skip to content

Commit

Permalink
Dev merge to master (#5110)
Browse files Browse the repository at this point in the history
* Adding an option to save pokemon spawns

* Adding an option to save pokemon spawns

* Adding an option to save pokemon spawns

* Adding an option to save pokemon spawns

* Adding time to saved_spawns

* Added function to Set Player Team
 * Configurable at config file
 * Only tries to pick team one team (at each bot run)

* Checks if a team was already picked before trying to pick

* Updated config example files

* Litte fix

* 'red' not supported by logger

* implemented handling of symbolic "master" in telegram config (again)

* made min number of slots configurable for PokemonOptimizer ("min_slots_left")

* Added CompleteTutorial to Documentation (#5078)

* Updated docs/configuration_files.md about CompleteTutorial

* Added defualt team

* Sample configuration fix

* add poke lvl information to ._data

* Handle telegram.error.TelegramError exception instead of quit.

* Revert "Adding an option to save pokemon spawns"

This reverts commit 838fea4, reversing
changes made to e83c7e6.

* Added exception UnicodeDecodeError protection in mqtt publish.
  • Loading branch information
solderzzc authored Sep 2, 2016
1 parent 4269c79 commit 16a554e
Show file tree
Hide file tree
Showing 13 changed files with 131 additions and 23 deletions.
4 changes: 3 additions & 1 deletion configs/config.json.cluster.example
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
"config": {
"enabled": false,
"// set a name": "",
"nickname": ""
"nickname": "",
"// 0 = No Team, 1 = Blue, 2 = Red, 3 = Yellow": "",
"team": 0
}
},
{
Expand Down
4 changes: 3 additions & 1 deletion configs/config.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@
"config": {
"enabled": false,
"// set a name": "",
"nickname": ""
"nickname": "",
"// 0 = No Team, 1 = Blue, 2 = Red, 3 = Yellow": "",
"team": 0
}
},
{
Expand Down
4 changes: 3 additions & 1 deletion configs/config.json.map.example
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
"config": {
"enabled": false,
"// set a name": "",
"nickname": ""
"nickname": "",
"// 0 = No Team, 1 = Blue, 2 = Red, 3 = Yellow": "",
"team": 0
}
},
{
Expand Down
1 change: 1 addition & 0 deletions configs/config.json.optimizer.example
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"may_use_lucky_egg": true,
"upgrade": true,
"upgrade_level": 60,
"min_slots_left": 5,
"groups": {
"gym": ["Dragonite", "Snorlax", "Lapras", "Arcanine"]
},
Expand Down
4 changes: 3 additions & 1 deletion configs/config.json.path.example
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
"config": {
"enabled": false,
"// set a name": "",
"nickname": ""
"nickname": "",
"// 0 = No Team, 1 = Blue, 2 = Red, 3 = Yellow": "",
"team": 0
}
},
{
Expand Down
4 changes: 3 additions & 1 deletion configs/config.json.pokemon.example
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
"config": {
"enabled": false,
"// set a name": "",
"nickname": ""
"nickname": "",
"// 0 = No Team, 1 = Blue, 2 = Red, 3 = Yellow": "",
"team": 0
}
},
{
Expand Down
44 changes: 44 additions & 0 deletions docs/configuration_files.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
- [Egg Incubator](#egg-incubator)
- [ShowBestPokemon](#showbestpokemon)
- [Telegram Task](#telegram-task)
- [CompleteTutorial](#completetutorial)

#Configuration files

Expand Down Expand Up @@ -1017,3 +1018,46 @@ Bot answer on command '/info' self stats.
}
}
```

## CompleteTutorial
[[back to top](#table-of-contents)]

### Description
[[back to top](#table-of-contents)]

Completes the tutorial:

* Legal screen
* Avatar selection
* First Pokemon capture
* Set nickname
* Firte time experience
* Pick team at level 5


### Options
[[back to top](#table-of-contents)]

* `nickname` : Nickname to be used ingame.
* `team` : `Default: 0`. Team to pick after reaching level 5.

Available `team` :
```
0: Neutral (No team)
1: Blue (Mystic)
2: Red (Valor)
3: Yellow (Instinct)
```

### Sample configuration
[[back to top](#table-of-contents)]
```json
{
"type": "CompleteTutorial",
"config": {
"enabled": true,
"nickname": "PokemonGoF",
"team": 2
}
}
```
2 changes: 1 addition & 1 deletion pokemongo_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1351,7 +1351,7 @@ def _load_recent_forts(self):
with open(cached_forts_path) as f:
cached_recent_forts = json.load(f)
except (IOError, ValueError) as e:
self.logger.info('[x] Error while opening cached forts: %s' % e, 'red')
self.logger.info('[x] Error while opening cached forts: %s' % e)
pass
except:
raise FileIOException("Unexpected error opening {}".cached_forts_path)
Expand Down
57 changes: 45 additions & 12 deletions pokemongo_bot/cell_workers/complete_tutorial.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import random

from pokemongo_bot import logger
from pokemongo_bot.inventory import player
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.worker_result import WorkerResult
from pokemongo_bot.human_behaviour import sleep
Expand All @@ -15,23 +16,22 @@ def initialize(self):
self.api = self.bot.api
self.nickname = self.config.get('nickname','')
self.team = self.config.get('team',0)
self.may_run = True

def should_run(self):
return self.may_run
self.tutorial_run = True
self.team_run = True

def work(self):

if not self.should_run():
return WorkerResult.SUCCESS
if self.tutorial_run:
self.tutorial_run = False
if not self._check_tutorial_state():
return WorkerResult.ERROR

# Only execute the worker once to avoid error loop
self.may_run = False
if self.team_run and player()._level >= 5:
self.team_run = False
if not self._set_team():
return WorkerResult.ERROR

if self._check_tutorial_state():
return WorkerResult.SUCCESS
else:
return WorkerResult.ERROR
return WorkerResult.SUCCESS

def _check_tutorial_state(self):
self._player=self.bot.player_data
Expand Down Expand Up @@ -179,3 +179,36 @@ def _set_tutorial_state(self, completed):
except KeyError:
self.logger.error("KeyError while setting tutorial state")
return False

def _set_team(self):
if self.team == 0:
return True

if self.bot.player_data.get('team', 0) != 0:
self.logger.info(u'Team already picked')
return True

sleep(10)
response_dict = self.api.set_player_team(team=self.team)
try:
result = response_dict['responses']['SET_PLAYER_TEAM']['status']
if result == 1:
team_codes = {
1: 'Mystic (BLUE)',
2: 'Valor (RED)',
3: 'Instinct (YELLOW)'
}
self.logger.info(u'Picked Team {}.'.format(team_codes[self.team]))
return True
else:
error_codes = {
0: 'UNSET',
1: 'SUCCESS',
2: 'TEAM_ALREADY_SET',
3: 'FAILURE'
}
self.logger.error(u'Error while picking team : {}'.format(error_codes[result]))
return False
except KeyError:
return False

4 changes: 2 additions & 2 deletions pokemongo_bot/cell_workers/pokemon_optimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def get_pokemon_slot_left(self):
return inventory.Pokemons.get_space_left()

def work(self):
if (not self.enabled) or (self.get_pokemon_slot_left() > 5):
if (not self.enabled) or self.get_pokemon_slot_left() > self.config.get("min_slots_left", 5):
return WorkerResult.SUCCESS

self.open_inventory()
Expand Down Expand Up @@ -443,7 +443,7 @@ def apply_optimization(self, transfer, evolve, upgrade, xp):
skip_evolve = True
self.emit_event("skip_evolve",
formatted="Skipping evolution step. Not enough Pokemon to evolve with lucky egg: %s/%s" % (len(evolve) + len(xp), self.config_evolve_count_for_lucky_egg))
elif self.get_pokemon_slot_left() > 5:
elif self.get_pokemon_slot_left() > self.config.get("min_slots_left", 5):
skip_evolve = True
self.emit_event("skip_evolve",
formatted="Waiting for more Pokemon to evolve with lucky egg: %s/%s" % (len(evolve) + len(xp), self.config_evolve_count_for_lucky_egg))
Expand Down
5 changes: 4 additions & 1 deletion pokemongo_bot/event_handlers/social_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@ def mqtt_on_subscribe(self, mqttc, obj, mid, granted_qos):
# print string
def publish(self, channel, message):
if self._mqttc:
self._mqttc.publish(channel, message)
try:
self._mqttc.publish(channel, message)
except UnicodeDecodeError:
pass
def connect_to_mqtt(self):
try:
if DEBUG_ON:
Expand Down
18 changes: 16 additions & 2 deletions pokemongo_bot/event_handlers/telegram_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@ class TelegramClass:

update_id = None

def __init__(self, bot, master, pokemons):
def __init__(self, bot, master, pokemons, config):
self.bot = bot
self.master = master
self.pokemons = pokemons
self._tbot = None
self.config = config

def sendMessage(self, chat_id=None, parse_mode='Markdown', text=None):
self._tbot.sendMessage(chat_id=chat_id, parse_mode=parse_mode, text=text)
Expand Down Expand Up @@ -78,6 +79,16 @@ def run(self):
self.bot.logger.info("message from {} ({}): {}".format(update.message.from_user.username, update.message.from_user.id, update.message.text))
if self.master and self.master not in [update.message.from_user.id, "@{}".format(update.message.from_user.username)]:
continue
if not re.match(r'^[0-9]+$', self.master):
# the "master" is not numeric, set self.master to update.message.chat_id and re-instantiate the handler
newconfig = self.config
newconfig['master'] = update.message.chat_id
# remove old handler
self.bot.event_manager._handlers = filter(lambda x: not isinstance(x, TelegramHandler), self.bot.event_manager._handlers)
# add new handler (passing newconfig as parameter)
self.bot.event_manager.add_handler(TelegramHandler(self.bot, newconfig))


if update.message.text == "/info":
self.send_player_stats_to_chat(update.message.chat_id)
elif update.message.text == "/start" or update.message.text == "/help":
Expand All @@ -88,6 +99,8 @@ def run(self):
self._tbot.sendMessage(chat_id=update.message.chat_id, parse_mode='Markdown', text="\n".join(res))
except telegram.error.NetworkError:
time.sleep(1)
except telegram.error.TelegramError:
time.sleep(10)
except telegram.error.Unauthorized:
self.update_id += 1

Expand All @@ -98,11 +111,12 @@ def __init__(self, bot, config):
self.master = config.get('master', None)
self.pokemons = config.get('alert_catch', {})
self.whoami = "TelegramHandler"
self.config = config

def handle_event(self, event, sender, level, formatted_msg, data):
if self.tbot is None:
try:
self.tbot = TelegramClass(self.bot, self.master, self.pokemons)
self.tbot = TelegramClass(self.bot, self.master, self.pokemons, self.config)
self.tbot.connect()
thread.start_new_thread(self.tbot.run)
except Exception as inst:
Expand Down
3 changes: 3 additions & 0 deletions pokemongo_bot/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -868,6 +868,9 @@ def __init__(self, data):
# Current pokemon level (half of level is a normal value)
self.level = LevelToCPm.level_from_cpm(self.cp_m)

if 'level' not in self._data:
self._data['level'] = self.level

# Maximum health points
self.hp_max = data['stamina_max']
# Current health points
Expand Down

0 comments on commit 16a554e

Please sign in to comment.