-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDDRBot.py
More file actions
1736 lines (1515 loc) · 86.3 KB
/
DDRBot.py
File metadata and controls
1736 lines (1515 loc) · 86.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import List, Any
import discord, sys, asyncio, datetime, io, os, json, traceback, random, aiohttp, urllib.parse, pytz, inflect, emoji
from word2number import w2n
from py573jp.EAGate import EAGate
from py573jp.DDRPage import DDRApi
from py573jp.EALink import EALink
from py573jp.Exceptions import EALinkException, EALoginException, EAMaintenanceException
from Misc import RepresentsInt
from asyncio import queues
from pygroovestats.GrooveStatsClient import GrooveStatsClient
from pygroovestats.GrooveStatsUtils import GSScoreEntry, GSSongInfo, parse_score_judges, diff_to_id
if os.path.exists("DDR_GENIE_ON"):
from DDRScoreDB import db, User, Score, IIDXScore, DBTaskWorkItem
from DDRGenie.DDRDataTypes import DDRParsedData, DDRScreenshot
from DDRGenie.IIDXDataTypes import IIDXParsedData, IIDXScreenshot
db.connect()
def divide_chunks(l, n):
# looping till length l
for i in range(0, len(l), n):
yield l[i:i + n]
def harvest_cover(ss, pd):
"""
Harvests an album cover if it's needed.
:type ss: DDRScreenshot
:type pd: DDRParsedData
"""
if os.path.exists("covers/"):
if not os.path.exists("covers/%s.png" % pd.song_title.value.strip()):
print("[CoverScrape] Harvesting for %s" % pd.song_title)
ss.album_art.save("covers/%s.png" % pd.song_title.value.strip(), format='PNG')
def save_json(filename, obj):
try:
with open(filename, 'w') as f:
json.dump(obj, f)
except IOError as ex:
print("[JSON] Exception occured saving %s!\n%s" % (filename, ex))
else:
print("[JSON] Saved %s successfully." % filename)
def archive_screenshot(userid, filename, data):
if not os.path.exists("archive/%s/" % userid):
os.makedirs("archive/%s/" % userid)
if not os.path.exists("archive/%s/%s" % (userid, filename)):
with open("archive/%s/%s" % (userid, filename), 'wb') as f:
f.write(data)
def load_json(filename):
try:
with open(filename, 'r') as f:
obj = json.load(f)
except IOError as ex:
print("[JSON] Exception occured loading %s!\n%s" % (filename, ex))
return None
else:
print("[JSON] Loaded %s successfully." % filename)
return obj
def get_emoji_for_fc(fc_text):
if 'MFC' in fc_text:
return '<:mfc:472191264796966926>'
elif 'PFC' in fc_text:
return '<:pfc:472191264402702347>'
elif 'GFC' in fc_text:
return '<:gfc:844785257852960778>'
elif 'FC' in fc_text:
return '<:fc:844785257164701708>'
else:
return ''
def generate_embed(score_data, score_player):
"""
:type score_data: DDRParsedData
"""
emb = discord.Embed()
first_mode = score_data.chart_play_mode.value[0]
if first_mode == "V":
first_mode = 'S'
total_notes = int(score_data.score_marv_count.value) + int(score_data.score_perfect_count.value) + int(score_data.score_great_count.value) + int(
score_data.score_good_count.value) + int(score_data.score_miss_count.value)
marv_percent = (int(score_data.score_marv_count.value) / total_notes) * 100
perfect_percent = (int(score_data.score_perfect_count.value) / total_notes) * 100
great_percent = (int(score_data.score_great_count.value) / total_notes) * 100
good_percent = (int(score_data.score_good_count.value) / total_notes) * 100
miss_percent = (int(score_data.score_miss_count.value) / total_notes) * 100
emb.title = "<:ddr_arrow:687073061039505454> %s by %s (%s%sP %s)" % (score_data.song_title, score_data.song_artist, score_data.chart_difficulty.value[0],
first_mode, score_data.chart_difficulty_number.value)
emb.description = "Played by %s" % score_player
emb.add_field(name="💯 Grade", value="%s %s" % (score_data.play_letter_grade, get_emoji_for_fc(score_data.play_full_combo)), inline=True)
emb.add_field(name="📈 Score", value="%s" % score_data.play_money_score, inline=True)
emb.add_field(name="🎯 EXScore", value="%s" % score_data.play_ex_score, inline=True)
emb.add_field(name="🔢 Max Combo", value="%s" % score_data.play_max_combo, inline=True)
emb.add_field(name="<:mfc:472191264796966926> Marvelous", value="%s (%0.2f%%)" % (score_data.score_marv_count, marv_percent), inline=True)
emb.add_field(name="<:pfc:472191264402702347> Perfect", value="%s (%0.2f%%)" % (score_data.score_perfect_count, perfect_percent), inline=True)
emb.add_field(name="<:gfc:472191264830259201> Great", value="%s (%0.2f%%)" % (score_data.score_great_count, great_percent), inline=True)
emb.add_field(name="<:fc:472191264453033984> Good", value="%s (%0.2f%%)" % (score_data.score_good_count, good_percent), inline=True)
emb.add_field(name="<:eming:572201816792629267> Miss", value="%s (%0.2f%%)" % (score_data.score_miss_count, miss_percent), inline=True)
emb.add_field(name="<:emiok:572201794982248452> OK", value="%s" % score_data.score_OK_count, inline=True)
emb.set_footer(text="DDR-Genie [β] - C: %i%%" % int(score_data.title_conf * 100))
if os.path.exists("covers/%s.png" % score_data.song_title.value.strip()):
emb.set_thumbnail(url="https://assets.cyberkitsune.net/ddr_cover/%s.png" % urllib.parse.quote(score_data.song_title.value.strip()))
if score_data.date_time is not None:
emb.timestamp = score_data.date_time
return emb
def generate_embed_iidx(score_data, score_player):
"""
:type score_data: IIDXParsedData
"""
emb = discord.Embed()
emb.title = "<:iidx:540794989316145162> %s by %s [%s %s]" % (score_data.song_title, score_data.song_artist, score_data.chart_play_mode,
score_data.chart_difficulty)
emb.description = "Played by %s" % score_player
emb.add_field(name="🎉 Clear Type", value="%s" % score_data.play_clear_type, inline=True)
emb.add_field(name="💯 DJ Level", value="%s" % score_data.play_dj_level, inline=True)
emb.add_field(name="🎯 EXScore", value="%s" % score_data.play_ex_score, inline=True)
emb.add_field(name="❌ Miss Count", value="%s" % score_data.play_miss_count, inline=True)
emb.add_field(name="🌈 PGreat", value="%s" % score_data.score_rainbow_count, inline=True)
emb.add_field(name="👍 Great", value="%s" % score_data.score_great_count, inline=True)
emb.add_field(name="😐 Good", value="%s" % score_data.score_good_count, inline=True)
emb.add_field(name="👎 Bad", value="%s" % score_data.score_bad_count, inline=True)
emb.add_field(name="🆖 Poor", value="%s" % score_data.score_poor_count, inline=True)
emb.add_field(name="⛓ Combo Break", value="%s" % score_data.score_combo_break, inline=True)
emb.add_field(name="🥕 Fast", value="%s" % score_data.score_fast_count, inline=True)
emb.add_field(name="🐢 Slow", value="%s" % score_data.score_slow_count, inline=True)
emb.set_footer(text="IIDX-Genie [α] - C: %i%%" % int(score_data.overall_conf))
if score_data.date_time is not None:
emb.timestamp = score_data.date_time
return emb
def generate_embed_iidx_db(score_data, score_player, verified=False, cmd_prefix='k!'):
"""
:type score_data: IIDXScore
"""
if verified:
v = '<:verified:680629672735670352>'
else:
v = ''
emb = discord.Embed()
emb.title = "<:iidx:540794989316145162> %s by %s [%s %s]" % (score_data.song_title, score_data.song_artist,
'DP' if score_data.double_play else 'SP', score_data.difficulty)
emb.description = "Played by %s %s\nView Screenshot `%sscreenshot iidx%i`" % (score_player, v, cmd_prefix, score_data.id)
emb.add_field(name="🎉 Clear Type", value="%s" % score_data.clear_type, inline=True)
emb.add_field(name="💯 DJ Level", value="%s" % score_data.dj_grade, inline=True)
emb.add_field(name="🎯 EXScore", value="%s" % score_data.ex_score, inline=True)
emb.add_field(name="❌ Miss Count", value="%s" % score_data.miss_count, inline=True)
emb.add_field(name="🌈 PGreat", value="%s" % score_data.p_great_count, inline=True)
emb.add_field(name="👍 Great", value="%s" % score_data.great_count, inline=True)
emb.add_field(name="😐 Good", value="%s" % score_data.good_count, inline=True)
emb.add_field(name="👎 Bad", value="%s" % score_data.bad_count, inline=True)
emb.add_field(name="🆖 Poor", value="%s" % score_data.poor_count, inline=True)
emb.add_field(name="⛓ Combo Break", value="%s" % score_data.combo_break, inline=True)
emb.add_field(name="🥕 Fast", value="%s" % score_data.fast_count, inline=True)
emb.add_field(name="🐢 Slow", value="%s" % score_data.slow_count, inline=True)
emb.set_footer(text="IIDX-Genie [α] - C: %i%% ID: iidx%i" % (int(score_data.overall_confidence), score_data.id))
if score_data.recorded_time is not None:
emb.timestamp = score_data.recorded_time
return emb
def generate_embed_from_db(score_data, score_player, verified=False, cmd_prefix='k!'):
"""
:type score_data: Score
"""
if isinstance(score_data, IIDXScore):
return generate_embed_iidx_db(score_data, score_player, verified, cmd_prefix)
emb = discord.Embed()
if score_data.doubles_play:
first_mode = 'D'
else:
first_mode = 'S'
if verified:
v = '<:verified:680629672735670352>'
else:
v = ''
total_notes = int(score_data.marv_count) + int(score_data.perf_count) + int(score_data.great_count) + \
int(score_data.good_count) + int(score_data.miss_count)
marv_percent = (int(score_data.marv_count) / total_notes)*100
perfect_percent = (int(score_data.perf_count) / total_notes) * 100
great_percent = (int(score_data.great_count) / total_notes) * 100
good_percent = (int(score_data.good_count) / total_notes) * 100
miss_percent = (int(score_data.miss_count) / total_notes) * 100
emb.title = "<:ddr_arrow:687073061039505454> %s by %s (%s%sP %s)" % (score_data.song_title, score_data.song_artist, score_data.difficulty_name[0],
first_mode, score_data.difficulty_number)
emb.description = "Played by %s %s\nView Screenshot `%sscreenshot %i`" % (score_player, v, cmd_prefix, score_data.id)
emb.add_field(name="💯 Grade", value="%s %s" % (score_data.letter_grade, get_emoji_for_fc(score_data.full_combo)), inline=True)
emb.add_field(name="📈 Score", value="%s" % score_data.money_score, inline=True)
emb.add_field(name="🎯 EXScore", value="%s" % score_data.ex_score, inline=True)
emb.add_field(name="🔢 Max Combo", value="%s" % score_data.max_combo, inline=True)
emb.add_field(name="<:mfc:472191264796966926> Marvelous", value="%s (%0.2f%%)" % (score_data.marv_count, marv_percent), inline=True)
emb.add_field(name="<:pfc:472191264402702347> Perfect", value="%s (%0.2f%%)" % (score_data.perf_count, perfect_percent), inline=True)
emb.add_field(name="<:gfc:472191264830259201> Great", value="%s (%0.2f%%)" % (score_data.great_count, great_percent), inline=True)
emb.add_field(name="<:fc:472191264453033984> Good", value="%s (%0.2f%%)" % (score_data.good_count, good_percent), inline=True)
emb.add_field(name="<:eming:572201816792629267> Miss", value="%s (%0.2f%%)" % (score_data.miss_count, miss_percent), inline=True)
emb.add_field(name="<:emiok:572201794982248452> OK", value="%s" % score_data.OK_count, inline=True)
emb.set_footer(text="DDR-Genie [β] - C: %i%% ID: %i" % (int(score_data.name_confidence * 100), score_data.id))
emb.timestamp = score_data.recorded_time
if os.path.exists("covers/%s.png" % score_data.song_title.strip()):
emb.set_thumbnail(url="https://assets.cyberkitsune.net/ddr_cover/%s.png" % urllib.parse.quote(score_data.song_title.strip()))
return emb
def generate_itg_embed(groovestats_data, song_info):
"""
:type groovestats_data: GSScoreEntry
:type song_info: GSSongInfo
"""
emb = discord.Embed()
emb.title = "<:ddr_arrow:687073061039505454> %s by %s (%sSP %s)" % (song_info.song_name, song_info.song_artist, groovestats_data.difficulty[0], song_info.song_level)
emb.description = "Played by %s" % groovestats_data.user_name
emb.add_field(name="📈 Score", value="%s" % groovestats_data.score, inline=True)
footer = ''
if groovestats_data.is_gslaunch:
total_notes = song_info.song_steps
extended = parse_score_judges(groovestats_data, total_notes)
fant_percent = (int(extended.fantastic) / total_notes) * 100
exec_percent = (int(extended.excellent) / total_notes) * 100
great_percent = (int(extended.great) / total_notes) * 100
desc_percent = (int(extended.decent) / total_notes) * 100
wo_percent = (int(extended.wayoff) / total_notes) * 100
miss_percent = (int(extended.miss) / total_notes) * 100
emb.add_field(name="<:mfc:472191264796966926> Fantastic",
value="%s (%0.2f%%)" % (extended.fantastic, fant_percent), inline=True)
emb.add_field(name="<:pfc:472191264402702347> Excellent",
value="%s (%0.2f%%)" % (extended.excellent, exec_percent), inline=True)
emb.add_field(name="<:gfc:844785257852960778> Great",
value="%s (%0.2f%%)" % (extended.great, great_percent), inline=True)
if not extended.boysoff:
emb.add_field(name="😠 Decent",
value="%s (%0.2f%%)" % (extended.decent, desc_percent), inline=True)
emb.add_field(name="<:CautionDDR:636661438085333002> Wayoff",
value="%s (%0.2f%%)" % (extended.wayoff, wo_percent), inline=True)
else:
footer += "No Decent/WO. "
emb.add_field(name="<:eming:572201816792629267> Miss",
value="%s (%0.2f%%)" % (extended.miss, miss_percent), inline=True)
if extended.cmod is not None:
footer += "CMod: %s. " % extended.cmod
if extended.rate is not None:
footer += "%s. " % extended.rate
else:
footer += "Score was not submitted with judgement data. "
emb.set_footer(text=footer)
if song_info.cover_url is not None:
emb.set_thumbnail(url="https://assets.cyberkitsune.net/gstats_proxy/%s" % urllib.parse.quote(song_info.cover_url))
return emb
class YeetException(Exception):
pass
class DDRBotClient(discord.Client):
admin_users = ['109500246106587136']
command_handlers = {}
command_prefix = 'k!'
authorized_channels = {}
linked_eamuse = {}
shown_screenshots = {}
memes = {}
generic_eamuse_session = None
task_created = False
lastrun = None
auto_task_created = False
auto_users = {}
gstats_task_created = False
gstats_users = {}
add_autos = []
remove_autos = []
warned_auto_error = []
warned_no_users = False
db_add_queue = queues.Queue()
db_task_started = False
feed_task_created = False
new_scores = queues.Queue()
def __init__(self, session_id):
self.generic_eamuse_session = session_id
self.command_handlers['help'] = self.help_command
self.command_handlers['lookup'] = self.lookup_command
self.command_handlers['search'] = self.search_command
self.command_handlers['addreport'] = self.addreport_command
self.command_handlers['link'] = self.link_command
self.command_handlers['scores'] = self.show_screenshots
self.command_handlers['auto'] = self.auto_command
self.command_handlers['authorize'] = self.auth_channel
self.command_handlers['last'] = self.last_command
self.command_handlers['yeet'] = self.yeet
self.command_handlers['debug_user'] = self.debug_user
self.command_handlers['gsrecent'] = self.itg_recent
self.command_handlers['gslink'] = self.track_gstats
if os.path.exists("ENABLE_SHITPOST"):
self.command_handlers['meme'] = self.meme_manage
self.command_handlers['memeon'] = self.shitpost_authorize
if os.path.exists("DDR_GENIE_ON"):
self.command_handlers['genie'] = self.genie_command
self.command_handlers['top'] = self.top_scores
self.command_handlers['setfeed'] = self.feed_authorize
self.command_handlers['screenshot'] = self.fetch_screenshot
self.command_handlers['show'] = self.show_score
self.command_handlers['redo'] = self.requeue_db
self.command_handlers['manual'] = self.manual_db
self.command_handlers['leaderboard'] = self.bot_leaderboard
self.command_handlers['csv'] = self.csv_command
#self.command_handlers['pb'] = self.list_pb
if os.path.exists("MACHINE_TRACKING"):
self.monitoring_arcades = {}
self.monitoring_users = []
self.active_users = {}
self.last_check = datetime.datetime.utcnow().timestamp()
self.notify_messages = []
self.command_handlers['addarcade'] = self.add_arcade
self.command_handlers['trackme'] = self.track_me
self.command_handlers['here'] = self.here
self.command_handlers['debug_trigger'] = self.debug_trigger
self.deep_ai = None
intents = discord.Intents.default()
intents.members = True
self.warned_eamuse = False
super().__init__(intents=intents)
async def on_ready(self):
print("[BOT] DDRBot is ready!")
if os.path.exists("linked.json"):
print("[BOT] Loading saved e-amusement accounts!")
self.linked_eamuse = load_json("linked.json")
if os.path.exists("shown.json"):
print("[BOT] Loading shown history!")
self.shown_screenshots = load_json("shown.json")
if os.path.exists("auto.json"):
print("[BOT] Loading automode users!")
self.auto_users = load_json("auto.json")
if os.path.exists("gstats.json"):
print("[BOT] Loading groovestats users")
self.gstats_users = load_json("gstats.json")
if os.path.exists("channels.json"):
print("[BOT] Loading authorized channels!")
self.authorized_channels = load_json("channels.json")
if os.path.exists("memes.json"):
print("[BOT] Loaded memes!")
self.memes = load_json("memes.json")
if not self.task_created and os.path.exists("MACHINE_TRACKING"):
if os.path.exists("monitor_arcades.json"):
self.monitoring_arcades = load_json("monitor_arcades.json")
if os.path.exists("monitor_users.json"):
self.monitoring_users = load_json("monitor_users.json")
self.loop.create_task(self.monitor_task())
self.task_created = True
print("[TASK] Created monitoring updating thread!")
if not self.auto_task_created:
self.loop.create_task(self.auto_task())
self.auto_task_created = True
print("[TASK] Created auto thread")
if not self.gstats_task_created:
self.loop.create_task(self.gstats_task())
self.gstats_task_created = True
print("[TASK] Created gstats thread")
if not self.db_task_started and os.path.exists("DDR_GENIE_ON"):
self.loop.create_task(self.db_task())
self.db_task_started = True
print("[TASK] Created DB task")
if not self.feed_task_created:
self.loop.create_task(self.feed_task())
self.feed_task_created = True
print("[TASK] Created Feed task")
if os.path.exists("deepai_key.txt"):
print("[DEEPAI] DeepAI Key Exists. Enabling AI upscaling.")
with open("deepai_key.txt", 'r') as f:
self.deep_ai = f.read()
else:
self.deep_ai = None
async def on_message(self, message: discord.Message):
if 'commands' not in self.authorized_channels:
self.authorized_channels['commands'] = []
should_listen = str(message.author.id) in self.admin_users or str(message.channel.id) in self.authorized_channels['commands']
if not should_listen:
if isinstance(message.channel, discord.DMChannel):
should_listen = True
else:
if str(message.author.id) == str(message.channel.guild.owner_id):
should_listen = True
do_command = message.content.startswith(self.command_prefix)
if should_listen:
if do_command:
try:
command_name = message.content.split(" ", 1)[0]
command_name = command_name.split(self.command_prefix, 1)[1]
except Exception:
command_name = ""
print("[CMD] %s#%s is running command %s" % (message.author.name, message.author.discriminator, command_name))
if command_name in self.command_handlers:
try:
await self.command_handlers[command_name](message)
except EALinkException as ex:
if ex.jscontext is not None:
await message.channel.send("Oops! uwu an error occured running that e-amusement command.\nError Reason:```\n%s```\nError JSON```\n%s```" % (ex, ex.jscontext))
else:
await message.channel.send("Oops! uwu an error occured running that e-amusement command.\nError Reason:```\n%s```" % ex)
except YeetException as ex:
print("[YEET] YEEEET")
if db is not None:
db.close()
await self.close()
except Exception as ex:
await message.channel.send("Oops! uwu an error occured running that command.\nTechnical Details of Error: ```\n%s```" % (traceback.format_exc()))
elif os.path.exists("ENABLE_SHITPOST") and command_name in self.memes:
await self.run_meme(message, command_name)
else:
await message.channel.send("Sorry! %s is not a command... try doing %shelp..." % (command_name, self.command_prefix))
elif do_command and not should_listen:
await message.channel.send("Sorry! I can't run commands in this channel. Ask a bot admin or the server owner to run %sauthorize in here." % self.command_prefix)
async def on_reaction_add(self, reaction, user):
message = reaction.message
if message.id in self.notify_messages and not user.bot:
emoj = emoji.demojize(reaction.emoji)
num_str = ''.join(i for i in emoj if i.isdigit())
num = w2n.word_to_num(num_str)
aid = str(user.id)
if aid in self.active_users:
self.active_users[aid]["arcade"] = list(self.monitoring_arcades.keys())[num - 1]
await message.channel.send("You've successfully checked into **%s**!" % list(self.monitoring_arcades.keys())[num - 1])
self.notify_messages.remove(message.id)
async def meme_manage(self, message):
can_add = str(message.author.id) in self.admin_users
if can_add:
args = message.content.split(" ")
if len(args) < 2:
await message.channel.send("Invalid Syntax! \nUsage:\n"
"```%smeme add <meme name> <string>\n%smeme del <meme name> [string]```" % (self.command_prefix, self.command_prefix))
return
cmdlet = args[1]
if args[1] == "add":
if len(args) < 3:
await message.channel.send("Invalid Syntax! \nUsage:\n"
"```%smeme add <meme name> <string>\n%smeme del <meme name> [string]```" % (
self.command_prefix, self.command_prefix))
return
name = args[2]
if name not in self.memes:
self.memes[name] = []
self.memes[name].append(' '.join(args[3:]))
print("[MEME] Added new meme %s %s" % (name, ' '.join(args[3:])))
await message.channel.send("Added meme!")
save_json("memes.json", self.memes)
elif args[1] == "del":
name = args[2]
if name not in self.memes:
await message.channel.send("%s isn't a meme yet! Can't delete!" % name)
return
if len(args) > 3:
msg = ' '.join(args[3:])
if msg in self.memes[name]:
self.memes[name].remove(msg)
await message.channel.send("Deleted %s from %s" % (msg, name))
print("[MEME] Deleted %s from %s" % (msg, name))
save_json("memes.json", self.memes)
else:
await message.channel.send("%s doesn't have message %s..." % (name, msg))
else:
if name in self.memes:
del self.memes[name]
await message.channel.send("Deleted %s from memes." % (name))
print("[MEME] Deleted %s from memes." % (name))
save_json("memes.json", self.memes)
else:
await message.channel.send("Invalid Syntax! \nUsage:\n"
"```%smeme add <meme name> <string>\n%smeme del <meme name> [string]```" % (
self.command_prefix, self.command_prefix))
return
else:
await message.add_reaction('<:eming:572201816792629267>')
async def run_meme(self, message, meme_name):
if self.check_shitpost(message):
string = random.choice(self.memes[meme_name])
await message.channel.send(string)
else:
if str(message.guild.id) == str('572200197124390922') and str(message.author.id) == str('303023183924166661'):
await message.delete()
else:
await message.add_reaction('<:eming:572201816792629267>')
async def yeet(self, message):
can_yeet = str(message.author.id) in self.admin_users
if can_yeet:
raise YeetException("YEET")
else:
await message.add_reaction('<:eming:572201816792629267>')
async def here(self, message):
if not isinstance(message.channel, discord.TextChannel):
await message.channel.send("Sorry, you can't run this in a DM.")
return
arcade_item = None
for arcade in self.monitoring_arcades:
if self.monitoring_arcades[arcade]['channel_id'] == str(message.channel.id):
arcade_item = arcade
if arcade_item is None:
await message.add_reaction('<:eming:572201816792629267>')
return
msg_string = "Verified users currently at **%s**:\n```" % arcade_item
for user in self.active_users:
if self.active_users[user]['arcade'] == arcade_item:
duser = self.get_user(int(user))
if duser is not None:
msg_string += " + \t%s#%s\n" % (duser.name, duser.discriminator)
msg_string += "```"
await message.channel.send(msg_string)
async def debug_trigger(self, message):
can_yeet = str(message.author.id) in self.admin_users
if not can_yeet:
await message.add_reaction('<:eming:572201816792629267>')
return
self.active_users[str(message.author.id)] = {'notified': False, 'reported': False, 'arcade': None, 'last_time': datetime.datetime.utcnow().timestamp()}
await message.channel.send("Making you play DDR RIGHT NOW...")
async def add_arcade(self, message):
if not isinstance(message.channel, discord.TextChannel):
await message.channel.send("Sorry, you can't run this in a DM.")
return
can_yeet = str(message.author.id) in self.admin_users
if not can_yeet:
await message.add_reaction('<:eming:572201816792629267>')
return
args = message.content.split(' ')
if len(args) < 2:
await message.channel.send("Usage: `%saddarcade Arcade Name`" % self.command_prefix)
return
name = ' '.join(args[1:])
if name in self.monitoring_arcades:
del self.monitoring_arcades[name]
await message.channel.send("Removed %s from arcade monitoring." % name)
cid = str(message.channel.id)
arcade_item = None
for arcade in self.monitoring_arcades:
if self.monitoring_arcades[arcade]['channel_id'] == cid:
arcade_item = arcade
if arcade_item is not None:
del self.monitoring_arcades[arcade_item]
await message.channel.send("Removed %s from arcade monitoring." % arcade_item)
else:
self.monitoring_arcades[name] = {'channel_id': cid}
await message.channel.send("Added %s to arcade monitoring." % name)
save_json("monitor_arcades.json", self.monitoring_arcades)
async def track_me(self, message):
if str(message.author.id) not in self.linked_eamuse:
await message.channel.send("You need to link your e-amusement account so the bot can know when you're playing DDR.")
await message.channel.send(
"To do this, use `%slink` in a DM with the bot to link your account." % self.command_prefix)
return
uid = str(message.author.id)
if uid in self.monitoring_users:
self.monitoring_users.remove(uid)
await message.channel.send("You will no longer be asked to check into arcades when you play!")
else:
self.monitoring_users.append(uid)
await message.channel.send("When you play DDR next, I'll DM you to see which arcade you're at!")
save_json("monitor_users.json", self.monitoring_users)
def check_shitpost(self, message):
if isinstance(message.channel, discord.DMChannel):
return True
if 'memes' in self.authorized_channels:
return (str(message.channel.id) in self.authorized_channels['memes'])
else:
return False
async def auth_channel(self, message):
if not isinstance(message.channel, discord.TextChannel):
await message.channel.send("Sorry, you can't run this in a DM.")
return
can_auth = message.author.id == message.channel.guild.owner_id
if not can_auth:
can_auth = str(message.author.id) in self.admin_users
if not can_auth:
await message.channel.send("Sorry, only bot admins or guild owners can authorize channels.")
return
if 'commands' not in self.authorized_channels:
self.authorized_channels['commands'] = []
if str(message.channel.id) in self.authorized_channels['commands']:
await message.channel.send("This channel is already authorized to run commands.\nRemoving authorization now.")
self.authorized_channels['commands'].remove(str(message.channel.id))
else:
await message.channel.send("Authorized this channel to use commands!")
self.authorized_channels['commands'].append(str(message.channel.id))
save_json("channels.json", self.authorized_channels)
async def shitpost_authorize(self, message):
if not isinstance(message.channel, discord.TextChannel):
await message.channel.send("Sorry, you can't run this in a DM.")
return
can_auth = message.author.id == message.channel.guild.owner_id
if not can_auth:
can_auth = str(message.author.id) in self.admin_users
if not can_auth:
await message.channel.send("Sorry, only bot admins or guild owners can authorize meme channels.")
return
if 'memes' not in self.authorized_channels:
self.authorized_channels['memes'] = []
if str(message.channel.id) in self.authorized_channels['memes']:
await message.channel.send(
"This channel is already authorized to run memes.\nRemoving authorization now.")
self.authorized_channels['memes'].remove(str(message.channel.id))
else:
await message.channel.send("Authorized this channel to use memes!")
self.authorized_channels['memes'].append(str(message.channel.id))
save_json("channels.json", self.authorized_channels)
async def feed_authorize(self, message):
if not isinstance(message.channel, discord.TextChannel):
await message.channel.send("Sorry, you can't run this in a DM.")
return
can_auth = message.author.id == message.channel.guild.owner_id
if not can_auth:
can_auth = str(message.author.id) in self.admin_users
if not can_auth:
await message.channel.send("Sorry, only bot admins or guild owners can authorize feed channels.")
return
if 'feed' not in self.authorized_channels:
self.authorized_channels['feed'] = []
if str(message.channel.id) in self.authorized_channels['feed']:
await message.channel.send(
"This channel is already a score feed.\nRemoving.")
self.authorized_channels['feed'].remove(str(message.channel.id))
else:
await message.channel.send("Designated channel as score feed!")
self.authorized_channels['feed'].append(str(message.channel.id))
save_json("channels.json", self.authorized_channels)
async def fetch_screenshot(self, message):
args = message.content.split(' ')
if len(args) < 2:
await message.channel.send("Usage: `%sscreenshot [screenshot_id]`" % self.command_prefix)
return
st = Score
if 'iidx' in args[1]:
st = IIDXScore
args[1] = args[1].strip('iidx')
if not RepresentsInt(args[1]):
await message.channel.send("`%s` is not a number!\n"
"Usage: `%sscreenshot [screenshot_id]`" % (args[1], self.command_prefix))
return
s = st.get_or_none(id=args[1])
if s is None:
await message.channel.send("I can't find a screenshot with ID `%s`" % args[1])
return
if os.path.exists("archive/%s/%s" % (s.user.id, s.file_name)):
await message.channel.send(file=discord.File("archive/%s/%s" % (s.user.id, s.file_name)))
else:
await message.channel.send("Weird, I don't have the screenshot file for that score recorded! 😦")
async def show_score(self, message):
args = message.content.split(' ')
if len(args) < 2:
await message.channel.send("Usage: `%sscore [score_id]`" % self.command_prefix)
return
st = Score
if 'iidx' in args[1]:
st = IIDXScore
args[1] = args[1].strip('iidx')
if not RepresentsInt(args[1]):
await message.channel.send("`%s` is not a number!\n"
"Usage: `%sscore [screenshot_id]`" % (args[1], self.command_prefix))
return
s = st.get_or_none(id=args[1])
if s is None:
await message.channel.send("I can't find a score with ID `%s`" % args[1])
return
await message.channel.send(embed=generate_embed_from_db(s, s.user.display_name, True))
async def requeue_db(self, message):
can_manual = str(message.author.id) in self.admin_users
if not can_manual:
await message.add_reaction('<:eming:572201816792629267>')
return
args = message.content.split(' ')
if len(args) < 2:
await message.channel.send("This command will re-process an old score to be fixed after genie changes.\n"
"Usage: `%sredo [score_id]`" % self.command_prefix)
return
game = 'ddr'
if 'iidx' in args[1]:
game = 'iidx'
args[1] = args[1].strip('iidx')
st = IIDXScore
else:
st = Score
if not RepresentsInt(args[1]):
await message.channel.send("`%s` is not a number!\n"
"Usage: `%sredo [screenshot_id]`" % (args[1], self.command_prefix))
return
s = st.get_or_none(id=args[1])
if s is None:
await message.channel.send("I can't find a score with ID `%s`" % args[1])
return
timestamp = s.file_name.split('-')[1].strip('.jpg')
await self.db_add_queue.put(DBTaskWorkItem(s.user.id, s.file_name, timestamp, redo=True, game=game))
await message.channel.send("Added score ID `%s` to the reprocessing queue. (It may take a moment to reprocess)"
% args[1])
async def manual_db(self, message):
can_manual = str(message.author.id) in self.admin_users
if not can_manual:
await message.add_reaction('<:eming:572201816792629267>')
return
args = message.content.split(' ')
if len(args) < 4:
await message.channel.send("This command will manually process archived screenshots.\n"
"Usage: `%smanual [discordid] [filename] [timestamp]`" % self.command_prefix)
return
if not RepresentsInt(args[1]) or not RepresentsInt(args[3]):
await message.channel.send("Invalid args.\n"
"Usage: `%smanual [discordid] [filename] [timestamp]`" % self.command_prefix)
return
if not os.path.exists("archive/%s/%s" % (args[1], args[2])):
await message.channel.send("I couldn't find the screenshot at `archive/%s/%s`" % (args[1], args[2]))
return
game = 'ddr'
if 'iidx' in args:
game = 'iidx'
await self.db_add_queue.put(DBTaskWorkItem(int(args[1]), args[2], int(args[3]), redo=False, game=game))
await message.channel.send("Added file `archive/%s/%s` to the processing queue."
% (args[1], args[2]))
async def help_command(self, message):
await message.channel.send("Hi! I'm KitsuneBot! I can do various actions related to Bemani games and e-amusement!\n"
"To use commands simply put `%s` before a command name listed below!\n"
"Have a look at the commands here <https://github.com/cyberkitsune/DDRBot/wiki/Commands>\n"
"I'm made by <@109500246106587136> so feel free to ask them any questions" % self.command_prefix)
command_list = ', '.join(self.command_handlers.keys())
await message.channel.send("You can run the following commands: %s" % command_list)
async def lookup_command(self, message):
args = message.content.split(" ")
if len(args) < 2 or not RepresentsInt(args[1]):
await message.channel.send("You didn't specify a valid DDR ID!")
return
ddrid = int(args[1])
await message.channel.send("Looking up player with DDR-ID %i..." % ddrid)
api = EAGate(self.generic_eamuse_session)
ddr = DDRApi(api)
player = ddr.lookup_rival(ddrid)
if player is None:
await message.channel.send("Hmm... I can't find that player!")
else:
await message.channel.send("```\n%s\t%i```" % (player.name, player.ddrid))
async def search_command(self, message):
args = message.content.split(" ", 1)
if len(args) < 2:
await message.channel.send("You didn't specify a name to search")
return
name = args[1]
await message.channel.send("Looking up players with names like %s..." % name)
api = EAGate(self.generic_eamuse_session)
ddr = DDRApi(api)
players = ddr.lookup_rivals(name)
if len(players) == 0:
await message.channel.send("Unable to find a players with a name like %s..." % name)
else:
userlist = ''.join(["%s\t%i\n" % (x.name, x.ddrid) for x in players])
user_message = "Found Users:\n```%s```" % userlist
await message.channel.send(user_message)
async def itg_recent(self, message):
args = message.content.split(" ")
if len(args) < 2 or not RepresentsInt(args[1]):
await message.channel.send("You didn't specify a Groove Stats user ID!")
return
gsid = int(args[1])
await message.channel.send("Checking Groovestats user with ID **%i**" % gsid)
gsc = GrooveStatsClient()
recent = gsc.get_recent(gsid)
if len(recent) < 1:
await message.channel.send("That user has no recent submissions or does not exist.")
return
most_recent = recent[0]
if most_recent.is_gslaunch and most_recent.comment is None:
most_recent = gsc.get_detailed_for(most_recent)
emb = generate_itg_embed(most_recent, gsc.song_info(most_recent.chart_id, most_recent.game_id, diff_to_id(most_recent.difficulty)))
await message.channel.send("**%s**'s most recent Groovestats Submission:" % most_recent.user_name, embed=emb)
async def track_gstats(self, message):
if str(message.author.id) in self.gstats_users:
del self.gstats_users[str(message.author.id)]
await message.channel.send("You've been removed from groovestats tracking.")
save_json("gstats.json", self.gstats_users)
return
args = message.content.split(" ")
if len(args) < 2 or not RepresentsInt(args[1]):
await message.channel.send("You didn't specify a Groove Stats user ID to assing yourself to!\n"
"Usage: `%sgslink [your_groovestats_id]`\n"
"You can find your Groove Stats ID in your profile url, after `id=`" % self.command_prefix)
return
gsid = int(args[1])
gsc = GrooveStatsClient()
recent = gsc.get_recent(gsid)
if len(recent) < 1:
await message.channel.send("Userid **%i** either does not exist or has never submitted any scores. "
"You can only link after submission of at least one score.")
return
most_recent = recent[0]
self.gstats_users[str(message.author.id)] = (gsid, str(most_recent))
await message.channel.send("Thanks, **%s**! New score submissions will show up in KitsuneBot score feed channels for any server you're in."
% most_recent.user_name)
save_json("gstats.json", self.gstats_users)
async def addreport_command(self, message):
if not isinstance(message.channel, discord.TextChannel):
await message.channel.send("Sorry, you can't run this in a DM.")
return
can_auth = message.author.id == message.channel.guild.owner_id
if not can_auth:
can_auth = str(message.author.id) in self.admin_users
if not can_auth:
await message.channel.send("Sorry, only bot admins or guild owners can authorize channels.")
return
if 'reporting' not in self.authorized_channels:
self.authorized_channels['reporting'] = []
if str(message.channel.id) not in self.authorized_channels['reporting']:
self.authorized_channels['reporting'].append(str(message.channel.id))
await message.channel.send("Added this channel to the reporting list!")
else:
await message.channel.send("This channel is already a reporting destination! Removing...")
self.authorized_channels['reporting'].remove(str(message.channel.id))
save_json('channels.json', self.authorized_channels)
async def link_command(self, message):
if not isinstance(message.channel, discord.DMChannel):
if str(message.author.id) not in self.linked_eamuse:
await message.channel.send("Your e-amusement account is not linked!")
await message.channel.send("Use this command in a DM with me to link your e-amusement account! **Do not use this command in public**")
await message.channel.send("Usage:\n```%slink [username] [password] [otp (optional)]```" % self.command_prefix)
await message.channel.send("```The bot will not save or log your username or password.\n"
"A token is saved instead and can be revoked by logging in to the e-amusement app if you ever feel the need.\n\n"
"You can review the code for this if you'd like over on github (it's open source)\n "
"https://github.com/cyberkitsune/DDRBot/blob/master/DDRBot.py```")
else:
await message.channel.send("Your e-amusement account is linked!")
await message.channel.send("Use this command in a DM with me to link a different e-amusement account or to login again!")
return
args = message.content.split(" ")
if len(args) < 3:
await message.channel.send("Usage:\n```%slink [username] [password] [otp (optional)]```" % self.command_prefix)
await message.channel.send("```The bot will not save or log your username or password.\n"
"A token is saved instead and can be revoked by logging in to the e-amusement app if you ever feel the need.\n\n"
"You can review the code for this if you'd like over on github (it's open source)\n "
"https://github.com/cyberkitsune/DDRBot/blob/master/DDRBot.py```")
return
eal = EALink()
if len(args) > 3:
eal.login(args[1], args[2], args[3])
else:
eal.login(args[1], args[2])
if eal.logged_in:
self.linked_eamuse[str(message.author.id)] = [eal.cookies[0], eal.cookies[1]]
await message.channel.send("Logged in! Your e-amsuement account is linked!\n"
"You can now use features of the bot that require e-amusement")
await message.channel.send("The bot will automatically DM you new screenshots you save to your e-amusement"
"account. To opt-out of this feature you can type `%sauto off`\nOtherwise, no "
"action is required" % self.command_prefix)
if str(message.author.id) not in self.auto_users:
self.add_autos.append(str(message.author.id))
save_json("linked.json", self.linked_eamuse)
else:
await message.channel.send("Unable to log in!")
async def auto_command(self, message):
args = message.content.split(" ")
if len(args) < 2:
if str(message.author.id) in self.auto_users:
await message.channel.send("You are opted-in to automatic screenshot DMs.")
else:
await message.channel.send("You are not yet opted in to automatic screenshot DMs.")
await message.channel.send("This command allows you to opt-in to having the bot send you your screenshots automatically in a DM.\n"
"Usage:\n"
"```%sauto (on | off)```" % self.command_prefix)
return
if args[1] == 'on':
if str(message.author.id) not in self.auto_users:
self.add_autos.append(str(message.author.id))
await message.channel.send("You have opted-in to automatic screenshots! You will be DM'd them around a minute after taking them.")
else:
await message.channel.send("You are already opted-in to automatic screenshots. Opt-out by running `%sauto off`" % self.command_prefix)
elif args[1] == 'off':
if str(message.author.id) in self.auto_users:
self.remove_autos.append(str(message.author.id))
await message.channel.send("You are now opted-out of automatic screenshots. Opt back in by running `%sauto on`" % self.command_prefix)
else:
await message.channel.send("You're not opted-in to automatic screenshots. Opt in by running `%sauto on`" % self.command_prefix)
else:
await message.channel.send("Invalid syntax.\nUsage:\n```%sauto (on | off)```" % self.command_prefix)