使用youtube api与python的youtube评论,每次都要询问“授权此应用程序”

我使用我在YouTube Dev帮助网站上找到的代码示例到发布在视频上的评论

# -*- coding: utf-8 -*-

# Sample Python code for youtube.commentThreads.insert
# See instructions for running these code samples locally:
# https://developers.google.com/explorer-help/guides/code_samples#python

import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]

def main():
    # 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 = "post.json"

    # Get credentials and create an API client
    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.commentThreads().insert(
        part="snippet",
        body={
          "snippet": {
            "videoId": "VIDEO_ID",
            "topLevelComment": {
              "snippet": {
                "textOriginal": "This is the start of a comment thread."
              }
            }
          }
        }
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

评论是工作,但每次都要求我再次授权申请,我不知道为什么,你能帮我吗?我得到的消息是:

“请访问此URL以授权此应用程序:URL_LINK.

输入授权代码:“

回答 1

  1. 赞同 0

    它是因为您不利用代码中的刷新令牌。此刷新令牌允许您在不再登录的情况下获取访问令牌。

    下面的链接应该帮助您利用它。

    Google API:使用OAuth2Client.client获取refresh令牌的凭据

    Goblin