Skip to content

Commit

Permalink
第2次提交
Browse files Browse the repository at this point in the history
  • Loading branch information
Yudaotor committed Mar 25, 2023
1 parent 24eeef0 commit bd73ac0
Show file tree
Hide file tree
Showing 8 changed files with 156 additions and 113 deletions.
5 changes: 3 additions & 2 deletions EsportsHelper/Config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import traceback
from pathlib import Path
from yaml.parser import ParserError
from rich import print
Expand Down Expand Up @@ -35,8 +36,8 @@ def __init__(self, log, configPath: str) -> None:
print("[red]配置文件格式错误")
raise ex
except Exception as ex:
log.error(ex)
print(ex)
traceback.print_exc()
self.log.error(traceback.format_exc())
raise ex

def __findConfig(self, configPath):
Expand Down
74 changes: 43 additions & 31 deletions EsportsHelper/LoginHandler.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,56 @@
import time
import traceback

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from rich import print


class LoginHandler:
def __init__(self, log, driver) -> None:
self.log = log
self.driver = driver

def automaticLogIn(self, username, password):
self.driver.get("https://lolesports.com/schedule")
time.sleep(2)
el = self.driver.find_element(by=By.CSS_SELECTOR, value="a[data-riotbar-link-id=login]")
self.driver.execute_script("arguments[0].click();", el)
self.log.info("登录中...")
print("[yellow]登录中...")
wait = WebDriverWait(self.driver, 20)
usernameInput = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "input[name=username]")))
usernameInput.send_keys(username)
passwordInput = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "input[name=password]")))
passwordInput.send_keys(password)
submitButton = wait.until(ec.element_to_be_clickable((By.CSS_SELECTOR, "button[type=submit]")))
self.driver.execute_script("arguments[0].click();", submitButton)
self.log.debug("账密 提交成功")
print("[green]账密 提交成功")
time.sleep(5)
if len(self.driver.find_elements(by=By.CSS_SELECTOR, value="div.text__web-code")) > 0:
self.insertTwoFactorCode()
wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "div.riotbar-summoner-name")))
try:
self.driver.get("https://lolesports.com/schedule")
time.sleep(2)
loginButton = self.driver.find_element(by=By.CSS_SELECTOR, value="a[data-riotbar-link-id=login]")
self.driver.execute_script("arguments[0].click();", loginButton)
self.log.info("登录中...")
print("[yellow]登录中...")
time.sleep(3)
wait = WebDriverWait(self.driver, 15)
usernameInput = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "input[name=username]")))
usernameInput.send_keys(username)
passwordInput = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "input[name=password]")))
passwordInput.send_keys(password)
submitButton = wait.until(ec.element_to_be_clickable((By.CSS_SELECTOR, "button[type=submit]")))
self.driver.execute_script("arguments[0].click();", submitButton)
self.log.debug("账密 提交成功")
print("[green]账密 提交成功")
time.sleep(5)
if len(self.driver.find_elements(by=By.CSS_SELECTOR, value="div.text__web-code")) > 0:
self.insertCode()
wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "div.riotbar-summoner-name")))
except Exception as e:
traceback.print_exc()
self.log.error(traceback.format_exc())

def insertTwoFactorCode(self):
wait = WebDriverWait(self.driver, 20)
authText = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "h5.grid-panel__subtitle")))
self.log.info(f'请输入二级验证代码 ({authText.text})')
print(f'[yellow]请输入二级验证代码 ({authText.text}')
code = input('二级验证代码: ')
codeInput = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "div.codefield__code--empty > div > input")))
codeInput.send_keys(code)
submitButton = wait.until(ec.element_to_be_clickable((By.CSS_SELECTOR, "button[type=submit]")))
self.driver.execute_script("arguments[0].click();", submitButton)
self.log.debug("二级验证代码 提交成功")
print("[green]二级验证代码 提交成功")
def insertCode(self):
try:
wait = WebDriverWait(self.driver, 20)
authText = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "h5.grid-panel__subtitle")))
self.log.info(f'请输入二级验证代码 ({authText.text})')
print(f'[yellow]请输入二级验证代码 ({authText.text}')
code = input('二级验证代码: ')
codeInput = wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "div.codefield__code--empty > div > input")))
codeInput.send_keys(code)
submitButton = wait.until(ec.element_to_be_clickable((By.CSS_SELECTOR, "button[type=submit]")))
self.driver.execute_script("arguments[0].click();", submitButton)
self.log.debug("二级验证代码 提交成功")
print("[green]二级验证代码 提交成功")
except Exception as e:
traceback.print_exc()
self.log.error(traceback.format_exc())
73 changes: 44 additions & 29 deletions EsportsHelper/Match.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,38 +39,44 @@ def __init__(self, log, driver, config) -> None:
self.driver = driver
self.config = config
self.rewards = Rewards(log=log, driver=driver, config=config)
self.twitch = Twitch(driver=driver)
self.twitch = Twitch(driver=driver, log=log)
self.youtube = Youtube(driver=driver, log=log)
self.currentWindows = {}
self.originalWindow = self.driver.current_window_handle
self.youtube = Youtube(driver=driver)
self.mainWindow = self.driver.current_window_handle

def watchForMatches(self, delay):
def watchMatches(self, delay):
self.currentWindows = {}
self.originalWindow = self.driver.current_window_handle
self.mainWindow = self.driver.current_window_handle
while True:
try:
self.driver.switch_to.window(self.originalWindow)
self.driver.switch_to.window(self.mainWindow)
time.sleep(3)
# raise Exception("测试")
self.driver.get("https://lolesports.com/schedule")
time.sleep(5)
liveMatches = self.getLiveMatches()
self.log.info(f"现在有 {len(liveMatches)} 场比赛正在直播中")
print(f"[green]现在有 {len(liveMatches)} 场比赛正在直播中[/green]")
self.closeFinishedMatches(liveMatches=liveMatches)
liveMatches = self.getMatches()
if len(liveMatches) == 0:
self.log.info("没有赛区正在直播")
print(f"[green]没有赛区正在直播[/green]")
else:
self.log.info(f"现在有 {len(liveMatches)} 个赛区正在直播中")
print(f"[green]现在有 {len(liveMatches)} 个赛区正在直播中[/green]")
self.closeTabs(liveMatches=liveMatches)
self.openNewMatches(liveMatches=liveMatches, disWatchMatches=self.config.disWatchMatches)
time.sleep(3)
self.driver.switch_to.window(self.originalWindow)
self.driver.switch_to.window(self.mainWindow)
self.log.info(f"下一次检查在: {datetime.now() + timedelta(seconds=delay)}")
self.log.debug("============================================")
print(f"[green]下一次检查在: {datetime.now() + timedelta(seconds=delay)}[/green]")
print(f"[green]下一次检查在: {(datetime.now() + timedelta(seconds=delay)).strftime('%m月%d日%H时%M分%S秒')}[/green]")
print(f"[green]============================================[/green]")
time.sleep(delay)
except Exception as e:
self.log.error("发生错误")
print(f"[red]发生错误[/red]")
traceback.print_exc()
self.log.error(traceback.format_exc())

def getLiveMatches(self):
def getMatches(self):
try:
matches = []
elements = self.driver.find_elements(by=By.CSS_SELECTOR, value=".EventMatch .event.live")
Expand All @@ -81,24 +87,29 @@ def getLiveMatches(self):
self.log.error("获取比赛列表失败")
print(f"[red]获取比赛列表失败[/red]")
traceback.print_exc()
self.log.error(traceback.format_exc())
return []

def closeFinishedMatches(self, liveMatches):
toRemove = []
for k in self.currentWindows.keys():
self.driver.switch_to.window(self.currentWindows[k])
if k not in liveMatches:
self.log.info(f"{k} 比赛结束")
print(f"[green]{k} 比赛结束[/green]")
self.driver.close()
toRemove.append(k)
self.driver.switch_to.window(self.originalWindow)
time.sleep(5)
else:
self.rewards.checkRewards(k)
for k in toRemove:
self.currentWindows.pop(k, None)
self.driver.switch_to.window(self.originalWindow)
def closeTabs(self, liveMatches):
try:
removeList = []
for k in self.currentWindows.keys():
self.driver.switch_to.window(self.currentWindows[k])
if k not in liveMatches:
self.log.info(f"{k} 比赛结束")
print(f"[green]{k} 比赛结束[/green]")
self.driver.close()
removeList.append(k)
self.driver.switch_to.window(self.mainWindow)
time.sleep(5)
else:
self.rewards.checkRewards(k)
for k in removeList:
self.currentWindows.pop(k, None)
self.driver.switch_to.window(self.mainWindow)
except Exception as e:
traceback.print_exc()
self.log.error(traceback.format_exc())

def openNewMatches(self, liveMatches, disWatchMatches):
newLiveMatches = set(liveMatches) - set(self.currentWindows.keys())
Expand Down Expand Up @@ -131,6 +142,8 @@ def openNewMatches(self, liveMatches, disWatchMatches):
except TimeoutException:
self.log.critical("无法设置 Twitch 清晰度. 这场比赛是在 Twitch 上吗?")
print("[red]无法设置 Twitch 清晰度. 这场比赛是在 Twitch 上吗?")
traceback.print_exc()
self.log.error(traceback.format_exc())
else:
url = match
self.driver.get(url)
Expand All @@ -142,4 +155,6 @@ def openNewMatches(self, liveMatches, disWatchMatches):
except TimeoutException:
self.log.critical(f"无法设置 Youtube 清晰度. 这场比赛是在 Youtube 上吗?")
print("[red]无法设置 Youtube 清晰度. 这场比赛是在 Youtube 上吗?")
traceback.print_exc()
self.log.error(traceback.format_exc())
time.sleep(5)
4 changes: 3 additions & 1 deletion EsportsHelper/Twitch.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@


class Twitch:
def __init__(self, driver) -> None:
def __init__(self, driver, log) -> None:
self.driver = driver
self.log = log

def setTwitchQuality(self):
try:
Expand All @@ -29,3 +30,4 @@ def setTwitchQuality(self):
self.driver.switch_to.default_content()
except Exception as e:
traceback.print_exc()
self.log.error(traceback.format_exc())
3 changes: 3 additions & 0 deletions EsportsHelper/VersionManager.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import traceback
import requests as req
from rich import print


class VersionManager:

@staticmethod
Expand All @@ -14,6 +16,7 @@ def getLatestTag():
return 0.0
except Exception as e:
print("[red]从github获取最新版信息失败!")
traceback.print_exc()
return 0.0

@staticmethod
Expand Down
3 changes: 2 additions & 1 deletion EsportsHelper/Webdriver.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import undetected_chromedriver as uc
from rich import print


class Webdriver:
def __init__(self, headless) -> None:
self.headless = headless

def createWebdriver(self):
options = self.addWebdriverOptions(uc.ChromeOptions())
print("[green]正在创建浏览器...")
print("[green]正在准备中...")
return uc.Chrome(options=options)

def addWebdriverOptions(self, options):
Expand Down
5 changes: 4 additions & 1 deletion EsportsHelper/Youtube.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By


class Youtube:
def __init__(self, driver) -> None:
def __init__(self, driver, log) -> None:
self.driver = driver
self.log = log

def setYoutubeQuality(self):
try:
Expand All @@ -29,3 +31,4 @@ def setYoutubeQuality(self):
self.driver.switch_to.default_content()
except Exception as e:
traceback.print_exc()
self.log.error(traceback.format_exc())
Loading

0 comments on commit bd73ac0

Please sign in to comment.