-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
836 lines (733 loc) · 30 KB
/
main.py
File metadata and controls
836 lines (733 loc) · 30 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
# import required dependencies
import os
from datetime import datetime as dt
from termcolor import colored
from dotenv import load_dotenv
import discord
import inflect
import spotipy
from discord import app_commands
from discord.ext import commands
from spotipy.oauth2 import SpotifyClientCredentials
from reactionmenu import ViewMenu, ViewButton
import database
import spotipy_integ
# import app # enable for web-app
intents = discord.Intents.default()
intents.members = True
p = inflect.engine()
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
client.remove_command("help")
load_dotenv()
BOT_TOKEN = os.getenv("CLIENT_TOKEN")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
OAUTH_URL = os.getenv("OAUTH_URL")
REDIRECT_URI = os.getenv("REDIRECT_URI")
# USAGE OF cmd() 🔽
# username = interaction.user.name
# params = f'param1[{param1}]'
# await cmd(interaction.command.name,username,params)
async def cmd(cmd, username, params=None):
date_time = dt.now()
date_time = date_time.replace(microsecond=0)
cmd = cmd.upper()
timestamp_text = colored(f"{date_time}", "grey", attrs=["bold"])
cmd_text = colored(f"{cmd}", "light_blue", attrs=["bold"])
user_text = colored(f"{username}", "magenta")
params_text = colored(f"{params}", "green")
print(f"\n{timestamp_text} {cmd_text} {user_text} {params_text}")
# USAGE OF cmdlink() 🔽
# (DO AT BOTTOM OF COMMAND)
# interaction_link = f"https://discord.com/channels/{interaction.guild.id}/{interaction.channel_id}/{interaction.id}"
# await cmdlink(interaction_link)
async def cmdlink(link):
link_text = colored(f"{link}", "light_cyan", attrs=["underline"])
print(f"{link_text}")
@client.event
async def on_ready():
await client.change_presence(
status=discord.Status.dnd,
activity=discord.Activity(type=discord.ActivityType.watching, name="/help"),
)
print("GrooveBot is online!")
print("-----------------------------")
try:
# 1155003686959980647 --> Development Server
# 1178193307541712906 --> GrooveBot Beta Testers
guild = discord.Object(id=1178193307541712906)
client.tree.copy_global_to(guild=guild)
synced = await client.tree.sync(guild=guild)
print(f"Synced {len(synced)} command(s)")
print("-----------------------------")
except Exception as e:
print(e)
@client.tree.command(name="help", description="Get information on commands!")
@app_commands.describe(commands="Commands to choose from")
@app_commands.choices(
commands=[
discord.app_commands.Choice(name="share", value=1),
discord.app_commands.Choice(name="top", value=2),
discord.app_commands.Choice(name="say", value=3),
discord.app_commands.Choice(name="ping", value=4),
discord.app_commands.Choice(name="help", value=5),
]
)
async def help(
interaction: discord.Interaction, commands: discord.app_commands.Choice[int] = 0
):
await interaction.response.defer()
em = discord.Embed(
title="Help",
description="**Use `/help [command_name]` to get more info on a command!**",
colour=0x00B0F4,
timestamp=dt.now(),
)
em.set_author(
name="Groovebot",
url="https://gg.gg/groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/musical-keyboard-microsoft.png",
)
em.add_field(
name="**Music Commands**",
value="```ansi\n\033[37;1m /share - \033[0m Shares a song\n\033[37;1m /top - \033[0m Shows top songs\n```",
inline=True,
)
em.add_field(
name="**Misc. Commands**",
value="```ansi\n\033[37;1m /say - \033[0m Bot says something\n\033[37;1m /ping - \033[0m Tests bot is online\n\033[37;1m /help - \033[0m Command information\n```",
inline=True,
)
em.set_footer(
text="Generated by Groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/counterclockwise-arrows-button-microsoft.png",
)
if commands == 0:
await interaction.followup.send(embed=em)
else:
command = commands.name
if command == "share":
share_embed = discord.Embed(
title="Info for `/share`",
description="Share a song with someone!",
colour=0x00B0F4,
timestamp=dt.now(),
)
share_embed.set_author(
name="Groovebot",
url="https://gg.gg/groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/musical-keyboard-microsoft.png",
)
share_embed.add_field(
name="**Parameters**",
value="```ansi\n\033[37;1m artist_name: \033[0m Artist for track. If unknown, put '$'\n\033[37;1m track_name: \033[0m Track name for track. If unknown, put '$'\n```",
inline=False,
)
share_embed.add_field(
name="**Output Info**",
value="```ansi\n\033[0m \033[37;1mSpotify Statistics:\n\033[0m Track, Artist, Album, Duration, Release Date, Popularity\n\033[0m \033[37;1mServer Statistics:\n\033[0m Shares\n```",
inline=False,
)
share_embed.set_footer(
text="Generated by Groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/counterclockwise-arrows-button-microsoft.png",
)
await interaction.followup.send(embed=share_embed)
elif command == "top":
showtop_embed = discord.Embed(
title="Info for `/top`",
description="Show the top shared songs in the server!",
colour=0x00B0F4,
timestamp=dt.now(),
)
showtop_embed.set_author(
name="Groovebot",
url="https://gg.gg/groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/musical-keyboard-microsoft.png",
)
showtop_embed.add_field(
name="**Parameters**",
value="```ansi\n\033[37;1m pages: \033[0m Number of pages you want to generate. (Default = 2)\n\033[37;1m rows: \033[0m Number of song entries shown per page. (Default = 5)\n```",
inline=False,
)
showtop_embed.add_field(
name="**Output Info**",
value="```ansi\n\033[37;1m Ranked by number of shares,\n\033[0m- Rank\n- Song name & Spotify link to song\n- Artist name\n- Spotify popularity\n- Server shares\n\033[37;1m All in the format of iterable pages!\n```",
inline=False,
)
showtop_embed.set_footer(
text="Generated by Groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/counterclockwise-arrows-button-microsoft.png",
)
await interaction.followup.send(embed=showtop_embed)
elif command == "say":
say_embed = discord.Embed(
title="Info for `/say`", colour=0x00B0F4, timestamp=dt.now()
)
say_embed.set_author(
name="Groovebot",
url="https://gg.gg/groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/musical-keyboard-microsoft.png",
)
say_embed.add_field(
name="**Parameters**",
value="```ansi\n\033[37;1m thing_to_say: \033[0m What the bot should say (Default = 'hi')\n```",
inline=False,
)
say_embed.add_field(
name="**Output Info**",
value="```ansi\n\033[37;1m Bot outputs the following:\n\033[0m <username> said '<thing_to_say>'\n```",
inline=False,
)
say_embed.set_footer(
text="Generated by Groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/counterclockwise-arrows-button-microsoft.png",
)
await interaction.followup.send(embed=say_embed)
elif command == "ping":
ping_embed = discord.Embed(
title="Info for `/ping`", colour=0x00B0F4, timestamp=dt.now()
)
ping_embed.set_author(
name="Groovebot",
url="https://gg.gg/groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/musical-keyboard-microsoft.png",
)
ping_embed.add_field(
name="**Parameters**",
value="```ansi\n\033[37;1m hidden: \033[0m Should the bot's response appear only to you? (Default = 'False')\n```",
inline=False,
)
ping_embed.add_field(
name="**Output Info**",
value="```ansi\n\033[37;1m Bot outputs the following:\n\033[0m Pong, @<user>!\n```",
inline=False,
)
ping_embed.set_footer(
text="Generated by Groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/counterclockwise-arrows-button-microsoft.png",
)
await interaction.followup.send(embed=ping_embed)
elif command == "help":
help_embed = discord.Embed(
title="Info for `/help`",
description="Get information on commands!",
colour=0x00B0F4,
timestamp=dt.now(),
)
help_embed.set_author(
name="Groovebot",
url="https://gg.gg/groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/musical-keyboard-microsoft.png",
)
help_embed.add_field(
name="**Parameters**",
value="```ansi\n\033[37;1m commands: \033[0m Commands to choose from\n```",
inline=False,
)
help_embed.add_field(
name="**Output Info**",
value="```ansi\n\033[37;1m Bot outputs information for each command\033[0m through Parameters and Output Info\n```",
inline=False,
)
help_embed.set_footer(
text="Generated by Groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/counterclockwise-arrows-button-microsoft.png",
)
await interaction.followup.send(embed=help_embed)
else:
await interaction.followup.send(
"idk what u did but u somehow messed this up :shrug:"
)
async def gen_embed(interaction, top_songs, embed, num_start: int, num_fields: int):
num_start -= 1
rank = num_start
embed.clear_fields()
num_end = num_start + num_fields
print(f"num_end = {num_end}")
for i in range(num_start, num_end):
top_artistname = top_songs[i]["artist"]
top_trackname = top_songs[i]["track"]
top_shares = top_songs[i]["shares"]
id = top_songs[i]["id"]
rank += 1
spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials())
results = spotify.search(
q="track:" + top_trackname + " artist:" + top_artistname,
type="track",
limit=1,
)
items = results["tracks"]["items"]
count = 0
for track in items:
count += 1
top_popularity = track["popularity"]
link = f"https://open.spotify.com/track/{id}"
top_embedaddfield(
embed, rank, top_artistname, top_trackname, top_popularity, top_shares, link # type: ignore
)
@client.tree.command(name="top", description="Show the top shared songs in the server!")
@app_commands.describe(
pages="Number of pages you want to generate. (Default = 2)",
rows="Number of song entries shown per page. (Default = 5",
)
async def top(interaction: discord.Interaction, pages: int = 2, rows: int = 5):
# if it's too long
top_songs = database.get_top_songs("song_list.csv")
selected_total_entries = pages * rows
if selected_total_entries > len(top_songs):
response = f"**ERROR:** You chose to list `{selected_total_entries}` entries, but there are only `{len(top_songs)}` entries! Try a lower number."
await interaction.response.send_message(response, ephemeral=True)
return
username = interaction.user.name
displayname = interaction.user.display_name
params = f"pages[{pages}], rows[{rows}]"
await cmd(interaction.command.name, username, params)
await interaction.response.defer()
top_embed_template = discord.Embed(
title=f"Top Songs in **{interaction.guild}**",
colour=0x00B0F4,
timestamp=dt.now(),
)
top_embed_template.set_author(
name="GrooveBot",
url="https://gg.gg/groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/musical-keyboard-microsoft.png",
)
menu = ViewMenu(interaction, menu_type=ViewMenu.TypeEmbed)
num = 0
start_field = 1
i = 1
for i in range(0, pages):
print(i)
globals()[f"embed{i}"] = 0
print(f"0 == {globals()[f'embed{i}']}")
globals()[f"embed{i}"] = discord.Embed(
title=f"Top Songs in **{interaction.guild}**",
colour=0x00B0F4,
timestamp=dt.now(),
)
globals()[f"embed{i}"].set_author(
name="GrooveBot",
url="https://gg.gg/groovebot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/musical-keyboard-microsoft.png",
)
globals()[f"embed{i}"].set_thumbnail(
url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/input-numbers-microsoft.png"
)
globals()[f"embed{i}"].set_footer(
text="Generated by GrooveBot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/counterclockwise-arrows-button-microsoft.png",
)
print(f"embeds == {globals()[f'embed{i}']}")
await gen_embed(
interaction, top_songs, globals()[f"embed{i}"], start_field, rows
)
menu.add_page(globals()[f"embed{i}"])
num += 1
start_field = 1 + num * rows
print(f"embeds == {globals()[f'embed{i}']}")
msg_followup = ViewButton.Followup(
f"**`/top`** shows the top songs in the server ordered by how many times they were shared. There are `{len(top_songs)}` total songs that have been shared. You selected `{pages}` pages and `{rows}` rows, `{pages*rows}` total entries!",
ephemeral=True,
)
menu.add_button(
ViewButton(
style=discord.ButtonStyle.grey,
emoji="ℹ️",
custom_id=ViewButton.ID_SEND_MESSAGE,
followup=msg_followup,
)
)
menu.add_button(
ViewButton(
style=discord.ButtonStyle.danger,
emoji="✖️",
custom_id=ViewButton.ID_END_SESSION,
followup=msg_followup,
)
)
menu.add_button(
ViewButton(
style=discord.ButtonStyle.blurple,
emoji="◀️",
custom_id=ViewButton.ID_PREVIOUS_PAGE,
)
)
menu.add_button(
ViewButton(
style=discord.ButtonStyle.blurple,
emoji="▶️",
custom_id=ViewButton.ID_NEXT_PAGE,
)
)
await menu.start()
interaction_link = f"https://discord.com/channels/{interaction.guild.id}/{interaction.channel_id}/{interaction.id}"
await cmdlink(interaction_link)
@client.tree.command(name="ping")
@app_commands.describe(hidden="Should the bot's response only appear to you?")
@app_commands.choices(
hidden=[
discord.app_commands.Choice(name="True", value=1),
discord.app_commands.Choice(name="False", value=2),
]
)
async def ping(
interaction: discord.Interaction, hidden: discord.app_commands.Choice[int] = 0
):
displayname = interaction.user.display_name
username = interaction.user.name
await cmd(interaction.command.name, username)
if hidden == 0:
await interaction.response.send_message(
f"Pong! {round(client.latency, 1)}ms, {interaction.user.mention}!",
ephemeral=False,
)
elif hidden.name == "True":
await interaction.response.send_message(
f"Pong! {round(client.latency, 1)}ms, {interaction.user.mention}!",
ephemeral=True,
)
elif hidden.name == "False":
await interaction.response.send_message(
f"Pong! {round(client.latency, 1)}ms, {interaction.user.mention}!",
ephemeral=False,
)
else:
await interaction.response.send_message(f"WTF, {interaction.user.mention}!")
@client.command()
async def get_spotify_user_id(ctx, user: discord.Member):
print("hi")
@client.tree.command(name="test", description="Owner only")
async def test(interaction: discord.Interaction):
if interaction.user.id == 757684983757275266:
displayname = interaction.user.display_name
username = interaction.user.name
await cmd(interaction.command.name, username)
await interaction.response.defer()
await interaction.followup.send("This is a test!", ephemeral=True)
else:
await interaction.response.send_message(
"You must be the owner to use this command!"
)
# Get the link to the interaction
interaction_link = f"https://discord.com/channels/{interaction.guild.id}/{interaction.channel_id}/{interaction.id}"
await cmdlink(interaction_link)
@client.tree.command(name="say")
@app_commands.describe(thing_to_say="What the bot should say")
async def say(interaction: discord.Interaction, thing_to_say: str = "hi"):
username = interaction.user.name
params = f"thing_to_say[{thing_to_say}]"
await cmd(interaction.command.name, username, params)
await interaction.response.send_message(f"{username} said '{thing_to_say}'")
# Get the link to the interaction
interaction_link = f"https://discord.com/channels/{interaction.guild.id}/{interaction.channel_id}/{interaction.id}"
await cmdlink(interaction_link)
def top_embedaddfield(embed, rank, artist, track, popularity, shares, link):
hyperlink = f"[{track}]({link})"
embed.add_field(
name="", value=f"**{rank}.⠀__{hyperlink}__ — `{artist}`**", inline=False
)
embed.add_field(
name=f"",
value=f"```ansi\n📈 –\033[37;49;1m Popularity:\033[0m {popularity}%\n⤴️ –\033[37;49;1m Shares:\033[0m {shares}\n```",
inline=False,
)
async def embedFormat(
interaction,
artistName,
trackName,
albumName,
releaseDate,
popularity,
duration,
URL,
image,
shares,
comment,
followup,
):
# Convert milliseconds to seconds
dur_secs = duration // 1000
# Calculate minutes and seconds
mins = dur_secs // 60
secs = dur_secs % 60
# Format the output as "min:sec"
duration = f"{mins}:{secs:02d}"
displayname = interaction.user.display_name
avatar = interaction.user.display_avatar
embed = discord.Embed(
title=f"_{trackName}_ — **{artistName}**",
url=f"{URL}",
colour=0x00B0F4,
timestamp=dt.now(),
)
embed.set_author(name=displayname, icon_url=avatar)
embed.add_field(
name="**Song Information:**",
value=f"```ansi\n🎹 – \033[37;49;1m Artist:\033[0m {artistName}\n📀 – \033[37;49;1m Album:\033[0m {albumName}\n⏱️ – \033[37;49;1m Duration:\033[0m {duration}\n📆 – \033[37;49;1m Released:\033[0m {releaseDate}\n📈 – \033[37;49;1m Popularity:\033[0m {popularity}%\n```",
inline=True,
)
embed.add_field(
name="**Server Statistics:**",
value=f"```ansi\n🔗 – \033[37;49;1m Shares: \033[0m {shares}\n```",
inline=True,
)
embed.add_field(
name=f"**Comment:**", value=f">>> ```ansi\n\033[0m{comment}\n```", inline=False
)
embed.set_thumbnail(url=f"{image}")
embed.set_footer(
text="Generated by GrooveBot",
icon_url="https://cdn-0.emojis.wiki/emoji-pics/microsoft/counterclockwise-arrows-button-microsoft.png",
)
if not followup:
await interaction.response.send_message(embed=embed)
else:
await interaction.followup.send(embed=embed)
@client.tree.command(name="share", description="Share a song with someone!")
@app_commands.describe(
artist_name="Artist for track. If unknown, put '$'",
track_name="Track name for track. If unknown, put '$'",
)
async def share(
interaction: discord.Interaction, artist_name: str, track_name: str, comment: str
):
username = interaction.user.name
displayname = interaction.user.display_name
params = f"artist_name[{artist_name}], track_name[{track_name}], comment[{comment}]"
await cmd(interaction.command.name, username, params)
view = ButtonView()
print(f"\033[37;49;1m Artist: [{artist_name}] -- Track: [{track_name}]")
# ------------------------------------------------------------------
if artist_name == "$":
spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials())
results = spotify.search(q="track:" + track_name, type="track", limit=5)
items = results["tracks"]["items"]
tracks_found = []
artists_found = []
rank_found = []
for count in range(5):
tracks_found.append(items[count]["name"])
artists_found.append(items[count]["artists"][0]["name"])
print()
print(tracks_found)
print()
print(artists_found)
print()
print(rank_found)
print()
response = f"## Top 5 song results for your query: `{track_name}` \n\n"
for count in range(5):
rank = p.number_to_words(count + 1)
entry_track_name = tracks_found[count]
entry_artist_name = artists_found[count]
results_of_item = spotify.search(
q="track:" + entry_track_name + " artist:" + entry_artist_name,
type="track",
limit=1,
)
items = results_of_item["tracks"]["items"]
for track in items:
response += f"## :{rank}: \n```🎵 – Song: {track['name']}\n🎹 – Artist: {track['artists'][0]['name']}\n📀 – Album: {track['album']['name']}\n⏱️ – Duration (ms): {track['duration_ms']}\n📆 – Released: {track['album']['release_date']}\n📈 – Popularity: {track['popularity']}%\n``` \n"
print(response)
await interaction.response.send_message(response, ephemeral=True)
await interaction.followup.send(view=view, ephemeral=True)
await view.wait()
selected_track_data = results["tracks"]["items"][view.value]
print(f"\n\n SELECTED_TRACK={view.value}")
selected_track_name = selected_track_data["name"]
selected_artist_name = selected_track_data["artists"][0]["name"]
print(f"\n\n TRACK={selected_track_name}\n\n ARTIST={selected_artist_name}")
(
query_artistName,
query_trackName,
query_albumName,
query_releaseDate,
query_popularity,
query_duration,
query_trackURL,
query_albumImage,
query_id,
) = spotipy_integ.shareTrack(selected_artist_name, selected_track_name)
share_count = database.add_song_to_database(
"song_list.csv", query_artistName, query_trackName, query_id
)
followup = True
await embedFormat(
interaction,
query_artistName,
query_trackName,
query_albumName,
query_releaseDate,
query_popularity,
query_duration,
query_trackURL,
query_albumImage,
share_count,
comment,
followup,
)
await interaction.followup.send(f"[⠀]({query_trackURL})")
# ------------------------------------------------------------------
elif track_name == "$":
spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials())
results = spotify.search(q="artist:" + artist_name, type="track", limit=5)
items = results["tracks"]["items"]
tracks_found = []
artists_found = []
rank_found = []
for count in range(5):
tracks_found.append(items[count]["name"])
artists_found.append(items[count]["artists"][0]["name"])
print()
print(tracks_found)
print()
print(artists_found)
print()
print(rank_found)
print()
response = f"## Top 5 song results for your query: `{artist_name}` \n\n"
for count in range(5):
rank = p.number_to_words(count + 1)
entry_track_name = tracks_found[count]
entry_artist_name = artists_found[count]
results_of_item = spotify.search(
q="track:" + entry_track_name + " artist:" + entry_artist_name,
type="track",
limit=1,
)
items = results_of_item["tracks"]["items"]
for track in items:
response += f"## :{rank}: \n```ansi🎵 – Song: {track['name']}\n🎹 – \033[37;49;1m Artist: {track['artists'][0]['name']}\n📀 – \033[37;49;1m Album: {track['album']['name']}\n⏱️ – Duration (ms): {track['duration_ms']}\n📆 – \033[37;49;1m Released: {track['album']['release_date']}\n📈 – \033[37;49;1m Popularity: {track['popularity']}%\n``` \n"
print(response)
await interaction.response.send_message(response, ephemeral=True)
await interaction.followup.send(view=view, ephemeral=True)
await view.wait()
selected_track_data = results["tracks"]["items"][view.value]
print(f"\n\n SELECTED_TRACK={view.value}")
selected_track_name = selected_track_data["name"]
selected_artist_name = selected_track_data["artists"][0]["name"]
print(f"\n\n TRACK={selected_track_name}\n\n ARTIST={selected_artist_name}")
(
query_artistName,
query_trackName,
query_albumName,
query_releaseDate,
query_popularity,
query_duration,
query_trackURL,
query_albumImage,
query_id,
) = spotipy_integ.shareTrack(selected_artist_name, selected_track_name)
share_count = database.add_song_to_database(
"song_list.csv", query_artistName, query_trackName, query_id
)
followup = True
await embedFormat(
interaction,
query_artistName,
query_trackName,
query_albumName,
query_releaseDate,
query_popularity,
query_duration,
query_trackURL,
query_albumImage,
share_count,
comment,
followup,
)
await interaction.followup.send(f"[⠀]({query_trackURL})")
else:
(
query_artistName,
query_trackName,
query_albumName,
query_releaseDate,
query_popularity,
query_duration,
query_trackURL,
query_albumImage,
query_id,
) = spotipy_integ.shareTrack(artist_name, track_name)
share_count = database.add_song_to_database(
"song_list.csv", query_artistName, query_trackName, query_id
)
followup = False
await embedFormat(
interaction,
query_artistName,
query_trackName,
query_albumName,
query_releaseDate,
query_popularity,
query_duration,
query_trackURL,
query_albumImage,
share_count,
comment,
followup,
)
await interaction.followup.send(f"[⠀]({query_trackURL})")
# Get the link to the interaction
interaction_link = f"https://discord.com/channels/{interaction.guild.id}/{interaction.channel_id}/{interaction.id}"
await cmdlink(interaction_link)
class ButtonView(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(style=discord.ButtonStyle.blurple, emoji="1️⃣")
async def select1(
self, interaction: discord.Interaction, button: discord.ui.Button
):
self.value = 0
await interaction.response.send_message(
f"You chose song option {self.value+1}!", ephemeral=True
)
self.stop()
@discord.ui.button(style=discord.ButtonStyle.blurple, emoji="2️⃣")
async def select2(
self, interaction: discord.Interaction, button: discord.ui.Button
):
self.value = 1
await interaction.response.send_message(
f"You chose song option {self.value+1}!", ephemeral=True
)
self.stop()
@discord.ui.button(style=discord.ButtonStyle.blurple, emoji="3️⃣")
async def select3(
self, interaction: discord.Interaction, button: discord.ui.Button
):
self.value = 2
await interaction.response.send_message(
f"You chose song option {self.value+1}!", ephemeral=True
)
self.stop()
@discord.ui.button(style=discord.ButtonStyle.blurple, emoji="4️⃣")
async def select4(
self, interaction: discord.Interaction, button: discord.ui.Button
):
self.value = 3
await interaction.response.send_message(
f"You chose song option {self.value+1}!", ephemeral=True
)
self.stop()
@discord.ui.button(style=discord.ButtonStyle.blurple, emoji="5️⃣")
async def select5(
self, interaction: discord.Interaction, button: discord.ui.Button
):
self.value = 4
await interaction.response.send_message(
f"You chose song option {self.value+1}!", ephemeral=True
)
self.stop()
@discord.ui.button(
label="Cancel Command", style=discord.ButtonStyle.danger, emoji="✖️"
)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message(
f"Cancelled, {interaction.user.mention}!", ephemeral=True
)
self.stop()
# app.keep_alive() # enable for web-app
client.run(BOT_TOKEN, root_logger=True) # type: ignore