Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Spotify&;Youtube API集成:喜欢Spotify中的Youtube音乐视频 项目概述。_Python_Rest_Api_Youtube Data Api_Libspotify - Fatal编程技术网

Python Spotify&;Youtube API集成:喜欢Spotify中的Youtube音乐视频 项目概述。

Python Spotify&;Youtube API集成:喜欢Spotify中的Youtube音乐视频 项目概述。,python,rest,api,youtube-data-api,libspotify,Python,Rest,Api,Youtube Data Api,Libspotify,使用的API 使用Spotify API创建播放列表并将音乐添加到播放列表 使用Youtube数据API检索喜欢的视频 用于验证的OAuth 2.0 目标: 我的youtube帐户中喜欢的youtube视频应该自动进入我的Spotify新创建的播放列表 代码: 导入json 导入操作系统 导入google_auth_oauthlib.flow 导入google.oauth2.credentials 导入GoogleAppClient.discovery 导入GoogleAppClient

使用的API

  • 使用Spotify API创建播放列表并将音乐添加到播放列表
  • 使用Youtube数据API检索喜欢的视频
  • 用于验证的OAuth 2.0
目标:
  • 我的youtube帐户中喜欢的youtube视频应该自动进入我的Spotify新创建的播放列表
代码:
导入json
导入操作系统
导入google_auth_oauthlib.flow
导入google.oauth2.credentials
导入GoogleAppClient.discovery
导入GoogleAppClient.errors
导入请求
导入youtube\u dl
从机密导入spotify_令牌,spotify_用户id
从异常导入响应异常
类创建播放列表:
定义初始化(自):
self.user\u id=spotify\u user\u id
self.spotify\u令牌=spotify\u令牌
self.youtube\u client=self.get\u youtube\u client()
self.all_song_info={}
#连接到youtube数据api
def get_youtube_客户端(自身):
#在本地运行时禁用OAuthlib的HTTPS验证。
#*请勿*在生产中启用此选项。
os.environ[“OAUTHLIB不安全传输”]=“1”
api_service_name=“youtube”
api_version=“v3”
client\u secrets\u file=“youtube\u auth.json”
#获取凭据并创建API客户端
作用域=[”https://www.googleapis.com/auth/youtube.readonly"]
flow=google\u auth\u oauthlib.flow.InstalledAppFlow.from\u client\u secrets\u文件(
客户(机密文件、范围)
凭据=流。运行控制台()
#从Youtube数据API
youtube\u client=googleapiclient.discovery.build(
api\服务\名称、api\版本、凭证=凭证)
返回youtube\u客户端
#删除未设置的**kwarg
def获取喜欢的视频(自我):
request=self.youtube\u client.videos().list(
part=“snippet,contentDetails,statistics”,myRating=“like”
)
response=request.execute()
#收集每个视频并获取重要信息
对于响应中的项['items']:
视频标题=项目['snippet']['title']
youtube_url=”https://www.youtube.com/watch?v={}格式(
项目[“id”])
#使用youtube_dl收集歌曲名称和艺术家名称
video=youtube\u dl.YoutubeDL({}).extract\u info(
youtube_url,下载=False)
song_name=视频['track']
艺术家=视频[“艺术家”]
#保存所有重要信息并跳过任何缺少的歌曲和艺术家
self.all_song_info[视频标题]={
“youtube_url”:youtube_url,
“song_name”:song_name,
“艺术家”:艺术家,
#添加uri,轻松将歌曲放入播放列表
“spotify_uri”:self.get_spotify_uri(歌曲名称、艺术家)
}
#创建一个新的播放列表
def创建_播放列表(自):
请求_body=json.dumps({
“名称”:“Youtube喜欢的歌曲”,
“描述”:“大家都喜欢youtube视频歌曲”,
“公众”:真的吗
})
查询=”https://api.spotify.com/v1/users/{}/播放列表“.格式(
self.user(用户id)
response=requests.post(
查询
数据=请求体,
标题={
“内容类型”:“应用程序/json”,
“授权”:“承载{}”.format(self.spotify_令牌)
}
)
response_json=response.json()
#playlis id
返回响应_json[“id”]
#在Spotify上搜索歌曲
def get_spotify_uri(自我、歌曲名称、艺术家):
查询=”https://api.spotify.com/v1/search?query=track%3A{}+artist%3A{}&type=track&offset=0&limit=20”。格式(
宋ê的名字,
艺术家
)
response=requests.get(
查询
标题={
“内容类型”:“应用程序/json”,
“授权”:“承载{}”.format(self.spotify_令牌)
}
)
response_json=response.json()
songs=response_json[“曲目”][“项目”]
#只使用第一首歌
uri=歌曲[0][“uri”]
返回uri
#在新的spotify_播放列表中添加歌曲
def将歌曲添加到播放列表(自我):
#用我们喜欢的歌曲填充字典
self.get_liked_videos()
#收集所有的uri
URI=[]
对于歌曲,请在self.all_song_info.items()中输入信息:
追加(信息['spotify_uri'])
#创建一个新的播放列表
playlist\u id=self.create\u playlist()
#将所有歌曲添加到新播放列表中
请求_data=json.dumps(URI)
查询=”https://api.spotify.com/v1/playlists/{}/tracks“。格式(
播放列表(U id)
response=requests.post(
查询
数据=请求数据,
标题={
“内容类型”:“应用程序/json”,
“授权”:“承载{}”.format(self.spotify_令牌)
})
如果response.status_代码<200或response.status_代码>300:
引发响应异常(响应状态\代码)
response_json=response.json()
返回响应
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
cp=CreatePlaylist()
cp.将歌曲添加到播放列表()
输出
  • spotify Library内部制作了一个新的播放列表,但列表中的歌曲不属于我喜欢的视频,而且这些歌曲在播放列表中重复播放。歌曲数量几乎为5-6首,而且都是相同的
歌曲链接:

提前谢谢你的帮助

import json
import os

import google_auth_oauthlib.flow
import google.oauth2.credentials
import googleapiclient.discovery
import googleapiclient.errors
import requests
import youtube_dl

from secret import spotify_token, spotify_user_id
from exceptions import ResponseException


class CreatePlaylist:

    def __init__(self):
        self.user_id = spotify_user_id
        self.spotify_token = spotify_token
        self.youtube_client = self.get_youtube_client()
        self.all_song_info = {}
# connect to youtube data api

    def get_youtube_client(self):

        # Disable OAuthlib's HTTPS verification when running locally.
        # *DO NOT* leave this option enabled in production.
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

        api_service_name = "youtube"
        api_version = "v3"
        client_secrets_file = "youtube_auth.json"

        # Get credentials and create an API client
        scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
            client_secrets_file, scopes)
        credentials = flow.run_console()

        # from the Youtube DATA API
        youtube_client = googleapiclient.discovery.build(
            api_service_name, api_version, credentials=credentials)

        return youtube_client

    # remove **kwarg that are not set

    def get_liked_videos(self):

        request = self.youtube_client.videos().list(
            part="snippet,contentDetails,statistics", myRating="like"
        )

        response = request.execute()

        # collect each video and get important information
        for item in response['items']:
            video_title = item['snippet']['title']
            youtube_url = "https://www.youtube.com/watch?v={}".format(
                item["id"])

        # use youtube_dl to collect song name and artist name
            video = youtube_dl.YoutubeDL({}).extract_info(
                youtube_url, download=False)

            song_name = video['track']
            artist = video['artist']

            # save all important info and skip any missing song and artist
            self.all_song_info[video_title] = {
                "youtube_url": youtube_url,
                "song_name": song_name,
                "artist": artist,
                # add the uri, easy to get song to put into playlist
                "spotify_uri": self.get_spotify_uri(song_name, artist)
            }

# create a new playlist

    def create_playlist(self):

        request_body = json.dumps({
            "name": "Youtube Liked Songs",
            "description": "All liked youtube video songs",
            "public": True
        })
        query = "https://api.spotify.com/v1/users/{}/playlists".format(
            self.user_id)
        response = requests.post(
            query,
            data=request_body,
            headers={
                "Content-Type": "application/json",
                "Authorization": "Bearer {}".format(self.spotify_token)
            }
        )
        response_json = response.json()
        # playlis id
        return response_json["id"]

# search for the song on Spotify

    def get_spotify_uri(self, song_name, artist):

        query = "https://api.spotify.com/v1/search?query=track%3A{}+artist%3A{}&type=track&offset=0&limit=20".format(
            song_name,
            artist
        )
        response = requests.get(
            query,
            headers={
                "Content-Type": "application/json",
                "Authorization": "Bearer {}".format(self.spotify_token)
            }
        )
        response_json = response.json()
        songs = response_json["tracks"]["items"]

        # only use the first song
        uri = songs[0]["uri"]
        return uri

# add the song in new spotify_playlist
    def add_song_to_playlist(self):

        # populate dictionary with our liked songs
        self.get_liked_videos()

        # collect all of uri
        uris = []
        for song, info in self.all_song_info.items():
            uris.append(info['spotify_uri'])

        # create a new playlist
        playlist_id = self.create_playlist()

        # add all songs into new playlist
        request_data = json.dumps(uris)

        query = "https://api.spotify.com/v1/playlists/{}/tracks".format(
            playlist_id)

        response = requests.post(
            query,
            data=request_data,
            headers={
                "Content-Type": "application/json",
                "Authorization": "Bearer {}".format(self.spotify_token)
            })

        if response.status_code < 200 or response.status_code > 300:
            raise ResponseException(response.status_code)

        response_json = response.json()
        return response_json


if __name__ == '__main__':
    cp = CreatePlaylist()
    cp.add_song_to_playlist()