Advertisement
Readdeo

Pokeminer0.2 db.py V0.3

Jul 27th, 2016
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.88 KB | None | 0 0
  1. import time
  2. import csv
  3. import os
  4. import json
  5. import time
  6. from datetime import datetime
  7. from datetime import timedelta
  8. from sqlalchemy.orm import sessionmaker
  9. from sqlalchemy import create_engine
  10. from sqlalchemy.ext.declarative import declarative_base
  11. from sqlalchemy import Column, Integer, String
  12. from sqlalchemy.sql import not_
  13. from pushbullet import Pushbullet
  14.  
  15. try:
  16. import config
  17. DB_ENGINE = config.DB_ENGINE
  18. except ImportError, AttributeError:
  19. DB_ENGINE = 'sqlite:///db.sqlite'
  20.  
  21. def get_engine():
  22. return create_engine(DB_ENGINE)
  23.  
  24. Base = declarative_base()
  25.  
  26.  
  27. class Sighting(Base):
  28. __tablename__ = 'sightings'
  29.  
  30. id = Column(Integer, primary_key=True)
  31. pokemon_id = Column(Integer)
  32. spawn_id = Column(String(32))
  33. expire_timestamp = Column(Integer)
  34. normalized_timestamp = Column(Integer)
  35. lat = Column(String(16))
  36. lon = Column(String(16))
  37.  
  38.  
  39. Session = sessionmaker(bind=get_engine())
  40.  
  41. def pkmn_time_text(time):
  42. s = (time - datetime.utcnow()).total_seconds()
  43. (m, s) = divmod(s, 60)
  44. (h, m) = divmod(m, 60)
  45. d = timedelta(hours = h, minutes = m, seconds = s)
  46. disappear_time = datetime.now() + d
  47. return "Available until %s (%dm %ds)." % (disappear_time.strftime("%H:%M:%S"),m,s)
  48.  
  49.  
  50. def normalize_timestamp(timestamp):
  51. return int(float(timestamp) / 120.0) * 120
  52.  
  53. def get_pokemon_name(pokemon_id):
  54. if not hasattr(get_pokemon_name, 'names'):
  55. file_path = os.path.join(os.getcwd()+'/pokemon.json')
  56.  
  57. with open(file_path, 'r') as f:
  58. get_pokemon_name.names = json.loads(f.read())
  59.  
  60. return get_pokemon_name.names[str(pokemon_id)]
  61.  
  62. def gmaps_link(lat, lng):
  63. latLon = '{},{}'.format(repr(lat), repr(lng))
  64. return 'http://maps.google.com/maps?q={}'.format(latLon)
  65.  
  66.  
  67. with open('locales/pokemon.en.json') as f:
  68. pokemon_names = json.load(f)
  69.  
  70.  
  71. def add_sighting(session, spawn_id, pokemon):
  72. obj = Sighting(
  73. pokemon_id=pokemon['id'],
  74. spawn_id=spawn_id,
  75. expire_timestamp=pokemon['disappear_time'],
  76. normalized_timestamp=normalize_timestamp(pokemon['disappear_time']),
  77. lat=pokemon['lat'],
  78. lon=pokemon['lng'],
  79. )
  80. # Check if there isn't the same entry already
  81. existing = session.query(Sighting) \
  82. .filter(Sighting.pokemon_id == obj.pokemon_id) \
  83. .filter(Sighting.spawn_id == obj.spawn_id) \
  84. .filter(Sighting.expire_timestamp > obj.expire_timestamp - 10) \
  85. .filter(Sighting.expire_timestamp < obj.expire_timestamp + 10) \
  86. .filter(Sighting.lat == obj.lat) \
  87. .filter(Sighting.lon == obj.lon) \
  88. .first()
  89. if existing:
  90. return
  91. session.add(obj)
  92.  
  93. #write to CSV
  94. dt = pokemon['disappear_time']+7200 # +7200 needed to match my timezone
  95. if dt > time.time()+7200: # +7200 needed to match my timezone
  96. negativetime = ' '
  97. if pokemon['disappear_time'] < time.time():
  98. negativetime = 'Negative time bug, dunno exp time'
  99. dt = time.time()
  100. f = open(os.getcwd()+'\spawn_locationPminer.csv', "a")
  101. out = csv.writer(f, delimiter=",")
  102. out.writerow([str(pokemon['id']),str(pokemon['lat']),str(pokemon['lng']),str(dt)])
  103. f.close()
  104.  
  105. # PUSHBULLET part
  106.  
  107. # 1,7,10,11,13,14,15,16,17,18,19,20,21,22,29,30,32,35,39,41,42,43,44,46,47,48,49,50,51,52,60,69,81,82,90,92,93,96,98,99,100,109,113,114,116,118,120,124,129,133
  108. mydict = {'Bulbasaur':1,'Ivysaur':2,'Venusaur':3,'Charmander':4,'Charmeleon':5,'Charizard':6,
  109. 'Squirtle':7,'Wartortle':8,'Blastoise':9,'Caterpie':10,'Metapod':11,'Butterfree':12,
  110. 'Weedle':13,'Kakuna':14,'Beedrill':15,'Pidgey':16,'Pidgeotto':17,'Pidgeot':18,'Rattata':19,
  111. 'Raticate':20,'Spearow':21,'Fearow':22,'Ekans':23,'Arbok':24,'Pikachu':25,'Raichu':26,
  112. 'Sandshrew':27,'Sandlash':28,'Nidoran M':29,'Nidorina':30,'Nidoqueen':31,'Nidoran F':32,
  113. 'Nidorino':33,'Nidoking':34,'Clefairy':35,'Clefable':36,'Vulpix':37,'Ninetales':38,
  114. 'Jigglypuff':39,'Wigglypuff':40,'Zubat':41,'Golbat':42,'Oddish':43,'Gloom':44,'Vileplume':45,
  115. 'Paras':46,'Parasect':47,'Venomat':48,'Venomoth':49,'Diglett':50,'Dugtrio':51,'Meowth':52,
  116. 'Persian':53,'Psyduck':54,'Golduck':55,'Mankey':56,'Primeape':57,'Growlithe':58,'Arcanine':59,
  117. 'Poliwag':60,'Poliwhirl':61,'Poliwrath':62,'Abra':63,'Kadabra':64,'Alakazam':65,'Machop':66,
  118. 'Machoke':67,'Machamp':68,'Bellsprout':69,'Weepinbell':70,'Victreebell':71,'Tentacool':72,'Tentacruel':73,
  119. 'Geodude':74,'Graveler':75,'Golem':76,'Ponyta':77,'Rapidash':78,'Slowpoke':79,'Slowbro':80,'Magnemite':81,
  120. 'Magneton':82,'FarfetchD':83,'Doduo':84,'Dodrio':85,'Seel':86,'Dewgong':87,'Grimer':88,'Muk':89,'Shellder':90,
  121. 'Cloyster':91,'GAstly':92,'Haunter':93,'Gengar':94,'Onix':95,'Drowzee':96,'Hypno':97,'Krabby':98,'Kingler':99,
  122. 'Voltorb':100,'Electrode':101,'Exeggcute':102,'Exeggutor':103,'Cubone':104,'Marowak':105,'Hitmonlee':106,
  123. 'Hitmonchan':107,'Lickitung':108,'Koffing':109,'Weezing':110,'Rhyhorn':111,'Rhydon':112,'Chansey':113,
  124. 'Tangela':114,'Kangaskhan':115,'Horsea':116,'Seadra':117,'Goldeen':118,'Seaking':119,'Staryu':120,
  125. 'Starmie':121,'MrMime':122,'Scyther':123,'Jynx':124,'Electabuzz':125,'Magmar':126,'Pinsir':127,'Tauros':128,
  126. 'Magikarp':129,'Gyarados':130,'Lapras':131,'Ditto':132,'Eevee':133,'Vaporeon':134,'Jolteon':135,'Flareon':136,
  127. 'Porygon':137,'Omanyte':138,'Omastar':139,'Kabuto':140,'Kabutops':141,'Aerodactyl':142,'Snorlax':143,'Articuno':144,
  128. 'Zapdos':145,'Moltres':146,'Dratini':147,'Dragonair':148,'Dragonite':149,'Mewtwo':150,'Mew':151}
  129. pokename = mydict.keys()[mydict.values().index(pokemon['id'])]
  130.  
  131. expsec = int(pokemon['disappear_time'] - time.time())
  132. m, s = divmod(expsec, 60)
  133. expat = datetime.fromtimestamp(pokemon['disappear_time']).strftime('%H:%M')
  134.  
  135. google_maps_link = gmaps_link(pokemon["lat"], pokemon["lng"])
  136.  
  137. try:
  138. pb = Pushbullet("PUSHBULLET KEY HERE")
  139. except:
  140. pass
  141.  
  142. #Here you can filter what to show:
  143. goodlist = [4,5,6,9,23,24,25,26,36,38,53,59,74,75,76,77,78,83,87,88,89,91,94,101,102,103,104,105,
  144. 110,111,112,115,126,127,128,130,131,134,135,136,137,138,139,140,141,142,143,144,145,
  145. 146,148,149,150,151]
  146.  
  147. if pokemon['id'] in goodlist:
  148. try:
  149. print 'PUSHBULLET'
  150. push = pb.push_link('A wild ' + pokename.title() + ' has appeared!',google_maps_link, 'Expires in: '+str(m)+'m'+str(s)+'s ('+str(expat)+') '+negativetime)
  151. except:
  152. print 'INVALIDKEY'
  153. pass
  154. else:
  155. print 'INVALIDKEY'
  156. pass
  157.  
  158.  
  159. # Here you can filter what not to show:
  160. # thrashlist = [1,7,10,11,13,14,15,16,17,18,19,20,21,22,29,30,32,35,39,41,42,43,44,46,47,48,49,
  161. # 50,51,52,60,69,81,82,90,92,93,96,98,99,100,109,113,114,116,118,120,124,129,133]
  162. # if pokemon['id'] in thrashlist:
  163. # pass
  164. # else:
  165. # try:
  166. # print 'asd'
  167. # push = pb.push_link('A wild ' + pokename.title() + ' has appeared!',google_maps_link, 'Expires in: '+str(m)+'m'+str(s)+'s ('+str(expat)+') '+negativetime)
  168. # except:
  169. # pass
  170.  
  171. def get_sightings(session):
  172. query = session.query(Sighting) \
  173. .filter(Sighting.expire_timestamp > time.time())
  174. trash_list = getattr(config, 'TRASH_IDS')
  175. if trash_list:
  176. query = query.filter(not_(Sighting.pokemon_id.in_(config.TRASH_IDS)))
  177. return query.all()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement