5 Commits

Author SHA1 Message Date
TheNetsky
1d6167aeca Missing await 2023-11-04 16:24:25 +01:00
TheNetsky
3b15fe19a7 1.2.5 2023-11-04 16:21:56 +01:00
TheNetsky
66dcdd4a7a 1.2.4
Disable "This or That" quiz.
2023-10-30 21:10:47 +01:00
TheNetsky
40f32af67f 1.2.3 2023-10-30 20:37:40 +01:00
TheNetsky
c2b68faa74 1.2.2 2023-10-26 15:31:35 +02:00
21 changed files with 1187 additions and 996 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "microsoft-rewards-script",
"version": "1.2.1",
"version": "1.2.5",
"description": "Automatically do tasks for Microsoft Rewards but in TS!",
"main": "index.js",
"engines": {
@@ -32,9 +32,10 @@
"cheerio": "^1.0.0-rc.12",
"eslint": "^8.49.0",
"eslint-plugin-modules-newline": "^0.0.6",
"puppeteer": "^21.2.1",
"fingerprint-generator": "^2.1.42",
"fingerprint-injector": "^2.1.42",
"puppeteer": "^21.4.1",
"puppeteer-extra": "^3.3.6",
"puppeteer-extra-plugin-stealth": "^2.11.2",
"ts-node": "^10.9.1"
}
}

View File

@@ -1,35 +1,60 @@
import puppeteer from 'puppeteer-extra'
import stealthPlugin from 'puppeteer-extra-plugin-stealth'
import { FingerprintInjector } from 'fingerprint-injector'
import { FingerprintGenerator } from 'fingerprint-generator'
import { getUserAgent } from '../util/UserAgent'
import { loadSesion } from './BrowserFunc'
import { MicrosoftRewardsBot } from '../index'
import { AccountProxy } from '../interface/Account'
import { headless } from '../config.json'
/* Test Stuff
https://abrahamjuliot.github.io/creepjs/
https://botcheck.luminati.io/
http://f.vision/
*/
puppeteer.use(stealthPlugin())
class Browser {
private bot: MicrosoftRewardsBot
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
async createBrowser(email: string, proxy: AccountProxy, isMobile: boolean) {
const userAgent = await getUserAgent(isMobile)
// const userAgent = await getUserAgent(isMobile)
const browser = await puppeteer.launch({
headless: headless,
userDataDir: await loadSesion(email),
headless: this.bot.config.headless,
userDataDir: await this.bot.browser.func.loadSesion(email),
args: [
'--no-sandbox',
'--mute-audio',
'--disable-setuid-sandbox',
`--user-agent=${userAgent.userAgent}`,
isMobile ? '--window-size=568,1024' : '',
'--ignore-certificate-errors',
'--ignore-certificate-errors-spki-list',
'--ignore-ssl-errors',
proxy.url ? `--proxy-server=${proxy.url}:${proxy.port}` : ''
]
})
const { fingerprint, headers } = new FingerprintGenerator().getFingerprint({
devices: isMobile ? ['mobile'] : ['desktop'],
operatingSystems: isMobile ? ['android'] : ['windows'],
browsers: ['edge'],
browserListQuery: 'last 2 Edge versions'
})
// Modify the newPage function to attach the fingerprint
const originalNewPage = browser.newPage
browser.newPage = async function () {
const page = await originalNewPage.apply(browser)
await new FingerprintInjector().attachFingerprintToPuppeteer(page, { fingerprint, headers })
return page
}
return browser
}
}
export default Browser

View File

@@ -1,34 +1,38 @@
import { Page } from 'puppeteer'
import { CheerioAPI, load } from 'cheerio'
import fs from 'fs'
import path from 'path'
import { CheerioAPI, load } from 'cheerio'
import { tryDismissAllMessages, tryDismissCookieBanner } from './BrowserUtil'
import { getFormattedDate, wait } from './../util/Utils'
import { log } from './../util/Logger'
import { MicrosoftRewardsBot } from '../index'
import { Counters, DashboardData, MorePromotion, PromotionalItem } from './../interface/DashboardData'
import { QuizData } from './../interface/QuizData'
import { baseURL, sessionPath } from './../config.json'
export async function goHome(page: Page): Promise<boolean> {
export default class BrowserFunc {
private bot: MicrosoftRewardsBot
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
async goHome(page: Page): Promise<boolean> {
try {
const dashboardURL = new URL(baseURL)
const dashboardURL = new URL(this.bot.config.baseURL)
await page.goto(baseURL)
await page.goto(this.bot.config.baseURL)
const maxIterations = 5 // Maximum iterations set to 5
for (let iteration = 1; iteration <= maxIterations; iteration++) {
await wait(3000)
await tryDismissCookieBanner(page)
await this.bot.utils.wait(3000)
await this.bot.browser.utils.tryDismissCookieBanner(page)
// Check if account is suspended
const isSuspended = await page.waitForSelector('#suspendedAccountHeader', { visible: true, timeout: 3000 }).then(() => true).catch(() => false)
const isSuspended = await page.waitForSelector('#suspendedAccountHeader', { visible: true, timeout: 2000 }).then(() => true).catch(() => false)
if (isSuspended) {
log('GO-HOME', 'This account is suspended!', 'error')
this.bot.log('GO-HOME', 'This account is suspended!', 'error')
throw new Error('Account has been suspended!')
}
@@ -44,14 +48,14 @@ export async function goHome(page: Page): Promise<boolean> {
const currentURL = new URL(page.url())
if (currentURL.hostname !== dashboardURL.hostname) {
await tryDismissAllMessages(page)
await this.bot.browser.utils.tryDismissAllMessages(page)
await wait(2000)
await page.goto(baseURL)
await this.bot.utils.wait(2000)
await page.goto(this.bot.config.baseURL)
}
await wait(5000)
log('GO-HOME', 'Visited homepage successfully')
await this.bot.utils.wait(5000)
this.bot.log('GO-HOME', 'Visited homepage successfully')
}
} catch (error) {
@@ -62,14 +66,14 @@ export async function goHome(page: Page): Promise<boolean> {
return true
}
export async function getDashboardData(page: Page): Promise<DashboardData> {
const dashboardURL = new URL(baseURL)
async getDashboardData(page: Page): Promise<DashboardData> {
const dashboardURL = new URL(this.bot.config.baseURL)
const currentURL = new URL(page.url())
// Should never happen since tasks are opened in a new tab!
if (currentURL.hostname !== dashboardURL.hostname) {
log('DASHBOARD-DATA', 'Provided page did not equal dashboard page, redirecting to dashboard page')
await goHome(page)
this.bot.log('DASHBOARD-DATA', 'Provided page did not equal dashboard page, redirecting to dashboard page')
await this.goHome(page)
}
// Reload the page to get new data
@@ -82,7 +86,7 @@ export async function getDashboardData(page: Page): Promise<DashboardData> {
if (targetScript) {
return targetScript.innerText
} else {
throw log('GET-DASHBOARD-DATA', 'Script containing dashboard data not found', 'error')
throw this.bot.log('GET-DASHBOARD-DATA', 'Script containing dashboard data not found', 'error')
}
})
@@ -95,14 +99,14 @@ export async function getDashboardData(page: Page): Promise<DashboardData> {
if (match && match[1]) {
return JSON.parse(match[1])
} else {
throw log('GET-DASHBOARD-DATA', 'Dashboard data not found within script', 'error')
throw this.bot.log('GET-DASHBOARD-DATA', 'Dashboard data not found within script', 'error')
}
}, scriptContent)
return dashboardData
}
export async function getQuizData(page: Page): Promise<QuizData> {
async getQuizData(page: Page): Promise<QuizData> {
try {
const html = await page.content()
const $ = load(html)
@@ -119,29 +123,29 @@ export async function getQuizData(page: Page): Promise<QuizData> {
const quizData = JSON.parse(match[1])
return quizData
} else {
throw log('GET-QUIZ-DATA', 'Quiz data not found within script', 'error')
throw this.bot.log('GET-QUIZ-DATA', 'Quiz data not found within script', 'error')
}
} else {
throw log('GET-QUIZ-DATA', 'Script containing quiz data not found', 'error')
throw this.bot.log('GET-QUIZ-DATA', 'Script containing quiz data not found', 'error')
}
} catch (error) {
throw log('GET-QUIZ-DATA', 'An error occurred:' + error, 'error')
throw this.bot.log('GET-QUIZ-DATA', 'An error occurred:' + error, 'error')
}
}
export async function getSearchPoints(page: Page): Promise<Counters> {
const dashboardData = await getDashboardData(page) // Always fetch newest data
async getSearchPoints(page: Page): Promise<Counters> {
const dashboardData = await this.getDashboardData(page) // Always fetch newest data
return dashboardData.userStatus.counters
}
export async function getEarnablePoints(data: DashboardData, page: null | Page = null): Promise<number> {
async getEarnablePoints(data: DashboardData, page: null | Page = null): Promise<number> {
try {
// Fetch new data if page is provided
if (page) {
data = await getDashboardData(page)
data = await this.getDashboardData(page)
}
// These only include the points from tasks that the script can complete!
@@ -156,7 +160,7 @@ export async function getEarnablePoints(data: DashboardData, page: null | Page =
}
// Daily Set
data.dailySetPromotions[getFormattedDate()]?.forEach(x => totalEarnablePoints += (x.pointProgressMax - x.pointProgress))
data.dailySetPromotions[this.bot.utils.getFormattedDate()]?.forEach(x => totalEarnablePoints += (x.pointProgressMax - x.pointProgress))
// More Promotions
data.morePromotions.forEach(x => {
@@ -168,25 +172,25 @@ export async function getEarnablePoints(data: DashboardData, page: null | Page =
return totalEarnablePoints
} catch (error) {
throw log('GET-EARNABLE-POINTS', 'An error occurred:' + error, 'error')
throw this.bot.log('GET-EARNABLE-POINTS', 'An error occurred:' + error, 'error')
}
}
export async function getCurrentPoints(data: DashboardData, page: null | Page = null): Promise<number> {
async getCurrentPoints(data: DashboardData, page: null | Page = null): Promise<number> {
try {
// Fetch new data if page is provided
if (page) {
data = await getDashboardData(page)
data = await this.getDashboardData(page)
}
return data.userStatus.availablePoints
} catch (error) {
throw log('GET-CURRENT-POINTS', 'An error occurred:' + error, 'error')
throw this.bot.log('GET-CURRENT-POINTS', 'An error occurred:' + error, 'error')
}
}
export async function loadSesion(email: string): Promise<string> {
const sessionDir = path.join(__dirname, sessionPath, email)
async loadSesion(email: string): Promise<string> {
const sessionDir = path.join(__dirname, this.bot.config.sessionPath, email)
try {
// Create session dir
@@ -200,22 +204,22 @@ export async function loadSesion(email: string): Promise<string> {
}
}
export async function waitForQuizRefresh(page: Page): Promise<boolean> {
async waitForQuizRefresh(page: Page): Promise<boolean> {
try {
await page.waitForSelector('#rqHeaderCredits', { visible: true, timeout: 5000 })
await wait(2000)
await page.waitForSelector('#rqHeaderCredits', { visible: true, timeout: 10_000 })
await this.bot.utils.wait(2000)
return true
} catch (error) {
log('QUIZ-REFRESH', 'An error occurred:' + error, 'error')
this.bot.log('QUIZ-REFRESH', 'An error occurred:' + error, 'error')
return false
}
}
export async function checkQuizCompleted(page: Page): Promise<boolean> {
async checkQuizCompleted(page: Page): Promise<boolean> {
try {
await page.waitForSelector('#quizCompleteContainer', { visible: true, timeout: 1000 })
await wait(2000)
await page.waitForSelector('#quizCompleteContainer', { visible: true, timeout: 2000 })
await this.bot.utils.wait(2000)
return true
} catch (error) {
@@ -223,14 +227,14 @@ export async function checkQuizCompleted(page: Page): Promise<boolean> {
}
}
export async function refreshCheerio(page: Page): Promise<CheerioAPI> {
async refreshCheerio(page: Page): Promise<CheerioAPI> {
const html = await page.content()
const $ = load(html)
return $
}
export async function getPunchCardActivity(page: Page, activity: PromotionalItem | MorePromotion): Promise<string> {
async getPunchCardActivity(page: Page, activity: PromotionalItem | MorePromotion): Promise<string> {
let selector = ''
try {
const html = await page.content()
@@ -241,8 +245,10 @@ export async function getPunchCardActivity(page: Page, activity: PromotionalItem
selector = `a[href*="${element.attribs.href}"]`
}
} catch (error) {
log('GET-PUNCHCARD-ACTIVITY', 'An error occurred:' + error, 'error')
this.bot.log('GET-PUNCHCARD-ACTIVITY', 'An error occurred:' + error, 'error')
}
return selector
}
}

View File

@@ -1,9 +1,16 @@
import { Page } from 'puppeteer'
import { wait } from './../util/Utils'
import { log } from './../util/Logger'
import { MicrosoftRewardsBot } from '../index'
export async function tryDismissAllMessages(page: Page): Promise<boolean> {
export default class BrowserUtil {
private bot: MicrosoftRewardsBot
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
async tryDismissAllMessages(page: Page): Promise<boolean> {
const buttons = [
{ selector: '#iLandingViewAction', label: 'iLandingViewAction' },
{ selector: '#iShowSkip', label: 'iShowSkip' },
@@ -31,7 +38,7 @@ export async function tryDismissAllMessages(page: Page): Promise<boolean> {
return result
}
export async function tryDismissCookieBanner(page: Page): Promise<void> {
async tryDismissCookieBanner(page: Page): Promise<void> {
try {
await page.waitForSelector('#cookieConsentContainer', { timeout: 1000 })
const cookieBanner = await page.$('#cookieConsentContainer')
@@ -40,7 +47,7 @@ export async function tryDismissCookieBanner(page: Page): Promise<void> {
const button = await cookieBanner.$('button')
if (button) {
await button.click()
await wait(2000)
await this.bot.utils.wait(2000)
}
}
@@ -49,7 +56,7 @@ export async function tryDismissCookieBanner(page: Page): Promise<void> {
}
}
export async function tryDismissBingCookieBanner(page: Page): Promise<void> {
async tryDismissBingCookieBanner(page: Page): Promise<void> {
try {
await page.waitForSelector('#bnp_btn_accept', { timeout: 1000 })
const cookieBanner = await page.$('#bnp_btn_accept')
@@ -62,9 +69,9 @@ export async function tryDismissBingCookieBanner(page: Page): Promise<void> {
}
}
export async function getLatestTab(page: Page): Promise<Page> {
async getLatestTab(page: Page): Promise<Page> {
try {
await wait(500)
await this.bot.utils.wait(500)
const browser = page.browser()
const pages = await browser.pages()
@@ -74,8 +81,10 @@ export async function getLatestTab(page: Page): Promise<Page> {
return newTab
}
throw log('GET-NEW-TAB', 'Unable to get latest tab', 'error')
throw this.bot.log('GET-NEW-TAB', 'Unable to get latest tab', 'error')
} catch (error) {
throw log('GET-NEW-TAB', 'An error occurred:' + error, 'error')
throw this.bot.log('GET-NEW-TAB', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -2,7 +2,7 @@
"baseURL": "https://rewards.bing.com",
"sessionPath": "sessions",
"headless": false,
"runOnZeroPoints": true,
"runOnZeroPoints": false,
"clusters": 1,
"workers": {
"doDailySet": true,
@@ -14,7 +14,11 @@
"searchSettings": {
"useGeoLocaleQueries": false,
"scrollRandomResults": true,
"clickRandomResults": true
"clickRandomResults": true,
"searchDelay": {
"min": 10000,
"max": 20000
}
},
"webhook": {
"enabled": false,

View File

@@ -0,0 +1,52 @@
import { Page } from 'puppeteer'
import { MicrosoftRewardsBot } from '../index'
import { Search } from './activities/Search'
import { ABC } from './activities/ABC'
import { Poll } from './activities/Poll'
import { Quiz } from './activities/Quiz'
import { ThisOrThat } from './activities/ThisOrThat'
import { UrlReward } from './activities/UrlReward'
import { DashboardData } from '../interface/DashboardData'
export default class Activities {
private bot: MicrosoftRewardsBot
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
doSearch = async (page: Page, data: DashboardData, mobile: boolean): Promise<void> => {
const search = new Search(this.bot)
await search.doSearch(page, data, mobile)
}
doABC = async (page: Page): Promise<void> => {
const abc = new ABC(this.bot)
await abc.doABC(page)
}
doPoll = async (page: Page): Promise<void> => {
const poll = new Poll(this.bot)
await poll.doPoll(page)
}
doThisOrThat = async (page: Page): Promise<void> => {
const thisOrThat = new ThisOrThat(this.bot)
await thisOrThat.doThisOrThat(page)
}
doQuiz = async (page: Page): Promise<void> => {
const quiz = new Quiz(this.bot)
await quiz.doQuiz(page)
}
doUrlReward = async (page: Page): Promise<void> => {
const urlReward = new UrlReward(this.bot)
await urlReward.doUrlReward(page)
}
}

View File

@@ -1,65 +1,71 @@
import { Page } from 'puppeteer'
import readline from 'readline'
import { MicrosoftRewardsBot } from '../index'
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
import { tryDismissAllMessages, tryDismissBingCookieBanner } from '../browser/BrowserUtil'
import { wait } from '../util/Utils'
import { log } from '../util/Logger'
export async function login(page: Page, email: string, password: string) {
export class Login {
private bot: MicrosoftRewardsBot
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
async login(page: Page, email: string, password: string) {
try {
// Navigate to the Bing login page
await page.goto('https://login.live.com/')
const isLoggedIn = await page.waitForSelector('html[data-role-name="MeePortal"]', { timeout: 5000 }).then(() => true).catch(() => false)
const isLoggedIn = await page.waitForSelector('html[data-role-name="MeePortal"]', { timeout: 10_000 }).then(() => true).catch(() => false)
if (!isLoggedIn) {
const isLocked = await page.waitForSelector('.serviceAbusePageContainer', { visible: true, timeout: 5000 }).then(() => true).catch(() => false)
const isLocked = await page.waitForSelector('.serviceAbusePageContainer', { visible: true, timeout: 10_000 }).then(() => true).catch(() => false)
if (isLocked) {
log('LOGIN', 'This account has been locked!', 'error')
this.bot.log('LOGIN', 'This account has been locked!', 'error')
throw new Error('Account has been locked!')
}
await page.waitForSelector('#loginHeader', { visible: true, timeout: 10_000 })
await execLogin(page, email, password)
log('LOGIN', 'Logged into Microsoft successfully')
await this.execLogin(page, email, password)
this.bot.log('LOGIN', 'Logged into Microsoft successfully')
} else {
log('LOGIN', 'Already logged in')
this.bot.log('LOGIN', 'Already logged in')
}
// Check if logged in to bing
await checkBingLogin(page)
await this.checkBingLogin(page)
// We're done logging in
log('LOGIN', 'Logged in successfully')
this.bot.log('LOGIN', 'Logged in successfully')
} catch (error) {
// Throw and don't continue
throw log('LOGIN', 'An error occurred:' + error, 'error')
throw this.bot.log('LOGIN', 'An error occurred:' + error, 'error')
}
}
async function execLogin(page: Page, email: string, password: string) {
private async execLogin(page: Page, email: string, password: string) {
await page.type('#i0116', email)
await page.click('#idSIButton9')
log('LOGIN', 'Email entered successfully')
this.bot.log('LOGIN', 'Email entered successfully')
try {
await page.waitForSelector('#i0118', { visible: true, timeout: 2000 })
await wait(2000)
await this.bot.utils.wait(2000)
await page.type('#i0118', password)
await page.click('#idSIButton9')
} catch (error) {
log('LOGIN', '2FA code required')
this.bot.log('LOGIN', '2FA code required')
const code = await new Promise<string>((resolve) => {
rl.question('Enter 2FA code:\n', (input) => {
@@ -72,13 +78,13 @@ async function execLogin(page: Page, email: string, password: string) {
await page.keyboard.press('Enter')
} finally {
log('LOGIN', 'Password entered successfully')
this.bot.log('LOGIN', 'Password entered successfully')
}
const currentURL = new URL(page.url())
while (currentURL.pathname !== '/' || currentURL.hostname !== 'account.microsoft.com') {
await tryDismissAllMessages(page)
await this.bot.browser.utils.tryDismissAllMessages(page)
currentURL.href = page.url()
}
@@ -86,9 +92,9 @@ async function execLogin(page: Page, email: string, password: string) {
await page.waitForSelector('html[data-role-name="MeePortal"]', { timeout: 10_000 })
}
async function checkBingLogin(page: Page): Promise<void> {
private async checkBingLogin(page: Page): Promise<void> {
try {
log('LOGIN-BING', 'Verifying Bing login')
this.bot.log('LOGIN-BING', 'Verifying Bing login')
await page.goto('https://www.bing.com/fd/auth/signin?action=interactive&provider=windows_live_id&return_url=https%3A%2F%2Fwww.bing.com%2F')
const maxIterations = 5
@@ -97,29 +103,31 @@ async function checkBingLogin(page: Page): Promise<void> {
const currentUrl = new URL(page.url())
if (currentUrl.hostname === 'www.bing.com' && currentUrl.pathname === '/') {
await wait(3000)
await tryDismissBingCookieBanner(page)
await this.bot.utils.wait(3000)
await this.bot.browser.utils.tryDismissBingCookieBanner(page)
const loggedIn = await checkBingLoginStatus(page)
const loggedIn = await this.checkBingLoginStatus(page)
if (loggedIn) {
log('LOGIN-BING', 'Bing login verification passed!')
this.bot.log('LOGIN-BING', 'Bing login verification passed!')
break
}
}
await wait(1000)
await this.bot.utils.wait(1000)
}
} catch (error) {
log('LOGIN-BING', 'An error occurred:' + error, 'error')
this.bot.log('LOGIN-BING', 'An error occurred:' + error, 'error')
}
}
async function checkBingLoginStatus(page: Page): Promise<boolean> {
private async checkBingLoginStatus(page: Page): Promise<boolean> {
try {
await page.waitForSelector('#id_n', { timeout: 5000 })
await page.waitForSelector('#id_n', { timeout: 10_000 })
return true
} catch (error) {
return false
}
}
}

View File

@@ -1,48 +1,42 @@
import { Page } from 'puppeteer'
import { doPoll } from './activities/Poll'
import { doQuiz } from './activities/Quiz'
import { doUrlReward } from './activities/UrlReward'
import { doThisOrThat } from './activities/ThisOrThat'
import { doABC } from './activities/ABC'
import { getPunchCardActivity } from '../browser/BrowserFunc'
import { getLatestTab } from '../browser/BrowserUtil'
import { getFormattedDate, wait } from '../util/Utils'
import { log } from '../util/Logger'
import { DashboardData, MorePromotion, PromotionalItem, PunchCard } from '../interface/DashboardData'
import { baseURL } from '../config.json'
import { MicrosoftRewardsBot } from '../index'
export class Workers {
public bot: MicrosoftRewardsBot
constructor(bot: MicrosoftRewardsBot) {
this.bot = bot
}
// Daily Set
export async function doDailySet(page: Page, data: DashboardData) {
const todayData = data.dailySetPromotions[getFormattedDate()]
async doDailySet(page: Page, data: DashboardData) {
const todayData = data.dailySetPromotions[this.bot.utils.getFormattedDate()]
const activitiesUncompleted = todayData?.filter(x => !x.complete && x.pointProgressMax > 0) ?? []
if (!activitiesUncompleted.length) {
log('DAILY-SET', 'All Daily Set" items have already been completed')
this.bot.log('DAILY-SET', 'All Daily Set" items have already been completed')
return
}
// Solve Activities
log('DAILY-SET', 'Started solving "Daily Set" items')
this.bot.log('DAILY-SET', 'Started solving "Daily Set" items')
await solveActivities(page, activitiesUncompleted)
await this.solveActivities(page, activitiesUncompleted)
log('DAILY-SET', 'All "Daily Set" items have been completed')
this.bot.log('DAILY-SET', 'All "Daily Set" items have been completed')
}
// Punch Card
export async function doPunchCard(page: Page, data: DashboardData) {
async doPunchCard(page: Page, data: DashboardData) {
const punchCardsUncompleted = data.punchCards?.filter(x => !x.parentPromotion.complete) ?? [] // Only return uncompleted punch cards
if (!punchCardsUncompleted.length) {
log('PUNCH-CARD', 'All "Punch Cards" have already been completed')
this.bot.log('PUNCH-CARD', 'All "Punch Cards" have already been completed')
return
}
@@ -50,27 +44,30 @@ export async function doPunchCard(page: Page, data: DashboardData) {
const activitiesUncompleted = punchCard.childPromotions.filter(x => !x.complete) // Only return uncompleted activities
// Solve Activities
log('PUNCH-CARD', `Started solving "Punch Card" items for punchcard: "${punchCard.parentPromotion.title}"`)
this.bot.log('PUNCH-CARD', `Started solving "Punch Card" items for punchcard: "${punchCard.parentPromotion.title}"`)
const browser = page.browser()
page = await browser.newPage()
// Got to punch card index page in a new tab
await page.goto(punchCard.parentPromotion.destinationUrl, { referer: baseURL })
await page.goto(punchCard.parentPromotion.destinationUrl, { referer: this.bot.config.baseURL })
await solveActivities(page, activitiesUncompleted, punchCard)
// Wait for new page to load, max 10 seconds, however try regardless in case of error
await page.waitForNetworkIdle({ timeout: 10_000 }).catch(() => { })
await this.solveActivities(page, activitiesUncompleted, punchCard)
// Close the punch card index page
await page.close()
log('PUNCH-CARD', `All items for punchcard: "${punchCard.parentPromotion.title}" have been completed`)
this.bot.log('PUNCH-CARD', `All items for punchcard: "${punchCard.parentPromotion.title}" have been completed`)
}
log('PUNCH-CARD', 'All "Punch Card" items have been completed')
this.bot.log('PUNCH-CARD', 'All "Punch Card" items have been completed')
}
// More Promotions
export async function doMorePromotions(page: Page, data: DashboardData) {
async doMorePromotions(page: Page, data: DashboardData) {
const morePromotions = data.morePromotions
// Check if there is a promotional item
@@ -81,45 +78,57 @@ export async function doMorePromotions(page: Page, data: DashboardData) {
const activitiesUncompleted = morePromotions?.filter(x => !x.complete && x.pointProgressMax > 0) ?? []
if (!activitiesUncompleted.length) {
log('MORE-PROMOTIONS', 'All "More Promotion" items have already been completed')
this.bot.log('MORE-PROMOTIONS', 'All "More Promotion" items have already been completed')
return
}
// Solve Activities
log('MORE-PROMOTIONS', 'Started solving "More Promotions" item')
this.bot.log('MORE-PROMOTIONS', 'Started solving "More Promotions" item')
await solveActivities(page, activitiesUncompleted)
await this.solveActivities(page, activitiesUncompleted)
log('MORE-PROMOTIONS', 'All "More Promotion" items have been completed')
this.bot.log('MORE-PROMOTIONS', 'All "More Promotion" items have been completed')
}
// Solve all the different types of activities
async function solveActivities(page: Page, activities: PromotionalItem[] | MorePromotion[], punchCard?: PunchCard) {
private async solveActivities(page: Page, activities: PromotionalItem[] | MorePromotion[], punchCard?: PunchCard) {
for (const activity of activities) {
try {
let selector = `[data-bi-id="${activity.offerId}"]`
if (punchCard) {
selector = await getPunchCardActivity(page, activity)
selector = await this.bot.browser.func.getPunchCardActivity(page, activity)
} else if (activity.name.toLowerCase().includes('membercenter')) {
// Promotion
if (activity.priority === 1) {
selector = '#promo-item'
selector = await page.waitForSelector('#promo-item', { visible: true, timeout: 2000 }).then(() => true).catch(() => false) ?
'#promo-item' : activity.name
} else {
selector = `[data-bi-id="${activity.name}"]`
}
}
// Wait for element to load
await page.waitForSelector(selector, { timeout: 5000 })
await page.waitForSelector(selector, { timeout: 10_000 })
// Click element, it will be opened in a new tab
await page.click(selector)
// Select the new activity page
const activityPage = await getLatestTab(page)
const activityPage = await this.bot.browser.utils.getLatestTab(page)
// Wait for the new tab to fully load, ignore error.
/*
Due to common false timeout on this function, we're ignoring the error regardless, if it worked then it's faster,
if it didn't then it gave enough time for the page to load.
*/
await activityPage.waitForNetworkIdle({ timeout: 10_000 }).catch(() => { })
// Cooldown
await this.bot.utils.wait(4000)
switch (activity.promotionType) {
// Quiz (Poll, Quiz or ABC)
@@ -129,45 +138,47 @@ async function solveActivities(page: Page, activities: PromotionalItem[] | MoreP
case 10:
// Normal poll
if (activity.destinationUrl.toLowerCase().includes('pollscenarioid')) {
log('ACTIVITY', `Found activity type: "Poll" title: "${activity.title}"`)
await doPoll(activityPage)
this.bot.log('ACTIVITY', `Found activity type: "Poll" title: "${activity.title}"`)
await this.bot.activities.doPoll(activityPage)
} else { // ABC
log('ACTIVITY', `Found activity type: "ABC" title: "${activity.title}"`)
await doABC(activityPage)
this.bot.log('ACTIVITY', `Found activity type: "ABC" title: "${activity.title}"`)
await this.bot.activities.doABC(activityPage)
}
break
// This Or That Quiz (Usually 50 points)
case 50:
log('ACTIVITY', `Found activity type: "ThisOrThat" title: "${activity.title}"`)
await doThisOrThat(activityPage)
this.bot.log('ACTIVITY', `Found activity type: "ThisOrThat" title: "${activity.title}"`)
await this.bot.activities.doThisOrThat(activityPage)
break
// Quizzes are usually 30-40 points
default:
log('ACTIVITY', `Found activity type: "Quiz" title: "${activity.title}"`)
await doQuiz(activityPage)
this.bot.log('ACTIVITY', `Found activity type: "Quiz" title: "${activity.title}"`)
await this.bot.activities.doQuiz(activityPage)
break
}
break
// UrlReward (Visit)
case 'urlreward':
log('ACTIVITY', `Found activity type: "UrlReward" title: "${activity.title}"`)
await doUrlReward(activityPage)
this.bot.log('ACTIVITY', `Found activity type: "UrlReward" title: "${activity.title}"`)
await this.bot.activities.doUrlReward(activityPage)
break
// Misc, Usually UrlReward Type
default:
log('ACTIVITY', `Found activity type: "Misc" title: "${activity.title}"`)
await doUrlReward(activityPage)
this.bot.log('ACTIVITY', `Found activity type: "Misc" title: "${activity.title}"`)
await this.bot.activities.doUrlReward(activityPage)
break
}
// Cooldown
await wait(1500)
await this.bot.utils.wait(2000)
} catch (error) {
log('ACTIVITY', 'An error occurred:' + error, 'error')
this.bot.log('ACTIVITY', 'An error occurred:' + error, 'error')
}
}
}
}

View File

@@ -1,52 +1,52 @@
import { Page } from 'puppeteer'
import { refreshCheerio } from '../../browser/BrowserFunc'
import { getLatestTab } from '../../browser/BrowserUtil'
import { log } from '../../util/Logger'
import { randomNumber, wait } from '../../util/Utils'
import { Workers } from '../Workers'
export async function doABC(page: Page) {
log('ABC', 'Trying to complete poll')
export class ABC extends Workers {
async doABC(page: Page) {
this.bot.log('ABC', 'Trying to complete poll')
try {
await wait(2000)
let $ = await refreshCheerio(page)
let $ = await this.bot.browser.func.refreshCheerio(page)
// Don't loop more than 15 in case unable to solve, would lock otherwise
const maxIterations = 15
let i
for (i = 0; i < maxIterations && !$('span.rw_icon').length; i++) {
await page.waitForSelector('.wk_OptionClickClass', { visible: true, timeout: 5000 })
await page.waitForSelector('.wk_OptionClickClass', { visible: true, timeout: 10_000 })
const answers = $('.wk_OptionClickClass')
const answer = answers[randomNumber(0, 2)]?.attribs['id']
const answer = answers[this.bot.utils.randomNumber(0, 2)]?.attribs['id']
await page.waitForSelector(`#${answer}`, { visible: true, timeout: 5000 })
await page.waitForSelector(`#${answer}`, { visible: true, timeout: 10_000 })
await wait(2000)
await this.bot.utils.wait(2000)
await page.click(`#${answer}`) // Click answer
await wait(4000)
await page.waitForSelector('div.wk_button', { visible: true, timeout: 5000 })
await this.bot.utils.wait(4000)
await page.waitForSelector('div.wk_button', { visible: true, timeout: 10_000 })
await page.click('div.wk_button') // Click next question button
page = await getLatestTab(page)
$ = await refreshCheerio(page)
await wait(1000)
page = await this.bot.browser.utils.getLatestTab(page)
$ = await this.bot.browser.func.refreshCheerio(page)
await this.bot.utils.wait(1000)
}
await wait(4000)
await this.bot.utils.wait(4000)
await page.close()
if (i === maxIterations) {
log('ABC', 'Failed to solve quiz, exceeded max iterations of 15', 'warn')
this.bot.log('ABC', 'Failed to solve quiz, exceeded max iterations of 15', 'warn')
} else {
log('ABC', 'Completed the ABC successfully')
this.bot.log('ABC', 'Completed the ABC successfully')
}
} catch (error) {
await page.close()
log('ABC', 'An error occurred:' + error, 'error')
this.bot.log('ABC', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -1,26 +1,29 @@
import { Page } from 'puppeteer'
import { log } from '../../util/Logger'
import { randomNumber, wait } from '../../util/Utils'
import { Workers } from '../Workers'
export async function doPoll(page: Page) {
log('POLL', 'Trying to complete poll')
export class Poll extends Workers {
async doPoll(page: Page) {
this.bot.log('POLL', 'Trying to complete poll')
try {
const buttonId = `#btoption${Math.floor(randomNumber(0, 1))}`
const buttonId = `#btoption${Math.floor(this.bot.utils.randomNumber(0, 1))}`
await page.waitForNetworkIdle({ timeout: 5000 })
await page.waitForSelector(buttonId, { visible: true, timeout: 5000 })
await wait(2000)
await page.waitForSelector(buttonId, { visible: true, timeout: 10_000 })
await this.bot.utils.wait(2000)
await page.click(buttonId)
await wait(4000)
await this.bot.utils.wait(4000)
await page.close()
log('POLL', 'Completed the poll successfully')
this.bot.log('POLL', 'Completed the poll successfully')
} catch (error) {
await page.close()
log('POLL', 'An error occurred:' + error, 'error')
this.bot.log('POLL', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -1,27 +1,25 @@
import { Page } from 'puppeteer'
import { getQuizData, waitForQuizRefresh } from '../../browser/BrowserFunc'
import { wait } from '../../util/Utils'
import { log } from '../../util/Logger'
import { Workers } from '../Workers'
export async function doQuiz(page: Page) {
log('QUIZ', 'Trying to complete quiz')
export class Quiz extends Workers {
async doQuiz(page: Page) {
this.bot.log('QUIZ', 'Trying to complete quiz')
try {
await page.waitForNetworkIdle({ timeout: 5000 })
await wait(2000)
// Check if the quiz has been started or not
const quizNotStarted = await page.waitForSelector('#rqStartQuiz', { visible: true, timeout: 3000 }).then(() => true).catch(() => false)
const quizNotStarted = await page.waitForSelector('#rqStartQuiz', { visible: true, timeout: 2000 }).then(() => true).catch(() => false)
if (quizNotStarted) {
await page.click('#rqStartQuiz')
} else {
log('QUIZ', 'Quiz has already been started, trying to finish it')
this.bot.log('QUIZ', 'Quiz has already been started, trying to finish it')
}
await wait(2000)
await this.bot.utils.wait(2000)
let quizData = await getQuizData(page)
let quizData = await this.bot.browser.func.getQuizData(page)
const questionsRemaining = quizData.maxQuestions - quizData.CorrectlyAnsweredQuestionCount // Amount of questions remaining
// All questions
@@ -31,7 +29,7 @@ export async function doQuiz(page: Page) {
const answers: string[] = []
for (let i = 0; i < quizData.numberOfOptions; i++) {
const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { visible: true, timeout: 5000 })
const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { visible: true, timeout: 10_000 })
const answerAttribute = await answerSelector?.evaluate(el => el.getAttribute('iscorrectoption'))
if (answerAttribute && answerAttribute.toLowerCase() === 'true') {
@@ -46,49 +44,48 @@ export async function doQuiz(page: Page) {
// Click the answer on page
await page.click(answer)
const refreshSuccess = await waitForQuizRefresh(page)
const refreshSuccess = await this.bot.browser.func.waitForQuizRefresh(page)
if (!refreshSuccess) {
await page.close()
log('QUIZ', 'An error occurred, refresh was unsuccessful', 'error')
this.bot.log('QUIZ', 'An error occurred, refresh was unsuccessful', 'error')
return
}
}
// Other type quiz
} else if ([2, 3, 4].includes(quizData.numberOfOptions)) {
quizData = await getQuizData(page) // Refresh Quiz Data
quizData = await this.bot.browser.func.getQuizData(page) // Refresh Quiz Data
const correctOption = quizData.correctAnswer
for (let i = 0; i < quizData.numberOfOptions; i++) {
const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { visible: true, timeout: 5000 })
const answerSelector = await page.waitForSelector(`#rqAnswerOption${i}`, { visible: true, timeout: 10_000 })
const dataOption = await answerSelector?.evaluate(el => el.getAttribute('data-option'))
if (dataOption === correctOption) {
// Click the answer on page
await page.click(`#rqAnswerOption${i}`)
const refreshSuccess = await waitForQuizRefresh(page)
const refreshSuccess = await this.bot.browser.func.waitForQuizRefresh(page)
if (!refreshSuccess) {
await page.close()
log('QUIZ', 'An error occurred, refresh was unsuccessful', 'error')
this.bot.log('QUIZ', 'An error occurred, refresh was unsuccessful', 'error')
return
}
}
}
await wait(2000)
await this.bot.utils.wait(2000)
}
}
// Done with
await wait(2000)
await this.bot.utils.wait(2000)
await page.close()
log('QUIZ', 'Completed the quiz successfully')
this.bot.log('QUIZ', 'Completed the quiz successfully')
} catch (error) {
await page.close()
log('QUIZ', 'An error occurred:' + error, 'error')
this.bot.log('QUIZ', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -1,19 +1,19 @@
import { Page } from 'puppeteer'
import axios from 'axios'
import { getLatestTab } from '../../browser/BrowserUtil'
import { getSearchPoints } from '../../browser/BrowserFunc'
import { log } from '../../util/Logger'
import { randomNumber, shuffleArray, wait } from '../../util/Utils'
import { searchSettings } from '../../config.json'
import { Workers } from '../Workers'
import { DashboardData, DashboardImpression } from '../../interface/DashboardData'
import { GoogleTrends } from '../../interface/GoogleDailyTrends'
import { GoogleSearch } from '../../interface/Search'
export async function doSearch(page: Page, data: DashboardData, mobile: boolean) {
log('SEARCH-BING', 'Starting bing searches')
export class Search extends Workers {
private searchPageURL = 'https://bing.com'
public async doSearch(page: Page, data: DashboardData, mobile: boolean) {
this.bot.log('SEARCH-BING', 'Starting bing searches')
const mobileData = data.userStatus.counters?.mobileSearch ? data.userStatus.counters.mobileSearch[0] : null // Mobile searches
const edgeData = data.userStatus.counters.pcSearch[1] as DashboardImpression // Edge searches
@@ -24,13 +24,13 @@ export async function doSearch(page: Page, data: DashboardData, mobile: boolean)
(edgeData.pointProgressMax - edgeData.pointProgress) + (genericData.pointProgressMax - genericData.pointProgress)
if (missingPoints == 0) {
log('SEARCH-BING', `Bing searches for ${mobile ? 'MOBILE' : 'DESKTOP'} have already been completed`)
this.bot.log('SEARCH-BING', `Bing searches for ${mobile ? 'MOBILE' : 'DESKTOP'} have already been completed`)
return
}
// Generate search queries
let googleSearchQueries = await getGoogleTrends(data.userProfile.attributes.country, missingPoints)
googleSearchQueries = shuffleArray(googleSearchQueries)
let googleSearchQueries = await this.getGoogleTrends(data.userProfile.attributes.country, missingPoints)
googleSearchQueries = this.bot.utils.shuffleArray(googleSearchQueries)
// Deduplicate the search terms
googleSearchQueries = [...new Set(googleSearchQueries)]
@@ -40,7 +40,7 @@ export async function doSearch(page: Page, data: DashboardData, mobile: boolean)
const searchPage = await browser.newPage()
// Go to bing
await searchPage.goto('https://bing.com')
await searchPage.goto(this.searchPageURL)
let maxLoop = 0 // If the loop hits 10 this when not gaining any points, we're assuming it's stuck. If it ddoesn't continue after 5 more searches with alternative queries, abort search
@@ -51,9 +51,9 @@ export async function doSearch(page: Page, data: DashboardData, mobile: boolean)
for (let i = 0; i < queries.length; i++) {
const query = queries[i] as string
log('SEARCH-BING', `${missingPoints} Points Remaining | Query: ${query} | Mobile: ${mobile}`)
this.bot.log('SEARCH-BING', `${missingPoints} Points Remaining | Query: ${query} | Mobile: ${mobile}`)
const newData = await bingSearch(page, searchPage, query)
const newData = await this.bingSearch(page, searchPage, query)
const newMobileData = newData.mobileSearch ? newData.mobileSearch[0] : null // Mobile searches
const newEdgeData = newData.pcSearch[1] as DashboardImpression // Edge searches
@@ -78,7 +78,7 @@ export async function doSearch(page: Page, data: DashboardData, mobile: boolean)
// If we didn't gain points for 10 iterations, assume it's stuck
if (maxLoop > 10) {
log('SEARCH-BING', 'Search didn\'t gain point for 10 iterations aborting searches', 'warn')
this.bot.log('SEARCH-BING', 'Search didn\'t gain point for 10 iterations aborting searches', 'warn')
maxLoop = 0 // Reset to 0 so we can retry with related searches below
break
}
@@ -86,19 +86,19 @@ export async function doSearch(page: Page, data: DashboardData, mobile: boolean)
// If we still got remaining search queries, generate extra ones
if (missingPoints > 0) {
log('SEARCH-BING', `Search completed but we're missing ${missingPoints} points, generating extra searches`)
this.bot.log('SEARCH-BING', `Search completed but we're missing ${missingPoints} points, generating extra searches`)
let i = 0
while (missingPoints > 0) {
const query = googleSearchQueries[i++] as GoogleSearch
// Get related search terms to the Google search queries
const relatedTerms = await getRelatedTerms(query?.topic)
const relatedTerms = await this.getRelatedTerms(query?.topic)
if (relatedTerms.length > 3) {
// Search for the first 2 related terms
for (const term of relatedTerms.slice(1, 3)) {
log('SEARCH-BING-EXTRA', `${missingPoints} Points Remaining | Query: ${term} | Mobile: ${mobile}`)
const newData = await bingSearch(page, searchPage, query.topic)
this.bot.log('SEARCH-BING-EXTRA', `${missingPoints} Points Remaining | Query: ${term} | Mobile: ${mobile}`)
const newData = await this.bingSearch(page, searchPage, query.topic)
const newMobileData = newData.mobileSearch ? newData.mobileSearch[0] : null // Mobile searches
const newEdgeData = newData.pcSearch[1] as DashboardImpression // Edge searches
@@ -124,7 +124,7 @@ export async function doSearch(page: Page, data: DashboardData, mobile: boolean)
// Try 5 more times, then we tried a total of 15 times, fair to say it's stuck
if (maxLoop > 5) {
log('SEARCH-BING-EXTRA', 'Search didn\'t gain point for 5 iterations aborting searches', 'warn')
this.bot.log('SEARCH-BING-EXTRA', 'Search didn\'t gain point for 5 iterations aborting searches', 'warn')
return
}
}
@@ -132,17 +132,17 @@ export async function doSearch(page: Page, data: DashboardData, mobile: boolean)
}
}
log('SEARCH-BING', 'Completed searches')
this.bot.log('SEARCH-BING', 'Completed searches')
}
async function bingSearch(page: Page, searchPage: Page, query: string) {
private async bingSearch(page: Page, searchPage: Page, query: string) {
// Try a max of 5 times
for (let i = 0; i < 5; i++) {
try {
const searchBar = '#sb_form_q'
await searchPage.waitForSelector(searchBar, { visible: true, timeout: 10_000 })
await searchPage.click(searchBar) // Focus on the textarea
await wait(500)
await this.bot.utils.wait(500)
await searchPage.keyboard.down('Control')
await searchPage.keyboard.press('A')
await searchPage.keyboard.press('Backspace')
@@ -150,50 +150,50 @@ async function bingSearch(page: Page, searchPage: Page, query: string) {
await searchPage.keyboard.type(query)
await searchPage.keyboard.press('Enter')
if (searchSettings.scrollRandomResults) {
await wait(2000)
await randomScroll(searchPage)
if (this.bot.config.searchSettings.scrollRandomResults) {
await this.bot.utils.wait(2000)
await this.randomScroll(searchPage)
}
if (searchSettings.clickRandomResults) {
await wait(2000)
await clickRandomLink(searchPage)
if (this.bot.config.searchSettings.clickRandomResults) {
await this.bot.utils.wait(2000)
await this.clickRandomLink(searchPage)
}
await wait(Math.floor(randomNumber(10_000, 20_000)))
await this.bot.utils.wait(Math.floor(this.bot.utils.randomNumber(this.bot.config.searchSettings.searchDelay.min, this.bot.config.searchSettings.searchDelay.max)))
return await getSearchPoints(page)
return await this.bot.browser.func.getSearchPoints(page)
} catch (error) {
if (i === 5) {
log('SEARCH-BING', 'Failed after 5 retries... An error occurred:' + error, 'error')
this.bot.log('SEARCH-BING', 'Failed after 5 retries... An error occurred:' + error, 'error')
break
}
log('SEARCH-BING', 'Search failed, An error occurred:' + error, 'error')
log('SEARCH-BING', `Retrying search, attempt ${i}/5`, 'warn')
this.bot.log('SEARCH-BING', 'Search failed, An error occurred:' + error, 'error')
this.bot.log('SEARCH-BING', `Retrying search, attempt ${i}/5`, 'warn')
await wait(4000)
await this.bot.utils.wait(4000)
}
}
log('SEARCH-BING', 'Search failed after 5 retries, ending', 'error')
return await getSearchPoints(page)
this.bot.log('SEARCH-BING', 'Search failed after 5 retries, ending', 'error')
return await this.bot.browser.func.getSearchPoints(page)
}
async function getGoogleTrends(geoLocale: string, queryCount: number): Promise<GoogleSearch[]> {
private async getGoogleTrends(geoLocale: string, queryCount: number): Promise<GoogleSearch[]> {
const queryTerms: GoogleSearch[] = []
let i = 0
geoLocale = (searchSettings.useGeoLocaleQueries && geoLocale.length === 2) ? geoLocale.toUpperCase() : 'US'
geoLocale = (this.bot.config.searchSettings.useGeoLocaleQueries && geoLocale.length === 2) ? geoLocale.toUpperCase() : 'US'
log('SEARCH-GOOGLE-TRENDS', `Generating search queries, can take a while! | GeoLocale: ${geoLocale}`)
this.bot.log('SEARCH-GOOGLE-TRENDS', `Generating search queries, can take a while! | GeoLocale: ${geoLocale}`)
while (queryCount > queryTerms.length) {
i += 1
const date = new Date()
date.setDate(date.getDate() - i)
const formattedDate = formatDate(date)
const formattedDate = this.formatDate(date)
try {
const request = {
@@ -216,14 +216,14 @@ async function getGoogleTrends(geoLocale: string, queryCount: number): Promise<G
}
} catch (error) {
log('SEARCH-GOOGLE-TRENDS', 'An error occurred:' + error, 'error')
this.bot.log('SEARCH-GOOGLE-TRENDS', 'An error occurred:' + error, 'error')
}
}
return queryTerms
}
async function getRelatedTerms(term: string): Promise<string[]> {
private async getRelatedTerms(term: string): Promise<string[]> {
try {
const request = {
url: `https://api.bing.com/osjson.aspx?query=${term}`,
@@ -237,12 +237,12 @@ async function getRelatedTerms(term: string): Promise<string[]> {
return response.data[1] as string[]
} catch (error) {
log('SEARCH-BING-RELTATED', 'An error occurred:' + error, 'error')
this.bot.log('SEARCH-BING-RELTATED', 'An error occurred:' + error, 'error')
}
return []
}
function formatDate(date: Date): string {
private formatDate(date: Date): string {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
@@ -250,31 +250,28 @@ function formatDate(date: Date): string {
return `${year}${month}${day}`
}
async function randomScroll(page: Page) {
private async randomScroll(page: Page) {
try {
// Press the arrow down key to scroll
for (let i = 0; i < randomNumber(5, 100); i++) {
for (let i = 0; i < this.bot.utils.randomNumber(5, 100); i++) {
await page.keyboard.press('ArrowDown')
}
} catch (error) {
log('SEARCH-RANDOM-SCROLL', 'An error occurred:' + error, 'error')
this.bot.log('SEARCH-RANDOM-SCROLL', 'An error occurred:' + error, 'error')
}
}
async function clickRandomLink(page: Page) {
private async clickRandomLink(page: Page) {
try {
const searchListingURL = new URL(page.url()) // Get searchPage info before clicking
await page.click('#b_results .b_algo h2').catch(() => { }) // Since we don't really care if it did it or not
// Wait for website to load
await wait(3000)
// Will get current tab if no new one is created
let lastTab = await getLatestTab(page)
let lastTab = await this.bot.browser.utils.getLatestTab(page)
// Wait for the body of the new page to be loaded
await lastTab.waitForSelector('body', { timeout: 10_000 }).catch(() => { })
// Let website load, if it doesn't load within 5 sec. exit regardless
await lastTab.waitForNetworkIdle({ timeout: 5000 }).catch(() => { })
// Check if the tab is closed or not
if (!lastTab.isClosed()) {
@@ -287,15 +284,15 @@ async function clickRandomLink(page: Page) {
if (lastTabURL.hostname == searchListingURL.hostname) {
await lastTab.goBack()
lastTab = await getLatestTab(page) // Get last opened tab
lastTab = await this.bot.browser.utils.getLatestTab(page) // Get last opened tab
// If "goBack" didn't return to search listing (due to redirects)
if (lastTabURL.hostname !== searchListingURL.hostname) {
await lastTab.goto(searchListingURL.href)
await lastTab.goto(this.searchPageURL)
}
} else { // No longer on bing, likely opened a new tab, close this tab
lastTab = await getLatestTab(page) // Get last opened tab
lastTab = await this.bot.browser.utils.getLatestTab(page) // Get last opened tab
lastTabURL = new URL(lastTab.url())
const tabs = await (page.browser()).pages() // Get all tabs open
@@ -311,21 +308,23 @@ async function clickRandomLink(page: Page) {
await lastTab.goBack()
lastTab = await getLatestTab(page) // Get last opened tab
lastTab = await this.bot.browser.utils.getLatestTab(page) // Get last opened tab
lastTabURL = new URL(lastTab.url())
// If "goBack" didn't return to search listing (due to redirects)
if (lastTabURL.hostname !== searchListingURL.hostname) {
await lastTab.goto(searchListingURL.href)
await lastTab.goto(this.searchPageURL)
}
}
}
lastTab = await this.bot.browser.utils.getLatestTab(page) // Finally update the lastTab var again
i++
}
}
} catch (error) {
this.bot.log('SEARCH-RANDOM-CLICK', 'An error occurred:' + error, 'error')
}
}
lastTab = await getLatestTab(page) // Finally update the lastTab var again
i++
}
} catch (error) {
log('SEARCH-RANDOM-CLICK', 'An error occurred:' + error, 'error')
}
}

View File

@@ -1,34 +1,34 @@
import { Page } from 'puppeteer'
import { wait } from '../../util/Utils'
import { log } from '../../util/Logger'
import { getQuizData } from '../../browser/BrowserFunc'
import { Workers } from '../Workers'
export async function doThisOrThat(page: Page) {
log('THIS-OR-THAT', 'Trying to complete ThisOrThat')
export class ThisOrThat extends Workers {
async doThisOrThat(page: Page) {
this.bot.log('THIS-OR-THAT', 'Trying to complete ThisOrThat')
return
try {
await page.waitForNetworkIdle({ timeout: 5000 })
await wait(2000)
// Check if the quiz has been started or not
const quizNotStarted = await page.waitForSelector('#rqStartQuiz', { visible: true, timeout: 3000 }).then(() => true).catch(() => false)
const quizNotStarted = await page.waitForSelector('#rqStartQuiz', { visible: true, timeout: 2000 }).then(() => true).catch(() => false)
if (quizNotStarted) {
await page.click('#rqStartQuiz')
} else {
log('THIS-OR-THAT', 'ThisOrThat has already been started, trying to finish it')
this.bot.log('THIS-OR-THAT', 'ThisOrThat has already been started, trying to finish it')
}
await wait(2000)
await this.bot.utils.wait(2000)
// Solving
const quizData = await getQuizData(page)
const quizData = await this.bot.browser.func.getQuizData(page)
quizData // correctAnswer property is always null?
log('THIS-OR-THAT', 'Completed the ThisOrthat successfully')
this.bot.log('THIS-OR-THAT', 'Completed the ThisOrThat successfully')
} catch (error) {
await page.close()
log('THIS-OR-THAT', 'An error occurred:' + error, 'error')
this.bot.log('THIS-OR-THAT', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -1,21 +1,22 @@
import { Page } from 'puppeteer'
import { wait } from '../../util/Utils'
import { log } from '../../util/Logger'
import { Workers } from '../Workers'
export async function doUrlReward(page: Page) {
log('URL-REWARD', 'Trying to complete UrlReward')
export class UrlReward extends Workers {
async doUrlReward(page: Page) {
this.bot.log('URL-REWARD', 'Trying to complete UrlReward')
try {
// After waiting, close the page
await page.waitForNetworkIdle({ timeout: 10_000 })
await wait(2000)
await page.close()
log('URL-REWARD', 'Completed the UrlReward successfully')
this.bot.log('URL-REWARD', 'Completed the UrlReward successfully')
} catch (error) {
await page.close()
log('URL-REWARD', 'An error occurred:' + error, 'error')
this.bot.log('URL-REWARD', 'An error occurred:' + error, 'error')
}
}
}

View File

@@ -1,40 +1,60 @@
import cluster from 'cluster'
import Browser from './browser/Browser'
import { getDashboardData, getEarnablePoints, goHome } from './browser/BrowserFunc'
import BrowserFunc from './browser/BrowserFunc'
import BrowserUtil from './browser/BrowserUtil'
import { log } from './util/Logger'
import { loadAccounts } from './util/Account'
import { chunkArray } from './util/Utils'
import Util from './util/Utils'
import { loadAccounts, loadConfig } from './util/Load'
import { login } from './functions/Login'
import { doDailySet, doMorePromotions, doPunchCard } from './functions/Workers'
import { doSearch } from './functions/activities/Search'
import { Login } from './functions/Login'
import { Workers } from './functions/Workers'
import Activities from './functions/Activities'
import { Account } from './interface/Account'
import { runOnZeroPoints, workers, clusters } from './config.json'
// Main bot class
class MicrosoftRewardsBot {
private activeWorkers: number = clusters
export class MicrosoftRewardsBot {
public log: typeof log
public config
public utils: Util
public activities: Activities = new Activities(this)
public browser: {
func: BrowserFunc,
utils: BrowserUtil
}
private collectedPoints: number = 0
private browserFactory: Browser = new Browser()
private activeWorkers: number
private browserFactory: Browser = new Browser(this)
private accounts: Account[]
private workers: Workers
private login = new Login(this)
constructor() {
this.log = log
this.accounts = []
this.utils = new Util()
this.workers = new Workers(this)
this.browser = {
func: new BrowserFunc(this),
utils: new BrowserUtil(this)
}
this.config = loadConfig()
this.activeWorkers = this.config.clusters
}
async initialize() {
this.accounts = await loadAccounts()
this.accounts = loadAccounts()
}
async run() {
log('MAIN', `Bot started with ${clusters} clusters`)
log('MAIN', `Bot started with ${this.config.clusters} clusters`)
// Only cluster when there's more than 1 cluster demanded
if (clusters > 1) {
if (this.config.clusters > 1) {
if (cluster.isPrimary) {
this.runMaster()
} else {
@@ -48,7 +68,7 @@ class MicrosoftRewardsBot {
private runMaster() {
log('MAIN-PRIMARY', 'Primary process started')
const accountChunks = chunkArray(this.accounts, clusters)
const accountChunks = this.utils.chunkArray(this.accounts, this.config.clusters)
for (let i = 0; i < accountChunks.length; i++) {
const worker = cluster.fork()
@@ -71,7 +91,6 @@ class MicrosoftRewardsBot {
private runWorker() {
log('MAIN-WORKER', `Worker ${process.pid} spawned`)
// Receive the chunk of accounts from the master
process.on('message', async ({ chunk }) => {
await this.runTasks(chunk)
@@ -86,7 +105,7 @@ class MicrosoftRewardsBot {
await this.Desktop(account)
// If runOnZeroPoints is false and 0 points to earn, stop and try the next account
if (!runOnZeroPoints && this.collectedPoints === 0) {
if (!this.config.runOnZeroPoints && this.collectedPoints === 0) {
continue
}
@@ -119,22 +138,22 @@ class MicrosoftRewardsBot {
log('MAIN', 'Starting DESKTOP browser')
// Login into MS Rewards
await login(page, account.email, account.password)
await this.login.login(page, account.email, account.password)
const wentHome = await goHome(page)
const wentHome = await this.browser.func.goHome(page)
if (!wentHome) {
throw log('MAIN', 'Unable to get dashboard page', 'error')
}
const data = await getDashboardData(page)
const data = await this.browser.func.getDashboardData(page)
log('MAIN-POINTS', `Current point count: ${data.userStatus.availablePoints}`)
const earnablePoints = await getEarnablePoints(data)
const earnablePoints = await this.browser.func.getEarnablePoints(data)
this.collectedPoints = earnablePoints
log('MAIN-POINTS', `You can earn ${earnablePoints} points today`)
// If runOnZeroPoints is false and 0 points to earn, don't continue
if (!runOnZeroPoints && this.collectedPoints === 0) {
if (!this.config.runOnZeroPoints && this.collectedPoints === 0) {
log('MAIN', 'No points to earn and "runOnZeroPoints" is set to "false", stopping')
// Close desktop browser
@@ -142,23 +161,23 @@ class MicrosoftRewardsBot {
}
// Complete daily set
if (workers.doDailySet) {
await doDailySet(page, data)
if (this.config.workers.doDailySet) {
await this.workers.doDailySet(page, data)
}
// Complete more promotions
if (workers.doMorePromotions) {
await doMorePromotions(page, data)
if (this.config.workers.doMorePromotions) {
await this.workers.doMorePromotions(page, data)
}
// Complete punch cards
if (workers.doPunchCards) {
await doPunchCard(page, data)
if (this.config.workers.doPunchCards) {
await this.workers.doPunchCard(page, data)
}
// Do desktop searches
if (workers.doDesktopSearch) {
await doSearch(page, data, false)
if (this.config.workers.doDesktopSearch) {
await this.activities.doSearch(page, data, false)
}
// Close desktop browser
@@ -182,11 +201,11 @@ class MicrosoftRewardsBot {
log('MAIN', 'Starting MOBILE browser')
// Login into MS Rewards
await login(page, account.email, account.password)
await this.login.login(page, account.email, account.password)
await goHome(page)
await this.browser.func.goHome(page)
const data = await getDashboardData(page)
const data = await this.browser.func.getDashboardData(page)
// If no mobile searches data found, stop (Does not exist on new accounts)
if (!data.userStatus.counters.mobileSearch) {
@@ -197,12 +216,12 @@ class MicrosoftRewardsBot {
}
// Do mobile searches
if (workers.doMobileSearch) {
await doSearch(page, data, true)
if (this.config.workers.doMobileSearch) {
await this.activities.doSearch(page, data, true)
}
// Fetch new points
const earnablePoints = await getEarnablePoints(data, page)
const earnablePoints = await this.browser.func.getEarnablePoints(data, page)
// If the new earnable is 0, means we got all the points, else retract
this.collectedPoints = earnablePoints === 0 ? this.collectedPoints : (this.collectedPoints - earnablePoints)

35
src/interface/Config.ts Normal file
View File

@@ -0,0 +1,35 @@
export interface Config {
baseURL: string;
sessionPath: string;
headless: boolean;
runOnZeroPoints: boolean;
clusters: number;
workers: Workers;
searchSettings: SearchSettings;
webhook: Webhook;
}
export interface SearchSettings {
useGeoLocaleQueries: boolean;
scrollRandomResults: boolean;
clickRandomResults: boolean;
searchDelay: SearchDelay;
}
export interface SearchDelay {
min: number;
max: number;
}
export interface Webhook {
enabled: boolean;
url: string;
}
export interface Workers {
doDailySet: boolean;
doMorePromotions: boolean;
doPunchCards: boolean;
doDesktopSearch: boolean;
doMobileSearch: boolean;
}

View File

@@ -1,9 +1,11 @@
import * as fs from 'fs'
import fs from 'fs'
import path from 'path'
import { Account } from '../interface/Account'
import { Config } from '../interface/Config'
export async function loadAccounts(): Promise<Account[]> {
export function loadAccounts(): Account[] {
try {
let file = 'accounts.json'
@@ -20,3 +22,14 @@ export async function loadAccounts(): Promise<Account[]> {
throw new Error(error as string)
}
}
export function loadConfig(): Config {
try {
const configDir = path.join(__dirname, '../', 'config.json')
const config = fs.readFileSync(configDir, 'utf-8')
return JSON.parse(config)
} catch (error) {
throw new Error(error as string)
}
}

View File

@@ -1,7 +1,7 @@
import { Webhook } from './Webhook'
export function log(title: string, message: string, type?: 'log' | 'warn' | 'error') {
const currentTime = new Date().toISOString()
const currentTime = new Date().toLocaleString()
let str = ''

View File

@@ -1,10 +1,12 @@
export async function wait(ms: number): Promise<void> {
export default class Util {
async wait(ms: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms)
})
}
export function getFormattedDate(ms = Date.now()): string {
getFormattedDate(ms = Date.now()): string {
const today = new Date(ms)
const month = String(today.getMonth() + 1).padStart(2, '0') // January is 0
const day = String(today.getDate()).padStart(2, '0')
@@ -13,7 +15,7 @@ export function getFormattedDate(ms = Date.now()): string {
return `${month}/${day}/${year}`
}
export function shuffleArray<T>(array: T[]): T[] {
shuffleArray<T>(array: T[]): T[] {
const shuffledArray = array.slice()
shuffledArray.sort(() => Math.random() - 0.5)
@@ -21,11 +23,11 @@ export function shuffleArray<T>(array: T[]): T[] {
return shuffledArray
}
export function randomNumber(min: number, max: number): number {
randomNumber(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min
}
export function chunkArray<T>(arr: T[], numChunks: number): T[][] {
chunkArray<T>(arr: T[], numChunks: number): T[][] {
const chunkSize = Math.ceil(arr.length / numChunks)
const chunks: T[][] = []
@@ -36,3 +38,5 @@ export function chunkArray<T>(arr: T[], numChunks: number): T[][] {
return chunks
}
}

View File

@@ -1,8 +1,11 @@
import axios from 'axios'
import { webhook } from '../config.json'
import { loadConfig } from './Load'
export async function Webhook(content: string) {
const webhook = loadConfig().webhook
if (!webhook.enabled || webhook.url.length < 10) return
const request = {

View File

@@ -64,7 +64,8 @@
},
"include": [
"src/**/*.ts",
"src/accounts.json"
"src/accounts.json",
"src/config.json"
],
"exclude": [
"node_modules"