Advertisement
Guest User

Untitled

a guest
Sep 10th, 2016
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.75 KB | None | 0 0
  1. import sys
  2. from geopy.distance import vincenty
  3. from datetime import datetime
  4. import ctypes
  5. import math
  6. import geopy.distance
  7. import time
  8. from pgoapi import pgoapi
  9. from pgoapi.exceptions import ServerSideRequestThrottlingException, NotLoggedInException
  10. from pgoapi import utilities as util
  11. from pgoapi.utilities import f2i
  12.  
  13.  
  14. #=========================
  15. # SETTINGS
  16.  
  17. scan_areas = [[0, 0, 0, 0],
  18.               [0, 0, 0, 0]]
  19.  
  20. for [top, left, bottom, right] in scan_areas:
  21.     assert top > bottom
  22.     assert left < right
  23.  
  24. username = ""
  25. password = ""
  26.  
  27. encryption_lib_path = "..\\lib\\encrypt32bit.dll"
  28.  
  29.  
  30. #==========================
  31. # DATA
  32. pokeid_to_name = {1: "Bulbasaur", 2: "Ivysaur", 3: "Venusaur", 4: "Charmander", 5: "Charmeleon", 6: "Charizard", 7: "Squirtle", 8: "Wartortle", 9: "Blastoise", 10: "Caterpie", 11: "Metapod", 12: "Butterfree", 13: "Weedle", 14: "Kakuna", 15: "Beedrill", 16: "Pidgey", 17: "Pidgeotto", 18: "Pidgeot", 19: "Rattata", 20: "Raticate", 21: "Spearow", 22: "Fearow", 23: "Ekans", 24: "Arbok", 25: "Pikachu", 26: "Raichu", 27: "Sandshrew", 28: "Sandslash", 29: "Nidoran?", 30: "Nidorina", 31: "Nidoqueen", 32: "Nidoran?", 33: "Nidorino", 34: "Nidoking", 35: "Clefairy", 36: "Clefable", 37: "Vulpix", 38: "Ninetales", 39: "Jigglypuff", 40: "Wigglytuff", 41: "Zubat", 42: "Golbat", 43: "Oddish", 44: "Gloom", 45: "Vileplume", 46: "Paras", 47: "Parasect", 48: "Venonat", 49: "Venomoth", 50: "Diglett", 51: "Dugtrio", 52: "Meowth", 53: "Persian", 54: "Psyduck", 55: "Golduck", 56: "Mankey", 57: "Primeape", 58: "Growlithe", 59: "Arcanine", 60: "Poliwag", 61: "Poliwhirl", 62: "Poliwrath", 63: "Abra", 64: "Kadabra", 65: "Alakazam", 66: "Machop", 67: "Machoke", 68: "Machamp", 69: "Bellsprout", 70: "Weepinbell", 71: "Victreebel", 72: "Tentacool", 73: "Tentacruel", 74: "Geodude", 75: "Graveler", 76: "Golem", 77: "Ponyta", 78: "Rapidash", 79: "Slowpoke", 80: "Slowbro", 81: "Magnemite", 82: "Magneton", 83: "Farfetch'd", 84: "Doduo", 85: "Dodrio", 86: "Seel", 87: "Dewgong", 88: "Grimer", 89: "Muk", 90: "Shellder", 91: "Cloyster", 92: "Gastly", 93: "Haunter", 94: "Gengar", 95: "Onix", 96: "Drowzee", 97: "Hypno", 98: "Krabby", 99: "Kingler", 100: "Voltorb", 101: "Electrode", 102: "Exeggcute", 103: "Exeggutor", 104: "Cubone", 105: "Marowak", 106: "Hitmonlee", 107: "Hitmonchan", 108: "Lickitung", 109: "Koffing", 110: "Weezing", 111: "Rhyhorn", 112: "Rhydon", 113: "Chansey", 114: "Tangela", 115: "Kangaskhan", 116: "Horsea", 117: "Seadra", 118: "Goldeen", 119: "Seaking", 120: "Staryu", 121: "Starmie", 122: "Mr. Mime", 123: "Scyther", 124: "Jynx", 125: "Electabuzz", 126: "Magmar", 127: "Pinsir", 128: "Tauros", 129: "Magikarp", 130: "Gyarados", 131: "Lapras", 132: "Ditto", 133: "Eevee", 134: "Vaporeon", 135: "Jolteon", 136: "Flareon", 137: "Porygon", 138: "Omanyte", 139: "Omastar", 140: "Kabuto", 141: "Kabutops", 142: "Aerodactyl", 143: "Snorlax", 144: "Articuno", 145: "Zapdos", 146: "Moltres", 147: "Dratini", 148: "Dragonair", 149: "Dragonite", 150: "Mewtwo", 151: "Mew"}
  33. moveid_to_name = {200: "Fury Cutter", 201: "Bug Bite", 202: "Bite", 203: "Sucker Punch", 204: "Dragon Breath", 205: "Thunder Shock", 206: "Spark", 207: "Low Kick", 208: "Karate Chop", 209: "Ember", 210: "Wing Attack", 211: "Peck", 212: "Lick", 213: "Shadow Claw", 214: "Vine Whip", 215: "Razor Leaf", 216: "Mud Shot", 217: "Ice Shard", 218: "Frost Breath", 219: "Quick Attack", 220: "Scratch", 221: "Tackle", 222: "Pound", 223: "Cut", 224: "Poison Jab", 225: "Acid", 226: "Psycho Cut", 227: "Rock Throw", 228: "Metal Claw", 229: "Bullet Punch", 230: "Water Gun", 231: "Splash", 232: "Water Gun", 233: "Mud Slap", 234: "Zen Headbutt", 235: "Confusion", 236: "Poison Sting", 237: "Bubble", 238: "Feint Attack", 239: "Steel Wing", 240: "Fire Fang", 241: "Rock Smash", 13: "Wrap", 14: "Hyper Beam", 16: "Dark Pulse", 18: "Sludge", 20: "Vice Grip", 21: "Flame Wheel", 22: "Megahorn", 24: "Flamethrower", 26: "Dig", 28: "Cross Chop", 30: "Psybeam", 31: "Earthquake", 32: "Stone Edge", 33: "Ice Punch", 34: "Heart Stamp", 35: "Discharge", 36: "Flash Cannon", 38: "Drill Peck", 39: "Ice Beam", 40: "Blizzard", 42: "Heat Wave", 45: "Aerial Ace", 46: "Drill Run", 47: "Petal Blizzard", 48: "Mega Drain", 49: "Bug Buzz", 50: "Poison Fang", 51: "Night Slash", 53: "Bubble Beam", 54: "Submission", 56: "Low Sweep", 57: "Aqua Jet", 58: "Aqua Tail", 59: "Seed Bomb", 60: "Psyshock", 62: "Ancient Power", 63: "Rock Tomb", 64: "Rock Slide", 65: "Power Gem", 66: "Shadow Sneak", 67: "Shadow Punch", 69: "Ominous Wind", 70: "Shadow Ball", 72: "Magnet Bomb", 74: "Iron Head", 75: "Parabolic Charge", 77: "Thunder Punch", 78: "Thunder", 79: "Thunderbolt", 80: "Twister", 82: "Dragon Pulse", 83: "Dragon Claw", 84: "Disarming Voice", 85: "Draining Kiss", 86: "Dazzling Gleam", 87: "Moonblast", 88: "Play Rough", 89: "Cross Poison", 90: "Sludge Bomb", 91: "Sludge Wave", 92: "Gunk Shot", 94: "Bone Club", 95: "Bulldoze", 96: "Mud Bomb", 99: "Signal Beam", 100: "X-Scissor", 101: "Flame Charge", 102: "Flame Burst", 103: "Fire Blast", 104: "Brine", 105: "Water Pulse", 106: "Scald", 107: "Hydro Pump", 108: "Psychic", 109: "Psystrike", 111: "Icy Wind", 114: "Giga Drain", 115: "Fire Punch", 116: "Solar Beam", 117: "Leaf Blade", 118: "Power Whip", 121: "Air Cutter", 122: "Hurricane", 123: "Brick Break", 125: "Swift", 126: "Horn Attack", 127: "Stomp", 129: "Hyper Fang", 131: "Body Slam", 132: "Rest", 133: "Struggle", 134: "Scald", 135: "Hydro Pump", 136: "Wrap", 137: "Wrap"}
  34.  
  35.  
  36. #==========================
  37. # KGO
  38.  
  39. def main():
  40.     seen_gyms = set([])
  41.  
  42.     work = get_work()
  43.  
  44.     api = login('ptc', username, password)
  45.     totalwork = len(work)
  46.  
  47.     while work:
  48.         ctypes.windll.kernel32.SetConsoleTitleA("{} out of {} remaining...".format(len(work), totalwork))
  49.  
  50.         if not api:
  51.             sys.stderr.write("login attempt failed!\n")
  52.             exit(1)
  53.  
  54.         w = work[0]
  55.         time.sleep(11)
  56.  
  57.         try:
  58.             api.set_position(w[0], w[1], 0)
  59.             cell_ids = util.get_cell_ids(lat=w[0], long=w[1])
  60.             timestamps = [0, ] * len(cell_ids)
  61.             response_dict = api.get_map_objects(latitude=f2i(w[0]), longitude=f2i(w[1]), since_timestamp_ms=timestamps, cell_id=cell_ids)
  62.         except ServerSideRequestThrottlingException:
  63.             sys.stderr.write("request throttled, will sleep a bit and try again\n")
  64.             continue
  65.  
  66.         except NotLoggedInException:
  67.             sys.stderr.write("got NotLoggedInException. will log in, sleep a bit and try again\n")
  68.             api = login('ptc', username, password)
  69.             continue
  70.  
  71.         else:
  72.             if isinstance(response_dict, NotLoggedInException):
  73.                 sys.stderr.write("got NotLoggedInException. will log in, sleep a bit and try again\n")
  74.                 api = login('ptc', username, password)
  75.                 continue
  76.  
  77.             if response_dict and 'status_code' in response_dict and response_dict['status_code'] == 3:
  78.                 sys.stderr.write("Account is banned\n")
  79.                 exit(1)
  80.  
  81.             if ((not response_dict)
  82.                 or not isinstance(response_dict, dict)
  83.                 or ('responses' not in response_dict)
  84.                 or 'GET_MAP_OBJECTS' not in response_dict['responses']
  85.                 or 'map_cells' not in response_dict['responses']['GET_MAP_OBJECTS']):
  86.                 # No idea what's wrong, but try and log in again
  87.                 sys.stderr.write('Failed for unknown reasons. Will sleep a bit and try again\n')
  88.                 continue
  89.  
  90.             for cell in response_dict['responses']['GET_MAP_OBJECTS']['map_cells']:
  91.                 for gym in [x for x in cell.get('forts', []) if (x.get('enabled') and 'gym_points' in x)]:
  92.                     parse(gym, api, w[0], w[1], seen_gyms)
  93.  
  94.             work.remove(w)
  95.  
  96.  
  97. def parse(gym, api, lat, lng, seen_gyms):
  98.     if vincenty((lat, lng), (gym['latitude'], gym['longitude'])) > .9:
  99.         # Not allowed to query gyms that are more than 900m away
  100.         return
  101.  
  102.     if gym['id'] in seen_gyms:
  103.         return
  104.  
  105.     gymdata = {
  106.         'gym_id': gym['id'],
  107.         'team_id': gym.get('owned_by_team', 0),
  108.         'gym_points': gym.get('gym_points', 0),
  109.         'latitude': gym['latitude'],
  110.         'longitude': gym['longitude'],
  111.         'last_modified': str(datetime.utcfromtimestamp(gym['last_modified_timestamp_ms'] / 1000.0)),
  112.         'members': []}
  113.  
  114.     try:
  115.         time.sleep(2)
  116.         response = api.get_gym_details(gym_id=gym['id'], player_latitude=lat, player_longitude=lng, gym_latitude=gym['latitude'], gym_longitude=gym['longitude'])
  117.         if response['responses']['GET_GYM_DETAILS']['result'] != 2:
  118.             gym_state = response['responses']['GET_GYM_DETAILS']['gym_state']
  119.  
  120.             for member in gym_state.get('memberships', []):
  121.                 poke_id = member['pokemon_data']['pokemon_id']
  122.                 move1_id = member['pokemon_data'].get('move_1')
  123.                 move2_id = member['pokemon_data'].get('move_2')
  124.                 gymdata['members'].append({
  125.                     'pokemon_id': pokeid_to_name.get(poke_id, poke_id),
  126.                     'cp': member['pokemon_data']['cp'],
  127.                     'move_1': moveid_to_name.get(move1_id, move1_id),
  128.                     'move_2': moveid_to_name.get(move2_id, move2_id),
  129.                     'hp': member['pokemon_data'].get('stamina'),
  130.                     'iv_defense': member['pokemon_data'].get('individual_defense', 0),
  131.                     'iv_stamina': member['pokemon_data'].get('individual_stamina', 0),
  132.                     'iv_attack': member['pokemon_data'].get('individual_attack', 0),
  133.                     'trainer_level': member['trainer_public_profile']['level'],
  134.                 })
  135.                 assert member['pokemon_data'].get('stamina') == member['pokemon_data'].get('stamina_max')
  136.         else:
  137.             dist = vincenty((lat, lng), (gym['latitude'], gym['longitude']))
  138.             sys.stderr.write('Error getting details for gym: {}, {}km away\n'.format(gym['id'], dist))
  139.  
  140.     except Exception as e:
  141.         sys.stderr.write(str(e))
  142.         sys.stderr.write('Exception while getting details for gym: {}'.format(gym['id']))
  143.  
  144.     print(gymdata)
  145.  
  146. def get_work():
  147.     work = []
  148.     for [top, left, bottom, right] in scan_areas:
  149.         xdist = math.sqrt(3) * 0.900
  150.         ydist = 3 * (0.900 / 2)
  151.  
  152.         cury = top
  153.         counter = 0
  154.  
  155.         while cury > bottom:
  156.             if counter % 2:
  157.                 curx = left
  158.             else:
  159.                 destination = geopy.distance.distance(kilometers=xdist / 2).destination(geopy.Point(cury, left), 90)
  160.                 curx = destination.longitude
  161.  
  162.             destination = geopy.distance.distance(kilometers=ydist).destination(geopy.Point(cury, curx), 180)
  163.             work.append((destination.latitude, destination.longitude))
  164.             cury = destination.latitude
  165.             counter += 1
  166.  
  167.             while curx < right:
  168.                 destination = geopy.distance.distance(kilometers=xdist).destination(geopy.Point(cury, curx), 90)
  169.                 work.append((destination.latitude, destination.longitude))
  170.                 curx = destination.longitude
  171.  
  172.     return work
  173.  
  174. def login(auth_service, username, password):
  175.     for i in range(10):
  176.         try:
  177.             sys.stderr.write("{}: Login attempt {}/10".format(username, str(i + 1)))
  178.             api = pgoapi.PGoApi(provider=auth_service, username=username, password=password,
  179.                                 position_lat=0, position_lng=0, position_alt=0)
  180.             api.activate_signature(encryption_lib_path)
  181.             time.sleep(1)
  182.             api.get_player()
  183.             time.sleep(1)
  184.             return api
  185.         except Exception:
  186.             sys.stderr.write("{}: Login failed, will try again in a bit...".format(username))
  187.             time.sleep(5)
  188.     return None
  189.  
  190. if __name__ == "__main__":
  191.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement