import
os
import
google_auth_oauthlib.flow
import
googleapiclient.discovery
import
googleapiclient.errors
import
youtube_dl
import
requests
import
json
spotify_token
=
'YOUR SPOTIFY TOKEN'
spotify_user_id
=
'YOUR USER ID'
def
get_play():
os.environ[
"OAUTHLIB_INSECURE_TRANSPORT"
]
=
"1"
api_service_name
=
"youtube"
api_version
=
"v3"
client_secrets_file
=
"YOUR_CLIENT_SECRET_FILE.json"
flow
=
google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, scopes)
credentials
=
flow.run_console()
youtube
=
googleapiclient.discovery.build(
api_service_name, api_version, credentials
=
credentials)
request
=
youtube.playlistItems().
list
(
part
=
"snippet"
,
playlistId
=
"PLvcDEv0bQcCgLS-OncIWVRlviC6vyZiju"
)
response
=
request.execute()
return
response
def
extract_song_from_yt(dic):
info
=
[]
song
=
""
for
i
in
range
(
len
(dic[
"items"
])):
video_url
=
url
+
str
(dic[
"items"
][i][
"snippet"
]
[
'resourceId'
][
'videoId'
])
details
=
youtube_dl.YoutubeDL(
{}).extract_info(video_url, download
=
False
)
track, artist
=
details[
'track'
], details[
'artist'
]
info.append((track, artist))
return
info
def
get_spotify_uri(track, artist):
query
=
"https:
/
/
api.spotify.com
/
v1
/
search?\
query
=
track
%
3A
{}
+
artist
%
3A
{}&
type
=
track".
format
(
track,
artist
)
response
=
requests.get(
query,
headers
=
{
"Content-Type"
:
"application/json"
,
"Authorization"
:
"Bearer {}"
.
format
(spotify_token)
}
)
response
=
response.json()
songs
=
response[
"tracks"
][
"items"
]
url
=
songs[
0
][
"uri"
]
return
url
def
create_playlist():
request_body
=
json.dumps(
{
"name"
:
"My New Geeks Playlist"
,
"description"
:
"Songs"
,
"public"
:
True
,
}
)
spotify_user_id)
response
=
requests.post(
query,
data
=
request_body,
headers
=
{
"Content-Type"
:
"application/json"
,
"Authorization"
:
"Bearer {}"
.
format
(spotify_token),
},
)
response
=
response.json()
return
response[
"id"
]
def
add_song(playlist_id, urls):
request_data
=
json.dumps(urls)
playlist_id)
response
=
requests.post(
query,
data
=
request_data,
headers
=
{
"Content-Type"
:
"application/json"
,
"Authorization"
:
"Bearer {}"
.
format
(spotify_token)
}
)
return
"songs added successfully"
response
=
get_play()
play_id
=
create_playlist()
song_info
=
extract_song_from_yt(response)
urls
=
[]
for
i
in
range
(
len
(response[
'items'
])):
urls.append(get_spotify_uri(song_info[i][
0
], song_info[i][
1
]))
add_song(play_id, urls)