je suis ptet en train de tout refaire mais chut

This commit is contained in:
piair 2024-01-17 17:22:26 +01:00
parent 7d81eb642e
commit d5ec96f1e8
8 changed files with 346205 additions and 176 deletions

36
V6.py
View File

@ -8,7 +8,6 @@ from modules.driver_tools import *
from modules.cards import *
import modules.globals as g
driver = g.driver
display = g.display
@ -83,7 +82,6 @@ def close_tab(tab, SwitchTo=0) -> None:
driver.switch_to.window(driver.window_handles[SwitchTo])
# play_quiz[N]([int : override]) make the quiz with N choice each time. They usually have between 4 and 10 questions.
# override is the number of question, by default, it's the number of question in this specific quiz. Can be useful in some case, where the program crashes before finishing the quiz
def play_quiz2(override=10) -> None:
@ -308,7 +306,8 @@ def promo():
if i > 3:
log_error("plus de 3 promo cards, probablement une pa skipable", driver)
try:
driver.find_element(By.CSS_SELECTOR, 'i[class="mee-icon pull-left icon mee-icon-Cancel ng-scope"]').click()
driver.find_element(By.CSS_SELECTOR,
'i[class="mee-icon pull-left icon mee-icon-Cancel ng-scope"]').click()
except Exception as e:
log_error(f"can't click to close : {e}")
return ()
@ -337,6 +336,7 @@ def promo():
# Find out which type of action to do
def try_play(nom="inconnu"):
rgpd_popup(driver)
def play(number):
if number == 8 or number == 9:
try:
@ -466,7 +466,7 @@ def login_part_2(ldriver, cookies = False):
if ('notice' in ldriver.current_url):
ldriver.find_element(By.ID, "id__0").click()
if ("proof" in ldriver.current_url):
ldriver.find_element(BY.ID, "iLooksGood")
ldriver.find_element(By.ID, "iLooksGood")
if cookies:
save_cookies(ldriver)
for id in ["iNext", "KmsiCheckboxField", "id__0", "iLooksGood", "idSIButton9", "iCancel"]:
@ -479,7 +479,6 @@ def login_part_2(ldriver, cookies = False):
wait_until_visible(By.CSS_SELECTOR, '[data-bi-id="sh-sharedshell-home"]', 20, ldriver)
# login() tries to login to your Microsoft account.
# it uses global variable g._mail and g._password to login
def login(ldriver):
@ -568,7 +567,8 @@ def log_points(account="unknown"):
driver.get("https://rewards.bing.com")
custom_sleep(1)
if "/proofs/" in driver.current_url:
webhookFailure.send(f"Is /proof Useful in logpoints?", username="Dev tests", avatar_url="https://cdn.discordapp.com/attachments/793934298977009677/1144560898879541268/image.png")
webhookFailure.send(f"Is /proof Useful in logpoints?", username="Dev tests",
avatar_url="https://cdn.discordapp.com/attachments/793934298977009677/1144560898879541268/image.png")
for id in ["KmsiCheckboxField", "iLooksGood", "idSIButton9", "iCancel"]:
try:
driver.find_element(By.ID, id).click()
@ -579,7 +579,9 @@ def log_points(account="unknown"):
point = search('availablePoints\":([\d]+)', driver.page_source)[1]
except Exception as e:
sleep(5)
log_error(f"Dev error, checking why it doesn't work (waited a bit, is this still white ?) {format_error(e)}", driver, True)
log_error(
f"Dev error, checking why it doesn't work (waited a bit, is this still white ?) {format_error(e)}",
driver, True)
driver.refresh()
sleep(5)
point = search('availablePoints\":([\d]+)', driver.page_source)[1]
@ -634,12 +636,14 @@ def fidelity():
custom_sleep(2)
card_elem = driver.find_element(By.CLASS_NAME, "spacer-48-bottom")
try:
button_text = search('<span class="pull-left margin-right-15">([^<^>]+)</span>',card_elem.get_attribute("innerHTML"))[1]
button_text = search('<span class="pull-left margin-right-15">([^<^>]+)</span>',
card_elem.get_attribute("innerHTML"))[1]
bouton_card = driver.find_element(By.XPATH, f'//span[text()="{button_text}"]')
bouton_card.click()
except Exception as e1:
try:
recover_elem = driver.find_element(By.XPATH,'/html/body/div[1]/div[2]/main/div[2]/div[2]/div[7]/div[3]/div[1]/a')
recover_elem = driver.find_element(By.XPATH,
'/html/body/div[1]/div[2]/main/div[2]/div[2]/div[7]/div[3]/div[1]/a')
recover_elem.click()
except Exception as e2:
log_error(f"fidélité - double erreur - e1 : {format_error(e1)} - e2 {format_error(e2)}")
@ -655,10 +659,12 @@ def fidelity():
printf("fidelity - done")
except Exception as e:
log_error(e)
if driver.current_url != "https://rewards.bing.com":
driver.get("https://rewards.bing.com")
try:
pause = driver.find_element(By.CSS_SELECTOR, f'[class="c-action-toggle c-glyph f-toggle glyph-pause"]') # mettre le truc en pause
pause = driver.find_element(By.CSS_SELECTOR,
f'[class="c-action-toggle c-glyph f-toggle glyph-pause"]') # mettre le truc en pause
pause.click()
except Exception as e:
printf(f"erreur lors du click de pause: probablement pas de cartes {e}")
@ -682,6 +688,7 @@ def fidelity():
cartes = driver.find_elements(By.CSS_SELECTOR, f'[ng-repeat="item in $ctrl.transcludedItems"]')
checked_list_all = driver.find_elements(By.CSS_SELECTOR, f'[ng-if="$ctrl.complete"]')
def mobile_alert_popup():
try:
alert = mobile_driver.switch_to.alert
@ -766,10 +773,10 @@ def dev():
pass
def CustomStart():
if not g.islinux:
raise NameError('You need to be on linux to do that, due to the utilisation of a module named enquieries, sorry.')
raise NameError(
'You need to be on linux to do that, due to the utilisation of a module named enquieries, sorry.')
global driver
system("clear") # clear from previous command to allow a clean choice
@ -823,6 +830,7 @@ def CustomStart():
printf(f"CustomStart {e}")
driver.quit()
def very_custom_start(json):
global driver
display = SmartDisplay(backend="xvnc", size=(1920, 1080), rfbport=2345, color_depth=24)
@ -897,6 +905,7 @@ def very_custom_start(json):
driver.close()
display.stop()
if g.very_custom:
dict_data = json.loads(g.very_custom.replace("'", "\""))
very_custom_start(dict_data)
@ -927,7 +936,8 @@ else :
else:
if g.update_version != "None":
if g.discord_enabled_error:
webhookFailure.send(f"Updated to {g.update_version}", username="UPDATE", avatar_url="https://cdn-icons-png.flaticon.com/512/1688/1688988.png")
webhookFailure.send(f"Updated to {g.update_version}", username="UPDATE",
avatar_url="https://cdn-icons-png.flaticon.com/512/1688/1688988.png")
for cred in g._cred:
if cred[0] != "":
g._mail = cred[0]

83
V7/V7.py Normal file
View File

@ -0,0 +1,83 @@
from playwright.sync_api import sync_playwright, expect, Page
from playwright_stealth import stealth_sync
from logging import *
from actions.checks import check_logged_in
from actions.quiz import play_quiz_2, play_quiz_4, play_quiz_8, play_poll, detect_quiz_type, play
from actions.login import login
from actions.websearch import pc_search
basicConfig(encoding='utf-8', level=DEBUG)
def daily_cards(page: Page):
for i in range(1, 4):
card = page.locator(f'#daily-sets > mee-card-group:nth-child(7) > div > mee-card:nth-child({i}) > div')
with page.expect_popup() as page1_info:
card.click()
page1 = page1_info.value
stealth_sync(page1)
page1.wait_for_load_state('load')
try:
selector = page1.get_by_role("button", name="Accepter")
expect(selector).to_be_visible(timeout=10_000)
selector.click()
except AssertionError as e:
pass # The RGPD button should not be there in the first place
play(page1)
page1.close()
page.reload()
info(f'Carte {i} : {not "mee-icon-AddMedium" in card.inner_html()}')
def more_cards(page: Page):
c = 1
while c < 15: # todo I don't really know why it stops without raising any errors, but I guess it's fine
card = page.locator(f"#more-activities > div > mee-card:nth-child({c})")
try:
"mee-icon-AddMedium" in card.inner_html()
except AssertionError as e:
break
if "mee-icon-AddMedium" in card.inner_html():
info(f"Playing more cards {c}.")
with page.expect_popup() as page1_info:
card.click()
page1 = page1_info.value
stealth_sync(page1)
page1.wait_for_load_state('load')
play(page1)
page1.close()
page.reload()
info(f'Carte {c} : {not "mee-icon-AddMedium" in card.inner_html()}')
c += 1
def all_cards(page: Page):
# input("1")
page.goto("https://rewards.bing.com")
page.wait_for_load_state('load')
daily_cards(page)
more_cards(page)
def routine(page: Page) -> None:
all_cards(page)
pc_search(page)
with sync_playwright() as p:
browser = p.firefox.launch_persistent_context("./data/", headless=False)
page = browser.new_page()
stealth_sync(page)
login(page, input("mail ? "), input("password ? "))
all_cards(page)
browser.close()
"""
TODO :
Fidelity management.
Daily search
custom start
vnc
mobile search
"""

10
V7/actions/checks.py Normal file
View File

@ -0,0 +1,10 @@
from playwright.sync_api import Playwright, sync_playwright, expect, Page
from playwright_stealth import stealth_sync
from logging import *
def check_logged_in(page: Page):
if "pas connecté à Microsoft Rewards" in page.content():
page.locator('css=[onclick="setsrchusr()"]').click()
page.wait_for_load_state('load')
info('Fixed logging in in card.')

30
V7/actions/login.py Normal file
View File

@ -0,0 +1,30 @@
from playwright.sync_api import Playwright, sync_playwright, expect, Page
from logging import *
def login(page: Page, mail: str, pwd: str) -> None:
page.goto("https://rewards.bing.com")
page.wait_for_load_state('load')
if page.url == "https://rewards.bing.com/":
info("Logged in via cookies")
return
else:
info("logging in")
page.get_by_placeholder("Email, phone, or Skype").click()
page.get_by_placeholder("Email, phone, or Skype").fill(mail)
page.get_by_placeholder("Email, phone, or Skype").press("Enter")
page.get_by_placeholder("Password").click()
page.get_by_placeholder("Password").fill(pwd)
page.get_by_placeholder("Password").press("Enter")
page.get_by_label("Don't show this again").check()
page.get_by_role("button", name="Yes").click()
page.wait_for_url("https://rewards.bing.com/")
page.wait_for_load_state('load')
page.goto("https://bing.com")
page.get_by_role("link", name="Sign in").click()
page.get_by_role("link", name="Accept").click()
page.wait_for_load_state('load')
page.wait_for_timeout(3000)
page.goto("https://rewards.bing.com")
page.wait_for_load_state('load')
info("Logged in via password.")

115
V7/actions/quiz.py Normal file
View File

@ -0,0 +1,115 @@
from random import choice, shuffle
from playwright.sync_api import Playwright, sync_playwright, expect, Page
from playwright_stealth import stealth_sync
from logging import *
from re import findall, search
from actions.checks import check_logged_in
def play(page: Page):
check_logged_in(page)
quiz_type = detect_quiz_type(page)
match quiz_type:
case 8 | 9:
info('Detected quiz_8.')
play_quiz_8(page)
case 5 | 4:
info('Detected quiz_4.')
play_quiz_4(page)
case 3 | 2:
info('Detected quiz_2.')
play_quiz_2(page)
case 1:
info('Detected poll.')
play_poll(page)
case 0:
info('Detected empty page.')
def detect_quiz_type(page: Page) -> int:
info("Detecting quiz type.")
if "bt_PollRadio" in page.content():
return 1
elif "rqQuestionState" in page.content():
# The quiz is already started
return page.content().count("rqAnswerOption") - 1
else:
try:
# RGPD
selector = page.locator("rqStartQuiz")
expect(selector).to_be_visible(timeout=10_000)
selector.click()
return page.content().count("rqAnswerOption") - 1
except AssertionError as e:
return 0
def play_quiz_8(page: Page):
info("Playing quiz 8.")
num_question = len(findall("<span id=\"rqQuestionState.\" class=\"emptyCircle\"></span>", page.content())) + 1
info(f"Looping on {num_question} questions.")
counter = 0
# rgpd_popup(driver)
for _ in range(num_question):
correct_answers = []
for i in range(1, 9):
element = page.locator(f'#rqAnswerOption{i - 1}')
# todo can probably be optimised using filter and has_text
if 'iscorrectoption="True"' in element.evaluate("el => el.outerHTML"):
correct_answers.append(f'rqAnswerOption{i - 1}')
shuffle(correct_answers)
for answer_id in correct_answers:
page.locator(answer_id).click()
page.wait_for_timeout(1000)
page.wait_for_timeout(3000) # todo check if there is a better method than hardcoded timout
def play_quiz_4(page: Page):
info("Playing quiz 4.")
num_question = len(findall("<span id=\"rqQuestionState.\" class=\"emptyCircle\"></span>", page.content())) + 1
info(f"Looping on {num_question} questions.")
for i in range(num_question):
txt = page.content()
answer_option = search('correctAnswer":"([^"]+)', txt)[1]
answer_option = answer_option.replace("\\u0027", "'") # replace Unicode weird symbols
page.locator(f'css=[data-option="{answer_option}"]').click()
info(f'Validated answer n°{i + 1}.')
page.wait_for_load_state('load')
debug(f'Next page loaded.')
info("Quiz 4 successful.")
def play_quiz_2(page: Page):
info("Playing quiz 2.")
for j in range(10): # todo de-hardcode the value
js_function = """
function get_correct_answer(){
function br(n) { for (var r, t = 0, i = 0; i < n.length; i++)t += n.charCodeAt(i); return r = parseInt(_G.IG.substr(_G.IG.length - 2), 16), t += r, t.toString() } // Ms check function
function namedRAValue() { //allow calls to getRAvalue
return _w.getRAValue()
};
if (br(document.getElementById("rqAnswerOption0").attributes["data-option"].value) == namedRAValue()){
return(0);
}
else {
return(1);
}
};
return(get_correct_answer())
"""
correct_answer_value = page.evaluate(js_function)
page.locator(f"#rqAnswerOption{correct_answer_value}").click()
page.wait_for_timeout(2000)
info("Quiz 2 successful.")
def play_poll(page: Page):
info("Playing poll.")
answer_elem = page.locator(f"#btoption{choice([0, 1])}")
answer_elem.click()
info("Poll successful.")

23
V7/actions/websearch.py Normal file
View File

@ -0,0 +1,23 @@
from random import choice
from playwright.sync_api import sync_playwright, expect, Page
from playwright_stealth import stealth_sync
h = open("../user_data/french", "r", encoding="utf-8")
lines = h.readlines()
if len(lines) < 3:
Liste_de_mot = list(lines[0].split(","))
else:
Liste_de_mot = [x.replace('\n', "") for x in lines]
h.close()
def pc_search(page: Page) -> None:
mot = choice(Liste_de_mot).replace(" ", "+")
page.goto(f"https://www.bing.com/search?q={mot}")
for _ in range(35): # todo de-hardcode this variable
word = choice(Liste_de_mot)
page.get_by_label("Enter your search here -").click()
page.get_by_label("Enter your search here -").fill(word)
page.get_by_label("Enter your search here -").press("Enter")

27
V7/logger.py Normal file
View File

@ -0,0 +1,27 @@
from playwright.sync_api import Page
from discord import Colour, Embed, File, RequestsWebhookAdapter, Webhook
class Logger:
def __init__(self, link):
self.wh = Webhook.from_url(link, adapter=RequestsWebhookAdapter())
def error(self, page: Page, error: str):
with open("page.html", "w") as f:
try:
f.write(page.content())
except Exception as e:
f.write(f"the driver has closed or crashed. Can't access page content\n{e}")
embed = Embed(
title="An Error has occurred",
description=str(error),
colour=Colour.red(),
)
try:
page.screenshot(path="screenshot.png")
except Exception as e:
with open("screenshot.png", "w") as f:
f.write(f"Can't take screenshot\n{e}")
file = File("screenshot.png")
embed.set_image(url="attachment://screenshot.png")
self.wh.send(embed=embed, username="error", file=file)

345731
user_data/french Normal file

File diff suppressed because it is too large Load Diff