forked from charlesbel/Microsoft-Rewards-Farmer
-
-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathmain.py
361 lines (308 loc) · 11.6 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
import argparse
import csv
import json
import logging
import logging.config
import logging.handlers as handlers
import random
import re
import sys
import traceback
from datetime import datetime
from enum import Enum, auto
from src import (
Browser,
Login,
MorePromotions,
PunchCards,
Searches,
ReadToEarn,
DailySet,
Account,
)
from src.browser import RemainingSearches
from src.loggingColoredFormatter import ColoredFormatter
from src.utils import Utils
def main():
args = argumentParser()
Utils.args = args
setupLogging()
loadedAccounts = setupAccounts()
# Load previous day's points data
previous_points_data = load_previous_points_data()
for currentAccount in loadedAccounts:
try:
earned_points = executeBot(currentAccount, args)
except Exception as e1:
logging.error("", exc_info=True)
Utils.sendNotification(
f"⚠️ Error executing {currentAccount.username}, please check the log",
traceback.format_exc(),
)
continue
previous_points = previous_points_data.get(currentAccount.username, 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(earned_points, points_difference)
# Update the previous day's points data
previous_points_data[currentAccount.username] = earned_points
logging.info(
f"[POINTS] Data for '{currentAccount.username}' appended to the file."
)
# 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(earned_points, points_difference):
logs_directory = Utils.getProjectRoot() / "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():
_format = "%(asctime)s [%(levelname)s] %(message)s"
terminalHandler = logging.StreamHandler(sys.stdout)
terminalHandler.setFormatter(ColoredFormatter(_format))
logs_directory = Utils.getProjectRoot() / "logs"
logs_directory.mkdir(parents=True, exist_ok=True)
# so only our code is logged if level=logging.DEBUG or finer
# if not working see https://stackoverflow.com/a/48891485/4164390
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": True,
}
)
logging.basicConfig(
level=logging.DEBUG,
format=_format,
handlers=[
handlers.TimedRotatingFileHandler(
logs_directory / "activity.log",
when="midnight",
interval=1,
backupCount=2,
encoding="utf-8",
),
terminalHandler,
],
)
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(
"-vn",
"--verbosenotifs",
action="store_true",
help="Optional: Send all the logs to the notification service",
)
parser.add_argument(
"-cv",
"--chromeversion",
type=int,
default=None,
help="Optional: Set fixed Chrome version (ex. 118)",
)
parser.add_argument(
"-da",
"--disable-apprise",
action="store_true",
help="Optional: Disable Apprise, overrides config.yaml, useful when developing",
)
parser.add_argument(
"-t",
"--searchtype",
type=str,
default=None,
help="Optional: Set to only search in either desktop or mobile (ex: 'desktop' or 'mobile')",
)
return parser.parse_args()
def setupAccounts() -> list[Account]:
"""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 = Utils.getProjectRoot() / "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(1)
loadedAccounts: list[Account] = []
for rawAccount in json.loads(accountPath.read_text(encoding="utf-8")):
account: Account = Account(**rawAccount)
if not validEmail(account.username):
logging.warning(
f"[CREDENTIALS] Invalid email: {account.username}, skipping this account"
)
continue
loadedAccounts.append(account)
random.shuffle(loadedAccounts)
return loadedAccounts
class AppriseSummary(Enum):
"""
configures how results are summarized via Apprise
"""
ALWAYS = auto()
"""
the default, as it was before, how many points were gained and goal percentage if set
"""
ON_ERROR = auto()
"""
only sends email if for some reason there's remaining searches
"""
NEVER = auto()
"""
never send summary
"""
def executeBot(currentAccount: Account, args: argparse.Namespace):
logging.info(f"********************{currentAccount.username}********************")
startingPoints: int | None = None
accountPoints: int
remainingSearches: RemainingSearches
goalTitle: str
goalPoints: int
if args.searchtype in ("desktop", None):
with Browser(mobile=False, account=currentAccount, args=args) as desktopBrowser:
utils = desktopBrowser.utils
Login(desktopBrowser, args).login()
startingPoints = utils.getAccountPoints()
logging.info(
f"[POINTS] You have {utils.formatNumber(startingPoints)} points on your account"
)
# todo Combine these classes so main loop isn't duplicated
DailySet(desktopBrowser).completeDailySet()
PunchCards(desktopBrowser).completePunchCards()
MorePromotions(desktopBrowser).completeMorePromotions()
# VersusGame(desktopBrowser).completeVersusGame()
with Searches(desktopBrowser) as searches:
searches.bingSearches()
goalPoints = utils.getGoalPoints()
goalTitle = utils.getGoalTitle()
remainingSearches = desktopBrowser.getRemainingSearches(
desktopAndMobile=True
)
accountPoints = utils.getAccountPoints()
if args.searchtype in ("mobile", None):
with Browser(mobile=True, account=currentAccount, args=args) as mobileBrowser:
utils = mobileBrowser.utils
Login(mobileBrowser, args).login()
if startingPoints is None:
startingPoints = utils.getAccountPoints()
ReadToEarn(mobileBrowser).completeReadToEarn()
with Searches(mobileBrowser) as searches:
searches.bingSearches()
goalPoints = utils.getGoalPoints()
goalTitle = utils.getGoalTitle()
remainingSearches = mobileBrowser.getRemainingSearches(
desktopAndMobile=True
)
accountPoints = utils.getAccountPoints()
logging.info(
f"[POINTS] You have earned {Utils.formatNumber(accountPoints - startingPoints)} points this run !"
)
logging.info(
f"[POINTS] You are now at {Utils.formatNumber(accountPoints)} points !"
)
appriseSummary = AppriseSummary[
Utils.loadConfig().get("apprise", {}).get("summary", AppriseSummary.ALWAYS.name)
]
if appriseSummary == AppriseSummary.ALWAYS:
goalStatus = ""
if goalPoints > 0:
logging.info(
f"[POINTS] You are now at {(Utils.formatNumber((accountPoints / goalPoints) * 100))}% of your "
f"goal ({goalTitle}) !"
)
goalStatus = (
f"🎯 Goal reached: {(Utils.formatNumber((accountPoints / goalPoints) * 100))}%"
f" ({goalTitle})"
)
Utils.sendNotification(
"Daily Points Update",
"\n".join(
[
f"👤 Account: {currentAccount.username}",
f"⭐️ Points earned today: {Utils.formatNumber(accountPoints - startingPoints)}",
f"💰 Total points: {Utils.formatNumber(accountPoints)}",
goalStatus,
]
),
)
elif appriseSummary == AppriseSummary.ON_ERROR:
if remainingSearches.getTotal() > 0:
Utils.sendNotification(
"Error: remaining searches",
f"account username: {currentAccount.username}, {remainingSearches}",
)
elif appriseSummary == AppriseSummary.NEVER:
pass
return accountPoints
def export_points_to_csv(points_data):
logs_directory = Utils.getProjectRoot() / "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():
try:
with open(
Utils.getProjectRoot() / "logs" / "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 = Utils.getProjectRoot() / "logs"
with open(logs_directory / "previous_points_data.json", "w") as file:
json.dump(data, file, indent=4)
if __name__ == "__main__":
try:
main()
except Exception as e:
logging.exception("")
Utils.sendNotification(
"⚠️ Error occurred, please check the log", traceback.format_exc()
)