nodejs- Spotify API检查播放列表中是否存在曲目

发布于 2025-01-23 01:53:04 字数 4357 浏览 3 评论 0 原文

我正在创建一个不和谐的机器人,该机器人在特定频道中添加共享歌曲,并将其添加到相应的播放列表中。该功能按预期工作,因此我遗漏了代码的那一部分。但是如果需要的话,我可以添加。

有了以下代码,我希望能够评估播放列表是否已包含共享歌曲,如果是这样,则不要添加它。 跳过基本上的

const playlists = new Map();
    
const spectrumPlaylist = {
  channelid: '948177541414404116',
  name: 'spectrum',
  id: '2SDsHpVc7yfQhGg0tS0RQ0'
}
playlists.set('948177541414404116', {
  name: 'spectrum',
  id: '2SDsHpVc7yfQhGg0tS0RQ0'
})
playlists.set('948185709037121566', {
  name: 'indie',
  id: '0JxWP48wGTRJrijEzg41fD'
})
playlists.set('948185876909936661', {
  name: 'instrumental',
  id: '37IIwZg5ek7mEYa2Ulmy85'
})

client.on('messageCreate', async message => {
  const playlist = playlists.get(message.channel.id);
  
  spotifyApi.getPlaylistTracks(playlist.id, {
    offset: 0,
    limit: 20,
    fields: 'items'
  })
  .then(
    function(data) {
      console.log('The playlist contains these tracks', data.body.items);
    },
    function(err) {
      console.log('Something went wrong!', err);
    }
  );
});

    The playlist contains these tracks [
  {
    added_at: '2022-04-18T20:25:51Z',
    added_by: {
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/users/<userid>',
      id: '<userid>',
      type: 'user',
      uri: 'spotify:user:<userid>'
    },
    is_local: false,
    primary_color: null,
    track: {
      album: [Object],
      artists: [Array],
      available_markets: [Array],
      disc_number: 1,
      duration_ms: 285122,
      episode: false,
      explicit: false,
      external_ids: [Object],
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/tracks/04wZnll09OSLNgvOEpWNHF',
      id: '04wZnll09OSLNgvOEpWNHF',
      is_local: false,
      name: 'Pacifica (Sultan + Shepard Remix)',
      popularity: 53,
      preview_url: 'https://p.scdn.co/mp3-preview/0fc9fadef348ded977208eea4a16135f497ecaa6?cid=d447a9a0d3d14fab83523430649b6c39',
      track: true,
      track_number: 1,
      type: 'track',
      uri: 'spotify:track:04wZnll09OSLNgvOEpWNHF'
    },
    video_thumbnail: { url: null }
  },
  {
    added_at: '2022-04-18T20:25:57Z',
    added_by: {
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/users/<userid>',
      id: '<userid>',
      type: 'user',
      uri: 'spotify:user:<userid>'
    },
    is_local: false,
    primary_color: null,
    track: {
      album: [Object],
      artists: [Array],
      available_markets: [Array],
      disc_number: 1,
      duration_ms: 265506,
      episode: false,
      explicit: false,
      external_ids: [Object],
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/tracks/5pEmeoMUW38w1oU3kPelvR',
      id: '5pEmeoMUW38w1oU3kPelvR',
      is_local: false,
      name: 'Spectrum',
      popularity: 46,
      preview_url: 'https://p.scdn.co/mp3-preview/5d9104b4cb82e3879867e2dc65997ab19b0f501b?cid=d447a9a0d3d14fab83523430649b6c39',
      track: true,
      track_number: 3,
      type: 'track',
      uri: 'spotify:track:5pEmeoMUW38w1oU3kPelvR'
    },
    video_thumbnail: { url: null }
  },
  {
    added_at: '2022-04-18T20:26:04Z',
    added_by: {
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/users/<userid>',
      id: '<userid>',
      type: 'user',
      uri: 'spotify:user:<userid>'
    },
    is_local: false,
    primary_color: null,
    track: {
      album: [Object],
      artists: [Array],
      available_markets: [Array],
      disc_number: 1,
      duration_ms: 244186,
      episode: false,
      explicit: false,
      external_ids: [Object],
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/tracks/1AA3ZjLo9tD2iSZAs2svyj',
      id: '1AA3ZjLo9tD2iSZAs2svyj',
      is_local: false,
      name: 'Chinatown (feat. Bruce Springsteen)',
      popularity: 54,
      preview_url: 'https://p.scdn.co/mp3-preview/993c6eecf44d181f50146c9cbf0d9e316d5c6cf8?cid=d447a9a0d3d14fab83523430649b6c39',
      track: true,
      track_number: 2,
      type: 'track',
      uri: 'spotify:track:1AA3ZjLo9tD2iSZAs2svyj'
    },
    video_thumbnail: { url: null }
  }
]

重复 另外,不确定如何处理限制,因为我无法将其设置得太高。

我正在使用 spotify-web-api-node

I'm creating a bot in Discord that adds shared songs in specific channels and adds it to corresponding playlist. The function work as intended, so I've left that part of the code out. But I can add if it's needed.

With the code below, I want to be able to evaluate if the playlist already contains the shared song and if so don't add it. Skip duplicates basically.

const playlists = new Map();
    
const spectrumPlaylist = {
  channelid: '948177541414404116',
  name: 'spectrum',
  id: '2SDsHpVc7yfQhGg0tS0RQ0'
}
playlists.set('948177541414404116', {
  name: 'spectrum',
  id: '2SDsHpVc7yfQhGg0tS0RQ0'
})
playlists.set('948185709037121566', {
  name: 'indie',
  id: '0JxWP48wGTRJrijEzg41fD'
})
playlists.set('948185876909936661', {
  name: 'instrumental',
  id: '37IIwZg5ek7mEYa2Ulmy85'
})

client.on('messageCreate', async message => {
  const playlist = playlists.get(message.channel.id);
  
  spotifyApi.getPlaylistTracks(playlist.id, {
    offset: 0,
    limit: 20,
    fields: 'items'
  })
  .then(
    function(data) {
      console.log('The playlist contains these tracks', data.body.items);
    },
    function(err) {
      console.log('Something went wrong!', err);
    }
  );
});

Code above logs the following:

    The playlist contains these tracks [
  {
    added_at: '2022-04-18T20:25:51Z',
    added_by: {
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/users/<userid>',
      id: '<userid>',
      type: 'user',
      uri: 'spotify:user:<userid>'
    },
    is_local: false,
    primary_color: null,
    track: {
      album: [Object],
      artists: [Array],
      available_markets: [Array],
      disc_number: 1,
      duration_ms: 285122,
      episode: false,
      explicit: false,
      external_ids: [Object],
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/tracks/04wZnll09OSLNgvOEpWNHF',
      id: '04wZnll09OSLNgvOEpWNHF',
      is_local: false,
      name: 'Pacifica (Sultan + Shepard Remix)',
      popularity: 53,
      preview_url: 'https://p.scdn.co/mp3-preview/0fc9fadef348ded977208eea4a16135f497ecaa6?cid=d447a9a0d3d14fab83523430649b6c39',
      track: true,
      track_number: 1,
      type: 'track',
      uri: 'spotify:track:04wZnll09OSLNgvOEpWNHF'
    },
    video_thumbnail: { url: null }
  },
  {
    added_at: '2022-04-18T20:25:57Z',
    added_by: {
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/users/<userid>',
      id: '<userid>',
      type: 'user',
      uri: 'spotify:user:<userid>'
    },
    is_local: false,
    primary_color: null,
    track: {
      album: [Object],
      artists: [Array],
      available_markets: [Array],
      disc_number: 1,
      duration_ms: 265506,
      episode: false,
      explicit: false,
      external_ids: [Object],
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/tracks/5pEmeoMUW38w1oU3kPelvR',
      id: '5pEmeoMUW38w1oU3kPelvR',
      is_local: false,
      name: 'Spectrum',
      popularity: 46,
      preview_url: 'https://p.scdn.co/mp3-preview/5d9104b4cb82e3879867e2dc65997ab19b0f501b?cid=d447a9a0d3d14fab83523430649b6c39',
      track: true,
      track_number: 3,
      type: 'track',
      uri: 'spotify:track:5pEmeoMUW38w1oU3kPelvR'
    },
    video_thumbnail: { url: null }
  },
  {
    added_at: '2022-04-18T20:26:04Z',
    added_by: {
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/users/<userid>',
      id: '<userid>',
      type: 'user',
      uri: 'spotify:user:<userid>'
    },
    is_local: false,
    primary_color: null,
    track: {
      album: [Object],
      artists: [Array],
      available_markets: [Array],
      disc_number: 1,
      duration_ms: 244186,
      episode: false,
      explicit: false,
      external_ids: [Object],
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/tracks/1AA3ZjLo9tD2iSZAs2svyj',
      id: '1AA3ZjLo9tD2iSZAs2svyj',
      is_local: false,
      name: 'Chinatown (feat. Bruce Springsteen)',
      popularity: 54,
      preview_url: 'https://p.scdn.co/mp3-preview/993c6eecf44d181f50146c9cbf0d9e316d5c6cf8?cid=d447a9a0d3d14fab83523430649b6c39',
      track: true,
      track_number: 2,
      type: 'track',
      uri: 'spotify:track:1AA3ZjLo9tD2iSZAs2svyj'
    },
    video_thumbnail: { url: null }
  }
]

I want to retrieve the id of each track and see if any matches the message.content that has been parsed to an id.
Also, not sure how to handle the limit as I couldn't set it too high.

I'm using spotify-web-api-node.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

人疚 2025-01-30 01:53:04

好吧,您拥有播放列表中所有曲目的数据库。您的用户将Spotify链接发送到您的频道,以将其添加到播放列表中。轨道的Spotify链接肯定在其URL中具有轨道的ID,正如您在轨道数据阵列中看到的那样,轨道ID在轨道数据中提供。让我们特别查看您的播放列表上的第一首歌,'Pacifica(Sultan + Shepard Remix)'为例。这是该歌曲的轨道数据相关部分的样子:

{
   track: {
      album: [Object],
      artists: [Array],
      available_markets: [Array],
      disc_number: 1,
      duration_ms: 285122,
      episode: false,
      explicit: false,
      external_ids: [Object],
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/tracks/04wZnll09OSLNgvOEpWNHF',
      id: '04wZnll09OSLNgvOEpWNHF', // <- Notice this
      is_local: false,
      name: 'Pacifica (Sultan + Shepard Remix)',
      popularity: 53,
      preview_url: 'https://p.scdn.co/mp3-preview/0fc9fadef348ded977208eea4a16135f497ecaa6?cid=d447a9a0d3d14fab83523430649b6c39',
      track: true,
      track_number: 1,
      type: 'track',
      uri: 'spotify:track:04wZnll09OSLNgvOEpWNHF'
   }
}

这就是用户sent spotify链接的样子:

"https://open.spotify.com/track/04wZnll09OSLNgvOEpWNHF?si=FEomY7F6T_WAXwgLqIhhEw"

如您所见,ID “ 04WZNLL09OSLNGVOEPWNHF” 都存在链接和轨道数据。这是我们可以用来确定轨道是否已经在播放列表中的方法。首先,让我们从链接中解析ID:

// Replace 'url' with the actual link from the message content
const url = "https://open.spotify.com/track/04wZnll09OSLNgvOEpWNHF?si=FEomY7F6T_WAXwgLqIhhEw";

const trackId = url.split("/").slice(-1)[0].split("?")[0];

这是上面示例所做的。首先,它将 url 分配到“/” 之间的所有字符串的数组中。 com”,“轨道”,“ 04WZNLL09OSLNGVOEPWNHF?si = FEOMY7F6T_WAXWGLQIHHEW”] 。然后,我们使用 .slice(-1)获取数组的“切片”,特别是数组的最后一个切片( .slice()接受索引作为一个参数,返回索引和数组末端之间的所有元素的新数组;数组,即只是数组中的最后一项)。完成此切片后,我们通过 [0] 获得切片阵列的第一个元素,现在我们剩下以下字符串:“ 04WZNLL09OSLNGVOEPWNHF?si = feomy7f6t_waxwaxwaxwglqhew” /代码>。现在,我们使用 .split(“?”)将数组分为问号之间的字符串,并获取第一个字符串(这是轨道ID:“ 04WZNLL09OSLNGVOEPWNHF” )。希望这解释了它是如何工作的。这是基本的JavaScript字符串解析。

现在我们已经拥有轨道ID,我们需要查看是否可以在跟踪数据项数组中找到轨道ID。我们可以使用 实现这一目标。该方法通过数组循环,然后返回 true 如果您通过其参数返回的回调函数返回 true true true 在数组中的任何项目。在您的情况下,它将其工作方式:

const hasTrack = data.body.items.some(item => item.track.id == trackId);

if (hasTrack) {
    // Track is already in playlist
}
else {
    // Add track to playlist
}

在解析轨道ID之前与摘要结合使用,是您答案的解决方案。请记住,每个单独的跟踪数据项看起来都像这样:

{
    added_at: '2022-04-18T20:25:51Z',
    added_by: {
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/users/<userid>',
      id: '<userid>',
      type: 'user',
      uri: 'spotify:user:<userid>'
    },
    is_local: false,
    primary_color: null,
    track: {
      album: [Object],
      artists: [Array],
      available_markets: [Array],
      disc_number: 1,
      duration_ms: 285122,
      episode: false,
      explicit: false,
      external_ids: [Object],
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/tracks/04wZnll09OSLNgvOEpWNHF',
      id: '04wZnll09OSLNgvOEpWNHF',
      is_local: false,
      name: 'Pacifica (Sultan + Shepard Remix)',
      popularity: 53,
      preview_url: 'https://p.scdn.co/mp3-preview/0fc9fadef348ded977208eea4a16135f497ecaa6?cid=d447a9a0d3d14fab83523430649b6c39',
      track: true,
      track_number: 1,
      type: 'track',
      uri: 'spotify:track:04wZnll09OSLNgvOEpWNHF'
    },
    video_thumbnail: { url: null }
}

因此,为什么我们需要做 item.track.id 才能在 .some() callback中获取曲目的ID。该解决方案应该对您有用。如果您以任何方式使用的过程,逻辑或代码感到困惑,请随时发表评论。

至于您提到的最后一件事:

不确定如何处理限制,因为我无法将其设置得太高

不确定如何处理 随着每个歌曲的添加到播放列表),然后从那里检索数据。这可能比试图绕过限制要容易得多。

Well, you have an array of data for all tracks in the playlist. And your users send Spotify links to your channels in order to add them to the playlist. The Spotify link for a track definitely has the track's ID in its URL, and as you can see in the array of track data, the track ID is provided in the track data. Let's specifically look at the first song on your playlist, 'Pacifica (Sultan + Shepard Remix)', as an example. This is what the relevant part of the track data looks like for that song:

{
   track: {
      album: [Object],
      artists: [Array],
      available_markets: [Array],
      disc_number: 1,
      duration_ms: 285122,
      episode: false,
      explicit: false,
      external_ids: [Object],
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/tracks/04wZnll09OSLNgvOEpWNHF',
      id: '04wZnll09OSLNgvOEpWNHF', // <- Notice this
      is_local: false,
      name: 'Pacifica (Sultan + Shepard Remix)',
      popularity: 53,
      preview_url: 'https://p.scdn.co/mp3-preview/0fc9fadef348ded977208eea4a16135f497ecaa6?cid=d447a9a0d3d14fab83523430649b6c39',
      track: true,
      track_number: 1,
      type: 'track',
      uri: 'spotify:track:04wZnll09OSLNgvOEpWNHF'
   }
}

And this is what the user-sent Spotify link looks like:

"https://open.spotify.com/track/04wZnll09OSLNgvOEpWNHF?si=FEomY7F6T_WAXwgLqIhhEw"

As you can see, the ID "04wZnll09OSLNgvOEpWNHF" is present within both the link and the track data. This is what we can use to determine if the track is already within the playlist. First, let's parse the ID from the link:

// Replace 'url' with the actual link from the message content
const url = "https://open.spotify.com/track/04wZnll09OSLNgvOEpWNHF?si=FEomY7F6T_WAXwgLqIhhEw";

const trackId = url.split("/").slice(-1)[0].split("?")[0];

Here's what the above example does. First, it splits url into an array of all strings between "/", like so: ["https:", "", "open.spotify.com", "track", "04wZnll09OSLNgvOEpWNHF?si=FEomY7F6T_WAXwgLqIhhEw"]. We then use .slice(-1) to get a "slice" of the array, specifically the last slice of the array (.slice() accepts an index as a parameter, and returns a new array of all elements between the index and the end of the array; if you give it a negative index, it moves backward from the end of the array; therefore -1 represents 1 item backward from the end of the array, i.e. just the last item in the array). Once we have done this slice, we get the first element of the sliced array via [0], and we're now left with the following string: "04wZnll09OSLNgvOEpWNHF?si=FEomY7F6T_WAXwgLqIhhEw". Now, we use .split("?") to split the array into the strings between the question mark, and get the first of those strings (which is the track ID: "04wZnll09OSLNgvOEpWNHF"). Hopefully that explained how it works. It's basic javascript string parsing.

Now that we have the track ID, we need to see if we can find the track ID somewhere within the array of track data items. We can use Array.some() to achieve this. That method loops through the array, and returns true if the callback function you pass as its parameter returns true for any item in the array. Here's how it will work in your case:

const hasTrack = data.body.items.some(item => item.track.id == trackId);

if (hasTrack) {
    // Track is already in playlist
}
else {
    // Add track to playlist
}

And that, combined with the snippet before that one that parses the track ID, is the solution to your answer. Remember that each individual track data item looks like this:

{
    added_at: '2022-04-18T20:25:51Z',
    added_by: {
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/users/<userid>',
      id: '<userid>',
      type: 'user',
      uri: 'spotify:user:<userid>'
    },
    is_local: false,
    primary_color: null,
    track: {
      album: [Object],
      artists: [Array],
      available_markets: [Array],
      disc_number: 1,
      duration_ms: 285122,
      episode: false,
      explicit: false,
      external_ids: [Object],
      external_urls: [Object],
      href: 'https://api.spotify.com/v1/tracks/04wZnll09OSLNgvOEpWNHF',
      id: '04wZnll09OSLNgvOEpWNHF',
      is_local: false,
      name: 'Pacifica (Sultan + Shepard Remix)',
      popularity: 53,
      preview_url: 'https://p.scdn.co/mp3-preview/0fc9fadef348ded977208eea4a16135f497ecaa6?cid=d447a9a0d3d14fab83523430649b6c39',
      track: true,
      track_number: 1,
      type: 'track',
      uri: 'spotify:track:04wZnll09OSLNgvOEpWNHF'
    },
    video_thumbnail: { url: null }
}

Hence why we need to do item.track.id to get to the track's ID in the .some() callback. This solution should work for you. Feel free to comment if you are confused about the process, logic, or code I used in any way.

As for the final thing you mentioned:

not sure how to handle the limit as I couldn't set it too high

If you aren't able to retrieve all songs in the playlist from Spotify, consider keeping track of the song list of each playlist in your own database (adding to the database as each song is being added to the playlist), and retrieving the data from there instead. That would probably be easier than trying to bypass the limit.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文