简体   繁体   English

如何设置 POST 请求以使用 R 添加歌曲到 Spotify 播放列表

[英]How to set up POST request to add song to spotify playlist with R

First lets say that i'm really new with R.首先让我们说我对 R 真的很陌生。 Yesterday I listened to my favorite radio station.昨天我听了我最喜欢的广播电台。 because there was so much advertising in between, I decided to scrape the music they play every day from their webpage.因为中间有很多广告,我决定从他们的网页上抓取他们每天播放的音乐。 So i can listen to it without any ads.所以我可以听它没有任何广告。

I wrote a script in R that takes the title and artist of every song the radio played from their website:我在 R 中编写了一个脚本,该脚本采用收音机从他们的网站播放的每首歌曲的标题和艺术家:

### Radio2 playlist scraper ###

#Loading packages#
install.packages("rvest")
library(rvest)
install.packages("dplyr")
library("dplyr")
install.packages("remotes")
remotes::install_github("charlie86/spotifyr")
library(spotifyr)
install.packages('knitr', dependencies = TRUE)
library(knitr)

#Get playlist url #
url <- "https://www.nporadio2.nl/playlist"

#Read HTML code from pagen#
webpage <- read_html(url)

#Get Artist and Title#
artist <- html_nodes(webpage, '.fn-artist')
title <- html_nodes(webpage, '.fn-song')

#Artist and Title to text#
artist_text <- html_text(artist)
title_text <- html_text(title)

#Artist and Title to dataframe#
artiest <- as.data.frame(artist_text)
titel_text <- as.data.frame(title_text)


#Make one dataframe#
radioplaylist <- cbind(artiest$artist_text, titel_text$title_text)
radioplaylist <- as.data.frame(radioplaylist) 
radioplaylist

#Rename columns#
colnames(radioplaylist)[1] <- "Artiest"
colnames(radioplaylist)[2] <- "Titel"
radioplaylist

#Remove duplicate songs#
radioplaylistuniek <- radioplaylist %>% distinct(Artiest, Titel, .keep_all = TRUE)

#Write to csv#
date <- Sys.Date()
date
write.csv(radioplaylistuniek, paste0("C://Users//Kantoor//Radio2playlists//playlist - ", date, ".csv"))

#Set spotify API#
Sys.setenv(SPOTIFY_CLIENT_ID = 'caxxxxxxxxxxxxxxxxxx')
Sys.setenv(SPOTIFY_CLIENT_SECRET = '7exxxxxxxxxxxxx')
access_token <- get_spotify_access_token()

clientID <- "xxxxxxxxxxxxxxx"
secret <- "xxxxxxxxxxxxxx"

library(httr)
library(magrittr)
library(rvest)
library(ggplot2)

response = POST(
  'https://accounts.spotify.com/api/token',
  accept_json(),
  authenticate(clientID, secret),
  body = list(grant_type = 'client_credentials'),
  encode = 'form',
  verbose()
)

token = content(response)$access_token
authorization.header = paste0("Bearer ", token)

#Get track info#
call1 <- GET(url = paste("https://api.spotify.com/v1/search?q=track:Ready%20To%20Go%20artist:Republica&type=track&limit=1"), config = add_headers(authorization = authorization.header))
call1

# JSON to TXT#
jsonResponseParsed <- content(call1, as="parsed") #JSON response structured into parsed data
jsonResponseParsed

# Extract track uri#
uri <- jsonResponseParsed$tracks$items[[1]]$uri
uri

# Add track to playlist #
POST(url= "https://api.spotify.com/v1/playlists/29fotSbWUGP1NmWbtGRaG6/tracks?uris=spotify%3Atrack%3A5Qt8U8Suu7MFH1VcJr17Td", config = add_headers(c('Accept="application/json"', 'Content-type= "application/JSON"', 'Authorization="Bearer BQDX9jbz99bCt6TXd7OSaaj12CgCh3s5F6KBwb-ATnv7AFkSnjuEASS9FOW0zx-xxxxxxxxxxxxxx"')))

What do i want?我想要什么?

I want to automatically add every song I picked up to my spotify playlist我想自动将我选择的每首歌曲添加到我的 spotify 播放列表中

What have i got so far?到目前为止我得到了什么?

I created an app via developer.spotify.com.我通过 developer.spotify.com 创建了一个应用程序。 For each song I can get a unique uri which is needed to add the song to my playlist.对于每首歌曲,我可以获得一个独特的 uri,将歌曲添加到我的播放列表所需的 uri。

Where do i get stuck?我在哪里卡住了?

I am unable to add the song to my playlist with a POST REQUEST.我无法通过 POST REQUEST 将歌曲添加到我的播放列表中。 I get the message "No token provided".我收到消息“未提供令牌”。

I have created a sample POST REQUEST via https://developer.spotify.com/console/post-playlist-tracks/?playlist_id=&position=&uris= which adds the song neatly to my playlist.我通过https://developer.spotify.com/console/post-playlist-tracks/?playlist_id=&position=&uris=创建了一个示例 POST REQUEST,它将歌曲巧妙地添加到我的播放列表中。 The code is:代码是:

POST https://api.spotify.com/v1/playlists/{playlist_id}/tracks
curl -X "POST" "https://api.spotify.com/v1/playlists/29fotSbWUGP1NmWbtGRaG6/tracks?uris=spotify%3Atrack%3A5Qt8U8Suu7MFH1VcJr17Td" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer BQDX9jbz99bCt6TXd7OSaaj12CgCh3s5F6KBwb-ATxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

How to setup the correct POST request?如何设置正确的 POST 请求?

Can someone help me with the last part to setup the correct POST request?有人可以帮助我设置正确的 POST 请求的最后一部分吗?

@webb thank you. @webb 谢谢。 It is working now with the following last code:它现在正在使用以下最后一个代码:

# GET user authorization code#
code <- get_spotify_authorization_code(client_id = Sys.getenv("SPOTIFY_CLIENT_ID"),
                               client_secret = Sys.getenv("SPOTIFY_CLIENT_SECRET"),
                               scope = "playlist-modify-public")

#Save code#
code2 = code[["credentials"]][["access_token"]]
usercode <- paste0("Bearer ", code2)

#Add track to playlist#
POST("https://api.spotify.com/v1/playlists/29fotSbWUGP1NmWbtGRaG6/tracks?uris=spotify%3Atrack%3A5Qt8U8Suu7MFH1VcJr17Td", 
     encode="json",
     add_headers(Authorization = usercode),
     body = "{\"texts\":[\"A simple string\"]}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM