-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatagrabber.py
1837 lines (1610 loc) · 91.1 KB
/
datagrabber.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
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# clovervidia
import csv
import datetime
import glob
import json
import os
import random
import re
import subprocess
import sys
import time
import urllib.request
from directaccesshelp import help_reader
import requests
from colorama import init, Fore, Style
from dateutil.relativedelta import relativedelta
init(autoreset=True)
try:
with open("config.txt", "r", encoding="utf8") as config_file:
config_data = json.load(config_file)
COOKIE = config_data["cookie"]
except IOError:
print("config.txt not found. Please check file.")
sys.exit(1)
except ValueError:
print("Cookie not found in config.txt. Please check file.")
sys.exit(1)
TIMEZONE_OFFSET = "0" # Offset is used to print the time on shared images. It's your offset from UTC in minutes.
# For example, EST (-4) is 240 and PST (-8) is 480
UNIQUE_ID = "8386546935489260343" # Used to order gear from the SplatNet Shop
FRIEND_CODE = "YOUR NSO FC" # Type "c" at the prompt to print your FC
# API endpoints
URL_API_SHARE_PROFILE = "https://app.splatoon2.nintendo.net/api/share/profile"
URL_API_SHARE_WINLOSS = "https://app.splatoon2.nintendo.net/api/share/results/summary"
URL_API_SHARE_BATTLE = "https://app.splatoon2.nintendo.net/api/share/results/{}"
URL_API_SHARE_CHALLENGE = "https://app.splatoon2.nintendo.net/api/share/challenges/{}"
URL_API_BATTLE_RESULTS = "https://app.splatoon2.nintendo.net/api/results/{}"
URL_API_RESULTS = "https://app.splatoon2.nintendo.net/api/results"
URL_API_RECORDS = "https://app.splatoon2.nintendo.net/api/records"
URL_API_COOP_SCHEDULES = "https://app.splatoon2.nintendo.net/api/coop_schedules"
URL_API_COOP_RESULTS = "https://app.splatoon2.nintendo.net/api/coop_results"
URL_API_DATA_STAGES = "https://app.splatoon2.nintendo.net/api/data/stages"
URL_API_ONLINESHOP_MERCH = "https://app.splatoon2.nintendo.net/api/onlineshop/merchandises"
URL_API_ONLINESHOP_ORDER = "https://app.splatoon2.nintendo.net/api/onlineshop/order/{}"
URL_API_RECORDS_HERO = "https://app.splatoon2.nintendo.net/api/records/hero"
URL_API_SCHEDULES = "https://app.splatoon2.nintendo.net/api/schedules"
URL_API_TIMELINE = "https://app.splatoon2.nintendo.net/api/timeline"
URL_API_FEST_ACTIVE = "https://app.splatoon2.nintendo.net/api/festivals/active"
URL_API_FEST_PASTS = "https://app.splatoon2.nintendo.net/api/festivals/pasts"
URL_API_FEST_RANKINGS = "https://app.splatoon2.nintendo.net/api/festivals/{}/rankings"
URL_API_FEST_RESULT = "https://app.splatoon2.nintendo.net/api/festivals/{}/result"
URL_API_FEST_VOTES = "https://app.splatoon2.nintendo.net/api/festivals/{}/votes"
URL_API_FEST_EVENTS = "https://app.splatoon2.nintendo.net/api/festivals/{}/events"
URL_API_LEAGUE_MATCH_RANKINGS = "https://app.splatoon2.nintendo.net/api/league_match_ranking/{}"
URL_API_NICKNAME_ICON = "https://app.splatoon2.nintendo.net/api/nickname_and_icon"
URL_API_X_POWER_RANKING_SUMMARY = "https://app.splatoon2.nintendo.net/api/x_power_ranking/{}T00_{}T00/summary"
URL_API_X_POWER_RANKING_PAGES = "https://app.splatoon2.nintendo.net/api/x_power_ranking/{}T00_{}T00/{}"
URL_API_BASE = "https://app.splatoon2.nintendo.net{}"
URL_API_SPLATOON2_INK_FEST_DATA = "https://splatoon2.ink/data/festivals.json"
# Folder names
JSON_FOLDER = "jsons"
BATTLES_FOLDER = "battles"
LEAGUE_RANKINGS_FOLDER = "league rankings"
X_RANKINGS_FOLDER = "x power rankings"
SPLATFEST_IMAGES_FOLDER = "splatfest images"
SPLATFEST_STATS_FOLDER = "splatfest stats"
GEAR_IMAGES_FOLDER = "gear images"
WEAPON_IMAGES_FOLDER = "weapon images"
SHARED_IMAGES = "shared images"
# Making sure the folders exist first
for folder in [JSON_FOLDER, os.path.join(JSON_FOLDER, BATTLES_FOLDER),
os.path.join(JSON_FOLDER, LEAGUE_RANKINGS_FOLDER), os.path.join(JSON_FOLDER, X_RANKINGS_FOLDER),
SPLATFEST_IMAGES_FOLDER, SPLATFEST_STATS_FOLDER, GEAR_IMAGES_FOLDER, WEAPON_IMAGES_FOLDER,
SHARED_IMAGES]:
if not os.path.exists(folder):
os.makedirs(folder)
# Clipboard command
CLIP_CMD = "clip.exe"
# Commonly used headers
app_head_share = {
"origin": "https://app.splatoon2.nintendo.net",
"x-unique-id": UNIQUE_ID,
"x-requested-with": "XMLHttpRequest",
"x-timezone-offset": TIMEZONE_OFFSET,
"User-Agent": "Mozilla/5.0 (Linux; Android 7.1.2; Pixel Build/NJH47D; wv) AppleWebKit/537.36 (KHTML, like Gecko) "
"Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36",
"Accept": "*/*",
"Referer": "https://app.splatoon2.nintendo.net/results",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US"
}
app_head_results = {
"Host": "app.splatoon2.nintendo.net",
"x-unique-id": UNIQUE_ID,
"x-requested-with": "XMLHttpRequest",
"x-timezone-offset": TIMEZONE_OFFSET,
"User-Agent": "Mozilla/5.0 (Linux; Android 7.1.2; Pixel Build/NJH47D; wv) AppleWebKit/537.36 (KHTML, like Gecko) "
"Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36",
"Accept": "*/*",
"Referer": "https://app.splatoon2.nintendo.net/home",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US"
}
app_head_shop = {
"origin": "https://app.splatoon2.nintendo.net",
"x-unique-id": UNIQUE_ID,
"x-requested-with": "XMLHttpRequest",
"x-timezone-offset": TIMEZONE_OFFSET,
"User-Agent": "Mozilla/5.0 (Linux; Android 7.1.2; Pixel Build/NJH47D; wv) AppleWebKit/537.36 (KHTML, like Gecko) "
"Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36",
"Accept": "*/*",
"Referer": "https://app.splatoon2.nintendo.net/results",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US"
}
# Splatfest IDs
FESTIVALS_NA = {"1": "2050", "2": "5051", "3": "2051", "4": "2052", "5": "2053", "6": "4051", "7": "2054", "8": "5052",
"9": "2055", "10": "5053", "11": "5054", "12": "5056", "13": "5059", "14": "4052", "15": "2056",
"16": "5060", "17": "4053", "18": "2057", "19": "4054", "20": "4055", "21": "5061"}
FESTIVALS_JP = {"1": "1051", "2": "1052", "3": "1054", "4": "1055", "5": "1056", "6": "4051", "7": "1057", "8": "1058",
"9": "1059", "10": "1060", "11": "1061", "12": "1062", "13": "1063", "14": "4052", "15": "1065",
"16": "1066", "17": "4053", "18": "1067", "19": "4054", "20": "4055", "21": "1068"}
FESTIVALS_EU = {"1": "3050", "2": "5051", "3": "3051", "4": "3052", "5": "3053", "6": "4051", "7": "3054", "8": "5052",
"9": "3055", "10": "5053", "11": "5054", "12": "5056", "13": "5059", "14": "4052", "15": "3056",
"16": "5060", "17": "4053", "18": "3057", "19": "4054", "20": "4055", "21": "5061"}
# Splatfest region
FESTIVALS = FESTIVALS_NA
def main():
menu()
def menu():
print("SplatNet 2 Shell")
while True:
print("\n1 - Profile")
print("2 - Win/Loss of Last 50 Battles")
print("3 - Results of a Specific Battle (Image + JSON)")
print("4 - Results of Latest Battle (Image + JSON)")
print("5 - Results of Latest Battle (Monitor) (Image + JSON)")
print("6 - Results of All Battles (Image + JSON)")
print(Fore.RED + Style.BRIGHT + "0 - Exit")
option = input("\nclover@splatnet2:~$ ")
if option == "1":
get_profile()
elif option == "2":
get_win_loss()
elif option == "3":
get_battle_results()
elif option == "4":
get_battle_results(True)
elif option == "5":
get_battle_results_monitor()
elif option == "6":
get_all_battle_results()
elif option == "0":
sys.exit(0)
elif option.lower() in ["c", "cookie"]:
print(COOKIE)
if os.name == "nt":
os.system('set /p="{}" < nul | clip'.format(COOKIE))
else:
os.system("echo -n {} | {}".format(COOKIE, CLIP_CMD))
elif option.lower() == "f":
script_path = os.path.dirname(os.path.realpath(__file__))
if os.name == "nt":
subprocess.Popen("explorer {}".format(script_path))
elif option.lower() == "fc":
print(FRIEND_CODE)
if os.name == "nt":
os.system('set /p="{}" < nul | clip'.format(FRIEND_CODE))
else:
os.system("echo -n {} | {}".format(FRIEND_CODE, CLIP_CMD))
elif len(re.split(";\s*", option)) > 1:
for i in re.split(";\s*", option):
direct_access(i)
else:
direct_access(option)
def countdown(timer):
for i in range(timer, -1, -1):
sys.stdout.write("Press Ctrl+C to exit. {} ".format(i))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\r")
def get_profile(auto=False):
if not auto:
profile_map = input("\nEnter the map ID you want in the image: ") # 0 - 8, 6 included this time
if profile_map == "":
profile_map = "0"
profile_color = input(
"Enter the color you want for the background: ") # Can be pink, green, yellow, purple, blue, or sun-yellow
if profile_color == "":
profile_color = "pink"
else:
profile_map = "0"
profile_color = "pink"
settings = {"stage": profile_map, "color": profile_color}
image_url = get_image(URL_API_SHARE_PROFILE, settings)
if auto:
image = "{}/{} profile {}".format(SHARED_IMAGES, time.strftime("%Y-%m-%d %H-%M-%S"), image_url.split("/")[-1])
else:
image = "{} profile {}".format(time.strftime("%Y-%m-%d %H-%M-%S"), image_url.split("/")[-1])
urllib.request.urlretrieve(image_url, image)
def get_win_loss(auto=False):
image_url = get_image(URL_API_SHARE_WINLOSS)
if auto:
image = "{}/{} wl {}".format(SHARED_IMAGES, time.strftime("%Y-%m-%d %H-%M-%S"), image_url.split("/")[-1])
else:
image = "{} wl {}".format(time.strftime("%Y-%m-%d %H-%M-%S"), image_url.split("/")[-1])
urllib.request.urlretrieve(image_url, image)
get_results(True)
def get_challenge():
challenge = input("Which challenge? ")
image_url = get_image(URL_API_SHARE_CHALLENGE.format(challenge))
urllib.request.urlretrieve(image_url, "{} {} {}".format(time.strftime("%Y-%m-%d %H-%M-%S"), challenge,
image_url.split("/")[-1]))
def get_battle_results(latest=False, battle_no=None, auto=False):
results = get_results(True)
battle_date = None
if latest:
battle_no = results[0]["battle_number"]
print("Your latest battle was #{}".format(battle_no))
image_url = get_image(URL_API_SHARE_BATTLE.format(battle_no))
battle_date = datetime.datetime.fromtimestamp(int(results[0]["start_time"])).strftime("%Y-%m-%d %H-%M-%S")
image = "{} {} {}".format(battle_date, battle_no, image_url.split("/")[-1])
urllib.request.urlretrieve(image_url, image)
else:
if battle_no is None:
battle_no = input("\nWhich battle do you want the results for? ")
if battle_no == "":
battle_no = results[0]["battle_number"]
battle_date = datetime.datetime.fromtimestamp(int(results[0]["start_time"])).strftime(
"%Y-%m-%d %H-%M-%S")
for i in range(len(results)):
if results[i]["battle_number"] == battle_no:
battle_date = datetime.datetime.fromtimestamp(int(results[i]["start_time"])).strftime(
"%Y-%m-%d %H-%M-%S")
break
if auto:
image_url = get_image(URL_API_SHARE_BATTLE.format(battle_no))
image = "{}/{} {} {}".format(SHARED_IMAGES, battle_date, battle_no, image_url.split("/")[-1])
else:
image_url = get_image(URL_API_SHARE_BATTLE.format(battle_no))
image = "{} {} {}".format(battle_date, battle_no, image_url.split("/")[-1])
image_url = get_image(URL_API_SHARE_BATTLE.format(battle_no))
urllib.request.urlretrieve(image_url, image)
url = URL_API_BATTLE_RESULTS.format(battle_no)
battle = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
battle_data = json.loads(battle.text)
print("{:<5} {:<23} {:<18} {:<15} {}{:<15}".format(battle_no, battle_data["stage"]["name"],
battle_data["game_mode"]["name"], battle_data["rule"]["name"],
Fore.GREEN if battle_data["my_team_result"][
"name"] == "VICTORY" else Fore.RED,
battle_data["my_team_result"]["name"]))
with open(os.path.join(JSON_FOLDER, os.path.join(BATTLES_FOLDER, "{} {}.json".format(battle_date, battle_no))), "w",
encoding="utf8") as file:
json.dump(battle_data, file, ensure_ascii=False)
def get_battle_results_monitor():
results = get_results(True)
last_battle = int(results[0]["battle_number"])
first = last_battle + 1
get_win_loss(True)
get_profile(True)
get_records()
wins = 0
losses = 0
splatfest_wins = 0
splatfest_losses = 0
splatfest_power = 0
mirror_matches = 0
try:
while True:
results = get_results(True)
if int(results[0]["battle_number"]) > last_battle:
get_battle_results(False, results[0]["battle_number"], True)
last_battle = int(results[0]["battle_number"])
get_records()
if results[0]["my_team_result"]["key"] == "victory":
wins += 1
if results[0]["game_mode"]["key"] in ["fes_solo", "fes_team"]:
if results[0]["my_team_fes_theme"]["key"] == results[0]["other_team_fes_theme"]["key"]:
mirror_matches += 1
else:
splatfest_wins += 1
else:
losses += 1
if results[0]["game_mode"]["key"] in ["fes_solo", "fes_team"]:
if results[0]["my_team_fes_theme"]["key"] == results[0]["other_team_fes_theme"]["key"]:
mirror_matches += 1
else:
splatfest_losses += 1
try:
if results[0]["fes_power"] != 0:
print("{:+4.1f}".format(results[0]["fes_power"] - splatfest_power))
splatfest_power = results[0]["fes_power"]
except Exception as e:
print("Encountered exception when parsing Splatfest power:\n{}\n".format(e))
else:
pass
countdown(90)
except KeyboardInterrupt:
print("\nDownloading win/loss and profile before stopping.")
results = get_results(True)
get_win_loss(True)
get_profile(True)
get_records()
if results[0]["type"] == "league":
print("Highest power was {}.".format(results[0]["max_league_point"]))
if results[0]["type"] == "fes":
if results[0]["max_fes_power"] != 0:
print("Highest power was {}.".format(results[0]["max_fes_power"]))
if results[0]["contribution_point_total"] != 0:
print("Final clout was {}.".format(results[0]["contribution_point_total"]))
battle_numbers(first, last_battle)
print("{} win{} and {} loss{}.".format(wins, "s" if wins != 1 else "", losses, "es" if losses != 1 else ""))
if splatfest_wins != 0 or splatfest_losses != 0:
print("{} win{} and {} loss{} against the other Splatfest team.".format(splatfest_wins,
"" if splatfest_wins == 1 else "s",
splatfest_losses,
"" if splatfest_losses == 1 else "es"))
print("{} mirror match{} against your Splatfest team.".format(mirror_matches,
"" if mirror_matches == 1 else "es"))
except Exception as e:
print("Encountered exception when downloading results from SplatNet:\n{}\nStopping.".format(e))
def get_all_battle_results():
results = get_results(True)
for n in range(len(results)):
battle_no = results[n]["battle_number"]
get_battle_results(False, battle_no)
def get_results(download=False):
r = requests.get(URL_API_RESULTS, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
data = json.loads(r.text)
try:
results = data["results"]
except KeyError:
print("Bad cookie. Please check config.txt.")
sys.exit(1)
if download:
with open(os.path.join(JSON_FOLDER, "{} results.json").format(
datetime.datetime.fromtimestamp(int(results[0]["start_time"])).strftime("%Y-%m-%d %H-%M-%S")), "w",
encoding="utf8") as file:
json.dump(data, file, ensure_ascii=False)
return results
def get_image(url, payload=None):
response = requests.post(url, headers=app_head_share, cookies=dict(iksm_session=COOKIE), data=payload)
data = json.loads(response.text)
try:
image_url = data["url"]
except KeyError:
print("Bad cookie. Please check config.txt.")
sys.exit(1)
return image_url
def get_records():
response = requests.get(URL_API_RECORDS, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
url = JSON_FOLDER
with open(os.path.join(url, "{} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-1])),
"w", encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
def direct_access(option=None):
if option is None:
option = input("Type in what you want to retrieve: ")
if option in ["help", "h", "?"]:
help_reader()
elif option in ["coop schedules", "coop", "salmon run", "salmon", "s"]:
print("\nRetrieving Salmon Run Schedule.")
url = URL_API_COOP_SCHEDULES
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-1]), "w",
encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
parse_salmon_run_schedule(json.loads(response.text))
elif option in ["coop results"]:
print("\nRetrieving Salmon Run Results.")
url = URL_API_COOP_RESULTS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-1]), "w",
encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
elif option in ["data stages", "stages", "stage data", "maps"]:
print("\nRetrieving list of current stages.")
url = URL_API_DATA_STAGES
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-2], url.split("/")[-1]),
"w", encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
elif option in ["nickname and icon"]:
pass # Coming soon(tm)
elif option in ["nickname", "name", "icon"]:
nicknames_and_icons()
elif option in ["update names", "update nicknames"]:
print("\nUpdating nickname database.")
update_nicknames()
elif option in ["onlineshop merchandises", "merchandise", "shop", "store", "annie", "order", "buy gear"]:
print("\nRetrieving available items at the SplatNet Gear Shop.")
url = URL_API_ONLINESHOP_MERCH
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-2], url.split("/")[-1]),
"w",
encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
parse_gear_images(json.loads(response.text))
parse_splatnet_shop(json.loads(response.text))
elif option in ["records"]:
print("\nRetrieving current records.")
url = URL_API_RECORDS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-1]), "w",
encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
elif option in ["records hero", "hero records", "hero"]:
print("\nRetrieving Hero Mode records.")
url = URL_API_RECORDS_HERO
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-2], url.split("/")[-1]),
"w", encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
elif option in ["stage records", "stage stats"]:
url = URL_API_RECORDS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
parse_records_stages(json.loads(response.text)["records"])
elif re.search("stage records \d+", option) is not None or re.search("stage stats \d+", option) is not None:
url = URL_API_RECORDS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
parse_records_stages(json.loads(response.text)["records"], re.search("\d+", option).group(0))
elif option in ["weapon records", "weapon stats"]:
url = URL_API_RECORDS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
parse_records_weapons(json.loads(response.text)["records"])
elif re.search("weapon records \d+", option) is not None or re.search("weapon stats \d+", option) is not None:
url = URL_API_RECORDS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
parse_records_weapons(json.loads(response.text)["records"], re.search("\d+", option).group(0))
elif option in ["league stats"]:
url = URL_API_RECORDS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
parse_league_stats(json.loads(response.text)["records"])
elif option in ["results"]:
print("\nRetrieving latest battle results.")
url = URL_API_RESULTS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-1]), "w",
encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
elif option in ["schedules", "schedule", "rotations", "rotation", "r"]:
print("\nRetrieving current and upcoming stage rotations.")
url = URL_API_SCHEDULES
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-1]), "w",
encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
rotation = json.loads(response.text)
parse_schedules(rotation, None)
elif option in ["rotation next", "next rotation", "next"]:
print("\nRetrieving upcoming stage rotations.")
url = URL_API_SCHEDULES
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
rotation = json.loads(response.text)
parse_schedules(rotation, None, 1)
elif re.search("next \d+", option) is not None:
print("\nRetrieving upcoming stage rotations.")
url = URL_API_SCHEDULES
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
rotation = json.loads(response.text)
parse_schedules(rotation, None, int(re.search("\d+", option).group(0)))
elif option in ["now and later", "nnl"]:
url = URL_API_SCHEDULES
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
rotation = json.loads(response.text)
print(Fore.BLUE + Style.BRIGHT + "\nRight now:")
parse_schedules(rotation, None)
print(Fore.BLUE + Style.BRIGHT + "Next:")
parse_schedules(rotation, None, 1)
print(Fore.BLUE + Style.BRIGHT + "Later:")
parse_schedules(rotation, None, 2)
elif option in ["timeline"]:
print("\nRetrieving your timeline.")
url = URL_API_TIMELINE
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-1]), "w",
encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
parse_gear_images(json.loads(response.text))
parse_timeline(json.loads(response.text))
elif option in ["festival", "splatfest", "fes", "fest"]:
festival_access()
elif option in ["league"]:
league_board_access()
elif option in ["league all", "l"]:
league_board_access_all()
elif re.search("league all \d+", option) is not None:
league_board_access_all(re.search("\d+", option).group(0))
elif option in ["league everything"]:
download_league_everything()
elif re.search("league everything \d+ \d+", option) is not None:
download_league_everything(re.search("(\d+) (\d+)", option).group(1), re.search("(\d+) (\d+)", option).group(2))
elif option in ["x rank", "rank x", "x"]:
download_x_rankings()
elif re.search("x rank \d+-\d+", option) is not None:
download_x_rankings(re.search("\d+-\d+", option).group(0))
elif option.lower() == "f":
script_path = os.path.dirname(os.path.realpath(__file__))
if os.name == "nt":
subprocess.Popen("explorer {}".format(script_path))
elif option in ["profile", "ranks"]:
url = URL_API_RECORDS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
profile_card(json.loads(response.text))
elif option in ["profile tracks", "tracks profile"]:
url = URL_API_RECORDS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
profile_tracks(json.loads(response.text))
elif option in ["patch notes"]:
print("JP Notes: https://support.nintendo.co.jp/app/answers/detail/a_id/34680")
print("US Notes: http://en-americas-support.nintendo.com/app/answers/detail/a_id/27028")
print("US History: https://en-americas-support.nintendo.com/app/answers/detail/a_id/28658")
if os.name == "nt":
os.system("echo http://en-americas-support.nintendo.com/app/answers/detail/a_id/27028 | clip")
else:
os.system("echo http://en-americas-support.nintendo.com/app/answers/detail/a_id/27028 | {}".
format(CLIP_CMD))
elif option in ["challenge"]:
get_challenge()
else:
festival_access(option)
def festival_access(option=None):
if option is None:
option = input("What Splatfest data would you like to retrieve? ")
if option in ["active"]:
print("\nRetrieving active Splatfests.")
url = URL_API_FEST_ACTIVE
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-2], url.split("/")[-1]),
"w", encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
parse_active_splatfests(json.loads(response.text))
elif option in ["pasts"]:
print("\nRetrieving past Splatfests.")
url = URL_API_FEST_PASTS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-2], url.split("/")[-1]),
"w", encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
elif option in ["votes"]:
festival_id = input("Which Splatfest do you want to retrieve the votes for? ")
parse_splatfest_votes(festival_id)
elif re.search("votes \d+", option) is not None:
festival_id = int(re.search("\d+", option).group(0))
parse_splatfest_votes(festival_id)
elif option in {"rankings"}:
festival_id = input("Which Splatfest do you want to retrieve the rankings for? ")
if festival_id in FESTIVALS:
festival_id = FESTIVALS[festival_id]
elif len(festival_id) != 4 or festival_id == "" or len(re.findall("[\D]", festival_id)) > 0:
print("Invalid Splatfest ID. Please check it and try again.")
return
print("\nRetrieving Splatfest rankings.")
url = URL_API_FEST_RANKINGS.format(festival_id)
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {} {} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-3], url.split("/")[-2],
url.split("/")[-1]), "w", encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
elif re.search("rankings \d+", option) is not None:
festival_id = int(re.search("\d+", option).group(0))
if str(festival_id) in FESTIVALS:
festival_id = FESTIVALS[str(festival_id)]
elif len(str(festival_id)) != 4 or str(festival_id) == "" or len(re.findall("[\D]", str(festival_id))) > 0:
print("Invalid Splatfest ID. Please check it and try again.")
return
print("\nRetrieving Splatfest rankings.")
url = URL_API_FEST_RANKINGS.format(festival_id)
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
with open("{} {} {} {}.json".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-3], url.split("/")[-2],
url.split("/")[-1]), "w", encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
elif option in ["ranking average", "average power", "splatfest power"]:
festival_id = input("Which Splatfest do you want to calculate statistics for the top 100 players for? ")
if festival_id in FESTIVALS:
festival_id = FESTIVALS[festival_id]
elif len(festival_id) != 4 or festival_id == "" or len(re.findall("[\D]", festival_id)) > 0:
print("Invalid Splatfest ID. Please check it and try again.")
return
url = URL_API_FEST_RANKINGS.format(festival_id)
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
try:
parse_splatfest_rankings(json.loads(response.text))
except Exception as e:
print("Encountered exception when parsing Splatfest rankings:\n{}\n".format(e))
elif option in ["splatfest power stats", "splatfest stats"]:
print("Calculating Splatfest Power statistics.\r", end="")
parse_splatfest_rankings_stats()
elif option in ["fest results", "results", "result"]:
parse_splatfest_results()
elif re.search("fest results \d+", option) is not None:
festival_id = int(re.search("\d+", option).group(0))
parse_splatfest_results(festival_id)
elif option in ["all festivals", "all fest", "all splatfest"]:
print("\nRetrieving Splatfest data.")
url = URL_API_SPLATOON2_INK_FEST_DATA
response = requests.get(url)
with open("{} {} {} {}".format(time.strftime("%Y-%m-%d %H-%M-%S"), url.split("/")[-3], url.split("/")[-2],
url.split("/")[-1]), "w", encoding="utf8") as file:
json.dump(json.loads(response.text), file, ensure_ascii=False)
elif option in ["colors", "splatfest colors"]:
url = URL_API_FEST_PASTS
response = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
url = URL_API_FEST_ACTIVE
response_active = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
try:
parse_splatfest_colors(json.loads(response_active.text))
except Exception as e:
print("Encountered exception when parsing Splatfest colors:\n{}\n".format(e))
try:
parse_splatfest_colors(json.loads(response.text))
except Exception as e:
print("Encountered exception when parsing Splatfest colors:\n{}\n".format(e))
elif option in ["na colors", "us colors"]:
url = URL_API_SPLATOON2_INK_FEST_DATA
response = requests.get(url)
try:
parse_splatfest_colors(json.loads(response.text)["na"])
except Exception as e:
print("Encountered exception when parsing Splatfest colors:\n{}\n".format(e))
elif option in ["eu colors"]:
url = URL_API_SPLATOON2_INK_FEST_DATA
response = requests.get(url)
try:
parse_splatfest_colors(json.loads(response.text)["eu"])
except Exception as e:
print("Encountered exception when parsing Splatfest colors:\n{}\n".format(e))
elif option in ["jp colors"]:
url = URL_API_SPLATOON2_INK_FEST_DATA
response = requests.get(url)
try:
parse_splatfest_colors(json.loads(response.text)["jp"])
except Exception as e:
print("Encountered exception when parsing Splatfest colors:\n{}\n".format(e))
elif option in ["team images", "images", "splatfest images", "fest images"]:
download_all_splatfest_images()
elif option in ["events", "event battles"]:
festival_id = input("Which Splatfest do you want to retrieve the events for? ")
get_splatfest_events(festival_id)
elif re.search("events \d+", option) is not None:
festival_id = int(re.search("\d+", option).group(0))
get_splatfest_events(festival_id)
else:
print("That's not an option.")
def league_board_access():
league_code = input("Enter the date and time code to download: ")
team_type = None
if len(league_code) > 9:
print("Invalid code. Check the URL and try again.")
return
if len(league_code) == 8:
team_type = input("Enter 't' for a team or 'p' for a pair: ") # How can I support getting both?
if team_type.lower() != "t" and team_type.lower() != "p":
print("That's not an option.")
return
region = input("Enter the region to retrieve (ALL, JP, US, or EU): ") # I think ALL should get all 4.
if region.lower() not in ["all", "jp", "us", "eu"]:
print("That's not an option.")
return
if region.lower() == "all":
download_league(league_code, team_type, "all")
download_league(league_code, team_type, "jp")
download_league(league_code, team_type, "us")
download_league(league_code, team_type, "eu")
download_league(league_code, team_type, region)
def league_board_access_all(league_code=None):
if league_code is None:
league_code = input("Enter the date and time code to download: ")
if len(league_code) > 9:
print("Invalid code. Check the URL and try again.")
return
download_league(league_code, "t", "all")
download_league(league_code, "t", "jp")
download_league(league_code, "t", "us")
download_league(league_code, "t", "eu")
download_league(league_code, "p", "all")
download_league(league_code, "p", "jp")
download_league(league_code, "p", "us")
download_league(league_code, "p", "eu")
def download_league(league_code, team_type, region):
league_code = league_code + team_type.upper()
league_code = "{}/{}".format(league_code, region.upper())
url = URL_API_LEAGUE_MATCH_RANKINGS.format(league_code)
league_raw_data = requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE))
league_data = json.loads(league_raw_data.text)
if "league_id" in league_data:
league_date = datetime.datetime.fromtimestamp(int(league_data["start_time"])).strftime("%Y-%m-%d %H-%M-%S")
else:
print("Something went wrong ({} had no {} squads in League).".format(
{"all": "all countries", "eu": "Europe", "jp": "Japan", "us": "North America"}.get(region, "some region"),
{"t": "team", "p": "pair"}.get(team_type)))
return
filename = "{} {} {} {}.json".format(league_date, url.split("/")[-3], url.split("/")[-2], url.split("/")[-1])
if os.path.exists(filename):
print("{} already exists. Skipping the download.".format(os.path.basename(filename)))
return
with open(filename, "w", encoding="utf8") as file:
json.dump(json.loads(league_raw_data.text), file, ensure_ascii=False)
def download_league_everything(start_code=None, end_code=None):
if start_code is None or end_code is None:
print("\nUsage: league everything <start code> <end code>.")
print("Use 0 for both to automatically set start and end codes.")
return
if start_code == "0":
try:
start_code = max(glob.glob(os.path.join(JSON_FOLDER, LEAGUE_RANKINGS_FOLDER, "*")),
key=os.path.getctime)[63:71]
except ValueError:
start_code = "17072108"
start_code = datetime.datetime(int("20" + start_code[0:2]), int(start_code[2:4]), int(start_code[4:6]),
int(start_code[6:8]), 00) + datetime.timedelta(hours=2)
start_code = time.strftime("%y%m%d%H", time.strptime(str(start_code), "%Y-%m-%d %H:%M:%S"))
elif start_code == "00":
start_code = "17072108"
if end_code == "0":
end_code = datetime.datetime.utcnow()
if end_code.hour % 2 == 0:
pass
else:
end_code = end_code - datetime.timedelta(hours=1)
end_code = end_code.replace(minute=15)
if end_code.minute >= 15:
pass
else:
end_code = end_code - datetime.timedelta(hours=2)
end_code = time.strftime("%y%m%d%H", time.strptime(str(end_code), "%Y-%m-%d %H:%M:%S.%f"))
else:
end_code = datetime.datetime(int("20" + end_code[0:2]), int(end_code[2:4]), int(end_code[4:6]),
int(end_code[6:8]), 00) + datetime.timedelta(hours=2)
end_code = time.strftime("%y%m%d%H", time.strptime(str(end_code), "%Y-%m-%d %H:%M:%S"))
if start_code == end_code:
new_results = datetime.datetime(int("20" + end_code[0:2]), int(end_code[2:4]), int(end_code[4:6]),
int(end_code[6:8]), 15) + datetime.timedelta(
hours=2) - datetime.datetime.utcnow()
print("\nNo new league records to retrieve. Next results will be available in {}.".format(
str(new_results).split(".")[0]))
return
if end_code < start_code:
print("\nSomething went horribly, horribly wrong.")
print("{} {}".format(end_code, start_code))
return
print("\nStarting at {} and stopping at {}.".format(start_code, end_code))
i = 0
while True: # (2017,7,21,4,00) or 2017-07-21 4:00 AM were the first recorded league rankings
rotation = datetime.timedelta(hours=i)
current_rotation = datetime.datetime(int("20" + start_code[0:2]), int(start_code[2:4]), int(start_code[4:6]),
int(start_code[6:8]), 00) + rotation
league_code = time.strftime("%y%m%d%H", time.strptime(str(current_rotation), "%Y-%m-%d %H:%M:%S"))
if league_code == end_code:
break
print(league_code + " " * 17)
try:
download_league(league_code, "t", "all")
time.sleep(random.randint(3, 8))
download_league(league_code, "t", "jp")
time.sleep(random.randint(3, 8))
download_league(league_code, "t", "us")
time.sleep(random.randint(3, 8))
download_league(league_code, "t", "eu")
time.sleep(random.randint(3, 8))
download_league(league_code, "p", "all")
time.sleep(random.randint(3, 8))
download_league(league_code, "p", "jp")
time.sleep(random.randint(3, 8))
download_league(league_code, "p", "us")
time.sleep(random.randint(3, 8))
download_league(league_code, "p", "eu")
except KeyboardInterrupt:
print("And we're up to date!")
return
except Exception as e:
print("Encountered exception when downloading league rankings:\n{}\n".format(e))
return
i += 2
try:
next_rotation = datetime.timedelta(hours=i)
next_current_rotation = datetime.datetime(int("20" + start_code[0:2]),
int(start_code[2:4]), int(start_code[4:6]),
int(start_code[6:8]), 00) + next_rotation
next_league_code = time.strftime("%y%m%d%H", time.strptime(str(next_current_rotation), "%Y-%m-%d %H:%M:%S"))
if next_league_code == end_code:
break
countdown(15)
except KeyboardInterrupt:
print("Stopping there. ")
return
except Exception as e:
print("Encountered exception when downloading league rankings:\n{}\n".format(e))
return
print("Stopping there. ")
return
def parse_salmon_run_schedule(salmon_run):
for i in range(len(salmon_run["details"])):
if time.time() > salmon_run["details"][i]["start_time"]:
time_left = datetime.datetime.fromtimestamp(salmon_run["details"][i]["end_time"]) - datetime.datetime.now()
print("You have {} left to finish your shift.".format(str(time_left).split(".")[0]))
else:
time_to_shift = datetime.datetime.fromtimestamp(
salmon_run["details"][i]["start_time"]) - datetime.datetime.now()
print("Next Salmon Run shift starts in {}. It starts at {}.".format(str(time_to_shift).split(".")[0],
datetime.datetime.fromtimestamp(
salmon_run["details"][i][
"start_time"])))
print("* You'll be heading to the {} for this one.".format(
Fore.GREEN + salmon_run["details"][i]["stage"]["name"] + Style.RESET_ALL))
print("* Your weapons will include: ", end="")
weapons = []
for j in salmon_run["details"][i]["weapons"]:
if "coop_special_weapon" in j.keys():
if j["id"] == "-1":
weapons.append(Fore.GREEN + Style.BRIGHT + "Random weapon" + Style.RESET_ALL)
elif j["id"] == "-2":
weapons.append(Fore.YELLOW + Style.BRIGHT + "Grizzco weapon" + Style.RESET_ALL)
else:
weapons.append(Fore.YELLOW + Style.BRIGHT + "Random weapon" + Style.RESET_ALL)
else:
weapons.append(Fore.CYAN + Style.BRIGHT + j["weapon"]["name"] + Style.RESET_ALL)
print(", ".join(weapons))
def parse_active_splatfests(active):
if len(active["festivals"][0]["colors"]) > 0:
if time.time() < active["festivals"][0]["times"]["start"]:
print("There is a Splatfest coming soon!")
elif time.time() < active["festivals"][0]["times"]["end"]:
print("There is a Splatfest going on!")
else:
print("The Splatfest is over, but the results are still to come.")
else:
print("No Splatfests going on right now.")
return
if time.time() < active["festivals"][0]["times"]["start"]:
print("The coming Splatfest is between {} and {}.".format(
Fore.GREEN + active["festivals"][0]["names"]["alpha_short"] + Style.RESET_ALL,
Fore.GREEN + active["festivals"][0]["names"]["bravo_short"] + Style.RESET_ALL))
time_to_start = datetime.datetime.fromtimestamp(
active["festivals"][0]["times"]["start"]) - datetime.datetime.now()
print("Splatfest starts in {}.".format(str(time_to_start).split(".")[0]))
if active["festivals"][0]["times"]["end"] > time.time() > active["festivals"][0]["times"]["start"]:
print("The current Splatfest is between {} and {}.".format(
Fore.GREEN + active["festivals"][0]["names"]["alpha_short"] + Style.RESET_ALL,
Fore.GREEN + active["festivals"][0]["names"]["bravo_short"] + Style.RESET_ALL))
time_left = datetime.datetime.fromtimestamp(active["festivals"][0]["times"]["end"]) - datetime.datetime.now()
print("There's {} left in this Splatfest.".format(str(time_left).split(".")[0]))
if time.time() > active["festivals"][0]["times"]["end"]:
time_to_results = datetime.datetime.fromtimestamp(
active["festivals"][0]["times"]["result"]) - datetime.datetime.now()
print("Results for {} vs {} will be out in {}.".format(
Fore.GREEN + active["festivals"][0]["names"]["alpha_short"] + Style.RESET_ALL,
Fore.GREEN + active["festivals"][0]["names"]["bravo_short"] + Style.RESET_ALL,
str(time_to_results).split(".")[0]))
download_splatfest_images(active)
def download_splatfest_images(splatfest):
for i in range(len(splatfest["festivals"])):
splatfest_folder = os.path.join(SPLATFEST_IMAGES_FOLDER, str(splatfest["festivals"][i]["festival_id"]))
if not os.path.exists(splatfest_folder):
os.makedirs(splatfest_folder)
else:
continue
urllib.request.urlretrieve(URL_API_BASE.format(splatfest["festivals"][i]["images"]["panel"]),
os.path.join(splatfest_folder,
splatfest["festivals"][i]["images"]["panel"].split("/")[-1]))
urllib.request.urlretrieve(URL_API_BASE.format(splatfest["festivals"][i]["images"]["alpha"]),
os.path.join(splatfest_folder,
splatfest["festivals"][i]["images"]["alpha"].split("/")[-1]))
urllib.request.urlretrieve(URL_API_BASE.format(splatfest["festivals"][i]["images"]["bravo"]),
os.path.join(splatfest_folder,
splatfest["festivals"][i]["images"]["bravo"].split("/")[-1]))
def download_all_splatfest_images():
url = URL_API_FEST_PASTS
download_splatfest_images(
json.loads(requests.get(url, headers=app_head_results, cookies=dict(iksm_session=COOKIE)).text))
def parse_splatfest_rankings(rankings, auto=False):
total_alpha = 0
total_bravo = 0
max_alpha = 0
max_bravo = 0
min_alpha = 3500
min_bravo = 3500
for i in range(len(rankings["rankings"]["alpha"])):
try:
total_alpha = total_alpha + int(rankings["rankings"]["alpha"][i]["score"])
max_alpha = int(rankings["rankings"]["alpha"][i]["score"]) if int(
rankings["rankings"]["alpha"][i]["score"]) > max_alpha else max_alpha
min_alpha = int(rankings["rankings"]["alpha"][i]["score"]) if int(
rankings["rankings"]["alpha"][i]["score"]) < min_alpha else min_alpha
except KeyError:
pass
except Exception as e:
print("Encountered exception when parsing Splatfest rankings for team Alpha:\n{}\n".format(e))
for i in range(len(rankings["rankings"]["bravo"])):
try:
total_bravo = total_bravo + int(rankings["rankings"]["bravo"][i]["score"])
max_bravo = int(rankings["rankings"]["bravo"][i]["score"]) if int(
rankings["rankings"]["bravo"][i]["score"]) > max_bravo else max_bravo
min_bravo = int(rankings["rankings"]["bravo"][i]["score"]) if int(
rankings["rankings"]["bravo"][i]["score"]) < min_bravo else min_bravo
except KeyError: