forked from babasa/coba
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ms_rewards_farmer.py
2237 lines (2037 loc) · 98.8 KB
/
ms_rewards_farmer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import json
import os
import platform
import random
import subprocess
import sys
import time
import urllib.parse
from argparse import ArgumentParser
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Union, List
import ipapi
import requests
from func_timeout import FunctionTimedOut, func_set_timeout
from notifiers import get_notifier
from random_word import RandomWords
from selenium import webdriver
from selenium.common.exceptions import (ElementNotInteractableException,
NoAlertPresentException,
NoSuchElementException,
SessionNotCreatedException,
TimeoutException,
UnexpectedAlertPresentException,
JavascriptException,
ElementNotVisibleException)
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
import tkinter as tk
from tkinter import messagebox, ttk
from math import ceil
# Define user-agents
PC_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.46'
MOBILE_USER_AGENT = 'Mozilla/5.0 (Linux; Android 12; SM-N9750) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Mobile Safari/537.36 EdgA/110.0.1587.41'
POINTS_COUNTER = 0
# Global variables
FINISHED_ACCOUNTS = [] # added accounts when finished or those have same date as today date in LOGS at beginning.
ERROR = True # A flag for when error occurred.
MOBILE = True # A flag for when the account has mobile bing search, it is useful for accounts level 1 to pass mobile.
CURRENT_ACCOUNT = None # save current account into this variable when farming.
LOGS = {} # Dictionary of accounts to write in 'logs_accounts.txt'.
FAST = False # When this variable set True then all possible delays reduced.
SUPER_FAST = False # fast but super
BASE_URL = "https://rewards.bing.com"
# Auto Redeem - Define max amount of auto-redeems per run and counter
MAX_REDEEMS = 1
auto_redeem_counter = 0
def isProxyWorking(proxy: str) -> bool:
"""Check if proxy is working or not"""
try:
requests.get("https://www.google.com/", proxies={"https": proxy}, timeout=5)
return True
except:
return False
def browserSetup(isMobile: bool, user_agent: str = PC_USER_AGENT, proxy: str = None) -> WebDriver:
"""Create Chrome browser"""
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.edge.options import Options as EdgeOptions
if ARGS.edge:
options = EdgeOptions()
else:
options = ChromeOptions()
if ARGS.session or ARGS.account_browser:
if not isMobile:
options.add_argument(f'--user-data-dir={Path(__file__).parent}/Profiles/{CURRENT_ACCOUNT}/PC')
else:
options.add_argument(f'--user-data-dir={Path(__file__).parent}/Profiles/{CURRENT_ACCOUNT}/Mobile')
options.add_argument("user-agent=" + user_agent)
options.add_argument('lang=' + LANG.split("-")[0])
options.add_argument('--disable-blink-features=AutomationControlled')
prefs = {"profile.default_content_setting_values.geolocation": 2,
"credentials_enable_service": False,
"profile.password_manager_enabled": False,
"webrtc.ip_handling_policy": "disable_non_proxied_udp",
"webrtc.multiple_routes_enabled": False,
"webrtc.nonproxied_udp_enabled": False}
if ARGS.account_browser:
prefs["detach"] = True
if proxy is not None:
if isProxyWorking(proxy):
options.add_argument(f'--proxy-server={proxy}')
prBlue(f"Using proxy: {proxy}")
else:
prYellow(f"[PROXY] Your entered proxy is not working, continuing without proxy.")
options.add_experimental_option("prefs", prefs)
options.add_experimental_option("useAutomationExtension", False)
options.add_experimental_option("excludeSwitches", ["enable-automation"])
if ARGS.headless and ARGS.account_browser is None:
options.add_argument("--headless=new")
options.add_argument('log-level=3')
options.add_argument("--start-maximized")
if platform.system() == 'Linux':
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
if ARGS.edge:
browser = webdriver.Edge(options=options)
else:
browser = webdriver.Chrome(options=options)
return browser
# Define login function
def login(browser: WebDriver, email: str, pwd: str, isMobile: bool = False):
"""Close welcome tab for new sessions"""
if ARGS.session:
time.sleep(2)
if len(browser.window_handles) > 1:
current_window = browser.current_window_handle
for handler in browser.window_handles:
if handler != current_window:
browser.switch_to.window(handler)
time.sleep(0.5)
browser.close()
browser.switch_to.window(current_window)
# Access to bing.com
browser.get('https://login.live.com/')
# Check if account is already logged in
if ARGS.session:
if browser.title == "We're updating our terms" or isElementExists(browser, By.ID, 'iAccrualForm'):
time.sleep(2)
browser.find_element(By.ID, 'iNext').click()
time.sleep(5)
if browser.title == 'Is your security info still accurate?' or isElementExists(browser, By.ID, 'iLooksGood'):
time.sleep(2)
browser.find_element(By.ID, 'iLooksGood').click()
time.sleep(5)
# Click No thanks on break free from password question
if isElementExists(browser, By.ID, "setupAppDesc"):
time.sleep(2)
browser.find_element(By.ID, "iCancel").click()
time.sleep(5)
if browser.title == 'Microsoft account | Home' or isElementExists(browser, By.ID, 'navs_container'):
prGreen('[LOGIN] Account already logged in !')
RewardsLogin(browser)
print('[LOGIN]', 'Ensuring login on Bing...')
checkBingLogin(browser, isMobile)
return
elif browser.title == 'Your account has been temporarily suspended':
LOGS[CURRENT_ACCOUNT]['Last check'] = 'Your account has been locked !'
FINISHED_ACCOUNTS.append(CURRENT_ACCOUNT)
updateLogs()
cleanLogs()
raise Exception(prRed('[ERROR] Your account has been locked !'))
elif isElementExists(browser, By.ID, 'mectrl_headerPicture') or 'Sign In or Create' in browser.title:
if isElementExists(browser, By.ID, 'i0118'):
browser.find_element(By.ID, "i0118").send_keys(pwd)
time.sleep(2)
browser.find_element(By.ID, 'idSIButton9').click()
time.sleep(5)
prGreen('[LOGIN] Account logged in again !')
RewardsLogin(browser)
print('[LOGIN]', 'Ensuring login on Bing...')
checkBingLogin(browser, isMobile)
return
# Wait complete loading
waitUntilVisible(browser, By.ID, 'loginHeader', 10)
# Enter email
print('[LOGIN]', 'Writing email...')
browser.find_element(By.NAME, "loginfmt").send_keys(email)
# Click next
browser.find_element(By.ID, 'idSIButton9').click()
# Wait 2 seconds
time.sleep(5 if not FAST and not SUPER_FAST else 1.5)
# Wait complete loading
waitUntilVisible(browser, By.ID, 'loginHeader', 10)
# Enter password
browser.find_element(By.ID, "i0118").send_keys(pwd)
# browser.execute_script("document.getElementById('i0118').value = '" + pwd + "';")
print('[LOGIN]', 'Writing password...')
# Click next
browser.find_element(By.ID, 'idSIButton9').click()
# Wait 5 seconds
time.sleep(5)
try:
if browser.title == "":
time.sleep(10 if not FAST and not SUPER_FAST else 3)
wait = WebDriverWait(browser, 10)
wait.until(ec.presence_of_element_located((By.TAG_NAME, "body")))
wait.until(ec.presence_of_all_elements_located)
wait.until(ec.title_contains(""))
wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "html[lang]")))
wait.until(lambda driver: driver.execute_script("return document.readyState") == "complete")
if browser.title == "We're updating our terms" or isElementExists(browser, By.ID, 'iAccrualForm'):
time.sleep(2)
browser.find_element(By.ID, 'iNext').click()
time.sleep(5)
if browser.title == 'Is your security info still accurate?' or isElementExists(browser, By.ID, 'iLooksGood'):
time.sleep(2)
browser.find_element(By.ID, 'iLooksGood').click()
time.sleep(5)
# Click No thanks on break free from password question
if isElementExists(browser, By.ID, "setupAppDesc"):
time.sleep(2)
browser.find_element(By.ID, "iCancel").click()
time.sleep(5)
if ARGS.session:
# Click Yes to stay signed in.
browser.find_element(By.ID, 'idSIButton9').click()
else:
# Click No.
browser.find_element(By.ID, 'idBtn_Back').click()
except NoSuchElementException:
# Check for if account has been locked.
if browser.title == "Your account has been temporarily suspended" or isElementExists(browser, By.CLASS_NAME,
"serviceAbusePageContainer PageContainer"):
LOGS[CURRENT_ACCOUNT]['Last check'] = 'Your account has been locked !'
FINISHED_ACCOUNTS.append(CURRENT_ACCOUNT)
updateLogs()
cleanLogs()
raise Exception(prRed('[ERROR] Your account has been locked !'))
elif browser.title == "Help us protect your account":
prRed('[ERROR] Unusual activity detected !')
LOGS[CURRENT_ACCOUNT]['Last check'] = 'Unusual activity detected !'
FINISHED_ACCOUNTS.append(CURRENT_ACCOUNT)
updateLogs()
cleanLogs()
if ARGS.telegram or ARGS.discord:
message = createMessage()
sendReportToMessenger(message)
input('Press any key to close...')
os._exit(0)
else:
LOGS[CURRENT_ACCOUNT]['Last check'] = 'Unknown error !'
FINISHED_ACCOUNTS.append(CURRENT_ACCOUNT)
updateLogs()
cleanLogs()
raise Exception(prRed('[ERROR] Unknown error !'))
# Wait 5 seconds
time.sleep(5)
# Click Security Check
print('[LOGIN]', 'Passing security checks...')
try:
browser.find_element(By.ID, 'iLandingViewAction').click()
except (NoSuchElementException, ElementNotInteractableException) as e:
pass
# Wait complete loading
try:
waitUntilVisible(browser, By.ID, 'KmsiCheckboxField', 10)
except (TimeoutException) as e:
pass
# Click next
try:
browser.find_element(By.ID, 'idSIButton9').click()
# Wait 5 seconds
time.sleep(5)
except (NoSuchElementException, ElementNotInteractableException) as e:
pass
print('[LOGIN]', 'Logged-in !')
# Check Microsoft Rewards
print('[LOGIN] Logging into Microsoft Rewards...')
RewardsLogin(browser)
# Check Login
print('[LOGIN]', 'Ensuring login on Bing...')
checkBingLogin(browser, isMobile)
def RewardsLogin(browser: WebDriver):
"""Login into Rewards"""
browser.get(BASE_URL)
try:
time.sleep(10 if not FAST and not SUPER_FAST else 5 if not SUPER_FAST else 2.5)
# click on sign up button if needed
if isElementExists(browser, By.ID, "start-earning-rewards-link"):
browser.find_element(By.ID, "start-earning-rewards-link").click()
time.sleep(5)
browser.refresh()
time.sleep(5)
except:
pass
time.sleep(10 if not FAST and not SUPER_FAST else 5 if not SUPER_FAST else 2.5)
# Check for ErrorMessage
try:
browser.find_element(By.ID, 'error').is_displayed()
# Check wheter account suspended or not
if browser.find_element(By.XPATH, '//*[@id="error"]/h1').get_attribute(
'innerHTML') == ' Uh oh, it appears your Microsoft Rewards account has been suspended.':
LOGS[CURRENT_ACCOUNT]['Last check'] = 'Your account has been suspended'
LOGS[CURRENT_ACCOUNT]["Today's points"] = 'N/A'
LOGS[CURRENT_ACCOUNT]["Points"] = 'N/A'
cleanLogs()
updateLogs()
FINISHED_ACCOUNTS.append(CURRENT_ACCOUNT)
raise Exception(prRed('[ERROR] Your Microsoft Rewards account has been suspended !'))
# Check whether Rewards is available in your region or not
elif browser.find_element(By.XPATH, '//*[@id="error"]/h1').get_attribute(
'innerHTML') == 'Microsoft Rewards is not available in this country or region.':
prRed('[ERROR] Microsoft Rewards is not available in this country or region !')
input('[ERROR] Press any key to close...')
os._exit(0)
except NoSuchElementException:
pass
@func_set_timeout(300)
def checkBingLogin(browser: WebDriver, isMobile: bool = False):
"""Check if logged in to Bing"""
global POINTS_COUNTER # pylint: disable=global-statement
# Access Bing.com
browser.get('https://bing.com/')
# Wait 15 seconds
time.sleep(15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
# try to get points at first if account already logged in
if ARGS.session:
try:
if not isMobile:
try:
POINTS_COUNTER = int(browser.find_element(By.ID, 'id_rc').get_attribute('innerHTML'))
except ValueError:
if browser.find_element(By.ID, 'id_s').is_displayed():
browser.find_element(By.ID, 'id_s').click()
time.sleep(15 if not FAST and not SUPER_FAST else 7 if not SUPER_FAST else 3)
checkBingLogin(browser, isMobile)
time.sleep(2)
POINTS_COUNTER = int(
browser.find_element(By.ID, "id_rc").get_attribute("innerHTML").replace(",", ""))
else:
browser.find_element(By.ID, 'mHamburger').click()
time.sleep(1)
POINTS_COUNTER = int(browser.find_element(By.ID, 'fly_id_rc').get_attribute('innerHTML'))
except:
pass
else:
return None
# Accept Cookies
try:
browser.find_element(By.ID, 'bnp_btn_accept').click()
except:
pass
if isMobile:
# close bing app banner
if isElementExists(browser, By.ID, 'bnp_rich_div'):
try:
browser.find_element(By.XPATH, '//*[@id="bnp_bop_close_icon"]/img').click()
except NoSuchElementException:
pass
try:
time.sleep(1)
browser.find_element(By.ID, 'mHamburger').click()
except:
try:
browser.find_element(By.ID, 'bnp_btn_accept').click()
except:
pass
time.sleep(1)
if isElementExists(browser, By.XPATH, '//*[@id="bnp_ttc_div"]/div[1]/div[2]/span'):
browser.execute_script("""var element = document.evaluate('/html/body/div[1]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
element.remove();""")
time.sleep(5)
time.sleep(1)
try:
browser.find_element(By.ID, 'mHamburger').click()
except:
pass
try:
time.sleep(1)
browser.find_element(By.ID, 'HBSignIn').click()
except:
pass
try:
time.sleep(2)
browser.find_element(By.ID, 'iShowSkip').click()
time.sleep(3)
except:
if str(browser.current_url).split('?')[0] == "https://account.live.com/proofs/Add":
prRed(f'[LOGIN] Please complete the Security Check on {CURRENT_ACCOUNT}')
FINISHED_ACCOUNTS.append(CURRENT_ACCOUNT)
LOGS[CURRENT_ACCOUNT]['Last check'] = 'Requires manual check!'
updateLogs()
sys.exit()
# Wait 5 seconds
time.sleep(5)
# Refresh page
browser.get('https://bing.com/')
# Wait 15 seconds
time.sleep(15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
# Update Counter
try:
if not isMobile:
try:
POINTS_COUNTER = int(browser.find_element(By.ID, 'id_rc').get_attribute('innerHTML'))
except:
if browser.find_element(By.ID, 'id_s').is_displayed():
browser.find_element(By.ID, 'id_s').click()
time.sleep(15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
checkBingLogin(browser, isMobile)
time.sleep(5)
POINTS_COUNTER = int(browser.find_element(By.ID, "id_rc").get_attribute("innerHTML").replace(",", ""))
else:
try:
browser.find_element(By.ID, 'mHamburger').click()
except:
try:
browser.find_element(By.ID, 'bnp_close_link').click()
time.sleep(4)
browser.find_element(By.ID, 'bnp_btn_accept').click()
except:
pass
time.sleep(1)
browser.find_element(By.ID, 'mHamburger').click()
time.sleep(1)
POINTS_COUNTER = int(browser.find_element(By.ID, 'fly_id_rc').get_attribute('innerHTML'))
except:
checkBingLogin(browser, isMobile)
def waitUntilVisible(browser: WebDriver, by_: By, selector: str, time_to_wait: int = 10):
"""Wait until visible"""
WebDriverWait(browser, time_to_wait).until(ec.visibility_of_element_located((by_, selector)))
def waitUntilClickable(browser: WebDriver, by_: By, selector: str, time_to_wait: int = 10):
"""Wait until clickable"""
WebDriverWait(browser, time_to_wait).until(ec.element_to_be_clickable((by_, selector)))
def waitUntilQuestionRefresh(browser: WebDriver):
"""Wait until question refresh"""
tries = 0
refreshCount = 0
while True:
try:
browser.find_elements(By.CLASS_NAME, 'rqECredits')[0]
return True
except:
if tries < 10:
tries += 1
time.sleep(0.5)
else:
if refreshCount < 5:
browser.refresh()
refreshCount += 1
tries = 0
time.sleep(5)
else:
return False
def waitUntilQuizLoads(browser: WebDriver):
"""Wait until quiz loads"""
tries = 0
refreshCount = 0
while True:
try:
browser.find_element(By.XPATH, '//*[@id="currentQuestionContainer"]')
return True
except:
if tries < 10:
tries += 1
time.sleep(0.5)
else:
if refreshCount < 5:
browser.refresh()
refreshCount += 1
tries = 0
time.sleep(5)
else:
return False
def findBetween(s: str, first: str, last: str) -> str:
"""Find between"""
try:
start = s.index(first) + len(first)
end = s.index(last, start)
return s[start:end]
except ValueError:
return ""
def getCCodeLangAndOffset() -> tuple:
"""Get lang, geo, time zone"""
try:
nfo = ipapi.location()
lang = nfo['languages'].split(',')[0]
geo = nfo['country']
tz = str(round(int(nfo['utc_offset']) / 100 * 60))
return lang, geo, tz
# Due to ipapi limitations it will default to US
except:
return 'en-US', 'US', '-480'
def getGoogleTrends(numberOfwords: int) -> list:
"""Get trends"""
search_terms = []
i = 0
while len(search_terms) < numberOfwords:
i += 1
r = requests.get('https://trends.google.com/trends/api/dailytrends?hl=' + LANG + '&ed=' + str(
(date.today() - timedelta(days=i)).strftime('%Y%m%d')) + '&geo=' + GEO + '&ns=15')
google_trends = json.loads(r.text[6:])
for topic in google_trends['default']['trendingSearchesDays'][0]['trendingSearches']:
search_terms.append(topic['title']['query'].lower())
for related_topic in topic['relatedQueries']:
search_terms.append(related_topic['query'].lower())
search_terms = list(set(search_terms))
del search_terms[numberOfwords:(len(search_terms) + 1)]
return search_terms
def getRelatedTerms(word: str) -> list:
"""Get related terms"""
try:
r = requests.get('https://api.bing.com/osjson.aspx?query=' + word, headers={'User-agent': PC_USER_AGENT})
return r.json()[1]
except:
return []
def resetTabs(browser: WebDriver):
"""Reset tabs"""
try:
curr = browser.current_window_handle
for handle in browser.window_handles:
if handle != curr:
browser.switch_to.window(handle)
time.sleep(0.5)
browser.close()
time.sleep(0.5)
browser.switch_to.window(curr)
time.sleep(0.5)
browser.get(BASE_URL)
waitUntilVisible(browser, By.ID, 'app-host', 30)
except:
browser.get(BASE_URL)
waitUntilVisible(browser, By.ID, 'app-host', 30)
def getAnswerCode(key: str, string: str) -> str:
"""Get answer code"""
t = 0
for i, _ in enumerate(string):
t += ord(string[i])
t += int(key[-2:], 16)
return str(t)
def bingSearches(browser: WebDriver, numberOfSearches: int, isMobile: bool = False):
"""Search Bing"""
global POINTS_COUNTER # pylint: disable=global-statement
i = 0
r = RandomWords()
try:
search_terms = r.get_random_words(limit=numberOfSearches)
if search_terms is None:
raise Exception
except Exception:
search_terms = getGoogleTrends(numberOfSearches)
if len(search_terms) == 0:
try:
words = open(f"{Path.cwd().resolve()}/searchwords.txt", "r").read().splitlines()
search_terms = random.sample(words, numberOfSearches)
except:
prRed('[ERROR] No search terms found, account skipped.')
finishedAccount()
cleanLogs()
updateLogs()
raise Exception()
for word in search_terms:
i += 1
print('[BING]', str(i) + "/" + str(numberOfSearches))
points = bingSearch(browser, word, isMobile)
if points <= POINTS_COUNTER:
relatedTerms = getRelatedTerms(word)
for term in relatedTerms:
points = bingSearch(browser, term, isMobile)
if points >= POINTS_COUNTER:
break
if points > 0:
POINTS_COUNTER = points
else:
break
def bingSearch(browser: WebDriver, word: str, isMobile: bool):
"""Bing search"""
try:
if not isMobile:
browser.find_element(By.ID, 'sb_form_q').clear()
time.sleep(1)
else:
browser.get('https://bing.com')
except:
browser.get('https://bing.com')
time.sleep(2)
searchbar = browser.find_element(By.ID, 'sb_form_q')
if FAST:
searchbar.send_keys(word)
time.sleep(1)
if SUPER_FAST:
searchbar.send_keys(word)
else:
for char in word:
searchbar.send_keys(char)
time.sleep(0.33)
searchbar.submit()
time.sleep(random.randint(12, 24) if not FAST and not SUPER_FAST else random.randint(6, 9) if not SUPER_FAST else 3)
points = 0
try:
if not isMobile:
try:
points = int(browser.find_element(By.ID, 'id_rc').get_attribute('innerHTML'))
except ValueError:
points = int(browser.find_element(By.ID, 'id_rc').get_attribute('innerHTML').replace(",", ""))
else:
try:
browser.find_element(By.ID, 'mHamburger').click()
except UnexpectedAlertPresentException:
try:
browser.switch_to.alert.accept()
time.sleep(1)
browser.find_element(By.ID, 'mHamburger').click()
except NoAlertPresentException:
pass
time.sleep(1)
points = int(browser.find_element(By.ID, 'fly_id_rc').get_attribute('innerHTML'))
except Exception as E: # skipcq
print(E)
return points
def completePromotionalItems(browser: WebDriver):
"""Complete promotional items"""
try:
item = getDashboardData(browser)["promotionalItem"]
if (item["pointProgressMax"] == 100 or item["pointProgressMax"] == 200) and item["complete"] is False and item["destinationUrl"] == BASE_URL:
browser.find_element(By.XPATH, '//*[@id="promo-item"]/section/div/div/div/a').click()
time.sleep(1)
browser.switch_to.window(window_name=browser.window_handles[1])
time.sleep(8 if not FAST and not SUPER_FAST else 5 if not SUPER_FAST else 2.5)
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
except:
pass
def completeDailySetSearch(browser: WebDriver, cardNumber: int):
"""Complete daily set search"""
time.sleep(5)
browser.find_element(By.XPATH, f'//*[@id="app-host"]/ui-view/mee-rewards-dashboard/main/div/mee-rewards-daily-set-section/div/mee-card-group/div/mee-card[{str(cardNumber)}]/div/card-content/mee-rewards-daily-set-item-content/div/a/div/span').click()
time.sleep(1)
browser.switch_to.window(window_name=browser.window_handles[1])
time.sleep(15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
def completeDailySetSurvey(browser: WebDriver, cardNumber: int):
"""Complete daily set survey"""
time.sleep(5)
browser.find_element(By.XPATH, f'//*[@id="app-host"]/ui-view/mee-rewards-dashboard/main/div/mee-rewards-daily-set-section/div/mee-card-group/div/mee-card[{str(cardNumber)}]/div/card-content/mee-rewards-daily-set-item-content/div/a/div/span').click()
time.sleep(1)
browser.switch_to.window(window_name=browser.window_handles[1])
time.sleep(8 if not FAST and not SUPER_FAST else 5 if not SUPER_FAST else 2.5)
# Accept cookie popup
if isElementExists(browser, By.ID, 'bnp_container'):
browser.find_element(By.ID, 'bnp_btn_accept').click()
time.sleep(2)
# Click on later on Bing wallpaper app popup
if isElementExists(browser, By.ID, 'b_notificationContainer_bop'):
browser.find_element(By.ID, 'bnp_hfly_cta2').click()
time.sleep(2)
browser.find_element(By.ID, "btoption" + str(random.randint(0, 1))).click()
time.sleep(10 if not FAST and not SUPER_FAST else 5 if not SUPER_FAST else 2)
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
def completeDailySetQuiz(browser: WebDriver, cardNumber: int):
"""Complete daily set quiz"""
time.sleep(5)
browser.find_element(By.XPATH,
f'//*[@id="app-host"]/ui-view/mee-rewards-dashboard/main/div/mee-rewards-daily-set-section[1]/div/mee-card-group[1]/div[1]/mee-card[{str(cardNumber)}]/div[1]/card-content[1]/mee-rewards-daily-set-item-content[1]/div[1]/a[1]/div[3]/span[1]').click()
time.sleep(3)
browser.switch_to.window(window_name=browser.window_handles[1])
time.sleep(12 if not FAST and not SUPER_FAST else random.randint(5, 8) if not SUPER_FAST else 3)
if not waitUntilQuizLoads(browser):
resetTabs(browser)
return
# Accept cookie popup
if isElementExists(browser, By.ID, 'bnp_container'):
browser.find_element(By.ID, 'bnp_btn_accept').click()
time.sleep(2)
browser.find_element(By.XPATH, '//*[@id="rqStartQuiz"]').click()
waitUntilVisible(browser, By.XPATH, '//*[@id="currentQuestionContainer"]/div/div[1]', 10 if not FAST and not SUPER_FAST else 5)
time.sleep(3)
numberOfQuestions = browser.execute_script("return _w.rewardsQuizRenderInfo.maxQuestions")
numberOfOptions = browser.execute_script("return _w.rewardsQuizRenderInfo.numberOfOptions")
for _ in range(numberOfQuestions):
if numberOfOptions == 8:
answers = []
for i in range(8):
if browser.find_element(By.ID, "rqAnswerOption" + str(i)).get_attribute(
"iscorrectoption").lower() == "true":
answers.append("rqAnswerOption" + str(i))
for answer in answers:
# Click on later on Bing wallpaper app popup
if isElementExists(browser, By.ID, 'b_notificationContainer_bop'):
browser.find_element(By.ID, 'bnp_hfly_cta2').click()
time.sleep(2)
browser.find_element(By.ID, answer).click()
time.sleep(5)
if not waitUntilQuestionRefresh(browser):
return
time.sleep(5)
elif numberOfOptions == 4:
correctOption = browser.execute_script("return _w.rewardsQuizRenderInfo.correctAnswer")
for i in range(4):
if browser.find_element(By.ID, "rqAnswerOption" + str(i)).get_attribute("data-option") == correctOption:
# Click on later on Bing wallpaper app popup
if isElementExists(browser, By.ID, 'b_notificationContainer_bop'):
browser.find_element(By.ID, 'bnp_hfly_cta2').click()
time.sleep(2)
browser.find_element(By.ID, "rqAnswerOption" + str(i)).click()
time.sleep(5)
if not waitUntilQuestionRefresh(browser):
return
break
time.sleep(5)
time.sleep(5)
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
def completeDailySetVariableActivity(browser: WebDriver, cardNumber: int):
"""Complete daily set variable activity"""
time.sleep(2)
browser.find_element(By.XPATH,
f'//*[@id="app-host"]/ui-view/mee-rewards-dashboard/main/div/mee-rewards-daily-set-section/div/mee-card-group/div/mee-card[{str(cardNumber)}]/div/card-content/mee-rewards-daily-set-item-content/div/a/div/span').click()
time.sleep(1)
browser.switch_to.window(window_name=browser.window_handles[1])
time.sleep(10 if not FAST and not SUPER_FAST else 5 if not SUPER_FAST else 2.5)
# Accept cookie popup
if isElementExists(browser, By.ID, 'bnp_container'):
browser.find_element(By.ID, 'bnp_btn_accept').click()
time.sleep(2)
try:
browser.find_element(By.XPATH, '//*[@id="rqStartQuiz"]').click()
waitUntilVisible(browser, By.XPATH, '//*[@id="currentQuestionContainer"]/div/div[1]', 3)
except (NoSuchElementException, TimeoutException):
try:
counter = str(browser.find_element(By.XPATH, '//*[@id="QuestionPane0"]/div[2]').get_attribute('innerHTML'))[
:-1][1:]
numberOfQuestions = max([int(s) for s in counter.split() if s.isdigit()])
for question in range(numberOfQuestions):
# Click on later on Bing wallpaper app popup
if isElementExists(browser, By.ID, 'b_notificationContainer_bop'):
browser.find_element(By.ID, 'bnp_hfly_cta2').click()
time.sleep(2)
browser.execute_script(
f'document.evaluate("//*[@id=\'QuestionPane{str(question)}\']/div[1]/div[2]/a[{str(random.randint(1, 3))}]/div", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click()')
time.sleep(8)
time.sleep(5)
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
return
except NoSuchElementException:
time.sleep(random.randint(5, 9))
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
return
time.sleep(3)
correctAnswer = browser.execute_script("return _w.rewardsQuizRenderInfo.correctAnswer")
if browser.find_element(By.ID, "rqAnswerOption0").get_attribute("data-option") == correctAnswer:
browser.find_element(By.ID, "rqAnswerOption0").click()
else:
browser.find_element(By.ID, "rqAnswerOption1").click()
time.sleep(10)
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
def completeDailySetThisOrThat(browser: WebDriver, cardNumber: int):
"""Complete daily set this or that"""
time.sleep(2)
browser.find_element(By.XPATH,
f'//*[@id="app-host"]/ui-view/mee-rewards-dashboard/main/div/mee-rewards-daily-set-section/div/mee-card-group/div/mee-card[{str(cardNumber)}]/div/card-content/mee-rewards-daily-set-item-content/div/a/div/span').click()
time.sleep(1)
browser.switch_to.window(window_name=browser.window_handles[1])
time.sleep(15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
# Accept cookie popup
if isElementExists(browser, By.ID, 'bnp_container'):
browser.find_element(By.ID, 'bnp_btn_accept').click()
time.sleep(2)
if not waitUntilQuizLoads(browser):
resetTabs(browser)
return
browser.find_element(By.XPATH, '//*[@id="rqStartQuiz"]').click()
waitUntilVisible(browser, By.XPATH, '//*[@id="currentQuestionContainer"]/div/div[1]', 15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
time.sleep(5)
for _ in range(10):
# Click on later on Bing wallpaper app popup
if isElementExists(browser, By.ID, 'b_notificationContainer_bop'):
browser.find_element(By.ID, 'bnp_hfly_cta2').click()
time.sleep(2)
answerEncodeKey = browser.execute_script("return _G.IG")
answer1 = browser.find_element(By.ID, "rqAnswerOption0")
answer1Title = answer1.get_attribute('data-option')
answer1Code = getAnswerCode(answerEncodeKey, answer1Title)
answer2 = browser.find_element(By.ID, "rqAnswerOption1")
answer2Title = answer2.get_attribute('data-option')
answer2Code = getAnswerCode(answerEncodeKey, answer2Title)
correctAnswerCode = browser.execute_script("return _w.rewardsQuizRenderInfo.correctAnswer")
if (answer1Code == correctAnswerCode):
answer1.click()
time.sleep(15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
elif (answer2Code == correctAnswerCode):
answer2.click()
time.sleep(15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
time.sleep(5)
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
def getDashboardData(browser: WebDriver) -> dict:
"""Get dashboard data"""
dashboard = findBetween(browser.find_element(By.XPATH, '/html/body').get_attribute('innerHTML'), "var dashboard = ",
";\n appDataModule.constant(\"prefetchedDashboard\", dashboard);")
dashboard = json.loads(dashboard)
return dashboard
def completeDailySet(browser: WebDriver):
"""Complete daily set"""
print('[DAILY SET]', 'Trying to complete the Daily Set...')
d = getDashboardData(browser)
error = False
todayDate = datetime.today().strftime('%m/%d/%Y')
todayPack = []
for date, data in d['dailySetPromotions'].items():
if date == todayDate:
todayPack = data
for activity in todayPack:
try:
if not activity['complete']:
cardNumber = int(activity['offerId'][-1:])
if activity['promotionType'] == "urlreward":
print('[DAILY SET]', 'Completing search of card ' + str(cardNumber))
completeDailySetSearch(browser, cardNumber)
if activity['promotionType'] == "quiz":
if activity['pointProgressMax'] == 50 and activity['pointProgress'] == 0:
print('[DAILY SET]', 'Completing This or That of card ' + str(cardNumber))
completeDailySetThisOrThat(browser, cardNumber)
elif (activity['pointProgressMax'] == 40 or activity['pointProgressMax'] == 30) and activity['pointProgress'] == 0:
print('[DAILY SET]', 'Completing quiz of card ' + str(cardNumber))
completeDailySetQuiz(browser, cardNumber)
elif activity['pointProgressMax'] == 10 and activity['pointProgress'] == 0:
searchUrl = urllib.parse.unquote(
urllib.parse.parse_qs(urllib.parse.urlparse(activity['destinationUrl']).query)['ru'][0])
searchUrlQueries = urllib.parse.parse_qs(urllib.parse.urlparse(searchUrl).query)
filters = {}
for filter in searchUrlQueries['filters'][0].split(" "):
filter = filter.split(':', 1)
filters[filter[0]] = filter[1]
if "PollScenarioId" in filters:
print('[DAILY SET]', 'Completing poll of card ' + str(cardNumber))
completeDailySetSurvey(browser, cardNumber)
else:
print('[DAILY SET]', 'Completing quiz of card ' + str(cardNumber))
completeDailySetVariableActivity(browser, cardNumber)
except:
error = True
resetTabs(browser)
if not error:
prGreen("[DAILY SET] Completed the Daily Set successfully !")
else:
prYellow("[DAILY SET] Daily Set did not completed successfully ! Streak not increased")
LOGS[CURRENT_ACCOUNT]['Daily'] = True
updateLogs()
def getAccountPoints(browser: WebDriver) -> int:
"""Get account points"""
return getDashboardData(browser)['userStatus']['availablePoints']
def completePunchCard(browser: WebDriver, url: str, childPromotions: dict):
"""complete punch card"""
browser.get(url)
for child in childPromotions:
if not child['complete']:
if child['promotionType'] == "urlreward":
browser.execute_script("document.getElementsByClassName('offer-cta')[0].click()")
time.sleep(1)
browser.switch_to.window(window_name=browser.window_handles[1])
time.sleep(15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
if child['promotionType'] == "quiz" and child['pointProgressMax'] >= 50:
browser.find_element(By.XPATH,
'//*[@id="rewards-dashboard-punchcard-details"]/div[2]/div[2]/div[7]/div[3]/div[1]/a').click()
time.sleep(1)
browser.switch_to.window(window_name=browser.window_handles[1])
time.sleep(15)
try:
browser.find_element(By.XPATH, '//*[@id="rqStartQuiz"]').click()
except:
pass
time.sleep(5)
waitUntilVisible(browser, By.XPATH, '//*[@id="currentQuestionContainer"]', 15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
numberOfQuestions = browser.execute_script("return _w.rewardsQuizRenderInfo.maxQuestions")
AnswerdQuestions = browser.execute_script(
"return _w.rewardsQuizRenderInfo.CorrectlyAnsweredQuestionCount")
numberOfQuestions -= AnswerdQuestions
for question in range(numberOfQuestions):
answer = browser.execute_script("return _w.rewardsQuizRenderInfo.correctAnswer")
browser.find_element(By.XPATH, f'//input[@value="{answer}"]').click()
time.sleep(15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
time.sleep(5)
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
browser.refresh()
break
elif child['promotionType'] == "quiz" and child['pointProgressMax'] < 50:
browser.execute_script("document.getElementsByClassName('offer-cta')[0].click()")
time.sleep(1)
browser.switch_to.window(window_name=browser.window_handles[1])
time.sleep(8)
counter = str(
browser.find_element(By.XPATH, '//*[@id="QuestionPane0"]/div[2]').get_attribute('innerHTML'))[:-1][
1:]
numberOfQuestions = max([int(s) for s in counter.split() if s.isdigit()])
for question in range(numberOfQuestions):
browser.execute_script(
'document.evaluate("//*[@id=\'QuestionPane' + str(question) + '\']/div[1]/div[2]/a['
+ str(random.randint(1, 3)) +
']/div", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click()')
time.sleep(15 if not FAST and not SUPER_FAST else 10 if not SUPER_FAST else 5)
time.sleep(5)
browser.close()
time.sleep(2)
browser.switch_to.window(window_name=browser.window_handles[0])
time.sleep(2)
browser.refresh()
break
def completePunchCards(browser: WebDriver):
"""Complete punch cards"""
print('[PUNCH CARDS]', 'Trying to complete the Punch Cards...')
punchCards = getDashboardData(browser)['punchCards']
for punchCard in punchCards:
try:
if punchCard['parentPromotion'] != None and punchCard['childPromotions'] != None and punchCard['parentPromotion']['complete'] is False and punchCard['parentPromotion']['pointProgressMax'] != 0:
url = punchCard['parentPromotion']['attributes']['destination']
if browser.current_url.startswith('https://rewards.'):
path = url.replace('https://rewards.microsoft.com', '')
new_url = 'https://rewards.microsoft.com/dashboard/'
userCode = path[11:15]
dest = new_url + userCode + path.split(userCode)[1]
else:
path = url.replace('https://account.microsoft.com/rewards/dashboard/', '')
new_url = 'https://account.microsoft.com/rewards/dashboard/'
userCode = path[:4]
dest = new_url + userCode + path.split(userCode)[1]
completePunchCard(browser, url, punchCard['childPromotions'])
except:
resetTabs(browser)