ログイン中のQiita Team
ログイン中のチームがありません

Qiita Team にログイン
コミュニティ
OrganizationイベントアドベントカレンダーQiitadon (β)
サービス
Qiita JobsQiita ZineQiita Blog
Python
YouTubeAPI
YoutubeDataAPIv3
0
どのような問題がありますか?

Youtubeへの自動投稿

YouTube Data API

YouTube Data APIを使って動画ファイルをアップロードします。

この作業にはGCPとBloggerの連携の手続きが先に必要です。

ライブラリの追加

$ pip install google-api-python-client
$ pip install google-auth-httplib2
$ pip install google-auth-oauthlib

Pythonプログラム

test.pyに以下のコードを記述します。
公式のサンプルを一部変更して持ってきています。

test.py
MAX_RETRIES = 10
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]

def resumable_upload(insert_request):
    response = None
    error = None
    retry = 0
    id = None
    while response is None:
        try:
            #print ("Uploading file...")
            status, response = insert_request.next_chunk()
            if response is not None:
                if 'id' in response:
                    id = response['id']
                    #print ("Video id '%s' was successfully uploaded." % id)
                else:
                    exit("The upload failed with an unexpected response: %s" % response)
        except HttpError as e:
            if e.resp.status in RETRIABLE_STATUS_CODES:
                error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
                                                                     e.content)
            else:
                raise
        except RETRIABLE_EXCEPTIONS as e:
            error = "A retriable error occurred: %s" % e

        if error is not None:
            print (error)
            retry += 1
            if retry > MAX_RETRIES:
                exit("No longer attempting to retry.")

            max_sleep = 2 ** retry
            sleep_seconds = random.random() * max_sleep
            # print ("Sleeping %f seconds and then retrying..." % sleep_seconds)
            time.sleep(sleep_seconds)

    return id

def youtube_upload(title ,description, tags):
    youtube = get_authenticated_service(YOUTUBE_API_SERVICE_NAME,YOUTUBE_API_VERSION)
    body=dict(
      snippet=dict(
        title=title,
        description=description,
        tags=tags,
        categoryId=22
      ),
      status=dict(
        privacyStatus='public'
      )
    )
    vid = None
    try:

        # Call the API's videos.insert method to create and upload the video.
        insert_request = youtube.videos().insert(
        part=",".join(body.keys()),
        body=body,
        # The chunksize parameter specifies the size of each chunk of data, in
        # bytes, that will be uploaded at a time. Set a higher value for
        # reliable connections as fewer chunks lead to faster uploads. Set a lower
        # value for better recovery on less reliable connections.
        #
        # Setting "chunksize" equal to -1 in the code below means that the entire
        # file will be uploaded in a single HTTP request. (If the upload fails,
        # it will still be retried where it left off.) This is usually a best
        # practice, but if you're using Python older than 2.6 or if you're
        # running on App Engine, you should set the chunksize to something like
        # 1024 * 1024 (1 megabyte).
        media_body=MediaFileUpload('/tmp/output.mp4', chunksize=-1, resumable=True)
        )

        vid = resumable_upload(insert_request)

    except Exception as e:
        print (e)
        vid = None

    return vid

以前のgetRss()から上記のyoutube_upload()を呼び出します。

test.py
def getRss():
    with open('/tmp/temp.mp3' ,mode='wb+') as f:
        f.truncate(0) 
    rssUrl = 'https://news.google.com/news/rss/headlines/section/topic/TECHNOLOGY'
    rssLang = '?hl=en-US&gl=US&ceid=US:en'
    feed = feedparser.parse(rssUrl + rssLang)
    for entry in feed.entries:
            link = entry.get('link')
            getBody(link)
    makeVideo()
    youtube_upload('この動画のタイトル','この記事の説明',['この動画のタグ']) 

音声ファイルが追加書きされていくので、連続で動作させていくとサイズが大きくなっていきますので、適宜音声ファイルを0にtruncateする必要があります。

ともかくこれで動画の自動アップロードまでできました!

RSSを自分のお気に入りに変更すると
YouTubeで自分だけのニュースが聞けます!
今までのスマホ片手に見ていたニュースを、聞き流ししましょう!
私のニュースを公開しているのでよかったら見てください。

https://www.youtube.com/channel/UCHlLpnqvCqyX82Vlsd0MaxA

注意 :投稿制限がある様で上限に達するとパブリックでアップロードした動画がロックされる様です。
   不完全ですが投稿制限の回避方法を参考にしてください。

参考URL:

https://developers.google.com/youtube/v3/guides/uploading_a_video?hl=ja

ユーザー登録して、Qiitaをもっと便利に使ってみませんか。
  1. あなたにマッチした記事をお届けします
    ユーザーやタグをフォローすることで、あなたが興味を持つ技術分野の情報をまとめてキャッチアップできます
  2. 便利な情報をあとで効率的に読み返せます
    気に入った記事を「ストック」することで、あとからすぐに検索できます
ronk
この記事は以下の記事からリンクされています

コメント

この記事にコメントはありません。
あなたもコメントしてみませんか :)
ユーザー登録
すでにアカウントを持っている方はログイン
記事投稿イベント開催中
Azure Kubernetes Serviceに関する記事を投稿しよう!
~
0
どのような問題がありますか?
ユーザー登録して、Qiitaをもっと便利に使ってみませんか。
この機能を利用するにはログインする必要があります。ログインするとさらに便利にQiitaを利用できます。
この機能を利用するにはログインする必要があります。ログインするとさらに便利にQiitaを利用できます。
  1. あなたにマッチした記事をお届けします
    ユーザーやタグをフォローすることで、あなたが興味を持つ技術分野の情報をまとめてキャッチアップできます
  2. 便利な情報をあとで効率的に読み返せます
    気に入った記事を「ストック」することで、あとからすぐに検索できます
ストックするカテゴリー