-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathworker.py
1390 lines (1237 loc) · 54.8 KB
/
worker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from asyncio import gather, Lock, Semaphore, sleep, CancelledError
from collections import deque
from time import time, monotonic
from queue import Empty
from itertools import cycle
from sys import exit
from distutils.version import StrictVersion
from aiopogo import PGoApi, HashServer, json_loads, exceptions as ex
from aiopogo.auth_ptc import AuthPtc
from cyrandom import choice, randint, uniform
from pogeo import get_distance
from .db import FORT_CACHE, MYSTERY_CACHE, SIGHTING_CACHE
from .utils import round_coords, load_pickle, get_device_info, get_start_coords, Units, randomize_point
from .shared import get_logger, LOOP, SessionManager, run_threaded, ACCOUNTS
from . import altitudes, avatar, bounds, db_proc, spawns, sanitized as conf
if conf.NOTIFY:
from .notification import Notifier
if conf.CACHE_CELLS:
from array import typecodes
if 'Q' in typecodes:
from pogeo import get_cell_ids_compact as _pogeo_cell_ids
else:
from pogeo import get_cell_ids as _pogeo_cell_ids
else:
from pogeo import get_cell_ids as _pogeo_cell_ids
_unit = getattr(Units, conf.SPEED_UNIT.lower())
if conf.SPIN_POKESTOPS:
if _unit is Units.miles:
SPINNING_SPEED_LIMIT = 21
UNIT_STRING = "MPH"
elif _unit is Units.kilometers:
SPINNING_SPEED_LIMIT = 34
UNIT_STRING = "KMH"
elif _unit is Units.meters:
SPINNING_SPEED_LIMIT = 34000
UNIT_STRING = "m/h"
UNIT = _unit.value
del _unit
class Worker:
"""Single worker walking on the map"""
download_hash = ''
scan_delay = conf.SCAN_DELAY if conf.SCAN_DELAY >= 10 else 10
g = {'seen': 0, 'captchas': 0}
if conf.CACHE_CELLS:
cells = load_pickle('cells') or {}
@classmethod
def get_cell_ids(cls, point):
rounded = round_coords(point, 4)
try:
return cls.cells[rounded]
except KeyError:
cells = _pogeo_cell_ids(rounded)
cls.cells[rounded] = cells
return cells
else:
get_cell_ids = _pogeo_cell_ids
login_semaphore = Semaphore(conf.SIMULTANEOUS_LOGINS, loop=LOOP)
sim_semaphore = Semaphore(conf.SIMULTANEOUS_SIMULATION, loop=LOOP)
multiproxy = False
if conf.PROXIES:
if len(conf.PROXIES) > 1:
multiproxy = True
proxies = cycle(conf.PROXIES)
else:
proxies = None
if conf.NOTIFY:
notifier = Notifier()
def __init__(self, worker_no):
self.worker_no = worker_no
self.log = get_logger('worker-{}'.format(worker_no))
# account information
try:
self.account = self.extra_queue.get_nowait()
except Empty as e:
try:
self.account = self.captcha_queue.get_nowait()
except Empty as e:
raise ValueError("You don't have enough accounts for the number of workers specified in GRID.") from e
self.username = self.account['username']
try:
self.location = self.account['location'][:2]
except KeyError:
self.location = get_start_coords(worker_no)
self.altitude = None
# last time of any request
self.last_request = self.account.get('time', 0)
# last time of a request that requires user interaction in the game
self.last_action = self.last_request
# last time of a GetMapObjects request
self.last_gmo = self.last_request
try:
self.items = self.account['items']
self.bag_items = sum(self.items.values())
except KeyError:
self.account['items'] = {}
self.items = self.account['items']
self.inventory_timestamp = self.account.get('inventory_timestamp', 0) if self.items else 0
self.player_level = self.account.get('level')
self.num_captchas = 0
self.eggs = {}
self.unused_incubators = deque()
self.initialize_api()
# State variables
self.busy = Lock(loop=LOOP)
# Other variables
self.after_spawn = 0
self.speed = 0
self.total_seen = 0
self.error_code = 'INIT'
self.item_capacity = 350
self.visits = 0
self.pokestops = conf.SPIN_POKESTOPS
self.next_spin = 0
self.handle = HandleStub()
def initialize_api(self):
device_info = get_device_info(self.account)
self.empty_visits = 0
self.api = PGoApi(device_info=device_info)
self.api.set_position(*self.location, self.altitude)
if self.proxies:
self.api.proxy = next(self.proxies)
try:
if self.account['provider'] == 'ptc' and 'auth' in self.account:
self.api.auth_provider = AuthPtc(username=self.username, password=self.account['password'], timeout=conf.LOGIN_TIMEOUT)
self.api.auth_provider._access_token = self.account['auth']
self.api.auth_provider._access_token_expiry = self.account['expiry']
if self.api.auth_provider.check_access_token():
self.api.auth_provider.authenticated = True
except KeyError:
pass
def swap_proxy(self):
proxy = self.api.proxy
while proxy == self.api.proxy:
self.api.proxy = next(self.proxies)
async def login(self, reauth=False):
"""Logs worker in and prepares for scanning"""
self.log.info('Trying to log in')
for attempt in range(-1, conf.MAX_RETRIES):
try:
self.error_code = '»'
async with self.login_semaphore:
self.error_code = 'LOGIN'
await self.api.set_authentication(
username=self.username,
password=self.account['password'],
provider=self.account.get('provider') or 'ptc',
timeout=conf.LOGIN_TIMEOUT
)
except ex.UnexpectedAuthError as e:
await self.swap_account('unexpected auth error')
except ex.AuthException as e:
err = e
await sleep(2, loop=LOOP)
else:
err = None
break
if reauth:
if err:
self.error_code = 'NOT AUTHENTICATED'
self.log.info('Re-auth error on {}: {}', self.username, err)
return False
self.error_code = None
return True
if err:
raise err
self.error_code = '°'
version = 6701
async with self.sim_semaphore:
self.error_code = 'APP SIMULATION'
if conf.APP_SIMULATION:
await self.app_simulation_login(version)
else:
await self.download_remote_config(version)
self.error_code = None
return True
async def get_player(self):
request = self.api.create_request()
request.get_player(player_locale=conf.PLAYER_LOCALE)
responses = await self.call(request, chain=False)
tutorial_state = None
try:
get_player = responses['GET_PLAYER']
if get_player.banned:
raise ex.BannedAccountException
player_data = get_player.player_data
tutorial_state = player_data.tutorial_state
self.item_capacity = player_data.max_item_storage
if 'created' not in self.account:
self.account['created'] = player_data.creation_timestamp_ms / 1000
except (KeyError, TypeError, AttributeError):
pass
return tutorial_state
async def download_remote_config(self, version):
request = self.api.create_request()
request.download_remote_config_version(platform=1, app_version=version)
responses = await self.call(request, stamp=False, buddy=False, settings=True, inbox=False, dl_hash=False)
try:
inventory_items = responses['GET_INVENTORY'].inventory_delta.inventory_items
for item in inventory_items:
level = item.inventory_item_data.player_stats.level
if level:
self.player_level = level
break
except KeyError:
pass
await self.random_sleep(.78, 1.05)
try:
remote_config = responses['DOWNLOAD_REMOTE_CONFIG_VERSION']
return (
remote_config.asset_digest_timestamp_ms / 1000000,
remote_config.item_templates_timestamp_ms / 1000)
except KeyError:
return 0.0, 0.0
async def set_avatar(self, tutorial=False):
plater_avatar = avatar.new()
request = self.api.create_request()
request.list_avatar_customizations(
avatar_type=plater_avatar['avatar'],
slot=tuple(),
filters=(2,)
)
await self.call(request, buddy=not tutorial, action=5)
await self.random_sleep(7, 14)
request = self.api.create_request()
request.set_avatar(player_avatar=plater_avatar)
await self.call(request, buddy=not tutorial, action=2)
if tutorial:
await self.random_sleep(.5, 4)
request = self.api.create_request()
request.mark_tutorial_complete(tutorials_completed=(1,))
await self.call(request, buddy=False)
await self.random_sleep(.5, 1)
request = self.api.create_request()
request.get_player_profile()
await self.call(request, action=1)
async def app_simulation_login(self, version):
self.log.info('Starting RPC login sequence (iOS app simulation)')
# empty request
request = self.api.create_request()
await self.call(request, chain=False)
await self.random_sleep(.43, .97)
# request 1: get_player
tutorial_state = await self.get_player()
await self.random_sleep(.53, 1.1)
# request 2: download_remote_config_version
asset_time, template_time = await self.download_remote_config(version)
if asset_time > self.account.get('asset_time', 0.0):
# request 3: get_asset_digest
i = randint(0, 3)
result = 2
page_offset = 0
page_timestamp = 0
while result == 2:
request = self.api.create_request()
request.get_asset_digest(
platform=1,
app_version=version,
paginate=True,
page_offset=page_offset,
page_timestamp=page_timestamp)
responses = await self.call(request, buddy=False, settings=True)
if i > 2:
await sleep(1.45)
i = 0
else:
i += 1
await sleep(.2)
try:
response = responses['GET_ASSET_DIGEST']
except KeyError:
break
result = response.result
page_offset = response.page_offset
page_timestamp = response.timestamp_ms
self.account['asset_time'] = asset_time
if template_time > self.account.get('template_time', 0.0):
# request 4: download_item_templates
i = randint(0, 3)
result = 2
page_offset = 0
page_timestamp = 0
while result == 2:
request = self.api.create_request()
request.download_item_templates(
paginate=True,
page_offset=page_offset,
page_timestamp=page_timestamp)
responses = await self.call(request, buddy=False, settings=True)
if i > 2:
await sleep(1.5)
i = 0
else:
i += 1
await sleep(.25)
try:
response = responses['DOWNLOAD_ITEM_TEMPLATES']
except KeyError:
break
result = response.result
page_offset = response.page_offset
page_timestamp = response.timestamp_ms
self.account['template_time'] = template_time
if (conf.COMPLETE_TUTORIAL and
tutorial_state is not None and
not all(x in tutorial_state for x in (0, 1, 3, 4, 7))):
self.log.warning('{} is starting tutorial', self.username)
await self.complete_tutorial(tutorial_state)
else:
# request 5: get_player_profile
request = self.api.create_request()
request.get_player_profile()
await self.call(request, settings=True, inbox=False)
await self.random_sleep(.2, .3)
if self.player_level:
# request 6: level_up_rewards
request = self.api.create_request()
request.level_up_rewards(level=self.player_level)
await self.call(request, settings=True)
await self.random_sleep(.45, .7)
else:
self.log.warning('No player level')
self.log.info('Finished RPC login sequence (iOS app simulation)')
await self.random_sleep(.5, 1.3)
self.error_code = None
return True
async def complete_tutorial(self, tutorial_state):
self.error_code = 'TUTORIAL'
if 0 not in tutorial_state:
# legal screen
request = self.api.create_request()
request.mark_tutorial_complete(tutorials_completed=(0,))
await self.call(request, buddy=False)
await self.random_sleep(.35, .525)
request = self.api.create_request()
request.get_player(player_locale=conf.PLAYER_LOCALE)
await self.call(request, buddy=False)
await sleep(1)
if 1 not in tutorial_state:
# avatar selection
await self.set_avatar(tutorial=True)
starter_id = None
if 3 not in tutorial_state:
# encounter tutorial
await self.random_sleep(.7, .9)
request = self.api.create_request()
request.get_download_urls(asset_id=
('1a3c2816-65fa-4b97-90eb-0b301c064b7a/1487275569649000',
'aa8f7687-a022-4773-b900-3a8c170e9aea/1487275581132582',
'e89109b0-9a54-40fe-8431-12f7826c8194/1487275593635524'))
await self.call(request)
await self.random_sleep(7, 10.3)
request = self.api.create_request()
starter = choice((1, 4, 7))
request.encounter_tutorial_complete(pokemon_id=starter)
await self.call(request, action=1)
await self.random_sleep(.4, .5)
request = self.api.create_request()
request.get_player(player_locale=conf.PLAYER_LOCALE)
responses = await self.call(request)
try:
inventory = responses['GET_INVENTORY'].inventory_delta.inventory_items
for item in inventory:
pokemon = item.inventory_item_data.pokemon_data
if pokemon.id:
starter_id = pokemon.id
break
except (KeyError, TypeError):
starter_id = None
if 4 not in tutorial_state:
# name selection
await self.random_sleep(12, 18)
request = self.api.create_request()
request.claim_codename(codename=self.username)
await self.call(request, action=2)
await sleep(.7, loop=LOOP)
request = self.api.create_request()
request.get_player(player_locale=conf.PLAYER_LOCALE)
await self.call(request)
await sleep(.13, loop=LOOP)
request = self.api.create_request()
request.mark_tutorial_complete(tutorials_completed=(4,))
await self.call(request, buddy=False)
if 7 not in tutorial_state:
# first time experience
await self.random_sleep(3.9, 4.5)
request = self.api.create_request()
request.mark_tutorial_complete(tutorials_completed=(7,))
await self.call(request)
if starter_id:
await self.random_sleep(4, 5)
request = self.api.create_request()
request.set_buddy_pokemon(pokemon_id=starter_id)
await self.call(request, action=2)
await self.random_sleep(.8, 1.2)
await sleep(.2, loop=LOOP)
return True
def update_inventory(self, inventory_items):
for thing in inventory_items:
obj = thing.inventory_item_data
if obj.HasField('item'):
item = obj.item
self.items[item.item_id] = item.count
self.bag_items = sum(self.items.values())
elif conf.INCUBATE_EGGS:
if obj.HasField('pokemon_data') and obj.pokemon_data.is_egg:
egg = obj.pokemon_data
self.eggs[egg.id] = egg
elif obj.HasField('egg_incubators'):
self.unused_incubators.clear()
for item in obj.egg_incubators.egg_incubator:
if item.pokemon_id:
continue
if item.item_id == 901:
self.unused_incubators.append(item)
else:
self.unused_incubators.appendleft(item)
async def call(self, request, chain=True, stamp=True, buddy=True, settings=False, inbox=True, dl_hash=True, action=None):
if chain:
request.check_challenge()
request.get_hatched_eggs()
request.get_inventory(last_timestamp_ms=self.inventory_timestamp)
request.check_awarded_badges()
if settings:
if dl_hash:
request.download_settings(hash=self.download_hash)
else:
request.download_settings()
if buddy:
request.get_buddy_walked()
if inbox:
request.get_inbox(is_history=True)
if action:
now = time()
# wait for the time required, or at least a half-second
if self.last_action > now + .5:
await sleep(self.last_action - now, loop=LOOP)
else:
await sleep(0.5, loop=LOOP)
response = None
err = None
for attempt in range(-1, conf.MAX_RETRIES):
try:
responses = await request.call()
self.last_request = time()
err = None
break
except (ex.NotLoggedInException, ex.AuthException) as e:
self.log.info('Auth error on {}: {}', self.username, e)
err = e
await sleep(3, loop=LOOP)
if not await self.login(reauth=True):
await self.swap_account(reason='reauth failed')
except ex.TimeoutException as e:
self.error_code = 'TIMEOUT'
if not isinstance(e, type(err)):
err = e
self.log.warning('{}', e)
await sleep(10, loop=LOOP)
except ex.HashingOfflineException as e:
if not isinstance(e, type(err)):
err = e
self.log.warning('{}', e)
self.error_code = 'HASHING OFFLINE'
await sleep(5, loop=LOOP)
except ex.NianticOfflineException as e:
if not isinstance(e, type(err)):
err = e
self.log.warning('{}', e)
self.error_code = 'NIANTIC OFFLINE'
await self.random_sleep()
except ex.HashingQuotaExceededException as e:
if not isinstance(e, type(err)):
err = e
self.log.warning('Exceeded your hashing quota, sleeping.')
self.error_code = 'QUOTA EXCEEDED'
refresh = HashServer.status.get('period')
now = time()
if refresh:
if refresh > now:
await sleep(refresh - now + 1, loop=LOOP)
else:
await sleep(5, loop=LOOP)
else:
await sleep(30, loop=LOOP)
except ex.BadRPCException:
raise
except ex.InvalidRPCException as e:
self.last_request = time()
if not isinstance(e, type(err)):
err = e
self.log.warning('{}', e)
self.error_code = 'INVALID REQUEST'
await self.random_sleep()
except ex.ProxyException as e:
if not isinstance(e, type(err)):
err = e
self.error_code = 'PROXY ERROR'
if self.multiproxy:
self.log.error('{}, swapping proxy.', e)
self.swap_proxy()
else:
if not isinstance(e, type(err)):
self.log.error('{}', e)
await sleep(5, loop=LOOP)
except (ex.MalformedResponseException, ex.UnexpectedResponseException) as e:
self.last_request = time()
if not isinstance(e, type(err)):
self.log.warning('{}', e)
self.error_code = 'MALFORMED RESPONSE'
await self.random_sleep()
if err is not None:
raise err
if action:
# pad for time that action would require
self.last_action = self.last_request + action
try:
delta = responses['GET_INVENTORY'].inventory_delta
self.inventory_timestamp = delta.new_timestamp_ms
self.update_inventory(delta.inventory_items)
except KeyError:
pass
if settings:
try:
dl_settings = responses['DOWNLOAD_SETTINGS']
Worker.download_hash = dl_settings.hash
except KeyError:
self.log.info('Missing DOWNLOAD_SETTINGS response.')
else:
if (not dl_hash
and conf.FORCED_KILL
and dl_settings.settings.minimum_client_version != '0.67.1'):
forced_version = StrictVersion(dl_settings.settings.minimum_client_version)
if forced_version > StrictVersion('0.67.1'):
err = '{} is being forced, exiting.'.format(forced_version)
self.log.error(err)
print(err)
exit()
try:
challenge_url = responses['CHECK_CHALLENGE'].challenge_url
if challenge_url != ' ':
self.g['captchas'] += 1
if conf.CAPTCHA_KEY:
self.log.warning('{} has encountered a CAPTCHA, trying to solve', self.username)
await self.handle_captcha(challenge_url)
else:
raise CaptchaException
except KeyError:
pass
return responses
def travel_speed(self, point):
'''Fast calculation of travel speed to point'''
time_diff = max(time() - self.last_request, self.scan_delay)
distance = get_distance(self.location, point, UNIT)
# conversion from seconds to hours
speed = (distance / time_diff) * 3600
return speed
async def bootstrap_visit(self, point):
for _ in range(3):
if await self.visit(point, bootstrap=True):
return True
self.error_code = '∞'
self.simulate_jitter(0.00005)
return False
async def visit(self, point, spawn_id=None, bootstrap=False):
"""Wrapper for self.visit_point - runs it a few times before giving up
Also is capable of restarting in case an error occurs.
"""
try:
try:
self.altitude = altitudes.get(point)
except KeyError:
self.altitude = await altitudes.fetch(point)
self.location = point
self.api.set_position(*self.location, self.altitude)
if not self.authenticated:
await self.login()
return await self.visit_point(point, spawn_id, bootstrap)
except ex.NotLoggedInException:
self.error_code = 'NOT AUTHENTICATED'
await sleep(1, loop=LOOP)
if not await self.login(reauth=True):
await self.swap_account(reason='reauth failed')
return await self.visit(point, spawn_id, bootstrap)
except ex.AuthException as e:
self.log.warning('Auth error on {}: {}', self.username, e)
self.error_code = 'NOT AUTHENTICATED'
await sleep(3, loop=LOOP)
await self.swap_account(reason='login failed')
except CaptchaException:
self.error_code = 'CAPTCHA'
self.g['captchas'] += 1
await sleep(1, loop=LOOP)
await self.bench_account()
except CaptchaSolveException:
self.error_code = 'CAPTCHA'
await sleep(1, loop=LOOP)
await self.swap_account(reason='solving CAPTCHA failed')
except ex.TempHashingBanException:
self.error_code = 'HASHING BAN'
self.log.error('Temporarily banned from hashing server for using invalid keys.')
await sleep(185, loop=LOOP)
except ex.BannedAccountException:
self.error_code = 'BANNED'
self.log.warning('{} is banned', self.username)
await sleep(1, loop=LOOP)
await self.remove_account()
except ex.ProxyException as e:
self.error_code = 'PROXY ERROR'
if self.multiproxy:
self.log.error('{} Swapping proxy.', e)
self.swap_proxy()
else:
self.log.error('{}', e)
except ex.TimeoutException as e:
self.log.warning('{} Giving up.', e)
except ex.NianticIPBannedException:
self.error_code = 'IP BANNED'
if self.multiproxy:
self.log.warning('Swapping out {} due to IP ban.', self.api.proxy)
self.swap_proxy()
else:
self.log.error('IP banned.')
except ex.NianticOfflineException as e:
await self.swap_account(reason='Niantic endpoint failure')
self.log.warning('{}. Giving up.', e)
except ex.ServerBusyOrOfflineException as e:
self.log.warning('{} Giving up.', e)
except ex.BadRPCException:
self.error_code = 'BAD REQUEST'
self.log.warning('{} received code 3 and is likely banned. Removing until next run.', self.username)
await self.new_account()
except ex.InvalidRPCException as e:
self.log.warning('{} Giving up.', e)
except ex.ExpiredHashKeyException as e:
self.error_code = 'KEY EXPIRED'
err = str(e)
self.log.error(err)
print(err)
exit()
except (ex.MalformedResponseException, ex.UnexpectedResponseException) as e:
self.log.warning('{} Giving up.', e)
self.error_code = 'MALFORMED RESPONSE'
except EmptyGMOException as e:
self.error_code = '0'
self.log.warning('Empty GetMapObjects response for {}. Speed: {:.2f}', self.username, self.speed)
except ex.HashServerException as e:
self.log.warning('{}', e)
self.error_code = 'HASHING ERROR'
except ex.AiopogoError as e:
self.log.exception(e.__class__.__name__)
self.error_code = 'AIOPOGO ERROR'
except CancelledError:
self.log.warning('Visit cancelled.')
except Exception as e:
self.log.exception('A wild {} appeared!', e.__class__.__name__)
self.error_code = 'EXCEPTION'
return False
async def visit_point(self, point, spawn_id, bootstrap,
encounter_conf=conf.ENCOUNTER, notify_conf=conf.NOTIFY,
more_points=conf.MORE_POINTS):
self.handle.cancel()
self.error_code = '∞' if bootstrap else '!'
self.log.info('Visiting {0[0]:.4f},{0[1]:.4f}', point)
start = time()
cell_ids = self.get_cell_ids(point)
since_timestamp_ms = (0,) * len(cell_ids)
request = self.api.create_request()
request.get_map_objects(cell_id=cell_ids,
since_timestamp_ms=since_timestamp_ms,
latitude=point[0],
longitude=point[1])
diff = self.last_gmo + self.scan_delay - time()
if diff > 0:
await sleep(diff, loop=LOOP)
responses = await self.call(request)
self.last_gmo = self.last_request
try:
map_objects = responses['GET_MAP_OBJECTS']
if map_objects.status != 1:
error = 'GetMapObjects code for {}. Speed: {:.2f}'.format(self.username, self.speed)
self.empty_visits += 1
if self.empty_visits > 3:
reason = '{} empty visits'.format(self.empty_visits)
await self.swap_account(reason)
raise ex.UnexpectedResponseException(error)
except KeyError:
await self.random_sleep(.5, 1)
await self.get_player()
raise ex.UnexpectedResponseException('Missing GetMapObjects response.')
pokemon_seen = 0
forts_seen = 0
points_seen = 0
seen_target = not spawn_id
if conf.ITEM_LIMITS and self.bag_items >= self.item_capacity:
await self.clean_bag()
for map_cell in map_objects.map_cells:
request_time_ms = map_cell.current_timestamp_ms
for pokemon in map_cell.wild_pokemons:
pokemon_seen += 1
normalized = self.normalize_pokemon(pokemon)
seen_target = seen_target or normalized['spawn_id'] == spawn_id
if (normalized not in SIGHTING_CACHE and
normalized not in MYSTERY_CACHE):
if (encounter_conf == 'all'
or (encounter_conf == 'some'
and normalized['pokemon_id'] in conf.ENCOUNTER_IDS)):
try:
await self.encounter(normalized, pokemon.spawn_point_id)
except CancelledError:
db_proc.add(normalized)
raise
except Exception as e:
self.log.warning('{} during encounter', e.__class__.__name__)
if notify_conf and self.notifier.eligible(normalized):
if encounter_conf and 'move_1' not in normalized:
try:
await self.encounter(normalized, pokemon.spawn_point_id)
except CancelledError:
db_proc.add(normalized)
raise
except Exception as e:
self.log.warning('{} during encounter', e.__class__.__name__)
LOOP.create_task(self.notifier.notify(normalized, map_objects.time_of_day))
db_proc.add(normalized)
for fort in map_cell.forts:
if not fort.enabled:
continue
forts_seen += 1
if fort.type == 1: # pokestops
if fort.HasField('lure_info'):
norm = self.normalize_lured(fort, request_time_ms)
pokemon_seen += 1
if norm not in SIGHTING_CACHE:
db_proc.add(norm)
if (self.pokestops and
self.bag_items < self.item_capacity
and time() > self.next_spin
and (not conf.SMART_THROTTLE or
self.smart_throttle(2))):
cooldown = fort.cooldown_complete_timestamp_ms
if not cooldown or time() > cooldown / 1000:
await self.spin_pokestop(fort)
if fort.id not in FORT_CACHE.pokestops:
pokestop = self.normalize_pokestop(fort)
db_proc.add(pokestop)
elif fort not in FORT_CACHE:
request = self.api.create_request()
request.gym_get_info(
gym_id=fort.id,
player_lat_degrees = self.location[0],
player_lng_degrees = self.location[1],
gym_lat_degrees=fort.latitude,
gym_lng_degrees=fort.longitude
)
responses = await self.call(request, action=1.2)
try:
if responses['GYM_GET_INFO'].result != 1:
self.log.warning("Failed to get gym_info {}", fort.id)
else:
gym_get_info = responses['GYM_GET_INFO']
rawFort = {}
rawFort['external_id'] = fort.id
rawFort['name'] = gym_get_info.name
rawFort['lat'] = fort.latitude
rawFort['lon'] = fort.longitude
rawFort['team'] = fort.owned_by_team
rawFort['guard_pokemon_id'] = fort.guard_pokemon_id
rawFort['last_modified'] = fort.last_modified_timestamp_ms // 1000
rawFort['is_in_battle'] = fort.is_in_battle
rawFort['slots_available'] = fort.gym_display.slots_available
rawFort['time_ocuppied'] = fort.gym_display.occupied_millis // 1000
db_proc.add(self.normalize_gym(rawFort))
gym_members = gym_get_info.gym_status_and_defenders
for gym_member in gym_members.gym_defender:
raw_member = {}
raw_member['external_id'] = fort.id
raw_member['player_name'] = gym_member.trainer_public_profile.name
raw_member['player_level'] = gym_member.trainer_public_profile.level
raw_member['pokemon_id'] = gym_member.motivated_pokemon.pokemon.pokemon_id
raw_member['pokemon_cp'] = gym_member.motivated_pokemon.pokemon.cp
raw_member['move_1'] = gym_member.motivated_pokemon.pokemon.move_1
raw_member['move_2'] = gym_member.motivated_pokemon.pokemon.move_2
raw_member['individual_attack'] = gym_member.motivated_pokemon.pokemon.individual_attack
raw_member['individual_defense'] = gym_member.motivated_pokemon.pokemon.individual_defense
raw_member['individual_stamina'] = gym_member.motivated_pokemon.pokemon.individual_stamina
raw_member['time_deploy'] = gym_member.motivated_pokemon.deploy_ms // 1000
raw_member['last_modified'] = rawFort['last_modified']
db_proc.add(self.normalize_gym_member(raw_member))
except KeyError:
self.log.warning("Failed to get gym_info {}", fort.id)
if more_points:
try:
for p in map_cell.spawn_points:
points_seen += 1
p = p.latitude, p.longitude
if spawns.have_point(p) or p not in bounds:
continue
spawns.cell_points.add(p)
except KeyError:
pass
if spawn_id:
db_proc.add({
'type': 'target',
'seen': seen_target,
'spawn_id': spawn_id})
if (conf.INCUBATE_EGGS and self.unused_incubators
and self.eggs and self.smart_throttle()):
await self.incubate_eggs()
if pokemon_seen > 0:
self.error_code = ':'
self.total_seen += pokemon_seen
self.g['seen'] += pokemon_seen
self.empty_visits = 0
else:
self.empty_visits += 1
if forts_seen == 0:
self.log.warning('Nothing seen by {}. Speed: {:.2f}', self.username, self.speed)
self.error_code = '0 SEEN'
else:
self.error_code = ','
if self.empty_visits > 3 and not bootstrap:
reason = '{} empty visits'.format(self.empty_visits)
await self.swap_account(reason)
self.visits += 1
if conf.MAP_WORKERS:
self.worker_dict.update([(self.worker_no,
(point, start, self.speed, self.total_seen,
self.visits, pokemon_seen))])
self.log.info(
'Point processed, {} Pokemon and {} forts seen!',
pokemon_seen,
forts_seen,
)
self.update_accounts_dict()
self.handle = LOOP.call_later(60, self.unset_code)
return pokemon_seen + forts_seen + points_seen
def smart_throttle(self, requests=1):
try:
# https://en.wikipedia.org/wiki/Linear_equation#Two_variables
# e.g. hashes_left > 2.25*seconds_left+7.5, spare = 0.05, max = 150
spare = conf.SMART_THROTTLE * HashServer.status['maximum']
hashes_left = HashServer.status['remaining'] - requests
usable_per_second = (HashServer.status['maximum'] - spare) / 60
seconds_left = HashServer.status['period'] - time()
return hashes_left > usable_per_second * seconds_left + spare
except (TypeError, KeyError):
return False
async def spin_pokestop(self, pokestop):
self.error_code = '$'
pokestop_location = pokestop.latitude, pokestop.longitude
distance = get_distance(self.location, pokestop_location)
# permitted interaction distance - 4 (for some jitter leeway)
# estimation of spinning speed limit
if distance > 36 or self.speed > SPINNING_SPEED_LIMIT:
self.error_code = '!'
return False
# randomize location up to ~1.5 meters
self.simulate_jitter(amount=0.00001)
request = self.api.create_request()
request.fort_details(fort_id = pokestop.id,
latitude = pokestop_location[0],
longitude = pokestop_location[1])
responses = await self.call(request, action=1.2)
name = responses['FORT_DETAILS'].name
request = self.api.create_request()
request.fort_search(fort_id = pokestop.id,
player_latitude = self.location[0],
player_longitude = self.location[1],
fort_latitude = pokestop_location[0],
fort_longitude = pokestop_location[1])
responses = await self.call(request, action=2)
try:
result = responses['FORT_SEARCH'].result
except KeyError:
self.log.warning('Invalid Pokéstop spinning response.')
self.error_code = '!'
return
if result == 1:
self.log.info('Spun {}.', name)
elif result == 2:
self.log.info('The server said {} was out of spinning range. {:.1f}m {:.1f}{}',
name, distance, self.speed, UNIT_STRING)
elif result == 3:
self.log.warning('{} was in the cooldown period.', name)
elif result == 4:
self.log.warning('Could not spin {} because inventory was full. {}',
name, self.bag_items)
self.inventory_timestamp = 0
elif result == 5:
self.log.warning('Could not spin {} because the daily limit was reached.', name)
self.pokestops = False
else:
self.log.warning('Failed spinning {}: {}', name, result)
self.next_spin = time() + conf.SPIN_COOLDOWN
self.error_code = '!'