从内容所有者报告中获取Youtube收入?

时间:2015-03-28 07:30:36

标签: python youtube youtube-api youtube-data-api

  1. 如果不使用youtube CMS帐户,我可以获得登录用户的收入。如果他请告诉我如何使用python做到这一点。我也有CMS帐户。     我添加了范围     https://www.googleapis.com/auth/yt-analytics-monetary.readonly要在documentation中提及内容报告。

        from datetime import datetime, timedelta
        import httplib2
        import os
        import sys
    
        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
    
        CLIENT_SECRETS_FILE = "client_secrets.json"
    
        YOUTUBE_SCOPES = ["https://www.googleapis.com/auth/youtube.readonly",
         "https://www.googleapis.com/auth/yt-analytics.readonly","https://www.googleapis.com/auth/yt-analytics-monetary.readonly"]
        YOUTUBE_API_SERVICE_NAME = "youtube"
        YOUTUBE_API_VERSION = "v3"
        YOUTUBE_ANALYTICS_API_SERVICE_NAME = "youtubeAnalytics"
        YOUTUBE_ANALYTICS_API_VERSION = "v1"
        MISSING_CLIENT_SECRETS_MESSAGE = "credentials missed"
    
        def get_authenticated_services(args):
          flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
            scope=" ".join(YOUTUBE_SCOPES),
            message=MISSING_CLIENT_SECRETS_MESSAGE)
    
          storage = Storage("%s-oauth2.json" % sys.argv[0])
          credentials = storage.get()
    
          if credentials is None or credentials.invalid:
            credentials = run_flow(flow, storage, args)
    
          http = credentials.authorize(httplib2.Http())
    
          youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
            http=http)
          youtube_analytics = build(YOUTUBE_ANALYTICS_API_SERVICE_NAME,
            YOUTUBE_ANALYTICS_API_VERSION, http=http)
    
          return (youtube, youtube_analytics)
    
    
        def get_channel_id(youtube):
          channels_list_response = youtube.channels().list(
            mine=True,
            part="id"
          ).execute()
    
          return channels_list_response["items"][0]["id"]
    
        def run_analytics_report(youtube_analytics, channel_id, options):
          print channel_id, options.metrics, options.end_date, '2015-03-28'
          # Call the Analytics API to retrieve a report. For a list of available
          # reports, see:
          # https://developers.google.com/youtube/analytics/v1/channel_reports
          analytics_query_response = youtube_analytics.reports().query(
            ids="channel==%s" % channel_id,
            metrics=options.metrics,
            dimensions=options.dimensions,
            start_date='2014-03-28',
            end_date='2015-03-28',
            max_results=options.max_results,
            sort=options.sort
          ).execute()
    
          print "Analytics Data for Channel %s" % channel_id
          print analytics_query_response
          for column_header in analytics_query_response.get("columnHeaders", []):
            print "%-20s" % column_header["name"],
    
          for row in analytics_query_response.get("rows", []):
            for value in row:
              print "%-20s" % value,
    
    
        if __name__ == "__main__":
          now = datetime.now()
          one_day_ago = (now - timedelta(days=1)).strftime("%Y-%m-%d")
          one_week_ago = (now - timedelta(days=7)).strftime("%Y-%m-%d")
    
          argparser.add_argument("--metrics", help="Report metrics",
            default="views,earnings")
          argparser.add_argument("--dimensions", help="Report dimensions",
            default="video")
          argparser.add_argument("--start-date", default=one_week_ago,
            help="Start date, in YYYY-MM-DD format")
          argparser.add_argument("--end-date", default=one_day_ago,
            help="End date, in YYYY-MM-DD format")
          argparser.add_argument("--max-results", help="Max results", default=10)
          argparser.add_argument("--sort", help="Sort order", default="-views")
          args = argparser.parse_args()
    
          (youtube, youtube_analytics) = get_authenticated_services(args)
          try:
            channel_id = get_channel_id(youtube)
            run_analytics_report(youtube_analytics, channel_id, args)
          except HttpError, e:
            print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
    
  2. 我使用了上面的代码我得到了以下错误。

            raise AccessTokenRefreshError(error_msg)
        oauth2client.client.AccessTokenRefreshError: invalid_grant
    

    如果我使用其他帐户登录,则会收到错误消息。

    An HTTP error 401 occurred:
    {
     "error": {
      "errors": [
       {
        "domain": "global",
        "reason": "unauthorized",
        "message": "Insufficient permission to access this report."
       }
      ],
      "code": 401,
      "message": "Insufficient permission to access this report."
     }
    }
    

    如果我运行上述代码,但指标中的“收益”除外,我可以根据需要获得准确的输出。

    请告诉我如何使用python获得收入。

    我也使用了this,但它显示了一个名为error: argument --content-owner-id is required

    的错误

    提前致谢!

1 个答案:

答案 0 :(得分:1)

很遗憾,您需要一个YouTube CMS帐户并访问YouTube Content ID API才能检索已登录用户的收入指标。

您可以在此处查看有关此内容的更多讨论:https://code.google.com/p/gdata-issues/issues/detail?id=4826