2

Building a discord bot using discord.py and I integrated the Spotify API to print the list of songs featured in a playlist.

The code I have right now prints each song 1 sentence at a time (so 50 in total) which is pretty inefficient and means a lot of pings. Any ideas for how I could print it all into 1 large block or something less than 50?

@client.command(name="ukmusic")
async def playlist(ctx):
    #Authortization for API usage
    headers = {
        "Authorization": "Bearer {}".format(oauth)
        }
    #These create the link that the program fetches (The playlist)
    endpoint = "https://api.spotify.com/v1/playlists/37i9dQZEVXbLnolsZ8PSNw"
    data = urlencode({"market": "GB"})
    lookup_url = f"{endpoint}?{data}"
    #This prints what the link looks like and the status code (200 if it works correctly)
    print (lookup_url)
    r = requests.get(lookup_url, headers = headers)
    print (r.status_code)

    #This prints out the playlist 
    await ctx.send("Here is what the good people of Britiania are listening to on Spotify")
    em = discord.Embed(title = "Song - Artist - Album\n")

    for item in r.json()['tracks']['items']:
        await ctx.send(
            item['track']['name'] + ' - ' +
            item['track']['artists'][0]['name'] + ' - ' +
            item['track']['album']['name']
        )
Man1mega
  • 21
  • 2

2 Answers2

1

The easiest way is to probably make a temporary string, which you use to "build" your track-list:


@client.command(name="ukmusic")
async def playlist(ctx):
    #Authortization for API usage
    headers = {
        "Authorization": "Bearer {}".format(oauth)
        }
    #These create the link that the program fetches (The playlist)
    endpoint = "https://api.spotify.com/v1/playlists/37i9dQZEVXbLnolsZ8PSNw"
    data = urlencode({"market": "GB"})
    lookup_url = f"{endpoint}?{data}"
    #This prints what the link looks like and the status code (200 if it works correctly)
    print (lookup_url)
    r = requests.get(lookup_url, headers = headers)
    print (r.status_code)

    #This prints out the playlist 
    await ctx.send("Here is what the good people of Britiania are listening to on Spotify")
    em = discord.Embed(title = "Song - Artist - Album\n")

    allTracks = ""

    for item in r.json()['tracks']['items']:
        allTracks += item['track']['name'] + ' - ' + item['track']['artists'][0]['name'] + ' - ' + item['track']['album']['name'] + '\n'

    await ctx.send(allTracks)

itzFlubby
  • 2,269
  • 1
  • 9
  • 31
0

Make a list that saves all the data and then send it using .join().

I would recommend using f string to make the string in an easier way.

Other method then what you said is saving the data into separate variables to make an embed with 3 columns

@client.command(name="ukmusic")
async def playlist(ctx):
    #Authortization for API usage
    headers = {
        "Authorization": "Bearer {}".format(oauth)
        }
    #These create the link that the program fetches (The playlist)
    endpoint = "https://api.spotify.com/v1/playlists/37i9dQZEVXbLnolsZ8PSNw"
    data = urlencode({"market": "GB"})
    lookup_url = f"{endpoint}?{data}"
    #This prints what the link looks like and the status code (200 if it works correctly)
    print (lookup_url)
    r = requests.get(lookup_url, headers = headers)
    print (r.status_code)

    #This prints out the playlist 
    em = discord.Embed(title = "Here is what the good people of Britiania are listening to on Spotify")

    tracks_names = []
    tracks_artists = []
    tracks_album = []

    # save the data into lists (could be better using a dict with a nested list
    for item in r.json()['tracks']['items']:
        tracks_names.append(item['track']['name'])
        tracks_artists.append(item['track']['artists'][0]['name'])
        tracks_album.append(item['track']['album']['name'])
        
    # add the 3 columns 
    em.add_field(name="Song", value='\n'.join(tracks_names), inline=True)
    em.add_field(name="Artist", value='\n'.join(tracks_artists), inline=True)
    em.add_field(name="Album", value='\n'.join(tracks_album), inline=True)

    await ctx.send(embed=em)
Abdulaziz
  • 3,363
  • 1
  • 7
  • 24