-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
1999 lines (1804 loc) · 107 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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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 animix:
BASE_URL = "https://pro-api.animix.tech/public/"
HEADERS = {
"accept": "*/*",
"accept-encoding": "gzip, deflate, br, zstd",
"accept-language": "en-GB,en;q=0.9,en-US;q=0.8",
"origin": "https://tele-game.animix.tech",
"priority": "u=1, i",
"referer": "https://tele-game.animix.tech/",
"sec-ch-ua": '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24", "Microsoft Edge WebView2";v="131"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
}
def __init__(self):
self.config = self.load_config()
self.query_list = self.load_query("query.txt")
self.token = None
self.token_reguler = 0
self.token_super = 0
self.premium_user = False
self._original_requests = {
"get": requests.get,
"post": requests.post,
"put": requests.put,
"delete": requests.delete,
}
self.proxy_session = None
self.session = self.sessions()
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 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 banner(self) -> None:
"""Displays the banner for the bot."""
self.log("🎉 Animix 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 load_config(self) -> dict:
"""Loads configuration from config.json."""
try:
with open("config.json", "r") as config_file:
return json.load(config_file)
except FileNotFoundError:
self.log("❌ File config.json not found!", Fore.RED)
return {}
except json.JSONDecodeError:
self.log("❌ Error reading config.json!", Fore.RED)
return {}
def load_query(self, path_file="query.txt") -> list:
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.", Fore.GREEN)
return queries
except FileNotFoundError:
self.log(f"❌ File not found: {path_file}", Fore.RED)
return []
except Exception as e:
self.log(f"❌ Error loading queries: {e}", Fore.RED)
return []
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
req_url = f"{self.BASE_URL}user/info"
token = self.query_list[index]
self.log(
f"📋 Using token: {token[:10]}... (truncated for security)",
Fore.CYAN,
)
headers = {**self.HEADERS, "Tg-Init-Data": token}
try:
self.log("📡 Sending request to fetch user information...", Fore.CYAN)
response = requests.get(req_url, headers=headers)
response.raise_for_status()
data = self.decode_response(response)
if "result" in data:
user_info = data["result"]
username = user_info.get("telegram_username", "Unknown")
balance = user_info.get("token", 0)
self.balance = (
int(balance)
if isinstance(balance, (int, str)) and str(balance).isdigit()
else 0
)
self.token = token
self.premium_user = user_info.get("is_premium", False)
self.log("✅ Login successful!", Fore.GREEN)
self.log(f"👤 Username: {username}", Fore.LIGHTGREEN_EX)
self.log(f"💰 Balance: {self.balance}", Fore.CYAN)
inventory = user_info.get("inventory", [])
token_reguler = next(
(item for item in inventory if item["id"] == 1), None
)
token_super = next(
(item for item in inventory if item["id"] == 3), None
)
if token_reguler:
self.log(
f"💵 Regular Token: {token_reguler['amount']}",
Fore.LIGHTBLUE_EX,
)
self.token_reguler = token_reguler["amount"]
else:
self.log("💵 Regular Token: 0", Fore.LIGHTBLUE_EX)
if token_super:
self.log(
f"💸 Super Token: {token_super['amount']}", Fore.LIGHTBLUE_EX
)
self.token_super = token_super["amount"]
else:
self.log("💸 Super Token: 0", Fore.LIGHTBLUE_EX)
# Mekanik baru: Kelola clan
clan_id = user_info.get("clan_id")
if clan_id:
if clan_id == 4556:
self.log(
"🔄 Already in clan 4556. No action needed.", Fore.CYAN
)
else:
self.log(
f"🔄 Detected existing clan membership (clan_id: {clan_id}). Attempting to quit current clan...",
Fore.CYAN,
)
quit_payload = {"clan_id": clan_id}
try:
quit_response = requests.post(
f"{self.BASE_URL}clan/quit",
headers=headers,
json=quit_payload,
)
quit_response.raise_for_status()
self.log("✅ Successfully quit previous clan.", Fore.GREEN)
except Exception as e:
self.log(f"❌ Failed to quit clan: {e}", Fore.RED)
self.log("🔄 Attempting to join clan 4556...", Fore.CYAN)
join_payload = {"clan_id": 4556}
try:
join_response = requests.post(
f"{self.BASE_URL}clan/join",
headers=headers,
json=join_payload,
)
join_response.raise_for_status()
self.log("✅ Successfully joined clan 4556.", Fore.GREEN)
except Exception as e:
self.log(f"❌ Failed to join clan: {e}", Fore.RED)
else:
self.log(
"ℹ️ No existing clan membership detected. Proceeding to join clan...",
Fore.CYAN,
)
join_payload = {"clan_id": 4556}
try:
join_response = requests.post(
f"{self.BASE_URL}clan/join",
headers=headers,
json=join_payload,
)
join_response.raise_for_status()
self.log("✅ Successfully joined clan 4556.", Fore.GREEN)
except Exception as e:
self.log(f"❌ Failed to join clan: {e}", Fore.RED)
else:
self.log("⚠️ Unexpected response structure.", Fore.YELLOW)
except requests.exceptions.RequestException as e:
self.log(f"❌ Failed to send login request: {e}", Fore.RED)
except ValueError as e:
self.log(f"❌ Data error (possible JSON issue): {e}", Fore.RED)
except KeyError as e:
self.log(f"❌ Key error: {e}", Fore.RED)
except Exception as e:
self.log(f"❌ Unexpected error: {e}", Fore.RED)
def gacha(self) -> None:
headers = {**self.HEADERS, "Tg-Init-Data": self.token}
# =================== REGULAR GACHA PROCESS ===================
if self.token_reguler > 0:
bonus_check_url_reg = f"{self.BASE_URL}pet/dna/gacha/bonus?is_super=False"
try:
bonus_response_reg = requests.get(bonus_check_url_reg, headers=headers)
if bonus_response_reg is None or bonus_response_reg.status_code != 200:
self.log("⚠️ Failed to retrieve regular bonus data.", Fore.YELLOW)
else:
bonus_data_reg = self.decode_response(bonus_response_reg) if bonus_response_reg.text else {}
if bonus_data_reg and "result" in bonus_data_reg:
bonus_result = bonus_data_reg["result"]
current_step = bonus_result.get("current_step", 0)
total_step = bonus_result.get("total_step", 200)
if current_step >= total_step:
self.log("✅ Regular bonus threshold reached. No regular gacha needed.", Fore.CYAN)
else:
missing_spins = total_step - current_step
spins_to_do = min(missing_spins, self.token_reguler)
self.log(f"🎲 Initiating {spins_to_do} regular gacha spin(s) (missing {missing_spins} spins for bonus)!", Fore.CYAN)
for i in range(spins_to_do):
req_url = f"{self.BASE_URL}pet/dna/gacha"
payload = {"amount": 1, "is_super": False}
try:
response = requests.post(req_url, headers=headers, json=payload)
if response is None or response.status_code != 200:
self.log("⚠️ Invalid response from regular gacha spin. Skipping spin.", Fore.YELLOW)
continue
data = self.decode_response(response) if response.text else {}
if not data:
self.log("⚠️ Empty JSON response from regular gacha spin.", Fore.YELLOW)
continue
if "result" in data and "dna" in data["result"]:
dna = data["result"]["dna"]
if isinstance(dna, list):
self.log("🎉 You received multiple DNA items (Regular)!", Fore.GREEN)
for dna_item in dna:
name = dna_item.get("name", "Unknown")
dna_class = dna_item.get("class", "Unknown")
star = dna_item.get("star", "Unknown")
self.log(f"🧬 Name: {name}", Fore.LIGHTGREEN_EX)
self.log(f"🏷️ Class: {dna_class}", Fore.YELLOW)
self.log(f"⭐ Star: {star}", Fore.MAGENTA)
else:
name = dna.get("name", "Unknown") if dna else "Unknown"
dna_class = dna.get("class", "Unknown") if dna else "Unknown"
star = dna.get("star", "Unknown") if dna else "Unknown"
self.log("🎉 You received a DNA item (Regular)!", Fore.GREEN)
self.log(f"🧬 Name: {name}", Fore.LIGHTGREEN_EX)
self.log(f"🏷️ Class: {dna_class}", Fore.YELLOW)
self.log(f"⭐ Star: {star}", Fore.MAGENTA)
# Update token_reguler berdasarkan respon gacha
self.token_reguler = data["result"].get("god_power", self.token_reguler)
else:
self.log("⚠️ Regular gacha response structure is invalid.", Fore.RED)
continue
except Exception as e:
self.log(f"❌ Error during regular gacha spin: {e}", Fore.RED)
continue
else:
self.log("⚠️ Regular bonus data is invalid.", Fore.YELLOW)
except Exception as e:
self.log(f"❌ Error during regular bonus check: {e}", Fore.RED)
else:
self.log("🚫 No regular tokens available for gacha.", Fore.RED)
# =================== SUPER GACHA PROCESS ===================
if self.token_super > 0:
bonus_check_url_super = f"{self.BASE_URL}pet/dna/gacha/bonus?is_super=True"
try:
bonus_response = requests.get(bonus_check_url_super, headers=headers)
if bonus_response is None or bonus_response.status_code != 200:
self.log("⚠️ Failed to retrieve super bonus data.", Fore.YELLOW)
else:
bonus_data = self.decode_response(bonus_response) if bonus_response.text else {}
if bonus_data and "result" in bonus_data:
bonus_result = bonus_data["result"]
current_step = bonus_result.get("current_step", 0)
total_step = bonus_result.get("total_step", 200)
if current_step >= total_step:
self.log("✅ Super bonus threshold reached. No super gacha needed.", Fore.CYAN)
else:
missing_spins = total_step - current_step
spins_to_do = min(missing_spins, self.token_super)
self.log(f"🎲 Initiating {spins_to_do} super gacha spin(s) (missing {missing_spins} spins for bonus)!", Fore.CYAN)
for i in range(spins_to_do):
req_url = f"{self.BASE_URL}pet/dna/gacha"
payload = {"amount": 1, "is_super": True}
try:
response = requests.post(req_url, headers=headers, json=payload)
if response is None or response.status_code != 200:
self.log("⚠️ Invalid response from super gacha spin. Skipping spin.", Fore.YELLOW)
continue
data = self.decode_response(response) if response.text else {}
if not data:
self.log("⚠️ Empty JSON response from super gacha spin.", Fore.YELLOW)
continue
if "result" in data and "dna" in data["result"]:
dna = data["result"]["dna"]
if isinstance(dna, list):
self.log("🎉 You received multiple DNA items (Super)!", Fore.GREEN)
for dna_item in dna:
name = dna_item.get("name", "Unknown")
dna_class = dna_item.get("class", "Unknown")
star = dna_item.get("star", "Unknown")
self.log(f"🧬 Name: {name}", Fore.LIGHTGREEN_EX)
self.log(f"🏷️ Class: {dna_class}", Fore.YELLOW)
self.log(f"⭐ Star: {star}", Fore.MAGENTA)
else:
name = dna.get("name", "Unknown") if dna else "Unknown"
dna_class = dna.get("class", "Unknown") if dna else "Unknown"
star = dna.get("star", "Unknown") if dna else "Unknown"
self.log("🎉 You received a DNA item (Super)!", Fore.GREEN)
self.log(f"🧬 Name: {name}", Fore.LIGHTGREEN_EX)
self.log(f"🏷️ Class: {dna_class}", Fore.YELLOW)
self.log(f"⭐ Star: {star}", Fore.MAGENTA)
self.token_super = data["result"].get("god_power", self.token_super)
else:
self.log("⚠️ Super gacha response structure is invalid.", Fore.RED)
continue
except Exception as e:
self.log(f"❌ Error during super gacha spin: {e}", Fore.RED)
continue
else:
self.log("⚠️ Super bonus data is invalid.", Fore.YELLOW)
except Exception as e:
self.log(f"❌ Failed during super bonus check: {e}", Fore.RED)
else:
self.log("🚫 No super tokens available for gacha.", Fore.RED)
# BONUS CLAIM: REGULAR GACHA BONUS
try:
bonus_check_url_reg = f"{self.BASE_URL}pet/dna/gacha/bonus?is_super=False"
bonus_response_reg = requests.get(bonus_check_url_reg, headers=headers)
if bonus_response_reg is None or bonus_response_reg.status_code != 200:
self.log("⚠️ Regular bonus check response is invalid.", Fore.YELLOW)
else:
bonus_data_reg = self.decode_response(bonus_response_reg) if bonus_response_reg.text else {}
if bonus_data_reg and "result" in bonus_data_reg:
bonus_result = bonus_data_reg["result"]
current_step = bonus_result.get("current_step", 0)
total_step = bonus_result.get("total_step", 200)
if current_step >= total_step:
rewards_to_claim = []
if not bonus_result.get("is_claimed_god_power", False):
rewards_to_claim.append(1)
if not bonus_result.get("is_claimed_dna", False):
rewards_to_claim.append(2)
for reward_no in rewards_to_claim:
claim_url = f"{self.BASE_URL}pet/dna/gacha/bonus/claim"
claim_payload = {"reward_no": reward_no, "is_super": False}
self.log(f"🎁 Claiming regular bonus reward {reward_no}...", Fore.CYAN)
try:
claim_response = requests.post(claim_url, headers=headers, json=claim_payload)
if claim_response is None or claim_response.status_code != 200:
self.log(f"⚠️ Invalid response for regular bonus reward {reward_no}.", Fore.YELLOW)
continue
claim_data = self.decode_response(claim_response) if claim_response.text else {}
if claim_data.get("error_code") is None:
result = claim_data.get("result", {})
name = result.get("name", "Unknown")
description = result.get("description", "No description")
amount = result.get("amount", 0)
self.log(f"✅ Successfully claimed regular bonus reward {reward_no}!", Fore.GREEN)
self.log(f"📦 Name: {name}", Fore.LIGHTGREEN_EX)
self.log(f"ℹ️ Description: {description}", Fore.YELLOW)
self.log(f"🔢 Amount: {amount}", Fore.MAGENTA)
else:
self.log(f"⚠️ Failed to claim regular bonus reward {reward_no}: {claim_data.get('message', 'Unknown error')}", Fore.YELLOW)
except Exception as e:
self.log(f"❌ Error claiming regular bonus reward {reward_no}: {e}", Fore.RED)
continue
else:
self.log("ℹ️ Regular bonus not ready to claim yet.", Fore.YELLOW)
else:
self.log("⚠️ Regular bonus data is invalid.", Fore.YELLOW)
except Exception as e:
self.log(f"❌ Error during regular bonus claim check: {e}", Fore.RED)
# BONUS CLAIM: SUPER GACHA BONUS
try:
bonus_check_url_super = f"{self.BASE_URL}pet/dna/gacha/bonus?is_super=True"
bonus_response_super = requests.get(bonus_check_url_super, headers=headers)
if bonus_response_super is None or bonus_response_super.status_code != 200:
self.log("⚠️ Super bonus check response is invalid.", Fore.YELLOW)
else:
bonus_data_super = self.decode_response(bonus_response_super) if bonus_response_super.text else {}
if bonus_data_super and "result" in bonus_data_super:
bonus_result = bonus_data_super["result"]
current_step = bonus_result.get("current_step", 0)
total_step = bonus_result.get("total_step", 200)
if current_step >= total_step:
rewards_to_claim = []
if not bonus_result.get("is_claimed_god_power", False):
rewards_to_claim.append(1)
if not bonus_result.get("is_claimed_dna", False):
rewards_to_claim.append(2)
for reward_no in rewards_to_claim:
claim_url = f"{self.BASE_URL}pet/dna/gacha/bonus/claim"
claim_payload = {"reward_no": reward_no, "is_super": True}
self.log(f"🎁 Claiming super bonus reward {reward_no}...", Fore.CYAN)
try:
claim_response = requests.post(claim_url, headers=headers, json=claim_payload)
if claim_response is None or claim_response.status_code != 200:
self.log(f"⚠️ Invalid response for super bonus reward {reward_no}.", Fore.YELLOW)
continue
claim_data = self.decode_response(claim_response) if claim_response.text else {}
if claim_data.get("error_code") is None:
result = claim_data.get("result", {})
name = result.get("name", "Unknown")
description = result.get("description", "No description")
amount = result.get("amount", 0)
self.log(f"✅ Successfully claimed super bonus reward {reward_no}!", Fore.GREEN)
self.log(f"📦 Name: {name}", Fore.LIGHTGREEN_EX)
self.log(f"ℹ️ Description: {description}", Fore.YELLOW)
self.log(f"🔢 Amount: {amount}", Fore.MAGENTA)
else:
self.log(f"⚠️ Failed to claim super bonus reward {reward_no}: {claim_data.get('message', 'Unknown error')}", Fore.YELLOW)
except Exception as e:
self.log(f"❌ Error claiming super bonus reward {reward_no}: {e}", Fore.RED)
continue
else:
self.log("ℹ️ Super bonus not ready to claim yet.", Fore.YELLOW)
else:
self.log("⚠️ Super bonus data is invalid.", Fore.YELLOW)
except Exception as e:
self.log(f"❌ Error during super bonus claim check: {e}", Fore.RED)
# REFRESH TOKENS
time.sleep(1)
self.log("🔄 Refreshing gacha tokens...", Fore.CYAN)
req_url = f"{self.BASE_URL}user/info"
try:
response = requests.get(req_url, headers=headers)
response.raise_for_status()
data = self.decode_response(response)
if "result" in data:
user_info = data["result"]
inventory = user_info.get("inventory", [])
token_reguler = next((item for item in inventory if item["id"] == 1), None)
token_super = next((item for item in inventory if item["id"] == 3), None)
if token_reguler:
self.log(f"💵 Regular Token: {token_reguler['amount']}", Fore.LIGHTBLUE_EX)
self.token_reguler = token_reguler["amount"]
else:
self.log("💵 Regular Token: 0", Fore.LIGHTBLUE_EX)
if token_super:
self.log(f"💸 Super Token: {token_super['amount']}", Fore.LIGHTBLUE_EX)
self.token_super = token_super["amount"]
else:
self.log("💸 Super Token: 0", Fore.LIGHTBLUE_EX)
else:
self.log("⚠️ User info response structure is invalid.", Fore.YELLOW)
except Exception as e:
self.log(f"❌ Failed to refresh tokens: {e}", Fore.RED)
def mix(self) -> None:
"""
Menggabungkan DNA untuk membuat pet baru tanpa membedakan antara dad dan mom.
Untuk config-specified mixing, sebelum eksekusi, sistem akan menghitung duplicate count
tiap ID di konfigurasi dan membandingkannya dengan total available 'amount' untuk DNA tersebut.
Jika available amount tidak mencukupi, pasangan mixing yang memerlukan ID tersebut tidak akan dieksekusi.
Jika mencukupi (atau lebih), maka semua pasangan dieksekusi tanpa pengurangan nilai amount.
Random mixing menggunakan metode lama (mengabaikan DNA yang ID-nya sudah ditetapkan di config).
Setelah phase mixing spesifik, ditambahkan phase baru "mission failed mixing"
(yang memeriksa resep dan requirement dari file mission_failed.json) sebelum melanjutkan ke random mixing.
Seluruh mix yang berhasil dari semua phase akan dicatat.
Di akhir fungsi, dicoba untuk mengirim catatan mix ke API eksternal
(POST ke https://lib-mix-animix.vercel.app/api/mix dengan header Content-Type: application/json).
"""
import json, time # pastikan modul diimpor bila belum
successful_mixes = [] # List untuk mencatat hasil mixing yang berhasil
req_url = f"{self.BASE_URL}pet/dna/list"
mix_url = f"{self.BASE_URL}pet/mix"
headers = {**self.HEADERS, "Tg-Init-Data": self.token}
self.log("🔍 Fetching DNA list...", Fore.CYAN)
try:
response = requests.get(req_url, headers=headers, timeout=10)
response.raise_for_status()
data = self.decode_response(response)
dna_list = []
if "result" in data and isinstance(data["result"], list):
for dna in data["result"]:
# Pastikan field 'star' ada dan jika ada field 'type', maka bisa digunakan di phase mission failed.
self.log(
f"✅ DNA found: Item ID {dna['item_id']} (Amount: {dna.get('amount', 0)}, Star: {dna['star']}, Can Mom: {dna.get('can_mom', 'N/A')})",
Fore.GREEN,
)
dna_list.append(dna)
else:
self.log("⚠️ No DNA found in the response.", Fore.YELLOW)
return
if len(dna_list) < 2:
self.log("❌ Not enough DNA data for mixing. At least two entries are required.", Fore.RED)
return
self.log(
f"📋 Filtered DNA list: {[(dna['item_id'], dna.get('amount', 0), dna['star'], dna.get('can_mom', 'N/A')) for dna in dna_list]}",
Fore.CYAN,
)
# -------------------------------
# Config-specified mixing
# -------------------------------
pet_mix_config = self.config.get("pet_mix", [])
config_ids = set()
if pet_mix_config:
# Kumpulkan semua ID dari config agar dikecualikan dari random mixing.
for pair in pet_mix_config:
if len(pair) == 2:
config_ids.add(str(pair[0]))
config_ids.add(str(pair[1]))
self.log("🔄 Attempting config-specified pet mixing...", Fore.CYAN)
# Buat mapping dari item_id ke total available amount (jika ada duplikat, jumlahkan)
available_config_dna = {}
for dna in dna_list:
key = str(dna["item_id"])
if key in available_config_dna:
available_config_dna[key]["amount"] += dna.get("amount", 0)
else:
available_config_dna[key] = dict(dna)
# Hitung duplicate count tiap ID di konfigurasi
config_required_counts = {}
for pair in pet_mix_config:
if len(pair) == 2:
for id_val in pair:
key = str(id_val)
config_required_counts[key] = config_required_counts.get(key, 0) + 1
# Cek apakah available amount sudah mencukupi untuk setiap ID di config
insufficient_ids = set()
for key, required in config_required_counts.items():
available = available_config_dna.get(key, {}).get("amount", 0)
if available < required:
insufficient_ids.add(key)
self.log(
f"⚠️ Insufficient quantity for DNA ID {key}: required {required}, available {available}",
Fore.YELLOW,
)
# Eksekusi mixing untuk pasangan config
for pair in pet_mix_config:
if len(pair) != 2:
self.log(f"⚠️ Invalid pet mix pair: {pair}", Fore.YELLOW)
continue
id1_config, id2_config = pair
key1 = str(id1_config)
key2 = str(id2_config)
# Jika salah satu ID tidak mencukupi, lewati pasangan ini
if key1 in insufficient_ids or key2 in insufficient_ids:
self.log(f"⚠️ Skipping config pair {pair} due to insufficient quantity.", Fore.YELLOW)
continue
dna1 = available_config_dna.get(key1)
dna2 = available_config_dna.get(key2)
if dna1 is not None and dna2 is not None:
payload = {"dad_id": dna1["item_id"], "mom_id": dna2["item_id"]}
self.log(
f"🔄 Mixing config pair: DNA1 (ID: {id1_config}, Item ID: {dna1['item_id']}), "
f"DNA2 (ID: {id2_config}, Item ID: {dna2['item_id']})",
Fore.CYAN,
)
while True:
try:
mix_response = requests.post(mix_url, headers=headers, json=payload, timeout=10)
if mix_response.status_code == 200:
mix_data = self.decode_response(mix_response)
if "result" in mix_data and "pet" in mix_data["result"]:
pet_info = mix_data["result"]["pet"]
self.log(
f"🎉 New pet created: {pet_info['name']} (ID: {pet_info['pet_id']})",
Fore.GREEN,
)
# Catat hasil mix yang berhasil
successful_mixes.append({
"pet_name": pet_info.get("name", "Unknown"),
"pet_id": pet_info.get("pet_id", "N/A"),
"pet_class": pet_info.get("class", "N/A"),
"pet_star": str(pet_info.get("star", "N/A")),
# Gunakan data dummy untuk DNA di sini
"dna": {"dna1id": dna1['item_id'], "dna2id": dna2['item_id']}
})
break
else:
message = mix_data.get("message", "No message provided.")
self.log(f"⚠️ Mixing failed for config pair {pair}: {message}", Fore.YELLOW)
break
elif mix_response.status_code == 429:
self.log("⏳ Too many requests (429). Retrying in 5 seconds...", Fore.YELLOW)
time.sleep(5)
else:
self.log(f"❌ Request failed for config pair {pair} (Status: {mix_response.status_code})", Fore.RED)
break
except requests.exceptions.RequestException as e:
self.log(f"❌ Request failed for config pair {pair}: {e}", Fore.RED)
break
else:
self.log(f"⚠️ Unable to find matching DNA for config pair: {pair}", Fore.YELLOW)
# -------------------------------------------
# Mission Failed Mixing Phase (baru)
# Dipindahkan setelah config-specified dan sebelum random mixing.
# -------------------------------------------
self.log("🔄 Starting mission failed mixing phase...", Fore.CYAN)
# 1. Refetch DNA list untuk mendapatkan data terbaru
try:
mission_response = requests.get(req_url, headers=headers, timeout=10)
mission_response.raise_for_status()
mission_data = self.decode_response(mission_response)
mission_dna_list = []
if "result" in mission_data and isinstance(mission_data["result"], list):
mission_dna_list = mission_data["result"]
else:
self.log("⚠️ No DNA found in the mission failed phase.", Fore.YELLOW)
except requests.exceptions.RequestException as e:
self.log(f"❌ Request failed while fetching DNA list for mission failed: {e}", Fore.RED)
mission_dna_list = []
# 2. Ambil resep mixing dari API eksternal (GET tanpa headers)
try:
recipe_response = requests.get("https://lib-mix-animix.vercel.app/api/mix", timeout=10)
recipe_response.raise_for_status()
recipe_data = recipe_response.json()
recipes = recipe_data.get("record", [])
except requests.exceptions.RequestException as e:
self.log(f"❌ Request failed while fetching recipe list: {e}", Fore.RED)
recipes = []
# 3. Baca file mission_failed.json (pastikan file ini berada di path yang benar)
try:
with open("mission_failed.json", "r") as f:
mission_failed_data = json.load(f)
except Exception as e:
self.log(f"❌ Failed to load mission_failed.json: {e}", Fore.RED)
mission_failed_data = {}
# 4. Iterasi setiap resep dan periksa requirement.
# Misalnya, pada mission_failed_data setiap entry memiliki format:
# [ [<element>, <star_required>], ... ]
for recipe in recipes:
for mission_requirements in mission_failed_data.values():
all_requirements_met = True
selected_dnas = {} # mapping element -> dna terpilih
for req in mission_requirements:
req_element = req[0].lower() # misalnya "wind"
req_star = req[1]
# Cari DNA pada mission_dna_list yang memenuhi: star yang sama dan field "type" sama dengan req_element
matching_dna = next(
(dna for dna in mission_dna_list
if str(dna.get("star")) == str(req_star)
and dna.get("type", "").lower() == req_element
and dna.get("amount", 0) > 0),
None
)
if matching_dna:
selected_dnas[req_element] = matching_dna
else:
all_requirements_met = False
self.log(f"⚠️ Requirement not met: {req_element} with star {req_star}", Fore.YELLOW)
break
# Jika seluruh requirement terpenuhi dan setidaknya ada 2 DNA terpilih untuk di-mix
if all_requirements_met and len(selected_dnas) >= 2:
dna_values = list(selected_dnas.values())
dna1 = dna_values[0]
dna2 = dna_values[1]
payload = {"dad_id": dna1["item_id"], "mom_id": dna2["item_id"]}
self.log(
f"🔄 Mission failed mixing: Mixing DNA pair for recipe {recipe.get('pet_name', 'Unknown')}: "
f"DNA1 (ID: {dna1['item_id']}), DNA2 (ID: {dna2['item_id']})",
Fore.CYAN,
)
while True:
try:
mix_response = requests.post(mix_url, headers=headers, json=payload, timeout=10)
if mix_response.status_code == 200:
mix_data = self.decode_response(mix_response)
if "result" in mix_data and "pet" in mix_data["result"]:
pet_info = mix_data["result"]["pet"]
self.log(
f"🎉 New pet created from mission failed mixing: {pet_info['name']} (ID: {pet_info['pet_id']})",
Fore.GREEN,
)
successful_mixes.append({
"pet_name": pet_info.get("name", "Unknown"),
"pet_id": pet_info.get("pet_id", "N/A"),
"pet_class": pet_info.get("class", "N/A"),
"pet_star": str(pet_info.get("star", "N/A")),
"dna": {"dna1id": dna1['item_id'], "dna2id": dna2['item_id']}
})
break
else:
message = mix_data.get("message", "No message provided.")
self.log(f"⚠️ Mission failed mixing failed for recipe {recipe.get('pet_name', 'Unknown')}: {message}", Fore.YELLOW)
break
elif mix_response.status_code == 429:
self.log("⏳ Too many requests (429) in mission failed mixing. Retrying in 5 seconds...", Fore.YELLOW)
time.sleep(5)
else:
self.log(f"❌ Mission failed mixing request failed (Status: {mix_response.status_code})", Fore.RED)
break
except requests.exceptions.RequestException as e:
self.log(f"❌ Mission failed mixing request failed: {e}", Fore.RED)
break
# Jika satu mixing berhasil, keluar dari iterasi resep
break
else:
continue
break
# -------------------------------------------
# Random mixing (metode lama)
# -------------------------------------------
self.log("🔄 Mixing remaining DNA (star below 5)...", Fore.CYAN)
n = len(dna_list)
for i in range(n):
if str(dna_list[i]["item_id"]) in config_ids:
continue
if dna_list[i].get("amount", 0) <= 0:
continue
for j in range(i + 1, n):
if str(dna_list[j]["item_id"]) in config_ids:
continue
if dna_list[j].get("amount", 0) <= 0:
continue
if dna_list[i]["star"] < 5 and dna_list[j]["star"] < 5:
payload = {"dad_id": dna_list[i]["item_id"], "mom_id": dna_list[j]["item_id"]}
self.log(
f"🔄 Mixing DNA pair: Item IDs ({dna_list[i]['item_id']}, {dna_list[j]['item_id']})",
Fore.CYAN,
)
while True:
try:
mix_response = requests.post(mix_url, headers=headers, json=payload, timeout=10)
if mix_response.status_code == 200:
mix_data = self.decode_response(mix_response)
if "result" in mix_data and "pet" in mix_data["result"]:
pet_info = mix_data["result"]["pet"]
self.log(
f"🎉 New pet created: {pet_info['name']} (ID: {pet_info['pet_id']})",
Fore.GREEN,
)
successful_mixes.append({
"pet_name": pet_info.get("name", "Unknown"),
"pet_id": pet_info.get("pet_id", "N/A"),
"pet_class": pet_info.get("class", "N/A"),
"pet_star": str(pet_info.get("star", "N/A")),
"dna": {"dna1id": dna_list[i]['item_id'], "dna2id": dna_list[j]['item_id']}
})
break
else:
message = mix_data.get("message", "No message provided.")
self.log(f"⚠️ Mixing failed for DNA pair ({dna_list[i]['item_id']}, {dna_list[j]['item_id']}): {message}", Fore.YELLOW)
break
elif mix_response.status_code == 429:
self.log("⏳ Too many requests (429). Retrying in 5 seconds...", Fore.YELLOW)
time.sleep(5)
else:
self.log(f"❌ Request failed for DNA pair ({dna_list[i]['item_id']}, {dna_list[j]['item_id']}) (Status: {mix_response.status_code})", Fore.RED)
break
except requests.exceptions.RequestException as e:
self.log(f"❌ Request failed for DNA pair ({dna_list[i]['item_id']}, {dna_list[j]['item_id']}): {e}", Fore.RED)
break
# -------------------------------------------
# Di akhir fungsi, kirim catatan mix yang berhasil ke API eksternal
# -------------------------------------------
self.log("🔄 Sending successful mixes log to external API...", Fore.CYAN)
external_api_url = "https://lib-mix-animix.vercel.app/api/mix"
external_headers = {"Content-Type": "application/json"}
payload = successful_mixes if successful_mixes else []
max_retries = 5
retry_delay = 3 # detik
for attempt in range(1, max_retries + 1):
try:
post_response = requests.post(
external_api_url,
headers=external_headers,
json=payload,
timeout=10
)
if post_response.status_code == 201:
self.log("🎉 Successfully sent mix log to external API.", Fore.GREEN)
break
else:
self.log(
f"❌ Attempt {attempt}: Failed to send mix log (Status: {post_response.status_code})",
Fore.RED
)
except requests.exceptions.RequestException as e:
self.log(f"❌ Attempt {attempt}: Request failed - {e}", Fore.RED)
if attempt < max_retries:
self.log(f"🔁 Retrying in {retry_delay} seconds...", Fore.YELLOW)
time.sleep(retry_delay)
else:
self.log("❌ All retry attempts failed.", Fore.RED)
except requests.exceptions.RequestException as e:
self.log(f"❌ Request failed while fetching DNA list: {e}", Fore.RED)
except ValueError as e:
self.log(f"❌ Data error while fetching DNA list: {e}", Fore.RED)
except Exception as e:
self.log(f"❌ Unexpected error while fetching DNA list: {e}", Fore.RED)
def achievements(self) -> None:
"""Handles fetching and claiming achievements."""
req_url_list = f"{self.BASE_URL}achievement/list"
req_url_claim = f"{self.BASE_URL}achievement/claim"
headers = {**self.HEADERS, "tg-init-data": self.token}
claimable_ids = []
try:
# Step 1: Fetch the list of achievements
self.log("⏳ Fetching the list of achievements...", Fore.CYAN)
response = requests.get(req_url_list, headers=headers)
response.raise_for_status()
data = self.decode_response(response)
if "result" in data and isinstance(data["result"], dict):
for achievement_type, achievement_data in data["result"].items():
if (
isinstance(achievement_data, dict)
and "achievements" in achievement_data
):
self.log(
f"📌 Checking achievements type: {achievement_type}",
Fore.BLUE,
)
for achievement in achievement_data["achievements"]:
if (
achievement.get("status") is True
and achievement.get("claimed") is False
):
claimable_ids.append(achievement.get("quest_id"))
self.log(
f"✅ Achievement ready to claim: {achievement_data['title']} (ID: {achievement.get('quest_id')})",
Fore.GREEN,
)
if not claimable_ids:
self.log("🚫 No achievements available for claiming.", Fore.YELLOW)
return
# Step 2: Claim each achievement found
for quest_id in claimable_ids:
self.log(
f"🔄 Attempting to claim achievement with ID {quest_id}...",
Fore.CYAN,
)
response = requests.post(
req_url_claim, headers=headers, json={"quest_id": quest_id}
)
response.raise_for_status()
claim_result = self.decode_response(response)
if claim_result.get("error_code") is None:
self.log(
f"🎉 Successfully claimed achievement with ID {quest_id}!",
Fore.GREEN,
)
else:
self.log(
f"⚠️ Failed to claim achievement with ID {quest_id}. Message: {claim_result.get('message')}",
Fore.RED,
)
except requests.exceptions.RequestException as e:
self.log(f"❌ Request processing failed: {e}", Fore.RED)
except ValueError as e:
self.log(f"❌ Data error: {e}", Fore.RED)
except Exception as e:
self.log(f"❌ Unexpected error: {e}", Fore.RED)
def mission(self) -> None:
"""List missions from API, claim finished missions, then assign pets
using mission.json definitions for missions that are not in progress.
Pet assignment is performed in three stages:
1. Fetch mission list and claim finished missions.
2. Read mission definitions from mission.json and sort by reward.
3. For missions yang belum berjalan, assign pets dengan memperbolehkan deploy pet yang sama
(bisa 2 atau 3 slot) selama jumlah (amount) mencukupi.
"""
import time, json, requests
headers = {**self.HEADERS, "Tg-Init-Data": self.token}
current_time = int(time.time())
# === Reset file log gagal setiap kali fungsi dijalankan ===
failed_log_path = "mission_failed.json"
try:
with open(failed_log_path, "w") as f: