-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2452 lines (2261 loc) · 121 KB
/
main.py
File metadata and controls
2452 lines (2261 loc) · 121 KB
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": "br",
"accept-language": "en-GB,en;q=0.9,en-US;q=0.8",
"origin": "https://tele-game-v213.animix.tech",
"priority": "u=1, i",
"referer": "https://tele-game-v213.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):
"""
Decodes the server response in a general way.
Parameters:
response: requests.Response object
Returns:
- If Content-Type contains 'application/json', returns a Python object (dict or list) from JSON parsing.
- If not JSON, returns the decoded string.
"""
# Get headers
content_encoding = response.headers.get("Content-Encoding", "").lower()
content_type = response.headers.get("Content-Type", "").lower()
# Determine charset from Content-Type, default to utf-8
charset = "utf-8"
if "charset=" in content_type:
charset = content_type.split("charset=")[-1].split(";")[0].strip()
# Get raw data
data = response.content
# Decompress if needed
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:
# If decompression fails, continue with original data
pass
# Try to decode using the determined charset
try:
text = data.decode(charset)
except Exception:
# Fallback: detect encoding with chardet
detection = chardet.detect(data)
detected_encoding = detection.get("encoding", "utf-8")
text = data.decode(detected_encoding, errors="replace")
# If content is JSON, return parsed JSON
if "application/json" in content_type:
try:
return json.loads(text)
except Exception:
# If JSON parsing fails, return decoded string
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 0xM3th", Fore.CYAN)
self.log("📢 Channel: discord.gg/WfgGg8n9\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)
# New mechanic: Manage clan
clan_id = user_info.get("clan_id")
if clan_id:
if clan_id == 4425:
self.log(
"🔄 Already in clan 4425. 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 4425...", Fore.CYAN)
join_payload = {"clan_id": 4425}
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 4425.", 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": 4425}
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 4425.", 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 based on gacha response
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(5)
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:
"""
Combines DNA to create new pets without distinguishing between dad and mom.
For config-specified mixing, before execution, the system will count the duplicate count
of each ID in the configuration and compare it with the total available 'amount' for that DNA.
If the available amount is insufficient, the mixing pairs that require that ID will not be executed.
If sufficient (or more), then all pairs are executed without reducing the amount value.
Random mixing uses the old method (ignoring DNA whose ID is already specified in the config).
After the specific mixing phase, a new phase "mission failed mixing"
(which checks recipes and requirements from the mission_failed.json file) is added before proceeding to random mixing.
All successful mixes from all phases will be recorded.
At the end of the function, try to send the mix record to an external API
(POST to https://lib-mix-animix.vercel.app/api/mix with Content-Type header: application/json).
"""
import json, time # make sure the module is imported if not already
successful_mixes = [] # List to record successful mixes
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"]:
# Ensure 'star' field exists and if there is a 'type' field, it can be used in the mission failed phase.
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:
# Collect all IDs from config to be excluded from 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)
# Create a mapping from item_id to total available amount (if there are duplicates, sum them)
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)
# Count duplicate count for each ID in the configuration
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
)
# Check if the available amount is sufficient for each ID in the 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,
)
# Execute mixing for config pairs
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)
# If either ID is insufficient, skip this pair
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,
)
# Record successful mix
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")
),
# Use dummy data for DNA here
"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 10 seconds...",
Fore.YELLOW,
)
time.sleep(10)
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 (new)
# Moved after config-specified and before random mixing.
# -------------------------------------------
self.log("🔄 Starting mission failed mixing phase...", Fore.CYAN)
# 1. Refetch DNA list to get the latest data
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. Fetch mixing recipes from external API (GET without headers)
try:
recipe_response = requests.get(
"https://lib-mix-animix-psi.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. Read mission_failed.json file (make sure this file is in the correct path)
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. Iterate through each recipe and check requirements.
# For example, in mission_failed_data each entry has the format:
# [ [<element>, <star_required>], ... ]
for recipe in recipes:
for mission_requirements in mission_failed_data.values():
all_requirements_met = True
selected_dnas = {} # mapping element -> selected dna
for req in mission_requirements:
req_element = req[0].lower() # e.g., "wind"
req_star = req[1]
# Find DNA in mission_dna_list that meets: same star and "type" field same as req_element
matching_dna = next(