This repository was archived by the owner on Mar 24, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
3475 lines (2845 loc) · 166 KB
/
bot.py
File metadata and controls
3475 lines (2845 loc) · 166 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
import discord
from discord import app_commands
from discord.ext import tasks
import aiohttp
import json
import asyncio
import re
import string
import io
import os
import uuid
import subprocess
import mido
import requests
import enum
import hashlib
import logging
import platform
import random
from difflib import get_close_matches
from datetime import datetime, timedelta
import statistics
from pydub import AudioSegment
import numpy as np
import base64
from hashlib import md5
from functools import partial
import concurrent.futures
import xmltodict
from pathlib import Path
import math
from pydub import utils as pdutils
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
BOT_TOKEN = ""
JSON_DATA_URL = "https://raw.githubusercontent.com/Encore-Developers/EncoreCustoms/refs/heads/main/data/tracks.json"
ASSET_BASE_URL = "https://encore-developers.github.io/EncoreCustoms/"
CONFIG_FILE = "config.json"
TRACK_CACHE_FILE = "tracks_cache.json"
TRACK_PLAYBACK_CONFIG_FILE = "track_playback_config.json"
TRACK_HISTORY_FILE = "track_history.json"
SUGGESTIONS_FILE = "suggestions.json"
CHANGELOG_FILE = "changelog.json"
MIDI_CHANGES_FILE = "midichanges.json"
USER_FILTERS_FILE = "user_filters.json"
LOCAL_MIDI_FOLDER = "midi_files/"
TEMP_FOLDER = "out/"
PREVIEW_FOLDER = "temp/"
LOG_CHANNEL = 1391736223286169720
def tz():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
KEY_NAME_MAP = { # I added this for /trackhistory
"album": "Album",
"artist": "Artist",
"ageRating": "Age Rating",
"bpm": "BPM",
"charter": "Charter",
"currentversion": "Chart Version",
"complete": "Progress",
"coverArist": "Cover | Artist",
"createdAt": "Creation Date",
"download": "Download",
"doubleBass": "Double Bass",
"duration": "Duration",
"filesize": "File Size",
"music_start_time": "Music Bot | Start Time",
"featured": "Updated Track",
"finish": "Finished Track",
"genre": "Genre",
"glowTimes": "Modal | Loading Phrase Glow Times",
"id": "Shortname",
"Has_Stems": "Has Stems",
"is_cover": "Is Cover",
"is_verified": "Is Verified",
"key": "Key",
"lastFeatured": "Last Updated",
"loading_phrase": "Loading Phrase",
"new": "Playable Track",
"newYear": "Cover | Release Year",
"preview_end_time": "Preview End Time",
"preview_time": "Preview Start Time",
"previewEndTime": "Audio Preview End Time",
"previewTime": "Audio Preview Start Time",
"previewUrl": "Audio Preview",
"proVoxHarmonies": "Classic Harmonies Tracks",
"rating": "Rating",
"releaseYear": "Release Year",
"rotated": "WIP Track",
"songlink": "Song Link",
"source": "Source",
"spotify": "Song Link ID",
"title": "Title",
"videoPosition": "Modal | Video Position",
"videoUrl": "Video URL",
"difficulties.vocals": "Vocals Difficulty",
"difficulties.lead": "Lead Difficulty",
"difficulties.rhythm": "Rhythm Difficulty",
"difficulties.bass": "Bass Difficulty",
"difficulties.drums": "Drums Difficulty",
"difficulties.keys": "Keys Difficulty",
"difficulties.pro-vocals": "Classic Vocals Difficulty",
"difficulties.plastic-guitar": "Classic Lead Difficulty",
"difficulties.plastic-rhythm": "Classic Rhythm Difficulty",
"difficulties.plastic-bass": "Classic Bass Difficulty",
"difficulties.plastic-drums": "Classic Drums Difficulty",
"difficulties.plastic-keys": "Classic Keys Difficulty",
"difficulties.real-guitar": "Pro Guitar Difficulty",
"difficulties.real-keys": "Pro Keys Difficulty",
"difficulties.real-bass": "Pro Bass Difficulty",
"difficulties.elite-drums": "Elite Drums Difficulty",
"youtubeLinks.vocals": "Vocals Video",
"youtubeLinks.drums": "Drums Video",
"youtubeLinks.bass": "Bass Video",
"youtubeLinks.lead": "Lead Video",
"modalShadowColors.default.color1": "Modal Color",
"modalShadowColors.default.color2": "Modal Secondary Color",
"modalShadowColors.hover.color1": "Modal Hover Color",
"modalShadowColors.hover.color2": "Modal Hover Secondary Color",
}
intents = discord.Intents.default()
intents.voice_states = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
music_queues = {}
music_control_messages = {}
if not os.path.exists(LOCAL_MIDI_FOLDER): os.makedirs(LOCAL_MIDI_FOLDER)
if not os.path.exists(TEMP_FOLDER): os.makedirs(TEMP_FOLDER)
if not os.path.exists(PREVIEW_FOLDER): os.makedirs(PREVIEW_FOLDER)
if not os.path.exists('temp'): os.makedirs('temp')
def load_json_file(filename: str, default_data: dict | list = None):
if default_data is None:
default_data = {}
if not os.path.exists(filename):
with open(filename, 'w') as f:
json.dump(default_data, f, indent=4)
return default_data
try:
with open(filename, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, FileNotFoundError):
return default_data
def save_json_file(filename: str, data: dict | list):
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
def ensure_playback_config():
logging.info("Checking and updating track playback config...")
playback_config = load_json_file(TRACK_PLAYBACK_CONFIG_FILE, default_data={})
cached_tracks = get_cached_track_data()
updated = False
for track in cached_tracks:
track_id = track.get('id')
if track_id and track_id not in playback_config:
playback_config[track_id] = 0 # Default to 0ms start time
updated = True
logging.info(f"Added new track '{track_id}' to playback config with default start time.")
if updated:
save_json_file(TRACK_PLAYBACK_CONFIG_FILE, playback_config)
logging.info("Saved updates to track playback config.")
class Instrument:
def __init__(self, english:str, lb_code:str, plastic:bool, chopt:str, midi_mapping:dict, lb_enabled:bool = True, path_enabled: bool = True) -> None:
self.english = english
self.lb_code = lb_code
self.plastic = plastic
self.chopt = chopt
self.midi_mapping = midi_mapping
self.lb_enabled = lb_enabled
self.path_enabled = path_enabled
class Difficulty:
def __init__(self, english:str = "Expert", chopt:str = "expert", pitch_ranges = None, diff_4k:bool = False) -> None:
self.english = english
self.chopt = chopt
self.pitch_ranges = pitch_ranges if pitch_ranges is not None else [96, 100]
self.diff_4k = diff_4k
class Instruments(enum.Enum):
ClassicLead = Instrument(english="Classic Lead", lb_code="Solo_PeripheralGuitar", plastic=True, chopt="proguitar", midi_mapping={'json': 'PLASTIC GUITAR', 'ini': 'PART GUITAR'}, path_enabled=True)
ClassicBass = Instrument(english="Classic Bass", lb_code="Solo_PeripheralBass", plastic=True, chopt="probass", midi_mapping={'json': 'PLASTIC BASS', 'ini': 'PART BASS'}, path_enabled=True)
ClassicDrums = Instrument(english="Classic Drums", lb_code="Solo_PeripheralDrum", plastic=True, chopt="drums", midi_mapping={'json': 'PLASTIC DRUMS', 'ini': 'PART DRUMS'}, lb_enabled=False, path_enabled=True)
ClassicVocals = Instrument(english="Classic Vocals", lb_code="Solo_PeripheralVocals", plastic=True, chopt="vocals", midi_mapping={'json': 'PRO VOCALS', 'ini': 'PART VOCALS'}, lb_enabled=False, path_enabled=False)
ClassicKeys = Instrument(english="Classic Keys", lb_code="Solo_PeripheralKeys", plastic=True, chopt="keys", midi_mapping={'json': 'PLASTIC KEYS', 'ini': 'PART KEYS'}, path_enabled=False)
Bass = Instrument(english="Bass", lb_code="Solo_Bass", plastic=False, chopt="bass", midi_mapping={'json': 'PART BASS', 'ini': 'PAD BASS'}, path_enabled=True)
Lead = Instrument(english="Lead", lb_code="Solo_Guitar", plastic=False, chopt="guitar", midi_mapping={'json': 'PART GUITAR', 'ini': 'PAD GUITAR'}, path_enabled=True)
Drums = Instrument(english="Drums", lb_code="Solo_Drums", plastic=False, chopt="drums", midi_mapping={'json': 'PART DRUMS', 'ini': 'PAD DRUMS'}, path_enabled=True)
Vocals = Instrument(english="Vocals", lb_code="Solo_Vocals", plastic=False, chopt="vocals", midi_mapping={'json': 'PART VOCALS', 'ini': 'PAD VOCALS'}, path_enabled=True)
Keys = Instrument(english="Keys", lb_code="Solo_Keys", plastic=False, chopt="keys", midi_mapping={'json': 'PART KEYS', 'ini': 'PAD KEYS'}, path_enabled=False)
class Difficulties(enum.Enum):
Expert = Difficulty()
Hard = Difficulty(english="Hard", chopt="hard", pitch_ranges=[84, 88], diff_4k=True)
Medium = Difficulty(english="Medium", chopt="medium", pitch_ranges=[72, 76], diff_4k=True)
Easy = Difficulty(english="Easy", chopt="easy", pitch_ranges=[60, 64], diff_4k=True)
class MidiArchiveTools:
def save_chart(self, chart_url:str, filename: str) -> str | None:
local_path = os.path.join(LOCAL_MIDI_FOLDER, filename)
if os.path.exists(local_path):
logging.info(f"Chart '{filename}' already exists in cache, using local copy.")
return local_path
logging.info(f"Downloading chart '{filename}' from {chart_url}")
try:
response = requests.get(chart_url)
response.raise_for_status()
with open(local_path, 'wb') as f:
f.write(response.content)
logging.info(f"Successfully saved chart '{filename}' to {local_path}")
return local_path
except requests.exceptions.RequestException as e:
logging.error(f"Failed to download chart from {chart_url}: {e}")
return None
def prepare_midi_for_chopt(self, midi_file: str, instrument: Instrument, session_hash: str, shortname: str, track_format: str) -> str:
source_mid = mido.MidiFile(midi_file, clip=True) # this is required to path midi's outside of a certain size
new_mid = mido.MidiFile(type=source_mid.type, ticks_per_beat=source_mid.ticks_per_beat)
source_track_name = instrument.midi_mapping.get(track_format)
if instrument.chopt == 'drums' and instrument.plastic:
target_track_name = 'PART DRUMS'
elif instrument.plastic:
target_track_name = instrument.midi_mapping.get('json')
else:
target_track_name = instrument.midi_mapping.get('json')
found_instrument_track = False
for track in source_mid.tracks:
if track.name in ['EVENTS', 'BEAT']:
new_mid.tracks.append(track)
continue
if track.name == source_track_name:
track.name = target_track_name
new_mid.tracks.append(track)
found_instrument_track = True
logging.info(f"Isolated and renamed track '{source_track_name}' to '{target_track_name}'.")
if not found_instrument_track:
logging.warning(f"Could not find the source track '{source_track_name}' in the MIDI file.")
modified_midi_file_name = f"{shortname}_{session_hash}_modified.mid"
modified_midi_file = os.path.join(TEMP_FOLDER, modified_midi_file_name)
new_mid.save(modified_midi_file)
return modified_midi_file
def run_chopt(midi_file: str, command_instrument: str, output_image: str, squeeze_percent: int = 20, instrument: Instrument = None, difficulty: str = 'expert', track_format: str = 'json', extra_args: list = []):
if platform.system() != "Linux":
raise OSError("The 'path' command is only available on the Linux version of the bot.")
bot_dir = "/home/ubuntu/DiscordBot" # change this based on where all the chopt files are located
chopt_executable_path = os.path.join(bot_dir, "chopt")
engine = 'fnf'
chopt_command = [
chopt_executable_path,
'-f', midi_file,
'--engine', engine,
'--squeeze', str(squeeze_percent),
'--early-whammy', '0',
'--diff', difficulty
]
if instrument:
midi_track_name = instrument.midi_mapping.get(track_format, instrument.midi_mapping.get('json'))
if midi_track_name == 'PLASTIC DRUMS':
engine = 'ch'
if midi_track_name != 'PLASTIC DRUMS':
chopt_command.append('--no-pro-drums')
chopt_command.extend(['-i', command_instrument, '-o', os.path.join(TEMP_FOLDER, output_image)])
chopt_command.extend(extra_args)
proc_env = os.environ.copy()
existing_ld_path = proc_env.get('LD_LIBRARY_PATH', '')
proc_env['LD_LIBRARY_PATH'] = f"{bot_dir}:{existing_ld_path}"
try:
result = subprocess.run(chopt_command, text=True, capture_output=True, env=proc_env)
except FileNotFoundError:
raise FileNotFoundError(f"Error: `chopt` not found at the specified path: {chopt_executable_path}. Please ensure the file exists and is executable.")
if result.returncode != 0:
raise Exception(f"Chopt execution failed. Stderr:\n{result.stderr}")
return result.stdout.strip()
def process_acts(arr):
sum_phrases, sum_overlaps = 0, 0
for string in arr:
try:
if "(" in string:
x, y = string.split("(")
y = y.replace(")", "")
sum_phrases += int(x)
sum_overlaps += int(y)
else:
sum_phrases += int(string)
except Exception:
pass
return sum_phrases, sum_overlaps
def generate_session_hash(user_id, song_name):
hash_int = int(hashlib.md5(f"{user_id}_{song_name}".encode()).hexdigest(), 16)
return str(hash_int % 10**8).zfill(8)
def delete_session_files(session_hash):
try:
for file_name in os.listdir(TEMP_FOLDER):
if session_hash in file_name:
file_path = os.path.join(TEMP_FOLDER, file_name)
os.remove(file_path)
logging.info(f"Deleted temp file: {file_path}")
except Exception as e:
logging.error(f"Error cleaning up files for session {session_hash}", exc_info=e)
class PreviewAudioMgr: # i stole this lmao ignore the epic games related stuff
def __init__(self, bot: discord.Client, track: any, interaction: discord.Interaction):
self.bot = bot
self.interaction = interaction
self.track = track
self.hash = md5(bytes(f"{interaction.user.id}-{interaction.id}-{interaction.message.id}", "utf-8")).digest().hex()
self.audio_duration = 0
qi = self.track['track']['qi']
quicksilver_data = json.loads(qi)
self.pid = quicksilver_data['pid']
output_path = f'{PREVIEW_FOLDER}{self.pid}/preview.ogg'
if not os.path.exists(output_path):
mpd = self.acquire_mpegdash_playlist(quicksilver_data)
master_audio_path = self.download_mpd_playlist(mpd)
output_path = self.convert_to_ogg(master_audio_path)
self.output_path = output_path
def _get_ffmpeg_path(self) -> str:
ffmpeg_path = Path('ffmpeg.exe')
if Path.exists(ffmpeg_path):
return str(ffmpeg_path.resolve()).replace('\\', '/')
def _get_ffprobe_path(self) -> str:
ffprobe_path = Path('ffprobe.exe')
if Path.exists(ffprobe_path):
return str(ffprobe_path.resolve()).replace('\\', '/')
def acquire_mpegdash_playlist(self, quicksilver_data: any) -> str:
endpoint = 'https://cdn.qstv.on.epicgames.com/'
url = endpoint + quicksilver_data['pid']
logging.info(f'[GET] {url}')
vod_data = requests.get(url)
vod_data.raise_for_status()
data = vod_data.json()
playlist = base64.b64decode(data['playlist'])
return playlist
def download_mpd_playlist(self, mpd: str) -> str:
data = xmltodict.parse(mpd)
mpd_node = data['MPD']
base_url = mpd_node['BaseURL']
audio_duration = float(mpd_node['@mediaPresentationDuration'].replace('PT', '').replace('S', ''))
self.audio_duration = audio_duration
segment_duration = float(mpd_node['@maxSegmentDuration'].replace('PT', '').replace('S', ''))
num_segments = math.ceil(audio_duration / segment_duration)
representation = mpd_node['Period']['AdaptationSet']['Representation']
repr_id = int(representation['@id'])
sample_rate = int(representation['@audioSamplingRate'])
init_template = representation['SegmentTemplate']['@initialization']
segment_template = representation['SegmentTemplate']['@media']
segment_start = int(representation['SegmentTemplate']['@startNumber'])
output = f'temp/streaming_{self.hash}_'
init_file = init_template.replace('$RepresentationID$', str(repr_id))
init_path = output + init_file
init_url = base_url + init_file
logging.info(f'[GET] {init_url}')
init_data = requests.get(init_url)
with open(init_path, 'wb') as init_file_io:
init_file_io.write(init_data.content)
segments = []
def download_segment(segment_id):
segment_file = segment_template.replace('$RepresentationID$', str(repr_id)).replace('$Number$', str(segment_id))
segment_path = output + segment_file
segment_url = base_url + segment_file
logging.info(f'[GET] {segment_url}')
segment_data = requests.get(segment_url)
with open(segment_path, 'wb') as segment_file_io:
segment_file_io.write(segment_data.content)
segments.append(segment_path)
with concurrent.futures.ThreadPoolExecutor(max_workers=15) as executor:
futures = [executor.submit(download_segment, idx) for idx in range(segment_start, num_segments + 1)]
concurrent.futures.wait(futures)
segments.sort(key=lambda x: int(x.split('_')[-1].split('.')[0]))
master_file = output + 'master_audio.mp4'
with open(master_file, 'wb') as master:
master.write(open(init_path, 'rb').read())
os.remove(init_path)
for segment in segments:
master.write(open(segment, 'rb').read())
os.remove(segment)
return master_file
def convert_to_ogg(self, master_audio_path):
output_path = f'{PREVIEW_FOLDER}{self.pid}'
os.makedirs(output_path, exist_ok=True)
output_path += '/preview.ogg'
ffmpeg_path = self._get_ffmpeg_path()
ffmpeg_command = [
ffmpeg_path,
'-i',
master_audio_path,
'-acodec',
'libopus',
'-ar',
'48000',
output_path
]
subprocess.run(ffmpeg_command)
return output_path
def get_waveform_bytearray(self) -> tuple[np.uint8, float]:
AudioSegment.converter = self._get_ffmpeg_path()
def override_prober() -> str:
return self._get_ffprobe_path()
pdutils.get_prober_name = override_prober
if os.path.exists(self.output_path.replace('preview.ogg', 'waveform.dat')):
with open(self.output_path.replace('preview.ogg', 'waveform.dat'), 'rb') as f:
if os.path.exists(self.output_path.replace('preview.ogg', 'duration.dat')):
duration = float(open(self.output_path.replace('preview.ogg', 'duration.dat'), 'r').read())
else:
audio = AudioSegment.from_file(self.output_path, format="ogg")
duration = audio.duration_seconds
open(self.output_path.replace('preview.ogg', 'duration.dat'), 'w').write(f'{duration}')
return (np.frombuffer(f.read(), dtype=np.uint8), duration)
audio = AudioSegment.from_file(self.output_path, format="ogg")
audio.converter = self._get_ffmpeg_path()
duration = audio.duration_seconds
samples = np.array(audio.get_array_of_samples())
sample_rate = audio.frame_rate
# Normalize to range [-1.0, 1.0]
samples = samples / np.max(np.abs(samples))
# Downsample to 256 points
total_samples = len(samples)
stride = max(1, total_samples // 256)
downsampled = samples[::stride][:256]
# Scale to 0-255
byte_array = np.uint8((downsampled + 1.0) * 127.5)
# Cache the waveform bytearray
with open(self.output_path.replace('preview.ogg', 'waveform.dat'), 'wb') as f:
f.write(byte_array.tobytes())
with open(self.output_path.replace('preview.ogg', 'duration.dat'), 'w') as f:
f.write(f'{duration}')
return (byte_array, duration)
async def reply_to_interaction_message(self):
msg = self.interaction.message
# url = f'https://discord.com/api/v10/channels/{msg.channel.id}/messages'
# for responding to an ephmeral button interaction:
url = f'https://discord.com/api/v10/webhooks/{self.bot.application.id}/{self.interaction.token}/messages/@original'
# + remove message_reference from the payload
# + change the method to PATCH
flags = discord.MessageFlags()
flags.voice = True
wvform_bytearray, audio_duration = self.get_waveform_bytearray()
wvform_b64 = base64.b64encode(wvform_bytearray.tobytes()).decode('utf-8')
payload = {
"tts": False,
"flags": flags.value,
"attachments": [
{
"id": "0",
"filename": f"{self.hash}_voice-message.ogg",
"duration_secs": audio_duration,
"waveform": wvform_b64
}
] # ,
# "message_reference": {
# "message_id": msg.id,
# "channel_id": msg.channel.id,
# "guild_id": msg.guild.id
# }
}
data = bytearray()
data.extend(b"--boundary\r\n")
data.extend(b"Content-Disposition: form-data; name=\"payload_json\"\r\n")
data.extend(b"Content-Type: application/json\r\n\r\n")
data.extend(json.dumps(payload, indent=4).encode('utf-8'))
data.extend(b"\r\n--boundary\r\n")
data.extend(f"Content-Disposition: form-data; name=\"files[0]\"; filename=\"{self.hash}_voice-message.ogg\"\r\n".encode('utf-8'))
data.extend(b"Content-Type: audio/ogg\r\n\r\n")
data.extend(open(self.output_path, 'rb').read())
data.extend(b"\r\n--boundary--")
logging.info(f'[POST] {url}')
resp = requests.patch(url, data=data, headers={
"Content-Type": "multipart/form-data; boundary=\"boundary\"",
"Authorization": "Bot " + self.bot.http.token
})
logging.info(f'[Interaction {self.interaction.id}] Voice Message Received: {resp.status_code} {resp.reason}')
if not resp.ok:
logging.error(resp.text)
await self.bot.get_channel(LOG_CHANNEL).send(content=f"{tz()} Voice Message for {self.track['track']['sn']} sent to {self.interaction.user.id}")
async def log_error_to_channel(error_message: str):
logging.error(error_message)
config = load_json_file(CONFIG_FILE)
error_channel_id = config.get('error_log_channels', {}).get('default')
if error_channel_id:
channel = client.get_channel(int(error_channel_id))
if channel:
try:
embed = discord.Embed(
title="Bot Error",
description=error_message[:4000],
color=discord.Color.red(),
timestamp=datetime.now()
)
await channel.send(embed=embed)
except discord.Forbidden:
logging.error(f"Failed to send error log to channel {error_channel_id}: Missing permissions.")
except Exception as e:
logging.error(f"Failed to send error log message: {e}")
async def update_bot_status():
try:
tracks = get_cached_track_data()
track_count = len(tracks)
activity = discord.Activity(type=discord.ActivityType.playing, name=f"{track_count} Tracks")
await client.change_presence(activity=activity)
logging.info(f"Updated bot status: Playing {track_count} Tracks")
except Exception as e:
await log_error_to_channel(f"Error updating bot status: {str(e)}")
async def get_live_track_data() -> list | None:
logging.info("Attempting to fetch live track data from source...")
try:
async with aiohttp.ClientSession() as session:
async with session.get(JSON_DATA_URL, timeout=10) as response:
if response.status == 200:
data = await response.json(content_type=None)
tracks_list = []
if isinstance(data, dict):
for track_id, track_info in data.items():
track_info['id'] = track_id
tracks_list.append(track_info)
else:
await log_error_to_channel(f"Error: JSON data is not in the expected format (dictionary of tracks). Got type: {type(data)}")
return None
logging.info(f"Successfully fetched {len(tracks_list)} live tracks.")
return tracks_list
else:
await log_error_to_channel(f"Failed to fetch live data. Status code: {response.status}")
return None
except (aiohttp.ClientError, json.JSONDecodeError, asyncio.TimeoutError) as e:
await log_error_to_channel(f"Error during live data fetching or parsing: {str(e)}")
return None
def get_cached_track_data() -> list:
try:
return load_json_file(TRACK_CACHE_FILE, {"tracks": []}).get("tracks", [])
except Exception as e:
asyncio.create_task(log_error_to_channel(f"Error reading track cache: {str(e)}"))
return []
def parse_duration_to_seconds(duration_str: str) -> int:
try:
if not isinstance(duration_str, str): return 0
seconds = 0
if (minutes_match := re.search(r'(\d+)m', duration_str)):
seconds += int(minutes_match.group(1)) * 60
if (seconds_match := re.search(r'(\d+)s', duration_str)):
seconds += int(seconds_match.group(1))
return seconds
except Exception as e:
asyncio.create_task(log_error_to_channel(f"Error parsing duration: {str(e)}"))
return 0
def get_sort_display_name(sort_by: str) -> str:
sort_display_names = {
'latest': 'Latest (Recent Creation Date)',
'earliest': 'Earliest (Oldest Creation Date)',
'longest': 'Longest (Longest Length)',
'shortest': 'Shortest (Shortest Length)',
'fastest': 'Fastest (Highest BPM)',
'slowest': 'Slowest (Lowest BPM)',
'newest': 'Newest (Recent Release Year)',
'oldest': 'Oldest (Oldest Release Year)',
'charter': 'Charter (A-Z)',
'charter_za': 'Charter (Z-A)',
'hardest': 'Hardest (Avg. Difficulty)',
'easiest': 'Easiest (Avg. Difficulty)',
'filesize_largest': 'File Size (Largest)',
'filesize_smallest': 'File Size (Smallest)',
'genre_az': 'Genre (A-Z)',
'genre_za': 'Genre (Z-A)'
}
return sort_display_names.get(sort_by, sort_by.replace('_', '-').title())
def parse_filesize_to_mb(filesize_str) -> float:
try:
if not filesize_str:
return 0.0
filesize_str = str(filesize_str)
import re
match = re.match(r'([0-9.]+)\s*(GB|MB|KB|gb|mb|kb)?', filesize_str.strip())
if not match:
try:
return float(filesize_str)
except:
return 0.0
number = float(match.group(1))
unit = match.group(2)
if not unit:
return number
unit = unit.upper()
if unit == 'GB':
return number * 1024
elif unit == 'MB':
return number
elif unit == 'KB':
return number / 1024
else:
return number
except Exception as e:
asyncio.create_task(log_error_to_channel(f"Error parsing filesize: {str(e)}"))
return 0.0
def remove_punctuation(text: str) -> str:
try:
return text.translate(str.maketrans('', '', string.punctuation))
except Exception as e:
asyncio.create_task(log_error_to_channel(f"Error removing punctuation: {str(e)}"))
return text
def create_difficulty_bar(level: int, max_level: int = 7) -> str:
try:
if not isinstance(level, int) or level < 0: return ""
level = min(level, max_level)
return f"{'■' * level}{'□' * (max_level - level)}"
except Exception as e:
asyncio.create_task(log_error_to_channel(f"Error creating difficulty bar: {str(e)}"))
return ""
def calculate_average_difficulty(track: dict) -> float:
try:
difficulties = track.get('difficulties', {})
valid_diffs = [d for d in difficulties.values() if isinstance(d, int) and d != -1]
if not valid_diffs:
return 0.0
return statistics.mean(valid_diffs)
except Exception:
return 0.0
def fuzzy_search_tracks(tracks: list, query: str, sort_method: str = None, limit_results: bool = True) -> list:
try:
sort_map = {
'latest': ('createdAt', True, 25), 'earliest': ('createdAt', False, 25),
'longest': ('duration', True, 25), 'shortest': ('duration', False, 25),
'fastest': ('bpm', True, 25), 'slowest': ('bpm', False, 25),
'newest': ('releaseYear', True, 25), 'oldest': ('releaseYear', False, 25),
'charter': ('charter', False, 25), 'charter_za': ('charter', True, 25),
'hardest': ('avg_difficulty', True, 25), 'easiest': ('avg_difficulty', False, 25),
'filesize_largest': ('filesize', True, 25), 'filesize_smallest': ('filesize', False, 25),
'genre_az': ('genre', False, 25), 'genre_za': ('genre', True, 25)
}
if sort_method and sort_method.lower() in sort_map:
key, reverse, limit = sort_map[sort_method.lower()]
if key == 'duration':
sort_key_func = lambda t: parse_duration_to_seconds(t.get(key, '0s'))
elif key == 'createdAt':
sort_key_func = lambda t: datetime.fromisoformat(t.get(key, '1970-01-01T00:00:00Z').replace('Z', '+00:00')).timestamp()
elif key == 'charter':
sort_key_func = lambda t: t.get(key, '').lower()
elif key == 'genre':
sort_key_func = lambda t: t.get(key, '').lower()
elif key == 'avg_difficulty':
sort_key_func = calculate_average_difficulty
elif key == 'filesize':
sort_key_func = lambda t: parse_filesize_to_mb(t.get(key, '0'))
else:
sort_key_func = lambda t: t.get(key, 0) if isinstance(t.get(key, 0), (int, float)) else 0
sortable_tracks = [t for t in tracks if t.get(key) is not None and t.get(key) != ''] if key != 'avg_difficulty' else tracks
sorted_tracks = sorted(sortable_tracks, key=sort_key_func, reverse=reverse)
return sorted_tracks[:limit] if limit_results else sorted_tracks
if not query:
return []
# Fish
if query.strip() == "🐟":
fish_tracks = []
for track in tracks:
fish_field = track.get('fish', '')
if fish_field and '🐟' in fish_field:
fish_tracks.append(track)
return fish_tracks
search_term = remove_punctuation(query.lower())
exact_matches, fuzzy_matches = [], []
for track in tracks:
title = remove_punctuation(track.get('title', '').lower())
artist = remove_punctuation(track.get('artist', '').lower())
track_id = track.get('id', '').lower()
if search_term == track_id or search_term in title or search_term in artist:
exact_matches.append(track)
elif get_close_matches(search_term, [title, artist], n=1, cutoff=0.7):
fuzzy_matches.append(track)
filtered_tracks, seen_ids = [], set()
for track in exact_matches + fuzzy_matches:
if (track_id := track.get('id')) not in seen_ids:
filtered_tracks.append(track)
seen_ids.add(track_id)
return filtered_tracks
except Exception as e:
asyncio.create_task(log_error_to_channel(f"Error in fuzzy search/sort: {str(e)}"))
return []
def format_key(key_str: str) -> str:
try:
if not key_str or not isinstance(key_str, str):
return "N/A"
key_map = {"A♭": "G♯", "B♭": "A♯", "D♭": "C♯", "E♭": "D♯", "G♭": "F♯"}
for flat, sharp in key_map.items():
if flat in key_str:
return f"{sharp} / {key_str}"
return key_str
except Exception as e:
asyncio.create_task(log_error_to_channel(f"Error formatting key: {str(e)}"))
return "N/A"
def create_track_embed_and_view(track: dict, author_id: int, is_log: bool = False):
try:
embed_title = "Track Added" if is_log else None
if is_log:
color = discord.Color.green()
else:
source = track.get('source', '').lower()
if source in ['custom', 'encore']:
color = discord.Color(0x7d1f6e)
elif 'rb' in source:
color = discord.Color.blue()
elif 'gh' in source:
color = discord.Color.orange()
else:
color = discord.Color.purple()
description = f"## {track.get('title', 'N/A')} - {track.get('artist', 'N/A')}"
embed = discord.Embed(
title=embed_title,
description=description,
color=color
)
if (is_verified := track.get('is_verified')) is not None:
if is_verified is True or str(is_verified).lower() == 'true':
embed.add_field(name="", value="✅ ***Verified Track***", inline=False)
else:
embed.add_field(name="", value="***Unverified Track***", inline=False)
if track.get('cover'):
embed.set_thumbnail(url=f"{ASSET_BASE_URL}/assets/covers/{track.get('cover')}")
avg_difficulty = calculate_average_difficulty(track)
embed.add_field(name="Release Year", value=str(track.get('releaseYear', 'N/A')))
embed.add_field(name="Album", value=track.get('album', 'N/A'))
embed.add_field(name="Genre", value=track.get('genre', 'N/A'))
embed.add_field(name="Duration", value=track.get('duration', 'N/A'))
embed.add_field(name="BPM", value=str(track.get('bpm', 'N/A')))
embed.add_field(name="Key", value=format_key(track.get('key', 'N/A')))
embed.add_field(name="Charter", value=track.get('charter', 'N/A'))
embed.add_field(name="Rating", value=track.get('ageRating', 'N/A'))
embed.add_field(name="Avg. Difficulty", value=f"{avg_difficulty:.1f}")
embed.add_field(name="Shortname", value=f"`{track.get('id', 'N/A')}`")
embed.add_field(name="Source", value=f"`{track.get('source', 'N/A')}`")
instrument_display_order = [
('vocals', 'Vocals'),
('lead', 'Lead'),
('rhythm', 'Rhythm'),
('keys', 'Keys'),
('bass', 'Bass'),
('drums', 'Drums'),
('pro-vocals', 'Classic Vocals'),
('plastic-guitar', 'Classic Lead'),
('plastic-rhythm', 'Classic Rhythm'),
('plastic-keys', 'Classic Keys'),
('plastic-bass', 'Classic Bass'),
('plastic-drums', 'Classic Drums'),
('real-guitar', 'Pro Guitar'),
('real-keys', 'Pro Keys'),
('real-bass', 'Pro Bass'),
('elite-drums', 'Elite Drums'),
]
difficulties = track.get('difficulties', {})
diff_lines = []
classic_instruments = ['pro-vocals', 'plastic-guitar', 'plastic-keys', 'plastic-bass', 'plastic-drums']
has_classic = any(difficulties.get(key) is not None and difficulties.get(key) != -1 for key, _ in instrument_display_order if key in classic_instruments)
for key, name in instrument_display_order:
if (lvl := difficulties.get(key)) is not None and lvl != -1:
difficulty_bar = create_difficulty_bar(lvl)
total_width = 50
center_pos = total_width // 2
name_part = name
colon_pos = center_pos - 9
bar_start = colon_pos + 2
name_to_colon_spaces = max(1, colon_pos - len(name_part))
line_content = f"{name_part}{' ' * name_to_colon_spaces}:{' ' + difficulty_bar}"
diff_lines.append(line_content)
diff_text = "\n".join(diff_lines)
if diff_text:
embed.add_field(name="Instrument Difficulties", value=f"```\n{diff_text}```", inline=False)
if (loading_phrase := track.get('loading_phrase')):
embed.add_field(name="Loading Phrase", value=f"\"{loading_phrase}\"", inline=False)
compatibility_text = "N/A"
track_format = track.get('format')
if track_format == 'json':
compatibility_text = "json - (Only Compatible with Encore)"
elif track_format == 'ini':
compatibility_text = "ini - (Compatible with Clone Hero, YARG and Encore)"
filesize = track.get('filesize', '0.0')
if isinstance(filesize, str) and ('MB' in filesize.upper() or 'GB' in filesize.upper() or 'KB' in filesize.upper()):
filesize_display = filesize
else:
filesize_display = f"{filesize}MB"
embed.add_field(name="File Size", value=filesize_display, inline=True)
has_stems_value = track.get('has_stems')
has_stems_display = "True" if (has_stems_value is True or has_stems_value == "true") else "False"
embed.add_field(name="Has Stems", value=has_stems_display, inline=True)
embed.add_field(name="Compatibility", value=compatibility_text, inline=True)
if (created_at := track.get('createdAt')):
ts = int(datetime.fromisoformat(created_at.replace('Z', '+00:00')).timestamp())
embed.add_field(name="Date Added", value=f"<t:{ts}:F>", inline=False)
return embed, TrackInfoView(track=track, author_id=author_id, is_log=is_log)
except Exception as e:
asyncio.create_task(log_error_to_channel(f"Error creating track embed: {str(e)}"))
return None, None
def create_update_log_embed(old_track: dict, new_track: dict) -> tuple[discord.Embed | None, dict]:
try:
embed = discord.Embed(title="Track Modified", description=f"## {new_track.get('title', 'N/A')} - {new_track.get('artist', 'N/A')}",
color=discord.Color.orange(), timestamp=datetime.now())
if new_track.get('cover'):
embed.set_thumbnail(url=f"{ASSET_BASE_URL}/assets/covers/{new_track.get('cover')}")
changes_dict = {}
def flatten(d, parent_key='', sep='.'):
items = {}
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict): items.update(flatten(v, new_key))
else: items[new_key] = v
return items
flat_old, flat_new = flatten(old_track), flatten(new_track)
all_keys = sorted(list(set(flat_old.keys()) | set(flat_new.keys())))
ignored_keys = ['id', 'rotated', 'glowTimes']
change_strings = []
for key in all_keys:
if any(key.startswith(ignored) for ignored in ignored_keys): continue
old_val, new_val = flat_old.get(key), flat_new.get(key)
if old_val != new_val:
key_title = KEY_NAME_MAP.get(key) or KEY_NAME_MAP.get(key.lower(), key.replace('.', ' ').title())
changes_dict[key] = {'old': old_val, 'new': new_val}
change_strings.append(f"**{key_title}**\n```\nOld: {old_val or 'N/A'}\nNew: {new_val or 'N/A'}\n```")
if not change_strings: return None, {}
embed.description += "\n\n" + "\n\n".join(change_strings)
if len(embed.description) > 4096:
embed.description = embed.description[:4093] + "..."
return embed, changes_dict
except Exception as e:
asyncio.create_task(log_error_to_channel(f"Error creating update log embed: {str(e)}"))
return None, {}
class TrackInfoView(discord.ui.View):
def __init__(self, track: dict, author_id: int, is_log: bool = False):
super().__init__(timeout=300.0)
self.track = track
self.author_id = author_id
self.is_log = is_log
if track.get('id'):
self.add_item(self.PreviewAudioButton(track=track))
if track.get('videoUrl'):
self.add_item(self.PreviewVideoButton(track=track))
if is_log and track.get('id'):
stream_url = track.get('songlink') or f"{ASSET_BASE_URL}/tracks/{track['id']}"
download_url = track.get('download') or f"{ASSET_BASE_URL}/downloads/{track['id']}.zip"
self.add_item(discord.ui.Button(label="Stream Song", url=stream_url, row=1, emoji='🎧'))
self.add_item(discord.ui.Button(label="Download Chart", url=download_url, row=1, emoji='📥'))
else:
if track.get('songlink'):
self.add_item(discord.ui.Button(label="Stream Song", url=track.get('songlink'), row=1, emoji='🎧'))
if track.get('download'):
self.add_item(discord.ui.Button(label="Download Chart", url=track.get('download'), row=1, emoji='📥'))
youtube_links = track.get('youtubeLinks', {})
inst_video_map = {'vocals': 'Vocals', 'lead': 'Lead', 'drums': 'Drums', 'bass': 'Bass'}