forked from klept0/MS-Rewards-Farmer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
367 lines (310 loc) · 12.8 KB
/
main.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
import argparse
import atexit
import csv
import json
import logging
import logging.handlers as handlers
import random
import re
import sys
import time
from datetime import datetime
from pathlib import Path
import os
import pandas as pd
import psutil
from src import (
Browser,
DailySet,
Login,
MorePromotions,
PunchCards,
Searches,
VersusGame,
)
from src.loggingColoredFormatter import ColoredFormatter
from src.notifier import Notifier
from src.utils import Utils
POINTS_COUNTER = 0
def main():
print("test", Utils.randomSeconds(5, 10))
args = argumentParser()
notifier = Notifier(args)
setupLogging(args.verbosenotifs, notifier)
loadedAccounts = setupAccounts()
# Register the cleanup function to be called on script exit
atexit.register(cleanupChromeProcesses)
# Load previous day's points data
previous_points_data = load_previous_points_data()
loadedAccounts = setupAccounts()
# Process accounts
for currentAccount in loadedAccounts:
process_account_with_retry(currentAccount, notifier, args, previous_points_data)
# Save the current day's points data for the next day in the "logs" folder
save_previous_points_data(previous_points_data)
logging.info("[POINTS] Data saved for the next day.")
def log_daily_points_to_csv(date, earned_points, points_difference):
logs_directory = Path(__file__).resolve().parent / "logs"
csv_filename = logs_directory / "points_data.csv"
# Create a new row with the date, daily points, and points difference
date = datetime.now().strftime("%Y-%m-%d")
new_row = {
"Date": date,
"Earned Points": earned_points,
"Points Difference": points_difference,
}
fieldnames = ["Date", "Earned Points", "Points Difference"]
is_new_file = not csv_filename.exists()
with open(csv_filename, mode="a", newline="") as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
if is_new_file:
writer.writeheader()
writer.writerow(new_row)
def setupLogging(verbose_notifs, notifier):
ColoredFormatter.verbose_notifs = verbose_notifs
ColoredFormatter.notifier = notifier
format = "%(asctime)s [%(levelname)s] %(message)s"
terminalHandler = logging.StreamHandler(sys.stdout)
terminalHandler.setFormatter(ColoredFormatter(format))
logs_directory = Path(__file__).resolve().parent / "logs"
logs_directory.mkdir(parents=True, exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format=format,
handlers=[
handlers.TimedRotatingFileHandler(
logs_directory / "activity.log",
when="midnight",
interval=1,
backupCount=2,
encoding="utf-8",
),
terminalHandler,
],
)
def cleanupChromeProcesses():
# Get the current user's PID
current_pid = os.getpid()
# Function to recursively terminate child processes
def terminate_children(parent_pid):
# Get the list of all processes
all_processes = psutil.process_iter()
for process in all_processes:
if process.ppid() == parent_pid:
# Recursively terminate children of this process first
terminate_children(process.pid)
try:
process.terminate()
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
# Terminate child processes starting from the script's PID
terminate_children(current_pid)
def argumentParser() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="MS Rewards Farmer")
parser.add_argument(
"-v", "--visible", action="store_true", help="Optional: Visible browser"
)
parser.add_argument(
"-l", "--lang", type=str, default=None, help="Optional: Language (ex: en)"
)
parser.add_argument(
"-g", "--geo", type=str, default=None, help="Optional: Geolocation (ex: US)"
)
parser.add_argument(
"-p",
"--proxy",
type=str,
default=None,
help="Optional: Global Proxy (ex: http://user:pass@host:port)",
)
parser.add_argument(
"-t",
"--telegram",
metavar=("TOKEN", "CHAT_ID"),
nargs=2,
type=str,
default=None,
help="Optional: Telegram Bot Token and Chat ID (ex: 123456789:ABCdefGhIjKlmNoPQRsTUVwxyZ 123456789)",
)
parser.add_argument(
"-d",
"--discord",
type=str,
default=None,
help="Optional: Discord Webhook URL (ex: https://discord.com/api/webhooks/123456789/ABCdefGhIjKlmNoPQRsTUVwxyZ)",
)
parser.add_argument(
"-vn",
"--verbosenotifs",
action="store_true",
help="Optional: Send all the logs to discord/telegram",
)
parser.add_argument(
"-cv",
"--chromeversion",
type=int,
default=None,
help="Optional: Set fixed Chrome version (ex. 118)",
)
return parser.parse_args()
def setupAccounts() -> list:
"""Sets up and validates a list of accounts loaded from 'accounts.json'."""
def validEmail(email: str) -> bool:
"""Validate Email."""
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
return bool(re.match(pattern, email))
accountPath = Path(__file__).resolve().parent / "accounts.json"
if not accountPath.exists():
accountPath.write_text(
json.dumps(
[{"username": "Your Email", "password": "Your Password"}], indent=4
),
encoding="utf-8",
)
noAccountsNotice = """
[ACCOUNT] Accounts credential file "accounts.json" not found.
[ACCOUNT] A new file has been created, please edit with your credentials and save.
"""
logging.warning(noAccountsNotice)
exit()
loadedAccounts = json.loads(accountPath.read_text(encoding="utf-8"))
for account in loadedAccounts:
if not validEmail(account["username"]):
logging.error(f"[CREDENTIALS] Wrong Email Address: '{account['username']}'")
exit()
random.shuffle(loadedAccounts)
return loadedAccounts
def executeBot(currentAccount, notifier: Notifier, args: argparse.Namespace):
logging.info(
f'********************{currentAccount.get("username", "")}********************'
)
accountPointsCounter = 0
remainingSearches = 0
remainingSearchesM = 0
startingPoints = 0
with Browser(mobile=False, account=currentAccount, args=args) as desktopBrowser:
accountPointsCounter = Login(desktopBrowser).login()
startingPoints = accountPointsCounter
if startingPoints == "Locked":
notifier.send("🚫 Account is Locked", currentAccount)
return 0
if startingPoints == "Verify":
notifier.send("❗ Account needs to be verified", currentAccount)
return 0
logging.info(
f"[POINTS] You have {desktopBrowser.utils.formatNumber(accountPointsCounter)} points on your account"
)
DailySet(desktopBrowser).completeDailySet()
PunchCards(desktopBrowser).completePunchCards()
MorePromotions(desktopBrowser).completeMorePromotions()
# VersusGame(desktopBrowser).completeVersusGame()
(
remainingSearches,
remainingSearchesM,
) = desktopBrowser.utils.getRemainingSearches()
# Introduce random pauses before and after searches
pause_before_search = random.uniform(
11.0, 15.0
) # Random pause between 11 to 15 seconds
time.sleep(pause_before_search)
if remainingSearches != 0:
accountPointsCounter = Searches(desktopBrowser).bingSearches(
remainingSearches
)
pause_after_search = random.uniform(
11.0, 15.0
) # Random pause between 11 to 15 seconds
time.sleep(pause_after_search)
desktopBrowser.utils.goHome()
goalPoints = desktopBrowser.utils.getGoalPoints()
goalTitle = desktopBrowser.utils.getGoalTitle()
desktopBrowser.closeBrowser()
if remainingSearchesM != 0:
desktopBrowser.closeBrowser()
with Browser(mobile=True, account=currentAccount, args=args) as mobileBrowser:
accountPointsCounter = Login(mobileBrowser).login()
accountPointsCounter = Searches(mobileBrowser).bingSearches(
remainingSearchesM
)
mobileBrowser.utils.goHome()
goalPoints = mobileBrowser.utils.getGoalPoints()
goalTitle = mobileBrowser.utils.getGoalTitle()
mobileBrowser.closeBrowser()
logging.info(
f"[POINTS] You have earned {desktopBrowser.utils.formatNumber(accountPointsCounter - startingPoints)} points today !"
)
logging.info(
f"[POINTS] You are now at {desktopBrowser.utils.formatNumber(accountPointsCounter)} points !"
)
goalNotifier = ""
if goalPoints > 0:
logging.info(
f"[POINTS] You are now at {(desktopBrowser.utils.formatNumber((accountPointsCounter / goalPoints) * 100))}% of your goal ({goalTitle}) !\n"
)
goalNotifier = f"🎯 Goal reached: {(desktopBrowser.utils.formatNumber((accountPointsCounter / goalPoints) * 100))}% ({goalTitle})"
notifier.send(
"\n".join(
[
f"⭐️ Points earned today: {desktopBrowser.utils.formatNumber(accountPointsCounter - startingPoints)}",
f"💰 Total points: {desktopBrowser.utils.formatNumber(accountPointsCounter)}",
goalNotifier,
]
),
currentAccount,
)
return accountPointsCounter
def export_points_to_csv(points_data):
logs_directory = Path(__file__).resolve().parent / "logs"
csv_filename = logs_directory / "points_data.csv"
with open(csv_filename, mode="a", newline="") as file: # Use "a" mode for append
fieldnames = ["Account", "Earned Points", "Points Difference"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
# Check if the file is empty, and if so, write the header row
if file.tell() == 0:
writer.writeheader()
for data in points_data:
writer.writerow(data)
# Define a function to load the previous day's points data from a file in the "logs" folder
def load_previous_points_data():
logs_directory = Path(__file__).resolve().parent / "logs"
try:
with open(logs_directory / "previous_points_data.json", "r") as file:
return json.load(file)
except FileNotFoundError:
return {}
# Define a function to save the current day's points data for the next day in the "logs" folder
def save_previous_points_data(data):
logs_directory = Path(__file__).resolve().parent / "logs"
with open(logs_directory / "previous_points_data.json", "w") as file:
json.dump(data, file, indent=4)
def process_account_with_retry(currentAccount, notifier, args, previous_points_data):
retries = 5
while retries > 0:
try:
earned_points = executeBot(currentAccount, notifier, args)
account_name = currentAccount.get("username", "")
previous_points = previous_points_data.get(account_name, 0)
# Calculate the difference in points from the prior day
points_difference = earned_points - previous_points
# Append the daily points and points difference to CSV and Excel
log_daily_points_to_csv(account_name, earned_points, points_difference)
# Update the previous day's points data
previous_points_data[account_name] = earned_points
logging.info(f"[POINTS] Data for '{account_name}' appended to the file.")
break # Exit the loop if execution is successful
except Exception as e:
retries -= 1
if retries == 0:
notifier.send(
"⚠️ Error occurred after 5 attempts, please check the log",
currentAccount,
)
logging.error(
f"[CRITICAL] ⚠️ Error occurred after 3 attempts. Closing script!⚠️ | {currentAccount.get('username', '')}"
)
else:
account_name2 = currentAccount.get("username", "")
logging.warning(f"Error occurred: {e}. Retrying... | {account_name2}")
time.sleep(10) # Wait a bit before retrying
if __name__ == "__main__":
main()