-
Notifications
You must be signed in to change notification settings - Fork 7
/
game.py
1654 lines (1450 loc) · 80.4 KB
/
game.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
import inspect
import json
import threading
import time
from GAME_ATTR import GAME_ATTR, TUTORIAL
from channel import Channel
import requests
from requests.structures import CaseInsensitiveDict
class Game(Channel):
def __init__(self, bot, channel, verbose):
super().__init__(bot, channel, verbose)
self._making_room = False
self.__creator = ""
self.__invite_link = ""
self.__slots = {i: {"username": "", "team": "", "score": {}} for i in range(16)}
self.__host = ""
self.__in_progress = False
# osu tutorial as default 22538
self.__beatmap = TUTORIAL
self.__beatmap_name = "osu! Tutorial"
self.__match_history = self.fetch_match_history()
self.__size = 16
self.__locked = False
self._password = ""
self.__title = ""
self.__welcome_message = ""
self.__referees = []
self.__config_link = ""
self.__config_text = ""
self.__custom_config_text = ""
self.__beatmap_checker = False
self.__start_timer = False
self.__start_on_players_ready = False
self.__autostart_timer = -1
self.__maintain_password = False
self.__maintain_size = False
self.__maintain_title = False
self.__player_blacklist = bot.get_player_blacklist().copy()
self.__auto_download = {"status": False, "path": "", "auto_open": False, "with_video": False}
self._commands = {
"!info": {
"response": "Built with [https://github.com/jramseygreen/osu_bot_framework-v3 osu_bot_framework v3] | [https://osu.ppy.sh/u/qqzzy Developer]",
"description": "Built with osu_bot_framework v3"},
"!config": {
"response": self.common_commands.config_link,
"description": "Returns a link to the game rom configuration page"
}
}
# limits and ranges (done)
self.__ar_range = (0.0, 10.0)
self.__od_range = (0.0, 10.0)
self.__cs_range = (0.0, 10.0)
self.__hp_range = (0.0, 10.0)
self.__diff_range = (0.0, -1.0)
self.__bpm_range = (0.0, -1.0)
self.__length_range = (0, -1)
self.__map_status = ["any"]
self.__allow_unsubmitted = True
# game attributes
self.__mods = ["ANY"]
self.__scoring_type = "any"
self.__team_type = "any"
self.__game_mode = "any"
self.__allow_convert = True
# on_event methods
self.__on_match_start_method = None
self.__on_match_finish_method = None
self.__on_match_abort_method = None
self.__on_host_change_method = None
self.__on_beatmap_change_method = None
self.__on_changing_beatmap_method = None
self.__on_all_players_ready_method = None
self.__on_room_close_method = None
self.__on_slot_change_method = None
self.__on_team_change_method = None
self.__on_team_addition_method = None
self.__on_clear_host_method = None
self.__on_rule_violation_method = None
# whitelists + blacklists
self.__beatmap_creator_whitelist = []
self.__beatmap_creator_blacklist = []
self.__artist_whitelist = []
self.__artist_blacklist = []
self.__beatmap_whitelist = []
self.__beatmap_blacklist = []
def process_message(self, message):
super().process_message(message)
# update room attributes
if message["username"] == "BanchoBot":
if "joined in slot" in message["content"]:
username = message["content"][:message["content"].find("joined") - 1]
team = ""
if "for team" in message["content"]:
if "for team blue" in message["content"]:
team = "blue"
elif "for team red" in message["content"]:
team = "red"
if self.__on_team_addition_method:
argnum = len(str(inspect.signature(self.__on_team_addition_method)).strip("()").split(", "))
x = None
if argnum == 2:
x = threading.Thread(target=self.__on_team_addition_method, args=(username, team,))
elif str(inspect.signature(self.__on_team_addition_method)).strip("()").split(", ") != [""]:
x = threading.Thread(target=self.__on_team_addition_method, args=(username,))
else:
x = threading.Thread(target=self.__on_team_addition_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on team addition method executed --")
else:
self.clear_teams()
slot_num = int(message["content"].split("slot ", 1)[1].split(".", 1)[0].split(" ")[0]) - 1
self.set_slot(slot_num, {"username": username, "team": team, "score": {}})
self.add_user(username)
elif "left the game" in message["content"]:
username = message["content"][:message["content"].find("left") - 1]
self.del_user(username)
elif "moved to slot" in message["content"]:
slot = int(message["content"].split(" ")[-1]) - 1
username = message["content"].replace(" moved to slot " + str(slot + 1), "")
team = self.get_team(username)
score = self.get_score(username)
self.del_slot(self.get_slot_num(username))
self.set_slot(slot, {"username": username, "team": team, "score": score})
if self.__on_slot_change_method:
argnum = len(str(inspect.signature(self.__on_slot_change_method)).strip("()").split(", "))
x = None
if argnum == 2:
x = threading.Thread(target=self.__on_slot_change_method, args=(username, slot,))
elif str(inspect.signature(self.__on_slot_change_method)).strip("()").split(", ") != [""]:
x = threading.Thread(target=self.__on_slot_change_method, args=(username,))
else:
x = threading.Thread(target=self.__on_slot_change_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on slot change method executed --")
elif "changed to Blue" in message["content"]:
username = message["content"].replace(" changed to Blue", "")
slot = self.get_slot_num(username)
score = self.get_score(username)
self.set_slot(slot, {"username": username, "team": "blue", "score": score})
if self.__on_team_change_method:
argnum = len(str(inspect.signature(self.__on_team_change_method)).strip("()").split(", "))
x = None
if argnum == 2:
x = threading.Thread(target=self.__on_team_change_method, args=(username, "blue",))
elif str(inspect.signature(self.__on_team_change_method)).strip("()").split(", ") != [""]:
x = threading.Thread(target=self.__on_team_change_method, args=(username,))
else:
x = threading.Thread(target=self.__on_team_change_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on team change method executed --")
elif "changed to Red" in message["content"]:
username = message["content"].replace(" changed to Red", "")
slot = self.get_slot_num(username)
score = self.get_score(username)
self.set_slot(slot, {"username": username, "team": "red", "score": score})
if self.__on_team_change_method:
argnum = len(str(inspect.signature(self.__on_team_change_method)).strip("()").split(", "))
x = None
if argnum == 2:
x = threading.Thread(target=self.__on_team_change_method, args=(username, "red",))
elif str(inspect.signature(self.__on_team_change_method)).strip("()").split(", ") != [""]:
x = threading.Thread(target=self.__on_team_change_method, args=(username,))
else:
x = threading.Thread(target=self.__on_team_change_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on team change method executed --")
elif "became the host" in message["content"]:
self.__set_host(message["content"].replace(" became the host.", ""))
elif "The match has started!" == message["content"]:
self.abort_start_timer()
self.__check_attributes()
elif "The match has finished!" == message["content"]:
self.__in_progress = False
self.__fetch_scores()
self.__maintain_attributes()
if self.__on_match_finish_method:
x = threading.Thread(target=self.__on_match_finish_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on match finish method executed --")
elif "Aborted the match" == message["content"]:
self.__in_progress = False
elif "Beatmap changed to" in message["content"] or "Changed beatmap to" in message["content"]:
beatmapID = message["content"].split("/b/", 1)[1].split(" ", 1)[0].replace(")", "")
self.__check_beatmap_attributes(beatmapID)
line = message["content"].replace("Beatmap changed to:", "").replace("Changed beatmap to" ,"").split(" ")
for item in line:
if "https://" in item:
line.remove(item)
self.__beatmap_name = " ".join(line)
elif "Host is changing map..." == message["content"]:
self.abort_start_timer()
if self.__on_changing_beatmap_method:
x = threading.Thread(target=self.__on_changing_beatmap_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on changing beatmap method executed --")
elif "All players are ready" == message["content"]:
if self.__on_all_players_ready_method:
x = threading.Thread(target=self.__on_all_players_ready_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on all players ready method executed --")
if self.__start_on_players_ready:
self.start_match()
elif "Cleared match host" == message["content"]:
if self.__on_clear_host_method:
x = None
if str(inspect.signature(self.__on_clear_host_method)).strip("()").split(", ") != [""]:
x = threading.Thread(target=self.__on_clear_host_method, args=(self.__host,))
else:
x = threading.Thread(target=self.__on_clear_host_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on clear host method executed --")
self.__host = ""
elif "Room name updated to " in message["content"]:
title = message["content"].replace("Room name updated to ", "").strip('"')
if not title:
self.__title = self.__match_history["match"]["name"]
else:
self.__title = title
elif "Locked the match" == message["content"]:
self.__locked = True
elif "Unlocked the match" == message["content"]:
self.__locked = False
elif "Room name:" in message["content"]:
self.__title = message["content"].replace("Room name: ", "").split(",", 1)[0]
elif message["content"].split(" ", 1)[0] == "Slot" and "osu.ppy.sh/u/" in message["content"]:
slot = int(message["content"].split(" ", 2)[1]) - 1
username = ""
host = False
team = ""
for user in self._users:
if user in message["content"]:
username = user
break
attr = message["content"].split(username, 1)
if "Host" in attr[1]:
host = True
if "Team Blue" in attr[1]:
team = "blue"
elif "Team Red" in attr[1]:
team = "red"
self.set_slot(slot, {"username": username, "team": team, "score": {}})
if host:
self.__host = username
elif "Beatmap:" in message["content"] and self.__beatmap == TUTORIAL:
self.change_beatmap(message["content"].replace("Beatmap: ", "").split(" ", 1)[0].replace("https://osu.ppy.sh/b/", "", 1))
elif "Changed match to size " in message["content"]:
args = message["content"].split()
self.__size = int(args[-1])
elif "to the match referees" in message["content"]:
username = message["content"].split(" ", 1)[1].replace(" to the match referees", "")
if username not in self.__referees:
self.__referees.append(username)
self.get_config_link()
elif "from the match referees" in message["content"]:
username = message["content"].split(" ", 1)[1].replace(" from the match referees", "")
if username in self.__referees:
self.__referees.remove(username)
self.get_config_link()
elif self._making_room and message["content"] != "Match referees:":
user_profile = self._bot.fetch_user_profile(message["content"])
if user_profile:
if user_profile["username"] not in self.__referees:
self.__referees.append(user_profile["username"])
self.get_config_link()
if message["content"].replace(" ", "_").lower() == self.__creator.replace(" ", "_").lower():
self._making_room = False
elif self.has_referee(message["username"]):
message_arr = message["content"].lower().split(" ")
if len(message_arr) >= 2:
command = " ".join(message_arr[:2]).strip()
args = message_arr[2:]
if message["username"] == self.__creator.replace(" ", "_"):
self.get_config_link()
if command == "!mp password":
self.__invite_link = self.__invite_link.replace(self._password, "")
if args:
self._password = args[0]
self.__invite_link = self.__invite_link + args[0]
else:
self._password = ""
elif command == "!mp size":
if args:
self.__size = int(args[0])
elif command == "!mp abort" and self.in_progress():
if self.__on_match_abort_method:
x = threading.Thread(target=self.__on_match_abort_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on match abort method executed --")
self.__execute_commands(message)
def __execute_commands(self, message):
for command in self._commands:
if not message["content"].replace(command, "") or message["content"].replace(command, "")[0] == " ":
if callable(self._commands[command]["response"]):
x = None
if str(inspect.signature(self._commands[command]["response"])).strip("()").split(", ") != [""]:
x = threading.Thread(target=self._commands[command]["response"], args=(message,))
else:
x = threading.Thread(target=self._commands[command]["response"])
x.setDaemon(True)
x.start()
else:
self.send_message(str(self._commands[command]["response"]))
self._bot.log("-- Command '" + command + "' Executed --")
def send_message(self, message):
super().send_message(message)
self.__execute_commands({"username": self._bot.get_username(), "channel": self._channel, "content": message})
def del_user(self, username):
# remove from slots
if self.has_user(username):
for slot in self.__slots:
if self.__slots[slot]["username"].replace(" ", "_") == username.replace(" ", "_"):
self.__slots[slot] = {"username": "", "team": "", "score": {}}
break
super().del_user(username)
if not self.has_users():
self.abort_start_timer()
self.__maintain_attributes()
def add_user(self, username):
super().add_user(username)
# welcome message implementation
if self.__welcome_message:
self._bot.send_personal_message(username.replace(" ", "_"), self.__welcome_message)
self.__kick_users()
def __kick_users(self):
for username in self.get_formatted_player_blacklist():
if username in self._users:
self.kick_user(username)
self._bot.send_personal_message(username, "Sorry, you have been blacklisted from [https://osu.ppy.sh/mp/" + self._channel[4:] + " " + self.__title + "]")
def kick_user(self, username):
if username.replace(" ", "_") in self.get_formatted_users():
self.send_message("!mp kick " + username.replace(" ", "_"))
def get_formatted_users(self):
return [user.replace(" ", "_") for user in self._users]
def close(self):
self.send_message("!mp close")
self._bot.part(self._channel)
def fetch_match_history(self):
url = "https://osu.ppy.sh/community/matches/" + self._channel[4:]
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
r = requests.get(url, headers=headers)
self._bot.log("-- Fetched match history --")
return json.loads(r.text)
def get_match_history(self):
return self.__match_history
# fetches the most recent match data from ppy.sh
def get_match_data(self):
for event in reversed(self.get_match_history()["events"]):
if "game" in event:
return event["game"]
return {}
# fetches beatmap from ppy.sh
def __fetch_beatmap(self, beatmapID):
if self.__beatmap:
if int(beatmapID) == self.__beatmap["id"]:
return self.__beatmap
if int(beatmapID) == 0:
return {}
return self._bot.fetch_beatmap(beatmapID)
# fetches a beatmapset associated with a beatmapID from ppy.sh
def __fetch_beatmapset(self, beatmapID):
if int(beatmapID) == 0:
return {}
return self._bot.fetch_parent_set(beatmapID)
def __fetch_scores(self):
self.clear_scores()
self.__match_history = self.fetch_match_history()
for score in self.get_match_data()["scores"]:
if self.__slots[score["match"]["slot"]]["username"]:
self.__slots[score["match"]["slot"]]["score"] = score
if not self.__slots[score["match"]["slot"]]["team"]:
self.__slots[score["match"]["slot"]]["team"] = score["match"]["team"]
def clear_scores(self):
for slot in self.__slots:
self.__slots[slot]["score"] = {}
def get_score(self, username):
slot = self.get_slot(username)
if slot:
return slot["score"]
def get_scores(self):
scores = []
for slot in self.__slots:
if self.__slots[slot]["score"]:
if "username" not in self.__slots[slot]["score"]:
self.__slots[slot]["score"]["username"] = self.__slots[slot]["username"]
scores.append(self.__slots[slot]["score"])
return scores
def get_red_scores(self):
scores = []
for score in self.get_scores():
if score["team"] == "red":
scores.append(score)
return scores
def get_blue_scores(self):
scores = []
for score in self.get_scores():
if score["team"] == "blue":
scores.append(score)
return scores
def get_ordered_scores(self):
passed = []
failed = []
for score in self.get_scores():
if score["passed"]:
passed.append(score)
else:
failed.append(score)
match = self.get_match_data()
key = "max_combo"
if "score" in match["scoring_type"]:
key = "score"
elif "accuracy" == match["scoring_type"]:
key = "accuracy"
return sorted(passed, key=lambda x: x[key], reverse=True) + sorted(failed, key=lambda x: x[key], reverse=True)
def has_score(self, username):
if self.get_score(username):
return True
return False
def __check_beatmap_attributes(self, beatmapID, running=False):
if not running:
x = threading.Thread(target=self.__check_beatmap_attributes, args=(beatmapID, True,))
x.setDaemon(True)
x.start()
else:
self._bot.log("-- Beatmap checker started --")
beatmapID = int(beatmapID)
accept_beatmap = False
beatmap = None
if beatmapID == self.__beatmap["id"]:
beatmap = self.__beatmap
accept_beatmap = True
elif beatmapID == TUTORIAL["id"]:
beatmap = TUTORIAL
accept_beatmap = True
else:
beatmap = self.__fetch_beatmap(beatmapID)
if self.__beatmap_checker:
if self.__allow_unsubmitted and not beatmap:
beatmap = {"id": beatmapID, "url": "https://osu.ppy.sh/b/" + str(beatmapID)}
accept_beatmap = True
self.send_message("Can't check attributes, the selected beatmap is unsubmitted! " + "[" + str(self._bot.chimu.fetch_download_link(beatmapID, False)) + " Chimu.moe download]")
else:
error = self.check_beatmap(beatmap)
if error:
self.abort_start_timer()
if beatmap:
self.send_message("Rule violation: " + error["type"] + " - " + error["message"].replace("selected beatmap","[https://osu.ppy.sh/b/" + str(beatmap["id"]) + " selected beatmap]"))
else:
self.send_message("Rule violation: " + error["type"] + " - " + error["message"])
self.set_beatmap(self.__beatmap)
if self.__on_rule_violation_method:
x = None
if str(inspect.signature(self.__on_rule_violation_method)).strip("()").split(", ") != [""]:
x = threading.Thread(target=self.__on_rule_violation_method, args=(error,))
else:
x = threading.Thread(target=self.__on_rule_violation_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on rule violation method executed --")
else:
accept_beatmap = True
else:
if not beatmap:
beatmap = {"id": beatmapID, "url": "https://osu.ppy.sh/b/" + str(beatmapID)}
self.send_message("The selected beatmap is unsubmitted! " + "[" + str(self._bot.chimu.fetch_download_link(beatmapID, False)) + " Chimu.moe download]")
accept_beatmap = True
if accept_beatmap:
old_beatmap = self.__beatmap
self.__beatmap = beatmap
if self.__on_beatmap_change_method:
argnum = len(str(inspect.signature(self.__on_beatmap_change_method)).strip("()").split(", "))
x = None
if argnum == 2:
x = threading.Thread(target=self.__on_beatmap_change_method, args=(old_beatmap, beatmap,))
elif str(inspect.signature(self.__on_beatmap_change_method)).strip("()").split(", ") != [""]:
x = threading.Thread(target=self.__on_beatmap_change_method, args=(beatmap,))
else:
x = threading.Thread(target=self.__on_beatmap_change_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on beatmap change method executed --")
if old_beatmap != beatmap:
if self.__auto_download["status"]:
self._bot.chimu.download_beatmap(beatmap["id"], path=self.__auto_download["path"], with_video=self.__auto_download["with_video"], auto_open=self.__auto_download["auto_open"])
if self.__autostart_timer > 0:
self.start_match(self.__autostart_timer)
self._bot.log("-- Beatmap checker finished --")
def __check_attributes(self, running=False):
if not running:
x = threading.Thread(target=self.__check_attributes, args=(True,))
x.setDaemon(True)
x.start()
else:
self._bot.log("-- Attribute checker started --")
self.__match_history = self.fetch_match_history()
match = self.get_match_data()
abort = False
error = ""
if not match:
abort = True
error = {"type": "match_history", "message": "The match history cannot be read! Check that the match history is public."}
elif self.__scoring_type.lower() != "any" and match["scoring_type"] != self.__scoring_type.lower():
error = {"type": "scoring", "message": "The allowed scoring type is: " + self.__scoring_type}
abort = True
elif self.__mods != ["ANY"]:
if "FREEMOD" in self.__mods and match["mods"] != []:
error = {"type": "mods", "message": "The allowed mods are: " + ", ".join(self.__mods)}
abort = True
elif self.__mods != ["FREEMOD"] and (not all([mod in self.__mods for mod in match["mods"]]) or not all([mod in match["mods"] for mod in self.__mods])):
error = {"type": "mods", "message": "The allowed mods are: " + ", ".join(self.__mods)}
abort = True
elif self.__team_type != "any" and self.__team_type.lower() != match["team_type"]:
error = {"type": "team", "message": "The allowed team type is: " + self.__team_type}
abort = True
elif self.__beatmap_checker and self.__game_mode.lower() != "any" and match["mode"] != self.__game_mode.lower():
error = {"type": "mode", "message": "The selected beatmap's mode must be: " + self.__game_mode}
abort = True
elif "beatmap" in match and self.__beatmap["id"] != match["beatmap"]["id"]:
abort = True
elif self.__beatmap_checker:
error = self.check_beatmap(self.__beatmap)
if error and error["type"] == "unsubmitted":
if not self.__allow_unsubmitted:
abort = True
elif error:
abort = True
if abort:
# execute on_rule_break
self.send_message("!mp abort")
self.send_message("!mp set " + str(GAME_ATTR[self.__team_type]) + " " + str(GAME_ATTR[self.__scoring_type]) + " " + str(self.__size))
game_mode = ""
if self.__game_mode != "any":
game_mode = str(GAME_ATTR[self.__game_mode])
self.send_message("!mp map " + str(self.__beatmap["id"]) + " " + game_mode)
self.set_mods(self.__mods)
if error:
self.send_message("Rule violation: " + error["type"] + " - " + error["message"].replace("selected beatmap", "[https://osu.ppy.sh/b/" + str(self.__beatmap["id"]) + " selected beatmap]"))
if self.__on_rule_violation_method:
x = None
if str(inspect.signature(self.__on_rule_violation_method)).strip("()").split(", ") != [""]:
x = threading.Thread(target=self.__on_rule_violation_method, args=(error,))
else:
x = threading.Thread(target=self.__on_rule_violation_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on rule violation method executed --")
else:
self.__in_progress = True
if self.__on_match_start_method:
x = threading.Thread(target=self.__on_match_start_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on match start method executed --")
if "team" not in match["team_type"]:
self.clear_teams()
self._bot.log("-- Attribute checker finished --")
def check_beatmap(self, beatmap):
error = ""
if (not beatmap or len(beatmap) == 2) and not self.__allow_unsubmitted:
error = {"type": "unsubmitted", "message": "Only submitted beatmaps are allowed"}
elif self.__od_range[0] > beatmap["accuracy"] or beatmap["accuracy"] > self.__od_range[1]:
error = {"type": "od", "message": "The selected beatmap is outside the overall difficulty range: " + str(self.__od_range)}
elif self.__ar_range[0] > beatmap["ar"] or beatmap["ar"] > self.__ar_range[1]:
error = {"type": "ar", "message": "The selected beatmap is outside the approach rate range: " + str(self.__ar_range)}
elif self.__bpm_range[0] > beatmap["bpm"] or (self.__bpm_range[1] != -1 and self.__bpm_range[1] < beatmap["bpm"]):
error = {"type": "bpm", "message": "The selected beatmap is outside the BPM range: " + str(self.__bpm_range).replace("-1.0", "unlimited")}
elif self.__cs_range[0] > beatmap["cs"] or beatmap["cs"] > self.__cs_range[1]:
error = {"type": "cs", "message": "The selected beatmap is outside the circle size range: " + str(self.__cs_range)}
elif self.__hp_range[0] > beatmap["drain"] or beatmap["drain"] > self.__hp_range[1]:
error = {"type": "hp", "message": "The selected beatmap is outside the HP range: " + str(self.__hp_range)}
elif self.__length_range[0] > beatmap["total_length"] or (self.__length_range[1] != -1 and self.__length_range[1] < beatmap["hit_length"]):
if self.__length_range[1] == -1:
error = {"type": "length", "message": "The selected beatmap is outside the length range: " + str([str(x // 60) + "min, " + str(x % 60) + "sec" for x in [self.__length_range[0]]] + ["unlimited"])}
else:
error = {"type": "length", "message": "The selected beatmap is outside the length range: " + str([str(x // 60) + "min, " + str(x % 60) + "sec" for x in self.__length_range])}
elif self.__map_status != ["any"] and beatmap["status"] not in self.__map_status:
error = {"type": "status", "message": "The selected beatmap must be: " + " or ".join(self.__map_status)}
elif beatmap["difficulty_rating"] < self.__diff_range[0] or (beatmap["difficulty_rating"] > self.__diff_range[1] != -1):
error = {"type": "difficulty", "message": "The selected beatmap is outside the difficulty range: " + str(self.__diff_range).replace("-1.0", "unlimited") + "*"}
elif self.__game_mode != "any" and beatmap["mode"] != self.__game_mode and not self.__allow_convert:
error = {"type": "mode", "message": "The selected beatmap's mode must be: " + self.__game_mode}
elif self.__beatmap_creator_blacklist or self.__beatmap_creator_whitelist or self.__artist_blacklist or self.__artist_whitelist or self.__beatmap_blacklist or self.__beatmap_whitelist:
beatmapset = self.__fetch_beatmapset(beatmap["id"])
if self.__beatmap_creator_whitelist and beatmapset["creator"].lower() not in self.__beatmap_creator_whitelist and all([x not in beatmap["version"].lower() for x in self.__beatmap_creator_whitelist]):
error = {"type": "creator_whitelist", "message": "The selected beatmap's creator is not whitelisted. The whitelist is: '" + "', '".join(self.__beatmap_creator_whitelist) + "'"}
elif self.__beatmap_creator_blacklist and beatmapset["creator"].lower() in self.__beatmap_creator_blacklist or any([x in beatmap["version"].lower() for x in self.__beatmap_creator_blacklist]):
error = {"type": "creator_blacklist", "message": "The selected beatmap's creator is blacklisted. The blacklist is: '" + "', '".join(self.__beatmap_creator_blacklist) + "'"}
elif self.__artist_whitelist and beatmapset["artist"].lower() not in self.__artist_whitelist:
error = {"type": "artist_whitelist", "message": "The selected beatmap's artist is not whitelisted. The whitelist is: '" + "', '".join(self.__artist_whitelist) + "'"}
elif self.__artist_blacklist and beatmapset["artist"].lower() in self.__artist_blacklist:
error = {"type": "artist_blacklist", "message": "The selected beatmap's artist is blacklisted. The blacklist is: '" + "', '".join(self.__artist_blacklist) + "'"}
elif self.__beatmap_blacklist and str(beatmap["id"]) in self.__beatmap_blacklist:
blacklist = []
for beatmapID in self.__beatmap_blacklist:
blacklist.append("[https://osu.ppy.sh/b/" + beatmapID + " " + beatmapID + "]")
error = {"type": "beatmap_blacklist", "message": "This beatmap has been blacklisted. The blacklist is: '" + "', '".join(blacklist) + "'"}
elif self.__beatmap_whitelist and str(beatmap["id"]) not in self.__beatmap_whitelist:
whitelist = []
for beatmapID in self.__beatmap_whitelist:
whitelist.append("[https://osu.ppy.sh/b/" + beatmapID + " " + beatmapID + "]")
error = {"type": "beatmap_whitelist", "message": "This beatmap is not whitelisted. The whitelist is: '" + "', '".join(whitelist) + "'"}
return error
def abort_match(self):
self.send_message("!mp abort")
self.__maintain_attributes()
if self.__on_match_abort_method:
x = threading.Thread(target=self.__on_match_abort_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on match abort method executed --")
def __maintain_attributes(self):
if self.__maintain_size:
self.set_size(self.__size)
if self.__maintain_password:
self.set_password(self._password)
if self.__maintain_title:
self.set_title(self.__title)
def start_match(self, secs=0, running=False):
if not running:
x = threading.Thread(target=self.start_match, args=(secs, True,))
x.setDaemon(True)
x.start()
else:
self.__start_timer = False
secs = int(secs)
if secs > 0:
time.sleep(1.1)
self.__start_timer = True
if self.has_users():
msg = ("Queued the match to start in " + str(secs // 60) + " minutes " + str(secs % 60) + " seconds").replace(" 0 minutes", "").replace(" 0 seconds", "").replace("1 minutes", "1 minute")
for command in self._commands:
if self._commands[command]["response"] == self.common_commands.abort_start_timer:
msg += " (" + command + " to stop)"
break
self.send_message(msg)
secs -= 1
while secs > 0:
time.sleep(1)
if not self.__start_timer or not self._bot.has_channel(self._channel) or not self.has_users() or self.in_progress():
return
if secs % 30 == 0 or secs == 10 or secs <= 5:
self.send_message(("Match starts in " + str(secs // 60) + " minutes " + str(secs % 60) + " seconds").replace(" 0 minutes", "").replace(" 0 seconds", "").replace("1 minutes", "1 minute"))
if secs == 1:
self.send_message("Good luck & Have fun!")
secs -= 1
self.send_message("!mp start")
self.__start_timer = False
def abort_start_timer(self):
self.__start_timer = False
def in_progress(self):
return self.__in_progress
def set_invite_link(self, link):
self.__invite_link = link
def get_invite_link(self):
return self.__invite_link
def get_slots(self):
return self.__slots
def get_formatted_slots(self):
slots = {}
for slot in self.__slots:
slots[slot] = {"username": self.__slots[slot]["username"].replace(" ", "_"), "team": self.__slots[slot]["team"], "score": self.__slots[slot]["score"]}
return slots
def set_slot(self, slot, data):
if type(slot) == int:
self.__slots[slot] = data
def del_slot(self, slot):
if type(slot) == int:
self.__slots[slot] = {"username": "", "team": "", "score": {}}
def get_slot(self, username):
slotnum = self.get_slot_num(username)
if slotnum:
return self.__slots[slotnum]
def get_formatted_slot(self, username):
slotnum = self.get_slot_num(username)
if slotnum:
return self.get_formatted_slots()[slotnum]
def get_slot_username(self, number):
return self.__slots[number]["username"]
def get_formatted_slot_username(self, number):
return self.get_formatted_slots()[number]["username"]
def get_slot_num(self, username):
for i in range(16):
if self.__slots[i]["username"].replace(" ", "_") == username.replace(" ", "_"):
return i
def get_next_empty_slot_num(self, offset=0):
for i in range(offset, 16):
if not self.__slots[i]["username"]:
return i
for i in range(0, offset):
if not self.__slots[i]["username"]:
return i
def get_next_full_slot_num(self, offset=0):
for i in range(offset, 16):
if self.__slots[i]["username"]:
return i
for i in range(0, offset):
if self.__slots[i]["username"]:
return i
def get_next_full_slot(self, offset=0):
return self.__slots[self.get_next_full_slot_num(offset)]
def get_next_empty_slot(self, offset=0):
return self.__slots[self.get_next_empty_slot_num(offset)]
def clear_teams(self):
for slot in self.__slots:
self.__slots[slot]["team"] = ""
def get_red_team(self):
users = []
for slot in self.__slots:
if self.__slots[slot]["team"] == "red":
users.append(self.__slots[slot]["username"])
return users
def get_blue_team(self):
users = []
for slot in self.__slots:
if self.__slots[slot]["team"] == "blue":
users.append(self.__slots[slot]["username"])
return users
def get_team(self, username):
if username in self.get_blue_team():
return "blue"
if username in self.get_red_team():
return "red"
return ""
def set_team(self, username, colour):
colour = colour.lower()
if self.has_user(username) and colour in ["red", "blue"]:
self.send_message("!mp team " + username.replace(" ", "_") + " " + colour)
def move(self, username, slot_num):
if self.has_user(username) and str(slot_num).isnumeric() and 0 <= int(slot_num) < 16:
self.send_message("!mp move " + username.replace(" ", "_") + " " + str(slot_num))
def get_host(self):
return self.__host
def get_formatted_host(self):
return self.__host.replace(" ", "_")
def is_host(self, username):
return username.replace(" ", "_") == self.get_formatted_host()
def __set_host(self, username):
old_host = self.__host
self.__host = username
if self.__on_host_change_method:
argnum = len(str(inspect.signature(self.__on_host_change_method)).strip("()").split(", "))
x = None
if argnum == 2:
x = threading.Thread(target=self.__on_host_change_method, args=(old_host, username,))
elif str(inspect.signature(self.__on_host_change_method)).strip("()").split(", ") != [""]:
x = threading.Thread(target=self.__on_host_change_method, args=(username,))
else:
x = threading.Thread(target=self.__on_host_change_method)
x.setDaemon(True)
x.start()
self._bot.log("-- on host change method executed --")
def set_host(self, username):
self.__host = username
self.send_message("!mp host " + username.replace(" ", "_"))
def set_password(self, password):
password = password.strip()
if password != self._password:
self.__invite_link = self.__invite_link.replace(self._password.replace(" ", "_"), "")
self._password = password
self.__invite_link = self.__invite_link + password.replace(" ", "_")
self.send_message("!mp password " + self._password)
def get_password(self):
return self._password
def has_password(self):
return self._password != ""
def add_referee(self, username):
self.send_message("!mp addref " + username)
def del_referee(self, username):
self.send_message("!mp removeref " + username)
def get_referees(self):
return self.__referees
def get_formatted_referees(self):
return [ref.replace(" ", "_") for ref in self.__referees]
def has_referee(self, username):
return username.replace(" ", "_").lower() in [x.lower() for x in self.get_formatted_referees()]
def get_creator(self):
return self.__creator
def is_creator(self, username):
return username.replace(" ", "_") == self.__creator.replace(" ", "_")
def get_formatted_creator(self):
return self.__creator.replace(" ", "_")
# grabs existing users, the room creator, and adds creator to referee list
def get_existing_attributes(self):
self._making_room = True
for user in self.__match_history["users"]:
if self.has_user(user["username"].replace(" ", "_")):
self._users.remove(user["username"].replace(" ", "_"))
self.add_user(user["username"])
self.__creator = self._bot.fetch_user_profile(self.__match_history["events"][0]["user_id"])["username"]
self.send_message("!mp listrefs")
self.send_message("!mp settings")
def set_beatmap(self, beatmap):
if beatmap:
self.__beatmap = beatmap
self.change_beatmap(beatmap["id"])
def get_beatmap(self):
return self.__beatmap
def change_beatmap(self, beatmapID):
game_mode = ""
if self.__game_mode != "any":
game_mode = str(GAME_ATTR[self.__game_mode])
self.send_message("!mp map " + str(beatmapID) + " " + game_mode)
# getters and setters for limits and ranges
# sets the allowed map statuses
def set_map_status(self, status):
if not status:
status = ["any"]
if type(status) == list:
self.__map_status = [x.lower() for x in status]
else:
self.__map_status = [status.lower()]
# returns the allowed map statuses
def get_map_status(self):
return self.__map_status
# sets the allowed difficulty range
def set_diff_range(self, range):
if range[0] == "":
range[0] = self.__diff_range[0]
if range[1] == "":
range[1] = self.__diff_range[1]
self.__diff_range = (float(range[0]), float(range[1]))
# returns the allowed difficulty range
def get_diff_range(self):
return self.__diff_range
# sets the allowed mods
def set_mods(self, mods):
if not mods:
mods = ["any"]
if type(mods) == list:
mods = [mod.upper() for mod in mods]
else:
mods = [mods.upper()]
self.__mods = mods
if self.__mods != ["ANY"]:
msg = " ".join([GAME_ATTR[x] for x in self.__mods]).lower()
if "EZ" in self.__mods and "HR" in self.__mods:
msg = (msg.replace("hr", "18").replace("ez", "18")).strip()
self.send_message("!mp mods " + msg)
# gets the allowed mods
def get_mods(self):
return self.__mods
# sets the allowed approach rate range
def set_ar_range(self, range):
if range[0] == "":
range[0] = self.__ar_range[0]
if range[1] == "":
range[1] = self.__ar_range[1]
self.__ar_range = (float(range[0]), float(range[1]))
# returns the allowed approach rate range
def get_ar_range(self):
return self.__ar_range
# sets the allowed overall difficulty range
def set_od_range(self, range):
if range[0] == "":
range[0] = self.__od_range[0]
if range[1] == "":
range[1] = self.__od_range[1]
self.__od_range = (float(range[0]), float(range[1]))
# gets the allowed overall difficulty range
def get_od_range(self):
return self.__od_range
# sets the allowed circle size range
def set_cs_range(self, range):
if range[0] == "":
range[0] = self.__cs_range[0]
if range[1] == "":
range[1] = self.__cs_range[1]
self.__cs_range = (float(range[0]), float(range[1]))
# gets the allowed circle size range
def get_cs_range(self):
return self.__cs_range
# sets the allowed hp range
def set_hp_range(self, range):
if range[0] == "":
range[0] = self.__hp_range[0]
if range[1] == "":
range[1] = self.__hp_range[1]
self.__hp_range = (float(range[0]), float(range[1]))
# gets the allowed hp range
def get_hp_range(self):
return self.__hp_range
# sets the allowed bpm range
def set_bpm_range(self, range):
if range[0] == "":