2016-06-10 1 views
0

필자는 youtube-api를 사용하여 Python (디스플레이 없음)을 사용하여 명령 줄에서 내 YouTube 구독 및 기타 데이터 목록을 검색하고 Google 개발자 문서를 읽은 후 사용자 인터페이스가 필요하지만 실제로는 또한 plugin 유튜브와 상호 작용을위한 유튜브 텔레비젼을 사용하는 코디에 사용할 수 있고 그것이 내 사건에서 유용 할 수 있다고 생각합니다.Retrieve youtube subscriptions python api

+0

당신이 무엇을 요구하고 있는지 명확히 할 수 있습니까? – Laurel

+0

파이썬을 사용하여 구독 한 채널 목록을 원합니다. – Saja

+0

"내 경우에 유용 할 수 있다고 생각합니다." 글쎄, 그것을 밖으로 시도 후 문제가 발생하는지 물어보십시오. – hashcode55

답변

0

Activities:list이 메서드는 요청 기준과 일치하는 채널 활동 이벤트 목록을 반환합니다. 예를 들어 특정 채널과 연결된 이벤트, 사용자의 구독 및 Google+ 친구와 연결된 이벤트 또는 각 사용자에 맞게 사용자 정의 된 YouTube 홈 페이지 피드를 검색 할 수 있습니다.

HTTP 요청 API 요청 데이터를 일치 Subscription:list 반환 구독 자원에서

GET https://www.googleapis.com/youtube/v3/activities 

.

성공하면,이 방법은 다음과 같은 구조의 응답 본문을 반환

{ 
"kind": "youtube#subscriptionListResponse", 
"etag": etag, 
"nextPageToken": string, 
"prevPageToken": string, 
"pageInfo": { 
"totalResults": integer, 
"resultsPerPage": integer 
}, 
"items": [ 
subscription Resource 
] 
} 
0

당신이 언급 한 바와 같이 구독 목록을 검색하기 위해, 먼저 인증하고 귀하의 응용 프로그램이나 스크립트를 인증해야 구독을 "읽습니다". 다음 Subscriptions: insert 유튜브 구독 데이터 API 삽입 방법에 대한 파이썬 예제 코드의 수정 된 버전을 사용 Subscriptions: list

:이 작업이 완료되면, 당신은 유튜브 구독 데이터 API 목록 방법을 사용하여 구독 정보를 검색 할 수 있습니다 코드는 사용자를 인증하고 권한을 부여한 다음 권한을 부여받은 사용자에게 모든 YouTube 구독을 검색합니다.

아래 코드는 명령 줄 인수를 사용하여 명시 적으로 작동하지 않지만 명령 줄 인수를 사용하면 작동하지 않아야하는 이유가 없습니다. Google YouTube API Python 예제 중 일부는이 효과를 내기위한 코드가 있습니다.

# coding: utf-8 
# https://developers.google.com/youtube/v3/docs/subscriptions/list 

import math 
import os 
import sys 

import httplib2 
from apiclient.discovery import build 
from apiclient.errors import HttpError 
from oauth2client.client import flow_from_clientsecrets 
from oauth2client.file import Storage 
from oauth2client.tools import argparser, run_flow 

# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains 
# the OAuth 2.0 information for this application, including its client_id and 
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from 
# the Google Developers Console at 
# https://console.developers.google.com/. 
# Please ensure that you have enabled the YouTube Data API for your project. 
# For more information about using OAuth2 to access the YouTube Data API, see: 
# https://developers.google.com/youtube/v3/guides/authentication 
# For more information about the client_secrets.json file format, see: 
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets 
CLIENT_SECRETS_FILE = "client_secrets.json" 

# This OAuth 2.0 access scope allows for full read/write access to the 
# authenticated user's account. 
YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube" 
YOUTUBE_API_SERVICE_NAME = "youtube" 
YOUTUBE_API_VERSION = "v3" 

# This variable defines a message to display if the CLIENT_SECRETS_FILE is 
# missing. 
MISSING_CLIENT_SECRETS_MESSAGE = """ 
WARNING: Please configure OAuth 2.0 

To make this sample run you will need to populate the client_secrets.json file 
found at: 

    {} 

with information from the Developers Console 
https://console.developers.google.com/ 

For more information about the client_secrets.json file format, please visit: 
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets 
""".format(os.path.abspath(os.path.join(os.path.dirname(__file__), 
             CLIENT_SECRETS_FILE))) 


def retrieve_youtube_subscriptions(): 
    # In order to retrieve the YouTube subscriptions for the current user, 
    # the user needs to authenticate and authorize access to their YouTube 
    # subscriptions. 
    youtube_authorization = get_authenticated_service() 

    try: 
     # init 
     next_page_token = '' 
     subs_iteration = 0 
     while True: 
      # retrieve the YouTube subscriptions for the authorized user 
      subscriptions_response = youtube_subscriptions(youtube_authorization, next_page_token) 
      subs_iteration += 1 
      total_results = subscriptions_response['pageInfo']['totalResults'] 
      results_per_page = subscriptions_response['pageInfo']['resultsPerPage'] 
      total_iterations = math.ceil(total_results/results_per_page) 
      print('Subscriptions iteration: {} of {} ({}%)'.format(subs_iteration, 
                    total_iterations, 
                    round(subs_iteration/total_iterations * 100), 
                    0)) 
      # get the token for the next page if there is one 
      next_page_token = get_next_page(subscriptions_response) 
      # extract the required subscription information 
      channels = parse_youtube_subscriptions(subscriptions_response) 
      # add the channels relieved to the main channel list 
      all_channels.extend(channels) 
      if not next_page_token: 
       break 
     return all_channels 

    except HttpError as err: 
     print("An HTTP error {} occurred:\n{}".format(err.resp.status, err.content)) 


def get_authenticated_service(): 
    # Create a Storage instance to store and retrieve a single 
    # credential to and from a file. Used to store the 
    # oauth2 credentials for the current python script. 
    storage = Storage("{}-oauth2.json".format(sys.argv[0])) 
    credentials = storage.get() 

    # Validate the retrieved oauth2 credentials 
    if credentials is None or credentials.invalid: 
     # Create a Flow instance from a client secrets file 
     flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, 
             scope=YOUTUBE_READ_WRITE_SCOPE, 
             message=MISSING_CLIENT_SECRETS_MESSAGE) 
     # The run_flow method requires arguments. 
     # Initial default arguments are setup in tools, and any 
     # additional arguments can be added from the command-line 
     # and passed into this method. 
     args = argparser.parse_args() 
     # Obtain valid credentials 
     credentials = run_flow(flow, storage, args) 

    # Build and return a Resource object for interacting with an YouTube API 
    return build(YOUTUBE_API_SERVICE_NAME, 
       YOUTUBE_API_VERSION, 
       http=credentials.authorize(httplib2.Http())) 


# Call youtube.subscriptions.list method 
# to list the channels subscribed to. 
def youtube_subscriptions(youtube, next_page_token): 
    subscriptions_response = youtube.subscriptions().list(
     part='snippet', 
     mine=True, 
     maxResults=50, 
     order='alphabetical', 
     pageToken=next_page_token).execute() 
    return subscriptions_response 


def get_next_page(subscriptions_response): 
    # check if the subscription response contains a reference to the 
    # next page or not 
    if 'nextPageToken' in subscriptions_response: 
     next_page_token = subscriptions_response['nextPageToken'] 
    else: 
     next_page_token = '' 
    return next_page_token 


def parse_youtube_subscriptions(subscriptions_response): 
    channels = [] 

    # Add each result to the appropriate list 
    for subscriptions_result in subscriptions_response.get("items", []): 
     if subscriptions_result["snippet"]["resourceId"]["kind"] == "youtube#channel": 
      channels.append("{} ({})".format(subscriptions_result["snippet"]["title"], 
              subscriptions_result["snippet"]["resourceId"]["channelId"])) 

    return channels 


if __name__ == "__main__": 
    # init 
    all_channels = [] 

    print('Perform youtube subscriptions') 
    # retrieve subscriptions 
    all_channels = retrieve_youtube_subscriptions() 
    print('Subscriptions complete') 
    print('Subscriptions found: {}'.format(len(all_channels))) 

    print("Channels:\n", "\n".join(all_channels), "\n") 

참고 :이 사용자에 대한 권한이 부여 된 자격 증명을 찾을 수없는 경우, 한 번 행동 오프, 위의 코드는, 로컬 URL을 열 및 인증을 위해 Google에 리디렉션으로.

추가 전제 조건 : 위의 파이썬 3 코드

  1. 는 "구글-API - 파이썬 클라이언트 py3"패키지는 주사위를 사용하여 설치해야 작동합니다.
  2. client_secrets.json 파일을 만들어야합니다. 이것은 파이썬 스크립트의 맨 위에있는 지침에 따라 수행됩니다.