Skip to content

Commit

Permalink
Merge pull request #24 from PokemonGoF/dev
Browse files Browse the repository at this point in the history
Importing Dev
  • Loading branch information
goedzo authored Jul 27, 2017
2 parents 1693851 + 37b67e8 commit a905768
Show file tree
Hide file tree
Showing 8 changed files with 254 additions and 130 deletions.
111 changes: 89 additions & 22 deletions MultiBot.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import sys
import threading
import time
from time import gmtime, strftime, sleep
from threading import *
import requests

Expand All @@ -26,6 +27,7 @@
except:
pass
AccountLock = Semaphore(value=1)
screen_lock = Semaphore(value=1)
MultiBotConfig = json.loads(open('configs/MultiBotConfig.json').read())

def getProxy():
Expand All @@ -48,15 +50,19 @@ def getProxy():
if requests.get('https://sso.pokemon.com/', headers=headers, proxies=proxies).status_code == 200:
return proxy
else:
print ("Proxy is Banned")
Lprint ("Proxy is Banned")
else:
print ("Proxy is Banned")
Lprint ("Proxy is Banned")

except Exception as e:
print (e)
Lprint (e)
pass
except KeyboardInterrupt:
stop()
except IOError:
print 'configs/{} does not exist'.format(MultiBotConfig[u'ProxyFile'])
Lprint ('configs/{} does not exist'.format(MultiBotConfig[u'ProxyFile']))
except KeyboardInterrupt:
stop()

try:
Accounts = []
Expand All @@ -65,7 +71,9 @@ def getProxy():
line = line.replace('\n', '').replace('\r', '').replace(',', '.')
Accounts.append(line)
except IOError:
print 'configs/{} does not exist'.format(MultiBotConfig[u'AccountsFile'])
Lprint ('configs/{} does not exist'.format(MultiBotConfig[u'AccountsFile']))
except KeyboardInterrupt:
stop()

def getHashKey():
try:
Expand All @@ -79,7 +87,18 @@ def getHashKey():
hashkeyCur += 1
return hashkeyAll[hashkeyCur].replace('\n', '').replace('\r', '')
except IOError:
print 'configs/{} does not exist'.format(MultiBotConfig[u'HashKeyFile'])
Lprint ('configs/{} does not exist'.format(MultiBotConfig[u'HashKeyFile']))
except KeyboardInterrupt:
stop()

def stop():
Lprint ('Interrupted stopping')
try:
sys.exit(0)
except SystemExit:
os._exit(0)



def AccountManager(Account=None):
AccountLock.acquire()
Expand All @@ -93,6 +112,12 @@ def AccountManager(Account=None):
Accounts.append(Account)
AccountLock.release()

def Lprint (content):
content = "{0} {1}".format(strftime("%Y-%m-%d %H:%M:%S"), content)
screen_lock.acquire()
print (content)
screen_lock.release()

def MakeConf(CurThread, username, password):
try:
jsonData = json.loads(open('configs/' + MultiBotConfig[u'AuthJsonFile']).read())
Expand All @@ -110,29 +135,50 @@ def MakeConf(CurThread, username, password):
try:
if jsonData[u'tasks'][i][u'config'][u'nickname']:
jsonData[u'tasks'][i][u'config'][u'nickname'] = username.replace('_', '')
except KeyboardInterrupt:
stop()
except:
pass
try:
if jsonData[u'websocket'][u'start_embedded_server']:
jsonData[u'websocket'][u'server_url'] = MultiBotConfig[u'WebSocket'][u'IP'] + ':' + str(MultiBotConfig[u'WebSocket'][u'Port'] + CurThread)
except:
print 'error websocket'
if MultiBotConfig[u'WebSocket'][u'start_embedded_server']:
try:
if jsonData[u'websocket'][u'server_url']:
jsonData[u'websocket'][u'server_url'] = MultiBotConfig[u'WebSocket'][u'IP'] + ':' + str(MultiBotConfig[u'WebSocket'][u'Port'] + CurThread)
except KeyboardInterrupt:
stop()
except:
jsonData.items().append("{u'websocket':,{u'server_url': u'" + MultiBotConfig[u'WebSocket'][u'IP'] + ":" + str(MultiBotConfig[u'WebSocket'][u'Port'] + CurThread) + "u'start_embedded_server': True}")



with open('configs/temp/config-' + str(CurThread) + '.json', 'w') as s:
s.write(json.dumps(jsonData))
s.close()

except IOError:
print 'config file error'
Lprint ('config file error')
time.sleep(30)
except KeyboardInterrupt:
stop()


class ThreadClass(threading.Thread):
def run(self):
self.CurThread = int(self.getName().replace('Thread-', '')) -1
def __init__(self):
threading.Thread.__init__(self)
self.paused = True # start out paused
self.state = threading.Condition()

def run(self):
time.sleep(.1)
self.resume() # unpause self
while True:
with self.state:
if self.paused:
self.state.wait() # block until notified
self.CurThread = int(self.getName().replace('Thread-', '')) -1

self.Account = AccountManager()
self.username, self.password = self.Account.split(':')
print 'Thread-{0} using account {1}'.format(self.CurThread, self.username)
Lprint ('Thread-{0} using account {1}'.format(self.CurThread, self.username))
try:
MakeConf(self.CurThread, self.username, self.password)
if MultiBotConfig[u'UseProxy']:
Expand All @@ -146,16 +192,37 @@ def run(self):
self.CurThread, MultiBotConfig[u'walker_limit_output']))
except Exception as e:
import traceback
print("Generic Exception: " + traceback.format_exc())
Lprint ((e))
time.sleep (60)
except KeyboardInterrupt:
stop()
finally:
AccountManager(self.Account)
time.sleep (60)

def resume(self):
with self.state:
self.paused = False
self.state.notify() # unblock self if waiting

def pause(self):
with self.state:
self.paused = True # make self block and wait
def stop(self):
self.stopped = True


def start():
for i in range(MultiBotConfig[u'Threads']):
t = ThreadClass()
time.sleep (0.1)
t.start()
time.sleep (10)
try:
for i in range(MultiBotConfig[u'Threads']):
t = ThreadClass()
time.sleep (0.1)
t.start()
time.sleep (10)
except KeyboardInterrupt:
Lprint("stopping all Threads")
for i in range(MultiBotConfig[u'Threads']):
t.stop()
stop()

if __name__ == "__main__":
start()
12 changes: 7 additions & 5 deletions configs/config.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,8 @@
"missing",
"vip",
"priority"
],
],
"teleport_back_to_last_location": false,
"sources": [
{
"enabled": false,
Expand Down Expand Up @@ -418,12 +419,13 @@
"pinap_on_level_below": 0,
"pinap_operator": "or",
"pinap_ignore_threshold": false,
"smart_pinap_enabled": true,
"smart_pinap_threshold": 0.85,
"smart_pinap_to_keep": 3,
"smart_pinap_enabled": true,
"smart_pinap_threshold": 0.85,
"smart_pinap_to_keep": 3,
"vip_berry_threshold": 0.9,
"treat_unseen_as_vip": true,
"daily_catch_limit": 800,
"daily_catch_limit": 500,
"exit_on_limit_reached": false,
"vanish_settings": {
"consecutive_vanish_limit": 10,
"rest_duration_min": "02:00:00",
Expand Down
21 changes: 12 additions & 9 deletions configs/config.json.map.example
Original file line number Diff line number Diff line change
Expand Up @@ -442,16 +442,19 @@
{
"type": "Sniper",
"config": {
"enabled": false,
"mode": "social",
"bullets": 1,
"homing_shots": true,
"special_iv": 100,
"order": [
"missing",
"vip",
"priority"
"enabled": false,
"mode": "social",
"bullets": 1,
"homing_shots": true,
"cooldown_enabled": false,
"loiter_after_snipe": false,
"special_iv": 100,
"order": [
"missing",
"vip",
"priority"
],
"teleport_back_to_last_location": false,
"sources": [
{
"enabled": false,
Expand Down
3 changes: 3 additions & 0 deletions docs/configuration_files.md
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,8 @@ This task will fetch current pokemon spawns from /raw_data of an PokemonGo-Map i

This task is an upgrade version of the MoveToMapPokemon task. It will fetch pokemon informations from any number of urls (sources), including PokemonGo-Map, or from the social feature. You can also use the old PokemonGo-Map project. For information on how to properly setup PokemonGo-Map have a look at the Github page of the project [here](https://github.com/PokemonGoMap/PokemonGo-Map). You can also use [this](https://github.com/YvesHenri/PogoLocationFeeder), which is an adapted version of the application that NecroBot used to snipe. There is an example config in `config/config.json.map.example`.

Please note that this feature only works with a radius of 15KM. By default, it will continue at new location once snipe is done unless you specify it not to with `teleport_back_to_last_location` set to true.

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

Expand All @@ -887,6 +889,7 @@ This task is an upgrade version of the MoveToMapPokemon task. It will fetch poke
- `missing` - Order by the target's pokedex missing status.
- `priority` - Order by the priority you have specified in the `catch` list.
- `expiration_timestamp_ms` - Order by the expiration time.
* `teleport_back_to_last_location` - Specify if you want to teleport back to last location. Default is false.
* `sources` - This should map a JSON param values from a given url. For example: different urls will provide different JSON response formats. **PLEASE ADVISED THAT, IF A PARAM DOES NOT EXIST (OR CONTAINS WRONG DATA LIKE PokeSnipers's ID PARAM), DO NOT SPECIFY IT!** Pokesnipers is a special case where it does provide IDs, however theyre wrong. Map bellow their corresponding values:
* `sources.key` - The JSON key that contains the results, eg.: For a JSON response such as `{ "SomeWeirdoName": [{"id": 123, ...}, {"id": 143, ...}]}`, `SomeWeirdoName` would be the key name.
* `sources.url` - The URL that will provide the JSON.
Expand Down
3 changes: 1 addition & 2 deletions pokemongo_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1644,7 +1644,7 @@ def get_forts(self, order_by_distance=False):
# Need to filter out disabled forts!
forts = filter(lambda x: x["enabled"] is True, forts)
forts = filter(lambda x: 'closed' not in fort, forts)

if order_by_distance:
forts.sort(key=lambda x: distance(
self.position[0],
Expand Down Expand Up @@ -1672,7 +1672,6 @@ def get_gyms(self, order_by_distance=False):
# Need to filter out disabled gyms!
forts = filter(lambda x: x["enabled"] is True, forts)
forts = filter(lambda x: 'closed' not in fort, forts)
# forts = filter(lambda x: 'type' not in fort, forts)

if order_by_distance:
forts.sort(key=lambda x: distance(
Expand Down
14 changes: 10 additions & 4 deletions pokemongo_bot/cell_workers/catch_limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,18 @@ def __init__(self, bot, config):
self.duration = self.config.get("duration", 15)
self.no_log_until = datetime.now()
self.min_ultraball_to_keep = 0
self.daily_catch_limit = 500 # default it to 500 if not found in CatchPokemon
self.exit_on_limit_reached = False # default it to false if not found in CatchPokemon

for catch_cfg in self.bot.config.raw_tasks:
if "type" in catch_cfg:
if catch_cfg["type"] == "CatchPokemon":
self.min_ultraball_to_keep = catch_cfg["config"]["min_ultraball_to_keep"]
self.daily_catch_limit = catch_cfg["config"]["daily_catch_limit"]
self.exit_on_limit_reached = catch_cfg["config"]["exit_on_limit_reached"]
if "min_ultraball_to_keep" in catch_cfg["config"]:
self.min_ultraball_to_keep = catch_cfg["config"]["min_ultraball_to_keep"]
if "daily_catch_limit" in catch_cfg["config"]:
self.daily_catch_limit = catch_cfg["config"]["daily_catch_limit"]
if "exit_on_limit_reached" in catch_cfg["config"]:
self.exit_on_limit_reached = catch_cfg["config"]["exit_on_limit_reached"]

if not hasattr(self.bot, "catch_resume_at"):
self.bot.catch_resume_at = None
Expand Down Expand Up @@ -76,7 +82,7 @@ def work(self):
if self.bot.catch_limit_reached:
self.emit_event(
'catch_limit_off',
formatted="Resume time hasn't passed yet, but catch limit passing ({} / {}}). Re-enabling catch tasks.".format(
formatted="Resume time hasn't passed yet, but catch limit passing ({} / {}). Re-enabling catch tasks.".format(
result[0],
self.daily_catch_limit))
self.bot.catch_disabled = False
Expand Down
9 changes: 8 additions & 1 deletion pokemongo_bot/cell_workers/pokemon_catch_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def initialize(self):
self.berry_threshold = self.config.get('berry_threshold', 0.35)
self.vip_berry_threshold = self.config.get('vip_berry_threshold', 0.9)
self.treat_unseen_as_vip = self.config.get('treat_unseen_as_vip', DEFAULT_UNSEEN_AS_VIP)
self.daily_catch_limit = self.config.get('daily_catch_limit', 800)
self.daily_catch_limit = self.config.get('daily_catch_limit', 500)
self.use_pinap_on_vip = self.config.get('use_pinap_on_vip', False)
self.pinap_on_level_below = self.config.get('pinap_on_level_below', 0)
self.pinap_operator = self.config.get('pinap_operator', "or")
Expand Down Expand Up @@ -121,6 +121,13 @@ def initialize(self):
############################################################################

def work(self, response_dict=None):
if self.daily_catch_limit > 500:
if not hasattr(self.bot, "no_notify_until") or self.bot.no_notify_until <= datetime.now():
self.logger.warning("BE WARNED! The total catch limit in 72 hours is 1500!")
self.logger.warning("Setting your daily limit to %s might get you account flagged or banned!" % self.daily_catch_limit)
sleep(5)
self.bot.no_notify_until = datetime.now() + timedelta(minutes=5)

response_dict = response_dict or self.create_encounter_api_call()

# validate response
Expand Down
Loading

0 comments on commit a905768

Please sign in to comment.