forked from masterking32/MasterHamsterKombatBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1630 lines (1360 loc) · 60.2 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
# Developed by: MasterkinG32
# Date: 2024
# Github: https://github.com/masterking32
import asyncio
import datetime
import json
import logging
import random
import time
import requests
from colorlog import ColoredFormatter
import uuid
import hashlib
from utilities import *
from promogames import *
try:
from config import *
except ImportError:
print("Config file not found.")
print("Create a copy of config.py.example and rename it to config.py")
print("And fill in the required fields.")
exit()
if "ConfigFileVersion" not in locals() or ConfigFileVersion != 1:
print("Invalid config file version.")
print("Please update the config file to the latest version.")
print("Create a copy of config.py.example and rename it to config.py")
print("And fill in the required fields.")
exit()
# ---------------------------------------------#
# Logging configuration
LOG_LEVEL = logging.DEBUG
# Include date and time in the log format
LOGFORMAT = "%(log_color)s[Master HamsterKombat Bot]%(reset)s[%(log_color)s%(levelname)s%(reset)s] %(asctime)s %(log_color)s%(message)s%(reset)s"
logging.root.setLevel(LOG_LEVEL)
formatter = ColoredFormatter(
LOGFORMAT, "%Y-%m-%d %H:%M:%S"
) # Specify the date/time format
stream = logging.StreamHandler()
stream.setLevel(LOG_LEVEL)
stream.setFormatter(formatter)
log = logging.getLogger("pythonConfig")
log.setLevel(LOG_LEVEL)
log.addHandler(stream)
# End of configuration
# ---------------------------------------------#
class HamsterKombatAccount:
def __init__(self, AccountData):
self.account_name = AccountData["account_name"]
self.Authorization = AccountData["Authorization"]
self.UserAgent = AccountData["UserAgent"]
self.Proxy = AccountData["Proxy"]
self.config = AccountData["config"]
self.isAndroidDevice = "Android" in self.UserAgent
self.balanceCoins = 0
self.availableTaps = 0
self.maxTaps = 0
self.ProfitPerHour = 0
self.earnPassivePerHour = 0
self.SpendTokens = 0
self.account_data = None
self.telegram_chat_id = AccountData["telegram_chat_id"]
self.totalKeys = 0
self.balanceKeys = 0
self.configVersion = ""
def GetConfig(self, key, default=None):
if key in self.config:
return self.config[key]
return default
def SendTelegramLog(self, message, level="other_errors"):
if (
not telegramBotLogging["is_active"]
or self.telegram_chat_id == ""
or telegramBotLogging["bot_token"] == ""
):
return
if (
level not in telegramBotLogging["messages"]
or telegramBotLogging["messages"][level] is False
):
return
try:
requests.get(
f"https://api.telegram.org/bot{telegramBotLogging['bot_token']}/sendMessage?chat_id={self.telegram_chat_id}&text={message}"
)
except Exception as e:
log.error(f"[{self.account_name}] TelegramLog error: {e}")
# Send HTTP requests
def HttpRequest(
self,
url,
headers,
method="POST",
validStatusCodes=200,
payload=None,
ignore_errors=False,
):
# Default headers
defaultHeaders = {
"Accept": "*/*",
"Connection": "keep-alive",
"Host": "api.hamsterkombatgame.io",
"Origin": "https://hamsterkombatgame.io",
"Referer": "https://hamsterkombatgame.io/",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-site",
"User-Agent": self.UserAgent,
}
# Add default headers for Android devices to avoid detection, Not needed for iOS devices
if self.isAndroidDevice:
defaultHeaders["HTTP_SEC_CH_UA_PLATFORM"] = '"Android"'
defaultHeaders["HTTP_SEC_CH_UA_MOBILE"] = "?1"
defaultHeaders["HTTP_SEC_CH_UA"] = (
'"Android WebView";v="125", "Chromium";v="125", "Not.A/Brand";v="24"'
)
defaultHeaders["HTTP_X_REQUESTED_WITH"] = "org.telegram.messenger.web"
# Add and replace new headers to default headers
for key, value in headers.items():
defaultHeaders[key] = value
try:
if method == "GET":
response = requests.get(url, headers=defaultHeaders, proxies=self.Proxy)
elif method == "POST":
response = requests.post(
url, headers=headers, data=payload, proxies=self.Proxy
)
elif method == "OPTIONS":
response = requests.options(url, headers=headers, proxies=self.Proxy)
else:
log.error(f"[{self.account_name}] Invalid method: {method}")
self.SendTelegramLog(
f"[{self.account_name}] Invalid method: {method}", "http_errors"
)
return None
if response.status_code != validStatusCodes:
if ignore_errors:
return None
log.error(
f"[{self.account_name}] Status code is not {validStatusCodes}"
)
log.error(f"[{self.account_name}] Response: {response.text}")
self.SendTelegramLog(
f"[{self.account_name}] Status code is not {validStatusCodes}",
"http_errors",
)
return None
if "config-version" in response.headers:
self.configVersion = response.headers["config-version"]
if method == "OPTIONS":
return True
return response.json()
except Exception as e:
if ignore_errors:
return None
log.error(f"[{self.account_name}] Error: {e}")
self.SendTelegramLog(f"[{self.account_name}] Error: {e}", "http_errors")
return None
# Sending sync request
def syncRequest(self):
url = "https://api.hamsterkombatgame.io/clicker/sync"
headers = {
"Access-Control-Request-Headers": self.Authorization,
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Authorization": self.Authorization,
}
# Send POST request
return self.HttpRequest(url, headers, "POST", 200)
# Get list of upgrades to buy
def UpgradesForBuyRequest(self):
url = "https://api.hamsterkombatgame.io/clicker/upgrades-for-buy"
headers = {
"Access-Control-Request-Headers": "authorization",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Authorization": self.Authorization,
}
# Send POST request
return self.HttpRequest(url, headers, "POST", 200)
# Buy an upgrade
def BuyUpgradeRequest(self, UpgradeId):
url = "https://api.hamsterkombatgame.io/clicker/buy-upgrade"
headers = {
"Access-Control-Request-Headers": "authorization,content-type",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Authorization": self.Authorization,
"Content-Type": "application/json",
"Accept": "application/json",
}
payload = json.dumps(
{
"upgradeId": UpgradeId,
"timestamp": int(datetime.datetime.now().timestamp() * 1000),
}
)
# Send POST request
return self.HttpRequest(url, headers, "POST", 200, payload)
# Tap the hamster
def TapRequest(self, tap_count):
url = "https://api.hamsterkombatgame.io/clicker/tap"
headers = {
"Access-Control-Request-Headers": "authorization,content-type",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Accept": "application/json",
"Authorization": self.Authorization,
"Content-Type": "application/json",
}
payload = json.dumps(
{
"timestamp": int(datetime.datetime.now().timestamp() * 1000),
"availableTaps": 0,
"count": int(tap_count),
}
)
# Send POST request
return self.HttpRequest(url, headers, "POST", 200, payload)
# Get list of boosts to buy
def BoostsToBuyListRequest(self):
url = "https://api.hamsterkombatgame.io/clicker/boosts-for-buy"
headers = {
"Access-Control-Request-Headers": "authorization",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Authorization": self.Authorization,
}
# Send POST request
return self.HttpRequest(url, headers, "POST", 200)
# Buy a boost
def BuyBoostRequest(self, boost_id):
url = "https://api.hamsterkombatgame.io/clicker/buy-boost"
headers = {
"Access-Control-Request-Headers": "authorization,content-type",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Accept": "application/json",
"Authorization": self.Authorization,
"Content-Type": "application/json",
}
payload = json.dumps(
{
"boostId": boost_id,
"timestamp": int(datetime.datetime.now().timestamp() * 1000),
}
)
# Send POST request
return self.HttpRequest(url, headers, "POST", 200, payload)
def getAccountData(self):
account_data = self.syncRequest()
if account_data is None or account_data is False:
log.error(f"[{self.account_name}] Unable to get account data.")
self.SendTelegramLog(
f"[{self.account_name}] Unable to get account data.", "other_errors"
)
return False
if "clickerUser" not in account_data:
log.error(f"[{self.account_name}] Invalid account data.")
self.SendTelegramLog(
f"[{self.account_name}] Invalid account data.", "other_errors"
)
return False
if "balanceCoins" not in account_data["clickerUser"]:
log.error(f"[{self.account_name}] Invalid balance coins.")
self.SendTelegramLog(
f"[{self.account_name}] Invalid balance coins.", "other_errors"
)
return False
self.account_data = account_data
self.balanceCoins = account_data["clickerUser"]["balanceCoins"]
self.availableTaps = account_data["clickerUser"]["availableTaps"]
self.maxTaps = account_data["clickerUser"]["maxTaps"]
self.earnPassivePerHour = account_data["clickerUser"]["earnPassivePerHour"]
if "balanceKeys" in account_data["clickerUser"]:
self.balanceKeys = account_data["clickerUser"]["balanceKeys"]
else:
self.balanceKeys = 0
if "totalKeys" in account_data["clickerUser"]:
self.totalKeys = account_data["clickerUser"]["totalKeys"]
else:
self.totalKeys = 0
return account_data
def BuyFreeTapBoostIfAvailable(self):
log.info(f"[{self.account_name}] Checking for free tap boost...")
BoostList = self.BoostsToBuyListRequest()
if BoostList is None:
log.error(f"[{self.account_name}] Failed to get boosts list.")
self.SendTelegramLog(
f"[{self.account_name}] Failed to get boosts list.", "other_errors"
)
return None
BoostForTapList = None
for boost in BoostList["boostsForBuy"]:
if boost["price"] == 0 and boost["id"] == "BoostFullAvailableTaps":
BoostForTapList = boost
break
if (
BoostForTapList is not None
and "price" in BoostForTapList
and "cooldownSeconds" in BoostForTapList
and BoostForTapList["price"] == 0
and BoostForTapList["cooldownSeconds"] == 0
):
log.info(f"[{self.account_name}] Free boost found, attempting to buy...")
time.sleep(5)
self.BuyBoostRequest(BoostForTapList["id"])
log.info(f"[{self.account_name}] Free boost bought successfully")
return True
else:
log.info(f"\033[1;34m[{self.account_name}] No free boosts available\033[0m")
return False
def IPRequest(self):
url = "https://api.hamsterkombatgame.io/ip"
headers = {
"Access-Control-Request-Headers": "authorization",
"Access-Control-Request-Method": "GET",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 200)
headers = {
"Authorization": self.Authorization,
}
# Send GET request
return self.HttpRequest(url, headers, "GET", 200)
def GetSkins(self):
url = "https://api.hamsterkombatgame.io/clicker/get-skin"
headers = {
"Access-Control-Request-Headers": "authorization,content-type",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Accept": "application/json",
"Authorization": self.Authorization,
"Content-Type": "application/json",
}
# Send POST request
return self.HttpRequest(url, headers, "POST", 200, "{}")
def AccountInfoTelegramRequest(self):
url = "https://api.hamsterkombatgame.io/auth/account-info"
headers = {
"Access-Control-Request-Headers": "authorization",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Authorization": self.Authorization,
}
# Send POST request
return self.HttpRequest(url, headers, "POST", 200)
def ListTasksRequest(self):
url = "https://api.hamsterkombatgame.io/clicker/list-tasks"
headers = {
"Access-Control-Request-Headers": "authorization",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Authorization": self.Authorization,
}
# Send POST request
return self.HttpRequest(url, headers, "POST", 200)
def GetListAirDropTasksRequest(self):
url = "https://api.hamsterkombatgame.io/clicker/list-airdrop-tasks"
headers = {
"Access-Control-Request-Headers": "authorization",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Authorization": self.Authorization,
}
# Send POST request
return self.HttpRequest(url, headers, "POST", 200)
def GetAccountConfigRequest(self):
url = "https://api.hamsterkombatgame.io/clicker/config"
headers = {
"Access-Control-Request-Headers": "authorization",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Authorization": self.Authorization,
}
# Send POST request
return self.HttpRequest(url, headers, "POST", 200)
def GetAccountConfigVersionRequest(self):
if self.configVersion == "":
return None
url = f"https://api.hamsterkombatgame.io/clicker/config/{self.configVersion}"
headers = {
"Access-Control-Request-Headers": "authorization",
"Access-Control-Request-Method": "GET",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Authorization": self.Authorization,
}
# Send GET request
return self.HttpRequest(url, headers, "GET", 200)
def ClaimDailyCipherRequest(self, DailyCipher):
url = "https://api.hamsterkombatgame.io/clicker/claim-daily-cipher"
headers = {
"Access-Control-Request-Headers": "authorization,content-type",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Accept": "application/json",
"Authorization": self.Authorization,
"Content-Type": "application/json",
}
payload = json.dumps(
{
"cipher": DailyCipher,
}
)
# Send POST request
return self.HttpRequest(url, headers, "POST", 200, payload)
def CheckTaskRequest(self, task_id):
url = "https://api.hamsterkombatgame.io/clicker/check-task"
headers = {
"Access-Control-Request-Headers": "authorization,content-type",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Accept": "application/json",
"Authorization": self.Authorization,
"Content-Type": "application/json",
}
payload = json.dumps(
{
"taskId": task_id,
}
)
# Send POST request
return self.HttpRequest(url, headers, "POST", 200, payload)
def BuyCard(self, card):
upgradesResponse = self.BuyUpgradeRequest(card["id"])
if upgradesResponse is None:
log.error(f"[{self.account_name}] Failed to buy the card.")
self.SendTelegramLog(
f"[{self.account_name}] Failed to buy the card.", "other_errors"
)
return False
log.info(f"[{self.account_name}] Card bought successfully")
time.sleep(3)
self.balanceCoins -= card["price"]
self.ProfitPerHour += card["profitPerHourDelta"]
self.SpendTokens += card["price"]
self.earnPassivePerHour += card["profitPerHourDelta"]
return True
def ListBuyOptions(self, selected_upgrades):
log.info(
f"[{self.account_name}] List of {self.GetConfig('show_num_buy_options', 0)} best buy options:"
)
count = 1
for selected_card in selected_upgrades:
if (
"cooldownSeconds" in selected_card
and selected_card["cooldownSeconds"] > 0
):
continue
profitCoefficient = CalculateCardProfitCoefficient(selected_card)
log.info(
f"[{self.account_name}] {count}: {selected_card['name']}, Profit: {selected_card['profitPerHourDelta']}, Price: {number_to_string(selected_card['price'])}, Coefficient: {int(profitCoefficient)} Level: {selected_card['level']}"
)
count = count + 1
if count > self.GetConfig("show_num_buy_options", 0):
break
def BuyBestCard(self):
log.info(f"[{self.account_name}] Checking for best card...")
time.sleep(2)
upgradesResponse = self.UpgradesForBuyRequest()
if upgradesResponse is None:
log.error(f"[{self.account_name}] Failed to get upgrades list.")
self.SendTelegramLog(
f"[{self.account_name}] Failed to get upgrades list.", "other_errors"
)
return False
upgrades = [
item
for item in upgradesResponse["upgradesForBuy"]
if not item["isExpired"]
and item["isAvailable"]
and item["profitPerHourDelta"] > 0
]
if len(upgrades) == 0:
log.warning(f"[{self.account_name}] No upgrades available.")
return False
balanceCoins = int(self.balanceCoins)
log.info(f"[{self.account_name}] Searching for the best upgrades...")
selected_upgrades = SortUpgrades(
upgrades, 999_999_999_999
) # Set max budget to a high number
if len(selected_upgrades) == 0:
log.warning(f"[{self.account_name}] No upgrades available.")
return False
if self.GetConfig("show_num_buy_options", 0) > 0:
self.ListBuyOptions(selected_upgrades)
current_selected_card = selected_upgrades[0]
for selected_card in selected_upgrades:
if (
"cooldownSeconds" in selected_card
and selected_card["cooldownSeconds"] > 0
and selected_card["cooldownSeconds"] < 180
):
log.warning(
f"[{self.account_name}] {selected_card['name']} is on cooldown and cooldown is less than 180 seconds..."
)
log.warning(
f"[{self.account_name}] Waiting for {selected_card['cooldownSeconds'] + 2} seconds..."
)
time.sleep(selected_card["cooldownSeconds"] + 2)
selected_card["cooldownSeconds"] = 0
if (
"cooldownSeconds" in selected_card
and selected_card["cooldownSeconds"] > 0
and not self.config["enable_parallel_upgrades"]
):
log.warning(
f"[{self.account_name}] {selected_card['name']} is on cooldown..."
)
return False
if (
"cooldownSeconds" in selected_card
and selected_card["cooldownSeconds"] > 0
):
log.warning(
f"[{self.account_name}] {selected_card['name']} is on cooldown, Checking for next card..."
)
continue
profitCoefficient = CalculateCardProfitCoefficient(selected_card)
coefficientLimit = self.config["parallel_upgrades_max_price_per_hour"]
if (
profitCoefficient > coefficientLimit
and self.config["enable_parallel_upgrades"]
):
log.warning(
f"[{self.account_name}] {selected_card['name']} is too expensive to buy in parallel..."
)
log.warning(
f"[{self.account_name}] Cost is: {int(profitCoefficient)} / coin increase in profit. Cost limit: {coefficientLimit}"
)
log.warning(
f"[{self.account_name}] Adjust `parallel_upgrades_max_price_per_hour` to change this behaviour"
)
return False
current_selected_card = selected_card
break
log.info(
f"[{self.account_name}] Best upgrade is {current_selected_card['name']} with profit {current_selected_card['profitPerHourDelta']} and price {number_to_string(current_selected_card['price'])}, Level: {current_selected_card['level']}"
)
if balanceCoins < current_selected_card["price"]:
log.warning(
f"[{self.account_name}] Balance is too low to buy the best card."
)
self.SendTelegramLog(
f"[{self.account_name}] Balance is too low to buy the best card, Best card: {current_selected_card['name']} with profit {current_selected_card['profitPerHourDelta']} and price {number_to_string(current_selected_card['price'])}, Level: {current_selected_card['level']}",
"upgrades",
)
return False
log.info(f"[{self.account_name}] Attempting to buy the best card...")
buy_result = self.BuyCard(current_selected_card)
if buy_result:
time.sleep(2)
log.info(
f"[{self.account_name}] Best card purchase completed successfully, Your profit per hour increased by {number_to_string(self.ProfitPerHour)} coins, Spend tokens: {number_to_string(self.SpendTokens)}"
)
self.SendTelegramLog(
f"[{self.account_name}] Bought {current_selected_card['name']} with profit {current_selected_card['profitPerHourDelta']} and price {number_to_string(current_selected_card['price'])}, Level: {current_selected_card['level']}",
"upgrades",
)
return True
return False
def StartMiniGame(self, AccountConfigData, AccountID):
if "dailyKeysMiniGames" not in AccountConfigData:
log.error(f"[{self.account_name}] Unable to get daily keys mini game.")
self.SendTelegramLog(
f"[{self.account_name}] Unable to get daily keys mini game.",
"other_errors",
)
return
response = self.GetPromos()
if response is None:
log.error(f"[{self.account_name}] Unable to get promo games befor starting minigames.")
self.SendTelegramLog(
f"[{self.account_name}] Unable to get promo games befor starting minigames.", "other_errors"
)
return
minigames = list(AccountConfigData["dailyKeysMiniGames"].values())
random.shuffle(minigames)
for game in minigames:
if game["id"] not in ["Candles", "Tiles"]:
log.warning(
f"[{self.account_name}] Detected new daily mini game {game['id']}, check project github for updates."
)
self.SendTelegramLog(
f"[{self.account_name}] Detected new daily mini game {game['id']}, check project github for updates.",
"other_errors",
)
continue
if game["isClaimed"] == True:
log.info(
f"\033[1;34m[{self.account_name}] Daily mini game {game['id']} already claimed.\033[0m"
)
continue
if game["id"] == "Candles" and game["remainSecondsToNextAttempt"] > 0:
log.info(
f"[{self.account_name}] Daily mini game {game['id']} is on cooldown..."
)
continue
## check timer.
url = "https://api.hamsterkombatgame.io/clicker/start-keys-minigame"
headers = {
"Access-Control-Request-Headers": "authorization",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Accept": "application/json",
"Authorization": self.Authorization,
"Content-Type": "application/json",
}
payload = json.dumps({"miniGameId": game["id"]})
# Send POST request
response = self.HttpRequest(url, headers, "POST", 200, payload)
if response is None:
log.error(
f"[{self.account_name}] Unable to start mini game {game['id']}."
)
self.SendTelegramLog(
f"[{self.account_name}] Unable to start mini game {game['id']}.",
"other_errors",
)
continue
if "dailyKeysMiniGames" not in response:
log.error(
f"[{self.account_name}] Unable to get daily mini game {game['id']}."
)
self.SendTelegramLog(
f"[{self.account_name}] Unable to get daily mini game {game['id']}.",
"other_errors",
)
continue
if response["dailyKeysMiniGames"]["isClaimed"] == True:
log.info(
f"\033[1;34m[{self.account_name}] Daily mini game {game['id']} already claimed.\033[0m"
)
continue
if "remainSecondsToGuess" not in response["dailyKeysMiniGames"]:
log.error(
f"[{self.account_name}] Unable to get daily mini game {game['id']}."
)
self.SendTelegramLog(
f"[{self.account_name}] Unable to get daily keys mini game {game['id']}.",
"other_errors",
)
continue
waitTime = 0
if game["id"] == "Candles":
waitTime = int(
response["dailyKeysMiniGames"]["remainSecondsToGuess"]
- random.randint(8, 15)
)
elif game["id"] == "Tiles":
waitTime = random.randint(35, 120)
if waitTime < 0:
log.error(
f"[{self.account_name}] Unable to claim mini game {game['id']}."
)
self.SendTelegramLog(
f"[{self.account_name}] Unable to claim mini game {game['id']}.",
"other_errors",
)
continue
log.info(
f"[{self.account_name}] Waiting for {waitTime} seconds, Mini-game {game['id']} will be completed in {waitTime} seconds..."
)
time.sleep(waitTime)
url = "https://api.hamsterkombatgame.io/clicker/claim-daily-keys-minigame"
headers = {
"Access-Control-Request-Headers": "authorization,content-type",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Accept": "application/json",
"Authorization": self.Authorization,
"Content-Type": "application/json",
}
responseGameData = response["dailyKeysMiniGames"]
startDate = responseGameData["startDate"]
remainPoints = responseGameData["remainPoints"]
maxMultiplier = min(self.GetConfig('mg_max_tiles_points_percent', 20), 100) / 100
number = int(
datetime.datetime.fromisoformat(
startDate.replace("Z", "+00:00")
).timestamp()
)
number_len = len(str(number))
index = (number % (number_len - 2)) + 1
res = ""
score_per_game = {
"Candles": 0,
"Tiles": (
random.randint(int(remainPoints * 0.01), int(remainPoints * maxMultiplier))
if remainPoints > 300
else remainPoints
),
}
for i in range(1, number_len + 1):
if i == index:
res += "0"
else:
res += str(random.randint(0, 9))
score_cipher = 2 * (number + (score_per_game[responseGameData["id"]]))
data_string = "|".join(
[
res,
AccountID,
responseGameData["id"],
str(score_cipher),
base64.b64encode(
hashlib.sha256(
f"R1cHard_AnA1{score_cipher}G1ve_Me_y0u7_Pa55w0rD".encode()
).digest()
).decode(),
]
).encode()
cipher_base64 = base64.b64encode(data_string).decode()
payload = json.dumps(
{
"miniGameId": response["dailyKeysMiniGames"]["id"],
"cipher": cipher_base64,
}
)
# Send POST request
response = self.HttpRequest(url, headers, "POST", 200, payload)
if response is None:
log.error(
f"[{self.account_name}] Unable to claim mini game {game['id']}."
)
self.SendTelegramLog(
f"[{self.account_name}] Unable to claim mini game {game['id']}.",
"other_errors",
)
return
log.info(
f"[{self.account_name}] Mini game {game['id']} claimed successfully, + {number_to_string(response['bonus'])} {'keys' if game['id'] == 'Candles' else 'coins'}"
)
log.info(f"[{self.account_name}] Mini game phase completed.")
def GetPromos(self):
url = "https://api.hamsterkombatgame.io/clicker/get-promos"
headers = {
"Access-Control-Request-Headers": "authorization",
"Access-Control-Request-Method": "POST",
}
# Send OPTIONS request
self.HttpRequest(url, headers, "OPTIONS", 204)
headers = {
"Authorization": self.Authorization,
}
# Send POST request
response = self.HttpRequest(url, headers, "POST", 200)
return response
def StartPlaygroundGame(self):
if not self.config["auto_playground_games"]:
log.info(f"[{self.account_name}] Playground games are disabled.")
return
log.info(f"[{self.account_name}] Starting getting playground games...")
response = self.GetPromos()
if response is None:
log.error(f"[{self.account_name}] Unable to get playground games.")
self.SendTelegramLog(
f"[{self.account_name}] Unable to get playground games.", "other_errors"
)
return
if "promos" not in response:
log.error(f"[{self.account_name}] Unable to get playground games.")
self.SendTelegramLog(
f"[{self.account_name}] Unable to get playground games.", "other_errors"
)
return
promo_count = 0
shuffled_promos = response["promos"][:]
random.shuffle(shuffled_promos)
for promo in shuffled_promos:
if promo["promoId"] not in SupportedPromoGames:
log.warning(
f"[{self.account_name}] Detected unknown playground game: {promo['title']['en']}. Check project github for updates."
)
continue
if self.CheckPlayGroundGameState(promo, response):
promoData = SupportedPromoGames[promo["promoId"]]
promo_count += 1
if self.GetConfig(
"max_promo_games_per_round", 3
) != 0 and promo_count > self.GetConfig("max_promo_games_per_round", 3):
log.info(
f"[{self.account_name}] Maximum number of playground games reached. We will retrieve other games in the next run."
)
return