This repository has been archived by the owner on May 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
660 lines (576 loc) · 25.7 KB
/
app.js
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
// imports
require('dotenv').config()
let fs = require('fs')
let treekill = require('tree-kill')
let DayJS = require('DayJS')
let puppeteer = require('puppeteer-core')
let cheerio = require('cheerio')
let ConsoleTitle = require('console-title')
let colors = require('colors')
let streamdata = require('./helper/streamdata')
// current version
let appversion = "0.3.5.0"
var logged_in_as = ""
let config = './config.json'
let base_url = 'https://www.twitch.tv/'
let user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'
let old_user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
let scroll_delay = 2000
let scroll_times = 2
let streamer_list_refresh = 1
let streamer_list_refresh_unit = 'hour'
let browser_clean = 1
let browser_clean_unit = 'hour'
var run = true
var first_run = true
var streamers = null
var collected_drops = 0
var last_drop = "Never"
var api_auth_key = null
let cfg = fs.existsSync(config) ? JSON.parse(fs.readFileSync(config, 'utf8')) : null
if (cfg) {
fs.writeFile(config + '.bak', JSON.stringify(cfg, null, "\t"), function (err) {
if (err) LogToConsole(err)
})
}
// config values
let browser_config, loc_cookie, auth_cookie
let exec_path, headless, proxy_server, proxy_auth, auth_token, country_code, game1, game2, game3, to_watch, streamheroes, client_id, client_secret, inactivity_sleep, min_watchtime, max_watchtime, only_idle_fixed, get_random_stream, get_streamhero_stream, new_watch_method, new_watch_idle
async function UpdateConfigValues() {
let cfg = fs.existsSync(config) ? await JSON.parse(fs.readFileSync(config, 'utf8')) : null
if (!cfg) return
// browser
exec_path = cfg.browser.exec_path ? cfg.browser.exec_path : null
headless = cfg.browser.headless != null ? cfg.browser.headless : true
proxy_server = cfg.browser.proxy_server ? cfg.browser.proxy_server : "";
proxy_auth = cfg.browser.proxy_auth ? cfg.browser.proxy_auth : "";
// cookie
auth_token = cfg.cookie.auth_token ? cfg.cookie.auth_token : null
country_code = cfg.cookie.country_code ? cfg.cookie.country_code : "GB"
// twitch
game1 = cfg.twitch.game1 ? cfg.twitch.game1 : ""
game2 = cfg.twitch.game2 ? cfg.twitch.game2 : ""
game3 = cfg.twitch.game3 ? cfg.twitch.game3 : ""
to_watch = cfg.twitch.to_watch ? cfg.twitch.to_watch : null
streamheroes = cfg.twitch.streamheroes ? cfg.twitch.streamheroes : null
// api
client_id = cfg.api.client_id ? cfg.api.client_id : null
client_secret = cfg.api.client_secret ? cfg.api.client_secret : null
// misc
inactivity_sleep = !isNaN(cfg.misc.inactivity_sleep) ? cfg.misc.inactivity_sleep : 20
min_watchtime = !isNaN(cfg.misc.min_watchtime) ? cfg.misc.min_watchtime : 15
max_watchtime = !isNaN(cfg.misc.max_watchtime) ? cfg.misc.max_watchtime : 20
only_idle_fixed = cfg.misc.only_idle_fixed ? cfg.misc.only_idle_fixed : false
get_random_stream = cfg.misc.get_random_stream ? cfg.misc.get_random_stream : true
get_streamhero_stream = cfg.misc.get_streamhero_stream ? cfg.misc.get_streamhero_stream : false
new_watch_method = cfg.misc.new_watch_method ? cfg.misc.new_watch_method : true
new_watch_idle = !isNaN(cfg.misc.new_watch_idle) ? cfg.misc.new_watch_idle : 5
browser_config = {
"headless": headless,
"defaultViewport": null,
"ignoreHTTPSErrors": true,
"executablePath": exec_path,
"args": [
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
`--window-size=1320,1080`,
'--no-zygote',
'--disable-gpu',
'--no-sandbox',
'--disable-setuid-sandbox'
]
}
loc_cookie = [{
"domain": ".twitch.tv",
"hostOnly": false,
"httpOnly": false,
"name": "twitch.lohp.countryCode",
"path": "/",
"sameSite": "no_restriction",
"secure": false,
"session": false,
"storeId": "0",
"id": 1,
"value": country_code
}]
auth_cookie = [{
"domain": ".twitch.tv",
"hostOnly": false,
"httpOnly": false,
"name": "auth-token",
"path": "/",
"sameSite": "no_restriction",
"secure": true,
"session": false,
"storeId": "0",
"id": 1,
"value": auth_token
}]
}
UpdateConfigValues()
let PriceUpdateQueries = [
priceUpdateQueryEN = 'button[aria-label="Dismiss promo message"]',
priceUpdateQueryDE = 'button[aria-label="Aktionsnachricht ausblenden"]',
priceUpdateQueryES = 'button[aria-label="Descartar mensaje promocional"]',
priceUpdateQueryES2 = 'button[aria-label="Descartar mensaje de promoción"]',
priceUpdateQueryFR = 'button[aria-label="Faire disparaître le message promotionnel"]',
priceUpdateQueryIT = 'button[aria-label="Chiudi messaggio promozionale"]',
priceUpdateQueryPT = 'button[aria-label="Ignorar mensagem da promoção"]',
priceUpdateQueryPT2 = 'button[aria-label="Descartar mensagem promocional"]',
priceUpdateQueryTR = 'button[aria-label="Promosyon mesajı kapat"]',
priceUpdateQueryDK = 'button[aria-label="Afvis kampagnemeddelelse"]',
priceUpdateQueryHU = 'button[aria-label="Promóciós üzenet bezárása"]',
priceUpdateQueryNL = 'button[aria-label="Promotiebericht sluiten"]',
priceUpdateQueryPL = 'button[aria-label="Odrzuć komunikat promocyjny"]'
]
let subtemberQuery = 'button[aria-label="Close"]'
let cookiePolicyQuery = 'button[data-a-target="consent-banner-accept"]'
let matureContentQuery = 'button[data-a-target="player-overlay-mature-accept"]'
let matureContentQuery2 = '*[data-a-target="player-overlay-mature-accept"]'
let sidebarQuery = '*[data-test-selector="user-menu__toggle"]'
let userStatusQuery = 'span[data-a-target="presence-text"]'
let channelsQuery = 'a[data-test-selector*="ChannelLink"]'
let streamPauseQuery = 'button[data-a-target="player-play-pause-button"]'
let closeNotificationQuery = 'button[aria-label="Close"]'
let streamSettingsQuery = '[data-a-target="player-settings-button"]'
let streamQualitySettingQuery = '[data-a-target="player-settings-menu-item-quality"]'
let streamQualityQuery = 'input[data-a-target="tw-radio"]'
let categoryNotFoundQuery = '[data-a-target="core-error-message"]'
let dropButtonQuery = 'button[data-test-selector="DropsCampaignInProgressRewardPresentation-claim-button"]'
let dropClaimedQuery = 'p[data-test-selector="drops-message-bar-title"]'
let chatClaimQuery = '[data-test-selector="tw-core-button-label-text"]'
// spawn browser with predefined configuration
async function SpawnBrowser() {
if (first_run) {LogToConsole(`[${'●'.brightRed}] ${'BROWSER'.brightRed}`)}
await UpdateConfigValues()
try {
var browser = await puppeteer.launch(browser_config)
var page = await browser.newPage()
await page.setUserAgent(user_agent)
await page.setCookie(...auth_cookie)
await page.setCookie(...loc_cookie)
page.setDefaultNavigationTimeout(0)
page.setDefaultTimeout(0)
if (proxy_auth) {
await page.setExtraHTTPHeaders({
'Proxy-Authorization': 'Basic ' + Buffer.from(proxy_auth).toString('base64')
})
}
LogToConsole(`[${'+'.brightGreen}] Successfully set up the browser.`)
} catch (e) {
Exit("set up the browser", e)
}
return {
browser,
page
}
}
// Idle for x ms
function Idle(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function GetQuery(page, GetQuery) {
let bodyHTML = await page.evaluate(() => document.body.innerHTML)
let $ = cheerio.load(bodyHTML)
let jquery = $(GetQuery)
return jquery
}
async function GetUserProperty(page, name) {
if (!name || !(/^[A-Za-z1-9]+$/.test(name))) throw new Error("Invalid cookie name: ", name)
let data = await page.cookies()
let cookieValue = undefined
for (let i = 0; i < data.length; i++) {
if (data[i].name == 'twilight-user') {
cookieValue = JSON.parse(decodeURIComponent(data[i].value))
if (!cookieValue[name]) throw new Error("Invalid cookie value returned")
}
}
return cookieValue[name]
}
// if cookie 'twilight-user' exists, print username, if not set cookie again
async function CheckLogin(page) {
let cookieSetByServer = await page.cookies()
for (var i = 0; i < cookieSetByServer.length; i++) {
if (cookieSetByServer[i].name == 'twilight-user') {
let name = await GetUserProperty(page, 'displayName')
if (first_run) {
LogToConsole(`[${'+'.brightGreen}] Successfully logged in as ${name.bold.green}!`)
logged_in_as = name
}
return true
}
}
auth_cookie.value = auth_token
await Idle(250)
CheckLogin(page)
}
async function LiveChecker(who, silent) {
try {
if (!silent) LogToConsole(`[${'!'.brightYellow}] Checking if ${who.brightMagenta} is online!`)
let api_data = await streamdata.getData(who, client_id, api_auth_key)
if (api_data.length == 0) {
if (!silent) LogToConsole(`[${'i'.brightCyan}] ${who.brightMagenta} is ${'offline'.brightRed}!`)
return false
}
let live = await api_data["is_live"], live_game, is_game, stream_title, is_rerun
if (live) {
live_game = await api_data["game_name"]
stream_title = await api_data["title"].toLowerCase()
is_rerun = await (stream_title.includes("rerun") || stream_title.includes("re-run") || stream_title.includes("restream") || stream_title.includes("re-stream"))
is_game = (live_game.toUpperCase() == game1.toUpperCase() || live_game.toUpperCase() == game2.toUpperCase() || live_game.toUpperCase() == game3.toUpperCase())
} else {
if (!silent) LogToConsole(`[${'i'.brightCyan}] ${who.brightMagenta} is ${'offline'.brightRed}!`)
return false
}
if (live && is_game && !is_rerun) {
if (!silent) LogToConsole(`[${'i'.brightCyan}] ${who.brightMagenta} is ${'online'.brightGreen} and plays ${live_game.brightGreen}!`)
return true
} else if (live && !is_game && !is_rerun) {
if (streamheroes.includes(who)) {
if (!silent) LogToConsole(`[${'i'.brightCyan}] Stream-Hero ${who.brightMagenta} is ${'online'.brightGreen}!`)
return true
} else {
if (!silent) LogToConsole(`[${'i'.brightCyan}] ${who.brightMagenta} is ${'online'.brightGreen} and plays ${live_game.brightYellow}!`)
return false
}
}
} catch(e) {
throw e
}
}
async function GetAllStreamer(page) {
try {
streamers = null
streamers = new Array()
if (game1 != "") {
await page.goto(`https://www.twitch.tv/directory/game/` + game1.toUpperCase() + "?tl=c2542d6d-cd10-4532-919b-3d19f30a768b", {
"waitUntil": "networkidle0"
})
let notFound = await GetQuery(page, categoryNotFoundQuery)
if (notFound.length || notFound.text() == "Category does not exist") {
LogToConsole(`[${'-'.brightRed}] Game category not found, did you enter the game as displayed on twitch?`)
Exit()
}
await Scroll(page, scroll_times)
let jquery = await GetQuery(page, channelsQuery)
for (var i = 0; i < jquery.length; i++) {
streamers[i] = jquery[i].attribs.href.split("/")[1]
}
if (streamers.length > 0) {
LogToConsole(`[${'+'.brightGreen}] Got streamers for ${game1.brightCyan} and filtered them!`)
} else {
LogToConsole(`[${'!'.brightRed}] No streamer found for ${game1.brightCyan}!`)
await Idle(50)
if (game2 != "") {
await page.goto(`https://www.twitch.tv/directory/game/` + game2.toUpperCase() + "?tl=c2542d6d-cd10-4532-919b-3d19f30a768b", {
"waitUntil": "networkidle0"
})
let notFound = await GetQuery(page, categoryNotFoundQuery)
if (notFound.length || notFound.text() == "Category does not exist") {
LogToConsole(`[${'-'.brightRed}] Game category not found, did you enter the game as displayed on twitch?`)
Exit()
}
await Scroll(page, scroll_times)
let jquery = await GetQuery(page, channelsQuery)
for (var i = 0; i < jquery.length; i++) {
streamers[i] = jquery[i].attribs.href.split("/")[1]
}
if (streamers.length > 0) {
LogToConsole(`[${'+'.brightGreen}] Got streamers for ${game2.brightCyan} and filtered them!`)
} else {
LogToConsole(`[${'!'.brightRed}] No streamer found for ${game2.brightCyan}!`)
await Idle(50)
if (game3 != "") {
await page.goto(`https://www.twitch.tv/directory/game/` + game3.toUpperCase() + "?tl=c2542d6d-cd10-4532-919b-3d19f30a768b", {
"waitUntil": "networkidle0"
})
let notFound = await GetQuery(page, categoryNotFoundQuery)
if (notFound.length || notFound.text() == "Category does not exist") {
LogToConsole(`[${'-'.brightRed}] Game category not found, did you enter the game as displayed on twitch?`)
Exit()
}
await Scroll(page, scroll_times)
let jquery = await GetQuery(page, channelsQuery)
for (var i = 0; i < jquery.length; i++) {
streamers[i] = jquery[i].attribs.href.split("/")[1]
}
if (streamers.length > 0) {
LogToConsole(`[${'+'.brightGreen}] Got streamers for ${game3.brightCyan} and filtered them!`)
} else {
LogToConsole(`[${'!'.brightRed}] No streamer found for ${game3.brightCyan}!`)
}
}
}
}
}
}
return
} catch (e) {
Exit("get streamers/filter streamer.", e)
}
}
async function WatchStream(browser, page) {
LogToConsole(`[${'●'.brightRed}] ${'MAIN'.brightRed}`)
var streamerLastRefresh = DayJS().add(streamer_list_refresh, streamer_list_refresh_unit)
var browserLastRefresh = DayJS().add(browser_clean, browser_clean_unit)
await CheckLogin(page)
while (run) {
try {
await UpdateConfigValues()
await Idle(75)
await ClaimDrops(page)
if (api_auth_key == null) {
api_auth_key = await streamdata.getKey(client_id, client_secret)
}
let watch = null
if (to_watch.length > 0) {
for (var i = 0; i < to_watch.length; i++) {
let isLive = await LiveChecker(to_watch[i], false)
if (isLive) {
watch = to_watch[i]
break
}
watch = null
}
}
if (!only_idle_fixed) {
if (watch == null || watch == undefined) {
if (DayJS(browserLastRefresh).isBefore(DayJS())) {
var newSpawn = await Cleanup(browser, page)
browser = newSpawn.browser
page = newSpawn.page
first_run = true
browserLastRefresh = DayJS().add(browser_clean, browser_clean_unit)
}
if (get_random_stream) {
await GetAllStreamer(page)
if (streamers.length > 0 && streamers.length != undefined) {
LogToConsole(`[${'!'.brightYellow}] Getting random Streamer.`)
watch = streamers[GetRandomInt(0, streamers.length - 1)]
streamerLastRefresh = DayJS().add(streamer_list_refresh, streamer_list_refresh_unit)
}
}
if (get_streamhero_stream) {
if (watch == undefined && streamheroes.length > 0) {
LogToConsole(`[${'!'.brightYellow}] Getting Stream Heroes Streamer.`)
for (var i = 0; i < streamheroes.length; i++) {
let isLive = await LiveChecker(streamheroes[i], false)
if (isLive) {
watch = streamheroes[i]
break
}
watch = null
}
}
}
LogToConsole(`${('[#] Switching to ' + watch).gray}`)
page.goto(base_url + watch, { "waitUntil": "networkidle2", "timeout": 30000})
await Idle(1500)
}
}
if (!first_run) {
await CheckLogin(page)
ConsoleTitle(logged_in_as + " @ IdleTwitch v" + appversion + " | Drops collected: " + collected_drops + " | Last Drop: " + last_drop)
} else {
ConsoleTitle("NodeJS @ IdleTwitch v" + appversion + " | Drops collected: " + collected_drops + " | Last Drop: " + last_drop)
}
await Idle(50)
if (watch != null) {
await page.goto(base_url + watch, { "waitUntil": "networkidle2" })
await Idle(125)
for (let element of PriceUpdateQueries){
let accepted = await ClickWhenExist(page, element)
if (accepted) {break}
}
await ClickWhenExist(page, subtemberQuery)
await ClickWhenExist(page, cookiePolicyQuery)
await ClickWhenExist(page, matureContentQuery)
await Idle(25)
await ClickWhenExist(page, matureContentQuery2)
if (first_run) {
await ClickWhenExist(page, streamPauseQuery)
await ClickWhenExist(page, closeNotificationQuery)
await page.waitForSelector(streamSettingsQuery)
await ClickWhenExist(page, streamSettingsQuery)
await page.waitForSelector(streamQualitySettingQuery)
await ClickWhenExist(page, streamQualitySettingQuery)
await page.waitForSelector(streamQualityQuery)
await ClickWhenExist(page, closeNotificationQuery)
var resolution = await GetQuery(page, streamQualityQuery)
resolution = resolution[resolution.length - 1].attribs.id
await page.evaluate((resolution) => { document.getElementById(resolution).click() }, resolution)
LogToConsole(`[${'!'.brightYellow}] Lowest resolution set!`)
await ClickWhenExist(page, closeNotificationQuery)
await ClickWhenExist(page, streamPauseQuery)
await page.keyboard.press('m')
}
await Idle(35)
await page.keyboard.press('m')
await Idle(35)
await page.keyboard.press('m')
await ClickWhenExist(page, sidebarQuery)
await page.waitForSelector(userStatusQuery)
let status = await GetQuery(page, userStatusQuery)
await ClickWhenExist(page, sidebarQuery)
LogToConsole(`[${'i'.brightCyan}] Watching: ` + base_url + watch)
LogToConsole(`[${'i'.brightCyan}] Time: ` + DayJS().format('HH:mm:ss') + ' => ' + DayJS().add((20), 'minutes').format('HH:mm:ss'))
if (new_watch_method) {
let heartbeat, timestamp = DayJS()
while (watch) {
heartbeat = await LiveChecker(watch, true)
if (!heartbeat) {break}
if (DayJS().isAfter(timestamp.add(20, 'minute'))) {
LogToConsole(`[${'i'.brightCyan}] Idled for 20 minutes.`)
break
}
dropClaimedQuery = await ClickWhenExist(page, chatClaimQuery)
if (dropClaimedQuery) {
LogToConsole(`[${'i'.brightCyan}] Claimed a drop.`)
collected_drops++
}
await page.goto(base_url + watch, { "waitUntil": "networkidle2" })
await Idle(35)
await page.keyboard.press('m')
await Idle(35)
await page.keyboard.press('m')
await Idle(new_watch_idle*60000)
}
if (heartbeat !== null && heartbeat === false) {LogToConsole(`[${'i'.brightCyan}] Heartbeat failed`);}
}
if (first_run) {
first_run = false
}
} else {
LogToConsole(`[${'i'.brightCyan}] Idling for ` + inactivity_sleep + ' minutes => ' + DayJS().add((inactivity_sleep), 'minutes').format('HH:mm:ss') + '\n')
await page.waitForTimeout(inactivity_sleep*60000)
}
if (!new_watch_method) await page.waitForTimeout(inactivity_sleep*60000)
} catch (e) {
Exit("trying to watch a stream.", e)
}
}
}
// scroll current page, for x {times} and for x {scroll_delay} ms
async function Scroll(page, times) {
for (var i = 0; i < times; i++) {
try {
await page.evaluate(async () => {
var x = document.getElementsByClassName("scrollable-trigger__wrapper")
if (x[0] != undefined) {
x[0].scrollIntoView()
}
})
} catch (e) {
Exit("emulate scroll.", e)
}
await page.waitForTimeout(scroll_delay)
}
return
}
function GetRandomInt(min, max) {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
}
// check if element exists and click on it if it does
async function ClickWhenExist(page, selector) {
let result = await GetQuery(page, selector)
try {
if (result[0].type == 'tag' && result[0].name == 'button') {
await page.click(selector)
await page.waitForTimeout(250)
return true
}
} catch (e) {
await Idle(10)
return false
}
}
async function ClaimDrops(page) {
await page.goto(base_url + `drops/inventory/`, { "waitUntil": "networkidle2" })
let drops = await GetQuery(page, dropButtonQuery)
if (drops.length == 1) {
for (var i = 0; i < drops.length; i++) {
await ClickWhenExist(page, dropButtonQuery)
last_drop = DayJS().format('DD. MMM HH:mm:ss')
}
LogToConsole(`[${'i'.brightCyan}] ${'Claimed 1 drop.'.brightCyan}`)
} else if (drops.length >= 2) {
for (var i = 0; i < drops.length; i++) {
await ClickWhenExist(page, dropButtonQuery)
await Idle(2000)
}
LogToConsole(`[${'i'.brightCyan}] ${'Claimed ' + drops.length + ' drops.'.brightCyan}`)
last_drop = DayJS().format('DD. MMM HH:mm:ss')
} else {
await Idle(1000)
}
collected_drops = collected_drops + drops.length
return
}
//
async function Cleanup(browser, page) {
let pages = await browser.pages()
await pages.map((page) => page.close())
treekill(browser.process().pid, 'SIGKILL')
LogToConsole(`${'Respawning Browser'.gray}`)
process.removeAllListeners("exit")
process.removeAllListeners("SIGHUP")
process.removeAllListeners("SIGINT")
process.removeAllListeners("SIGTERM")
process.on("SIGINT", shutdown)
process.on("SIGTERM", shutdown)
return await SpawnBrowser()
}
// Exit function, to give error output to the end-user
async function Exit(msg = "", e = null) {
run = false
if (e && msg.length > 0) {
LogToConsole(`[${'-'.brightRed}] An error occured while trying to ${msg}(${e.name}: ${e.message.brightRed})`)
} else {
LogToConsole(`[${'-'.brightRed}] ERROR!`)
}
await Idle(5000)
run = true
//main()
}
function LogToConsole(msg) {
let now = DayJS().format("HH:mm:ss")
console.log("[" + now + "] " + msg)
return
}
// initialize main
async function main() {
console.clear()
LogToConsole("IdleTwitch v" + appversion.italic.brightGreen)
ConsoleTitle("NodeJS @ IdleTwitch v" + appversion)
try {
UpdateConfigValues()
var {
browser,
page
} = await SpawnBrowser()
/*page.on('requestfailed', request => {
if (request.failure() && request.failure().errorText == "net::ERR_ABORTED" || request.failure().errorText == "net::ERR_FAILED") return
LogToConsole(`${('[e] url: ' + request.url() + ', error: ' + request.failure().errorText + ', method: ' + request.method()).red}`)
})
// Catch console log errors
page.on("pageerror", err => {
LogToConsole(`${('[e] page error:' + err.toString()).red}`)
})*/
await Idle(420)
await WatchStream(browser, page)
} catch (e) {
Exit("initialize main.", e)
}
}
main()
// shutdown function
async function shutdown() {
LogToConsole("Exiting...")
run = false
process.Exit()
}
process.on("SIGINT", shutdown)
process.on("SIGTERM", shutdown)