-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
718 lines (623 loc) · 31.3 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
from datetime import datetime
import time
from colorama import Fore
import requests
import random
from fake_useragent import UserAgent
import asyncio
import json
import gzip
import brotli
import zlib
import chardet
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
class yescoin_white:
BASE_URL = "https://api.yesco.in/app.v1.AppService/"
HEADERS = {
"accept": "application/json, text/plain, */*",
"accept-encoding": "gzip, deflate, br, zstd",
"accept-language": "en-GB,en;q=0.9,en-US;q=0.8",
"origin": "https://miniapp.yesco.in",
"referer": "https://miniapp.yesco.in/",
"priority": "u=1, i",
"Content-Type": "application/json",
"connect-protocol-version": "1",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0",
"Referrer-Policy": "strict-origin-when-cross-origin"
}
def __init__(self):
self.query_list = self.load_query("query.txt")
self.token = None
self.config = self.load_config()
self.session = self.sessions()
self._original_requests = {
"get": requests.get,
"post": requests.post,
"put": requests.put,
"delete": requests.delete,
}
self.proxy_session = None
def banner(self) -> None:
"""Displays the banner for the bot."""
self.log("🎉 Yescoin White Bot", Fore.CYAN)
self.log("🚀 Created by LIVEXORDS", Fore.CYAN)
self.log("📢 Channel: t.me/livexordsscript\n", Fore.CYAN)
def log(self, message, color=Fore.RESET):
safe_message = message.encode("utf-8", "backslashreplace").decode("utf-8")
print(
Fore.LIGHTBLACK_EX
+ datetime.now().strftime("[%Y:%m:%d ~ %H:%M:%S] |")
+ " "
+ color
+ safe_message
+ Fore.RESET
)
def sessions(self):
session = requests.Session()
retries = Retry(total=3,
backoff_factor=1,
status_forcelist=[500, 502, 503, 504, 520])
session.mount('https://', HTTPAdapter(max_retries=retries))
return session
def load_config(self) -> dict:
"""
Loads configuration from config.json.
Returns:
dict: Configuration data or an empty dictionary if an error occurs.
"""
try:
with open("config.json", "r") as config_file:
config = json.load(config_file)
self.log("✅ Configuration loaded successfully.", Fore.GREEN)
return config
except FileNotFoundError:
self.log("❌ File not found: config.json", Fore.RED)
return {}
except json.JSONDecodeError:
self.log(
"❌ Failed to parse config.json. Please check the file format.",
Fore.RED,
)
return {}
def load_query(self, path_file: str = "query.txt") -> list:
"""
Loads a list of queries from the specified file.
Args:
path_file (str): The path to the query file. Defaults to "query.txt".
Returns:
list: A list of queries or an empty list if an error occurs.
"""
self.banner()
try:
with open(path_file, "r") as file:
queries = [line.strip() for line in file if line.strip()]
if not queries:
self.log(f"⚠️ Warning: {path_file} is empty.", Fore.YELLOW)
self.log(f"✅ Loaded {len(queries)} queries from {path_file}.", Fore.GREEN)
return queries
except FileNotFoundError:
self.log(f"❌ File not found: {path_file}", Fore.RED)
return []
except Exception as e:
self.log(f"❌ Unexpected error loading queries: {e}", Fore.RED)
return []
def decode_response(self, response):
"""
Mendekode response dari server secara umum.
Parameter:
response: objek requests.Response
Mengembalikan:
- Jika Content-Type mengandung 'application/json', maka mengembalikan objek Python (dict atau list) hasil parsing JSON.
- Jika bukan JSON, maka mengembalikan string hasil decode.
"""
# Ambil header
content_encoding = response.headers.get('Content-Encoding', '').lower()
content_type = response.headers.get('Content-Type', '').lower()
# Tentukan charset dari Content-Type, default ke utf-8
charset = 'utf-8'
if 'charset=' in content_type:
charset = content_type.split('charset=')[-1].split(';')[0].strip()
# Ambil data mentah
data = response.content
# Dekompresi jika perlu
try:
if content_encoding == 'gzip':
data = gzip.decompress(data)
elif content_encoding in ['br', 'brotli']:
data = brotli.decompress(data)
elif content_encoding in ['deflate', 'zlib']:
data = zlib.decompress(data)
except Exception:
# Jika dekompresi gagal, lanjutkan dengan data asli
pass
# Coba decode menggunakan charset yang didapat
try:
text = data.decode(charset)
except Exception:
# Fallback: deteksi encoding dengan chardet
detection = chardet.detect(data)
detected_encoding = detection.get("encoding", "utf-8")
text = data.decode(detected_encoding, errors='replace')
# Jika konten berupa JSON, kembalikan hasil parsing JSON
if 'application/json' in content_type:
try:
return json.loads(text)
except Exception:
# Jika parsing JSON gagal, kembalikan string hasil decode
return text
else:
return text
def login(self, index: int) -> None:
self.log("🔐 Attempting to log in...", Fore.GREEN)
if index >= len(self.query_list):
self.log("❌ Invalid login index. Please check again.", Fore.RED)
return
token = self.query_list[index]
self.log(f"📋 Using token: {token[:10]}... (truncated for security)", Fore.CYAN)
# API: Get Status
status_url = f"{self.BASE_URL}GetStatus"
headers = {**self.HEADERS, "telegram-webappinitdata": token}
payload = json.dumps({}) # Payload kosong
try:
self.log("📡 Sending status request...", Fore.CYAN)
status_response = requests.post(status_url, headers=headers, data=payload)
status_response.raise_for_status()
status_data = self.decode_response(status_response)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to send status request: {e}", Fore.RED)
try:
self.log(f"📄 Response content: {status_response.text}", Fore.RED)
except Exception:
pass
return
except Exception as e:
self.log(f"❌ Unexpected error during status request: {e}", Fore.RED)
try:
self.log(f"📄 Response content: {status_response.text}", Fore.RED)
except Exception:
pass
return
# Proses respons yang diharapkan: {"username": "LIVEXORDS", "coins": "263"}
try:
username = status_data.get("username", "N/A")
coins = status_data.get("coins", "N/A")
self.log("✅ Status request successful!", Fore.GREEN)
self.log("👤 User Info:", Fore.GREEN)
self.log(f" - Username: {username}", Fore.CYAN)
self.log(f" - Coins: {coins}", Fore.CYAN)
self.token = token
except Exception as e:
self.log(f"❌ Error processing status response: {e}", Fore.RED)
return
def taps(self) -> None:
# Define headers with telegram-webappinitdata using the token
headers = {**self.HEADERS, "telegram-webappinitdata": self.token}
# API: GetTapStatus to get the initial energy
get_tap_status_url = f"{self.BASE_URL}GetTapStatus"
empty_payload = json.dumps({})
try:
self.log("📡 Sending initial GetTapStatus request...", Fore.CYAN)
tap_status_response = requests.post(get_tap_status_url, headers=headers, data=empty_payload)
tap_status_response.raise_for_status()
tap_status_data = self.decode_response(tap_status_response)
current_energy = tap_status_data.get("energy")
if current_energy is None:
self.log("❌ Energy value not found in GetTapStatus response.", Fore.RED)
return
self.log(f"✅ Initial energy: {current_energy}", Fore.GREEN)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to send initial GetTapStatus request: {e}", Fore.RED)
return
except Exception as e:
self.log(f"❌ Unexpected error during initial GetTapStatus: {e}", Fore.RED)
return
# Start a timer for 2 minutes (120 seconds)
start_time = time.time()
timeout = 120 # seconds
# Loop: Send ValidateTaps requests until energy runs out or time is up
validate_taps_url = f"{self.BASE_URL}ValidateTaps"
while True:
# Cek apakah timer 2 menit sudah habis
if time.time() - start_time >= timeout:
self.log("⏱️ Timer reached 2 minutes. Stopping the farming process.", Fore.YELLOW)
break
# Jika energy sudah habis, keluar dari loop
try:
# Pastikan current_energy adalah angka
current_energy = float(current_energy)
except Exception as e:
self.log(f"❌ Error converting energy to float: {current_energy} ({e})", Fore.RED)
break
if current_energy <= 0:
self.log("ℹ️ Energy depleted. Stopping the farming process.", Fore.YELLOW)
break
# Determine the number of taps to send: 20 atau sisa energy jika kurang dari 20
taps_to_send = 20 if current_energy >= 20 else int(current_energy)
payload_validate = json.dumps({"count": taps_to_send})
try:
self.log(f"📡 Sending ValidateTaps request with count: {taps_to_send}...", Fore.CYAN)
validate_response = requests.post(validate_taps_url, headers=headers, data=payload_validate)
validate_response.raise_for_status()
validate_data = self.decode_response(validate_response)
coins = validate_data.get("coins", "N/A")
energy_after = validate_data.get("energy", "N/A")
self.log("✅ ValidateTaps successful!", Fore.GREEN)
self.log(f" - Coins: {coins}", Fore.CYAN)
self.log(f" - Energy After Taps: {energy_after}", Fore.CYAN)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to send ValidateTaps request: {e}", Fore.RED)
try:
self.log(f"📄 Response content: {validate_response.text}", Fore.RED)
except Exception:
pass
break
except Exception as e:
self.log(f"❌ Unexpected error during ValidateTaps request: {e}", Fore.RED)
break
# Update current_energy from the ValidateTaps response
try:
# Mengonversi energy_after ke float agar bisa menangani nilai float maupun int
current_energy = float(energy_after)
except Exception as e:
self.log("❌ Invalid energy value received, stopping farming.", Fore.RED)
break
# Setelah energy habis atau waktu habis, re-check energy via GetTapStatus
try:
self.log("📡 Re-checking energy via GetTapStatus...", Fore.CYAN)
final_response = requests.post(get_tap_status_url, headers=headers, data=empty_payload)
final_response.raise_for_status()
final_data = self.decode_response(final_response)
final_energy = final_data.get("energy", "N/A")
self.log(f"✅ Final energy: {final_energy}", Fore.GREEN)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to re-check energy via GetTapStatus: {e}", Fore.RED)
try:
self.log(f"📄 Response content: {final_response.text}", Fore.RED)
except Exception:
pass
except Exception as e:
self.log(f"❌ Unexpected error during re-checking energy: {e}", Fore.RED)
def task(self) -> None:
# Define headers with telegram-webappinitdata using the token
headers = {**self.HEADERS, "telegram-webappinitdata": self.token}
# API: GetCampaigns to retrieve active campaigns and tasks
get_campaigns_url = f"{self.BASE_URL}GetCampaigns"
empty_payload = json.dumps({})
try:
self.log("📡 Sending GetCampaigns request...", Fore.CYAN)
campaigns_response = requests.post(get_campaigns_url, headers=headers, data=empty_payload)
campaigns_response.raise_for_status()
campaigns_data = self.decode_response(campaigns_response)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to get campaigns: {e}", Fore.RED)
return
except Exception as e:
self.log(f"❌ Unexpected error during GetCampaigns request: {e}", Fore.RED)
return
# Aggregate all tasks from activeTasks and activeCampaigns (inside their sections)
tasks = []
# Add tasks from activeTasks
active_tasks = campaigns_data.get("activeTasks", [])
for t in active_tasks:
tasks.append(t)
# Add tasks from each active campaign's sections
active_campaigns = campaigns_data.get("activeCampaigns", [])
for campaign in active_campaigns:
sections = campaign.get("sections", [])
for section in sections:
for t in section.get("tasks", []):
tasks.append(t)
self.log(f"✅ Retrieved {len(tasks)} tasks.", Fore.GREEN)
# PHASE 1: Start all tasks
start_task_url = f"{self.BASE_URL}StartTask"
for t in tasks:
task_id = t.get("id")
if not task_id:
continue
payload = json.dumps({"id": task_id})
try:
self.log(f"📡 Starting task {task_id}...", Fore.CYAN)
start_response = requests.post(start_task_url, headers=headers, data=payload)
start_response.raise_for_status()
start_data = self.decode_response(start_response)
# Use the 'code' field if present; otherwise fallback to HTTP response status code.
status_code = start_data.get("code")
if not status_code:
status_code = start_response.status_code
self.log(f"✅ StartTask response for {task_id}: Code: {status_code}", Fore.GREEN)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to start task {task_id}: {e}", Fore.RED)
except Exception as e:
self.log(f"❌ Unexpected error while starting task {task_id}: {e}", Fore.RED)
# PHASE 2: Validate all tasks
validate_task_url = f"{self.BASE_URL}ValidateTask"
for t in tasks:
task_id = t.get("id")
if not task_id:
continue
payload = json.dumps({"id": task_id})
try:
self.log(f"📡 Validating task {task_id}...", Fore.CYAN)
validate_response = requests.post(validate_task_url, headers=headers, data=payload)
validate_response.raise_for_status()
validate_data = self.decode_response(validate_response)
# Use the 'code' field if available; otherwise fallback to HTTP response status code.
status_code = validate_data.get("code")
if not status_code:
status_code = validate_response.status_code
self.log(f"✅ ValidateTask response for {task_id}: Code: {status_code}", Fore.GREEN)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to validate task {task_id}: {e}", Fore.RED)
except Exception as e:
self.log(f"❌ Unexpected error while validating task {task_id}: {e}", Fore.RED)
def wheel(self) -> None:
# Define headers with telegram-webappinitdata using the token
headers = {**self.HEADERS, "telegram-webappinitdata": self.token}
get_wheel_status_url = f"{self.BASE_URL}GetWheelOfFortuneStatus"
spin_wheel_url = f"{self.BASE_URL}SpinWheelOfFortune"
empty_payload = json.dumps({}) # Payload kosong untuk request status
spin_payload = json.dumps({"spins": 1}) # Payload untuk setiap spin
while True:
# Request status wheel untuk mendapatkan availableSpins
try:
self.log("📡 Requesting Wheel of Fortune status...", Fore.CYAN)
status_response = requests.post(get_wheel_status_url, headers=headers, data=empty_payload)
status_response.raise_for_status()
status_data = self.decode_response(status_response)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to get Wheel of Fortune status: {e}", Fore.RED)
return
except Exception as e:
self.log(f"❌ Unexpected error during GetWheelOfFortuneStatus: {e}", Fore.RED)
return
available_spins = status_data.get("availableSpins", 0)
if available_spins is None:
self.log("❌ availableSpins not found in response", Fore.RED)
return
self.log(f"✅ Available spins: {available_spins}", Fore.GREEN)
if available_spins <= 0:
self.log("ℹ️ No spins remaining. Exiting.", Fore.YELLOW)
break
# Lakukan spin sebanyak available_spins yang didapat
for i in range(available_spins):
try:
self.log(f"📡 Spinning the wheel (spin {i+1})...", Fore.CYAN)
spin_response = requests.post(spin_wheel_url, headers=headers, data=spin_payload)
spin_response.raise_for_status()
spin_data = self.decode_response(spin_response)
prizes = spin_data.get("prizes", [])
self.log(f"✅ Spin {i+1} prizes: {prizes}", Fore.GREEN)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to spin the wheel (spin {i+1}): {e}", Fore.RED)
except Exception as e:
self.log(f"❌ Unexpected error while spinning the wheel (spin {i+1}): {e}", Fore.RED)
def upgrade(self) -> None:
# Define headers with telegram-webappinitdata using the token
headers = {**self.HEADERS, "telegram-webappinitdata": self.token}
get_boosts_url = f"{self.BASE_URL}GetBoosts"
get_status_url = f"{self.BASE_URL}GetStatus"
buy_boost_url = f"{self.BASE_URL}BuyNextBoostLevel"
empty_payload = json.dumps({}) # Payload kosong untuk request status/boosts
upgrade_payload_template = lambda upgrade_type: json.dumps({"type": upgrade_type, "withRockets": True})
while True:
# Request data boosts
try:
self.log("📡 Requesting Boosts status...", Fore.CYAN)
boosts_response = requests.post(get_boosts_url, headers=headers, data=empty_payload)
boosts_response.raise_for_status()
boosts_data = self.decode_response(boosts_response)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to get boosts: {e}", Fore.RED)
return
except Exception as e:
self.log(f"❌ Unexpected error during GetBoosts: {e}", Fore.RED)
return
# Request data status user untuk ambil rockets
try:
self.log("📡 Requesting user status...", Fore.CYAN)
status_response = requests.post(get_status_url, headers=headers, data=empty_payload)
status_response.raise_for_status()
status_data = self.decode_response(status_response)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to get user status: {e}", Fore.RED)
return
except Exception as e:
self.log(f"❌ Unexpected error during GetStatus: {e}", Fore.RED)
return
rockets = status_data.get("rockets")
if rockets is None:
self.log("❌ 'rockets' not found in user status response", Fore.RED)
return
try:
# Mengonversi ke float agar bisa mengelola tipe data numerik (int atau float)
rockets = float(rockets)
except Exception as e:
self.log(f"❌ Invalid rockets value: {rockets} ({e})", Fore.RED)
return
self.log(f"✅ User rockets: {rockets}", Fore.GREEN)
upgrade_done = False # Flag untuk mengecek apakah ada upgrade yang dilakukan pada iterasi ini
# Daftar upgrade yang akan diproses (abaikan upgrade Tapbot)
upgrades = [
("TYPE_MULTITAP", "nextMultitapLevelRocketsPrice"),
("TYPE_RECHARGING_SPEED", "nextRechargingSpeedLevelRocketsPrice"),
("TYPE_ENERGY_LIMIT", "nextEnergyLimitLevelRocketsPrice")
]
for upgrade_type, price_key in upgrades:
price = boosts_data.get(price_key)
if price is None:
self.log(f"❌ {price_key} not found in boosts data", Fore.RED)
continue
try:
price = float(price)
except Exception as e:
self.log(f"❌ Invalid price for {upgrade_type}: {price} ({e})", Fore.RED)
continue
if rockets >= price:
payload = upgrade_payload_template(upgrade_type)
try:
self.log(f"📡 Upgrading {upgrade_type} (cost: {price} rockets, available: {rockets})...", Fore.CYAN)
buy_response = requests.post(buy_boost_url, headers=headers, data=payload)
buy_response.raise_for_status()
# Response kosong, jadi andalkan log dan GetStatus untuk cek update
self.log(f"✅ Upgrade {upgrade_type} successful.", Fore.GREEN)
upgrade_done = True
# Setelah upgrade, break untuk merefresh data boosts dan status
break
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to upgrade {upgrade_type}: {e}", Fore.RED)
except Exception as e:
self.log(f"❌ Unexpected error while upgrading {upgrade_type}: {e}", Fore.RED)
else:
self.log(f"ℹ️ Not enough rockets for {upgrade_type} (required: {price}, available: {rockets}).", Fore.YELLOW)
if not upgrade_done:
self.log("ℹ️ No more upgrades possible with current rockets. Exiting upgrade loop.", Fore.YELLOW)
break
def load_proxies(self, filename="proxy.txt"):
"""
Reads proxies from a file and returns them as a list.
Args:
filename (str): The path to the proxy file.
Returns:
list: A list of proxy addresses.
"""
try:
with open(filename, "r", encoding="utf-8") as file:
proxies = [line.strip() for line in file if line.strip()]
if not proxies:
raise ValueError("Proxy file is empty.")
return proxies
except Exception as e:
self.log(f"❌ Failed to load proxies: {e}", Fore.RED)
return []
def set_proxy_session(self, proxies: list) -> requests.Session:
"""
Creates a requests session with a working proxy from the given list.
If a chosen proxy fails the connectivity test, it will try another proxy
until a working one is found. If no proxies work or the list is empty, it
will return a session with a direct connection.
Args:
proxies (list): A list of proxy addresses (e.g., "http://proxy_address:port").
Returns:
requests.Session: A session object configured with a working proxy,
or a direct connection if none are available.
"""
# If no proxies are provided, use a direct connection.
if not proxies:
self.log("⚠️ No proxies available. Using direct connection.", Fore.YELLOW)
self.proxy_session = requests.Session()
return self.proxy_session
# Copy the list so that we can modify it without affecting the original.
available_proxies = proxies.copy()
while available_proxies:
proxy_url = random.choice(available_proxies)
self.proxy_session = requests.Session()
self.proxy_session.proxies = {"http": proxy_url, "https": proxy_url}
try:
test_url = "https://httpbin.org/ip"
response = self.proxy_session.get(test_url, timeout=5)
response.raise_for_status()
origin_ip = response.json().get("origin", "Unknown IP")
self.log(
f"✅ Using Proxy: {proxy_url} | Your IP: {origin_ip}", Fore.GREEN
)
return self.proxy_session
except requests.RequestException as e:
self.log(f"❌ Proxy failed: {proxy_url} | Error: {e}", Fore.RED)
# Remove the failed proxy and try again.
available_proxies.remove(proxy_url)
# If none of the proxies worked, use a direct connection.
self.log("⚠️ All proxies failed. Using direct connection.", Fore.YELLOW)
self.proxy_session = requests.Session()
return self.proxy_session
def override_requests(self):
import random
"""Override requests functions globally when proxy is enabled."""
if self.config.get("proxy", False):
self.log("[CONFIG] 🛡️ Proxy: ✅ Enabled", Fore.YELLOW)
proxies = self.load_proxies()
self.set_proxy_session(proxies)
# Override request methods
requests.get = self.proxy_session.get
requests.post = self.proxy_session.post
requests.put = self.proxy_session.put
requests.delete = self.proxy_session.delete
else:
self.log("[CONFIG] proxy: ❌ Disabled", Fore.RED)
# Restore original functions if proxy is disabled
requests.get = self._original_requests["get"]
requests.post = self._original_requests["post"]
requests.put = self._original_requests["put"]
requests.delete = self._original_requests["delete"]
async def process_account(account, original_index, account_label, yes, config):
# Menampilkan informasi akun
display_account = account[:10] + "..." if len(account) > 10 else account
yes.log(f"👤 Processing {account_label}: {display_account}", Fore.YELLOW)
# Override proxy jika diaktifkan
if config.get("proxy", False):
yes.override_requests()
else:
yes.log("[CONFIG] Proxy: ❌ Disabled", Fore.RED)
# Login (fungsi blocking, dijalankan di thread terpisah) dengan menggunakan index asli (integer)
await asyncio.to_thread(yes.login, original_index)
yes.log("🛠️ Starting task execution...", Fore.CYAN)
tasks_config = {
"task": "Automatically solving tasks 🤖",
"taps": "Automatically executing taps for energy accumulation ⚡",
"wheel": "Automatically spinning the wheel of fortune 🎡",
"upgrade": "Automatically upgrading boosts using rockets 🚀"
}
for task_key, task_name in tasks_config.items():
task_status = config.get(task_key, False)
color = Fore.YELLOW if task_status else Fore.RED
yes.log(f"[CONFIG] {task_name}: {'✅ Enabled' if task_status else '❌ Disabled'}", color)
if task_status:
yes.log(f"🔄 Executing {task_name}...", Fore.CYAN)
await asyncio.to_thread(getattr(yes, task_key))
delay_switch = config.get("delay_account_switch", 10)
yes.log(f"➡️ Finished processing {account_label}. Waiting {Fore.WHITE}{delay_switch}{Fore.CYAN} seconds before next account.", Fore.CYAN)
await asyncio.sleep(delay_switch)
async def worker(worker_id, yes, config, queue):
"""
Setiap worker akan mengambil satu akun dari antrian dan memprosesnya secara berurutan.
Worker tidak akan mengambil akun baru sebelum akun sebelumnya selesai diproses.
"""
while True:
try:
original_index, account = queue.get_nowait()
except asyncio.QueueEmpty:
break
account_label = f"Worker-{worker_id} Account-{original_index+1}"
await process_account(account, original_index, account_label, yes, config)
queue.task_done()
yes.log(f"Worker-{worker_id} finished processing all assigned accounts.", Fore.CYAN)
async def main():
yes = yescoin_white() # Inisialisasi instance class yescoin_white Anda
config = yes.load_config()
all_accounts = yes.query_list
num_threads = config.get("thread", 1) # Jumlah worker sesuai konfigurasi
if config.get("proxy", False):
proxies = yes.load_proxies()
yes.log("🎉 [LIVEXORDS] === Welcome to Yescoin White Automation === [LIVEXORDS]", Fore.YELLOW)
yes.log(f"📂 Loaded {len(all_accounts)} accounts from query list.", Fore.YELLOW)
while True:
# Buat queue baru dan masukkan semua akun (dengan index asli)
queue = asyncio.Queue()
for idx, account in enumerate(all_accounts):
queue.put_nowait((idx, account))
# Buat task worker sesuai dengan jumlah thread yang diinginkan
workers = [asyncio.create_task(worker(i+1, yes, config, queue)) for i in range(num_threads)]
# Tunggu hingga semua akun di queue telah diproses
await queue.join()
# Opsional: batalkan task worker (agar tidak terjadi tumpang tindih)
for w in workers:
w.cancel()
yes.log("🔁 All accounts processed. Restarting loop.", Fore.CYAN)
delay_loop = config.get("delay_loop", 30)
yes.log(f"⏳ Sleeping for {Fore.WHITE}{delay_loop}{Fore.CYAN} seconds before restarting.", Fore.CYAN)
await asyncio.sleep(delay_loop)
if __name__ == "__main__":
asyncio.run(main())