PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/player_alert.py

https://gitlab.com/rgorham1/fantasy-player-alert
Python | 237 lines | 221 code | 15 blank | 1 comment | 22 complexity | 2072c4c8a41b00450f5272ff06d746ae MD5 | raw file
  1. from selenium import webdriver
  2. from time import sleep
  3. import pymongo
  4. from pymongo import MongoClient
  5. import requests
  6. import schedule
  7. import time
  8. import datetime
  9. class Player:
  10. def __init__(self):
  11. self.name = ''
  12. self.news = ''
  13. self.impact = ''
  14. self.source = ''
  15. self.date = ''
  16. def set_news(self):
  17. pass
  18. class FantasyTool:
  19. def __init__(self):
  20. self.draftkings = 'https://www.draftkings.com'
  21. self.fanduel = 'https://www.fanduel.com'
  22. self.rotoworld = 'http://www.rotoworld.com/playernews/nba/basketball-player-news'
  23. self.browser = None
  24. self.dk_players = {}
  25. self.fd_players = {}
  26. def start_browser(self):
  27. """Method that initiates the browser and implicit wait time"""
  28. self.browser = webdriver.Chrome()
  29. self.browser.implicitly_wait(25)
  30. def fd_login(self):
  31. try:
  32. self.browser.get(self.fanduel)
  33. sign_in = self.browser.find_element_by_css_selector('#homepage > header > div > section.logged-out-user > '
  34. 'div.login-menu-block > a')
  35. sign_in.click()
  36. user_name = self.browser.find_element_by_name('email')
  37. pw = self.browser.find_element_by_name('password')
  38. user_name.send_keys('rgorham1@iona.edu')
  39. pw.send_keys('julie8610')
  40. sign_in_button = self.browser.find_element_by_css_selector('#ccf1 > div > div > '
  41. 'div.login-card > div > input')
  42. sign_in_button.click()
  43. except Exception, e:
  44. print str(e)
  45. def get_fd_players(self):
  46. self.fd_login()
  47. rp_popup = self.browser.find_element_by_css_selector('body > div.games-body-wrap > '
  48. 'header > div > nav.secondary-nav > '
  49. 'div:nth-child(2) > div > button')
  50. rp_popup.click()
  51. lineups = self.browser.find_element_by_css_selector('body > div.games-body-wrap > header > div > nav.primary-nav > '
  52. 'ul > li:nth-child(2) > a > span')
  53. lineups.click()
  54. rosters = self.browser.find_elements_by_class_name('rosters')
  55. for line in rosters:
  56. roster = line.find_element_by_class_name('roster')
  57. pics = roster.find_elements_by_tag_name('img')
  58. for pic in pics:
  59. pic.click()
  60. name = self.browser.find_element_by_xpath('//*[@id="global-view"]/div/player-card/section/div[1]/'
  61. 'player-card-header/section/div[1]/div[2]/h2/div[1]/span')
  62. avg = self.browser.find_element_by_css_selector('#global-view > div > '
  63. 'player-card > section > div.player-card__inner > '
  64. 'player-card-header > section > '
  65. 'div.player-card-header__stats-container > '
  66. 'ul > li:nth-child(1) > dl > dd').text
  67. player_name = name.text
  68. today = datetime.date.today()
  69. self.fd_players[player_name] = [avg, 'FD', today]
  70. close = self.browser.find_element_by_css_selector('#global-view > div > player-card > '
  71. 'section > div.player-card__inner > button > i')
  72. close.click()
  73. sleep(1)
  74. def dk_login(self):
  75. try:
  76. self.browser.get(self.draftkings)
  77. sign_in = self.browser.find_element_by_css_selector('#template-body-wrapper > div.top-nav > a.sign-in-btn')
  78. sign_in.click()
  79. user_name = self.browser.find_element_by_name('Username')
  80. pw = self.browser.find_element_by_name('Password')
  81. user_name.send_keys('rgorham1@iona.edu')
  82. pw.send_keys('julie8610')
  83. sign_in_button = self.browser.find_element_by_css_selector('#signin-popup > div.login_section > '
  84. 'div.modal-footer > a.dk-btn.dk-btn-success')
  85. sign_in_button.click()
  86. except Exception, e:
  87. print str(e)
  88. def get_dk_players(self):
  89. self.dk_login()
  90. lineups_link = self.browser.find_element_by_xpath('/html/body/header/div[1]/div/nav/ul[1]/li[2]/a')
  91. lineups_link.click()
  92. lineups = self.browser.find_elements_by_class_name('upcoming')
  93. for team, lineup in enumerate(lineups):
  94. if "MMA" not in lineup.text:
  95. tables = lineup.find_elements_by_tag_name('table')
  96. for table in tables:
  97. rows = table.find_elements_by_tag_name('tr')
  98. for num, row in enumerate(rows[1:9]):
  99. link = row.find_element_by_tag_name('a')
  100. link.click()
  101. name = self.browser.find_element_by_css_selector('#player-info > div.player-info > h1').text
  102. full_name = str(name).split()
  103. full_name[0] = str(full_name[0]).capitalize()
  104. full_name[1] = str(full_name[1]).capitalize()
  105. name = ' '.join(full_name)
  106. sleep(.5)
  107. self.browser.execute_script("document.getElementById('fancybox-close').focus()")
  108. x = self.browser.find_element_by_xpath('//*[@id="fancybox-close"]')
  109. x.click()
  110. sleep(.5)
  111. row = str(row.text).split()
  112. avg = row[3]
  113. sleep(.5)
  114. self.dk_players[name] = [avg, 'DK', team]
  115. def get_news(self, players, pages=2, dfs_check=False):
  116. self.browser.get(self.rotoworld)
  117. page = 0
  118. dfs_news = {}
  119. player_dict = {}
  120. while page < pages:
  121. player_news = self.browser.find_element_by_css_selector('#cp1_pnlNews > div > div.RW_pn')
  122. sleep(15)
  123. news_container = player_news.find_elements_by_class_name('pb')
  124. # TODO: change keywords to regex expressions
  125. keywords = ['DFS', 'boost', 'usage', 'ruled', '(', ')']
  126. for news in news_container:
  127. report = news.find_element_by_class_name('report').text
  128. impact = news.find_element_by_class_name('impact').text
  129. source = news.find_element_by_class_name('source').text
  130. date = news.find_element_by_class_name('date').text
  131. if players:
  132. for player in players:
  133. if player in news.text:
  134. print 'Player affected is %s' % player
  135. print 'here is the report: %s' % report
  136. print 'here is the impact: %s' % impact.encode("utf-8")
  137. print 'here is the source: %s' % source
  138. print 'here is the date: %s' % date
  139. player_dict[player] = {'Report': report, 'Analysis': impact, 'Source': source, 'Time': date}
  140. elif dfs_check:
  141. for keyword in keywords:
  142. if keyword in impact:
  143. impact = impact.encode("utf-8")
  144. dfs_news[keyword.upper()] = {'Report': report, 'Analysis': impact}
  145. next_page = self.browser.find_element_by_css_selector('#cp1_ctl00_btnNavigate1Bot')
  146. next_page.click()
  147. page += 1
  148. sleep(2)
  149. print 'checked page %s' % page
  150. if dfs_news:
  151. return dfs_news
  152. else:
  153. return player_dict
  154. @staticmethod
  155. def email(message):
  156. key = 'key-01577a41c5abaf547dfcdf0bc021c1f7'
  157. mailgun_domain = 'sandboxbf71083cbdc44a4c9ebcfd82601ba1d2.mailgun.org'
  158. url = 'https://api.mailgun.net/v3/{}/messages'.format(mailgun_domain)
  159. auth = ('api', key)
  160. receiver = 'rgorham1@iona.edu'
  161. data = {
  162. 'from': 'Mailgun User <mailgun@{}>'.format(mailgun_domain),
  163. 'to': receiver,
  164. 'subject': 'DFS news',
  165. 'text': str(message)
  166. }
  167. response = requests.post(url, auth=auth, data=data)
  168. response.raise_for_status()
  169. print 'email sent'
  170. def get_players(self, site):
  171. if site == 'fd':
  172. self.get_fd_players()
  173. players = self.fd_players
  174. else:
  175. self.get_dk_players()
  176. players = self.dk_players
  177. print '%s players are: ' % site
  178. for player in players:
  179. print player
  180. def job(self, pages, site, check_players=True, analysis=False):
  181. fd_players = ''
  182. if check_players:
  183. self.get_players(site)
  184. insight = self.get_news(fd_players, pages, analysis)
  185. # email(insight)
  186. # TODO: look into remote db mLab or heroku
  187. def save(self):
  188. try:
  189. client = MongoClient()
  190. print "Connected to db"
  191. except pymongo.errors.ConnectionFailure, e:
  192. print 'Connection failed: %s' % e
  193. db = client.players
  194. players = db.players
  195. for person, v in self.dk_players.iteritems():
  196. player = {'name': person, 'avg': float(v[0]), 'site': v[1], 'team': str(v[2])}
  197. players.insert(player)
  198. print 'Insertion complete'
  199. ft = FantasyTool()
  200. ft.start_browser()
  201. ft.job(5, 'fd', False, True)
  202. # TODO: check out fantasysp.com and nba.com stats
  203. '''
  204. def scheduler(task):
  205. schedule.every(9).minutes.do(task)
  206. while True:
  207. schedule.run_pending()
  208. time.sleep(1)
  209. print 'job done'
  210. # job(7)
  211. # scheduler(job)
  212. '''