- リンクを取得
- ×
- メール
- 他のアプリ
YouTube Data API
YouTube Data APIを使って動画ファイルをアップロードします。この作業にはGCPとBloggerの連携の手続きが先に必要です。
ライブラリの追加
$ pip install google-api-python-client
$ pip install google-auth-httplib2
$ pip install google-auth-oauthlib
$ pip install google-api-python-client
$ pip install google-auth-httplib2
$ pip install google-auth-oauthlib
test.pyに以下のコードを記述します。
公式のサンプルを一部変更して持ってきています。
test.pyMAX_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
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
test.pydef 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しています。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('この動画のタイトル','この記事の説明',['この動画のタグ'])
ともかくこれで動画の自動アップロードまでできました!
RSSを自分のお気に入りに変更すると
YouTubeで自分だけのニュースが聞けます!
今までのスマホ片手に見ていたニュースを、聞き流ししましょう!
私のニュースを公開しているのでよかったら見てください。
https://www.youtube.com/channel/UCHlLpnqvCqyX82Vlsd0MaxA
注意 :投稿制限がある様で上限に達するとパブリックでアップロードした動画がロックされる様です。
不完全ですが投稿制限の回避方法を参考にしてください。
RSSを自分のお気に入りに変更すると
YouTubeで自分だけのニュースが聞けます!
今までのスマホ片手に見ていたニュースを、聞き流ししましょう!
私のニュースを公開しているのでよかったら見てください。
https://www.youtube.com/channel/UCHlLpnqvCqyX82Vlsd0MaxA
注意 :投稿制限がある様で上限に達するとパブリックでアップロードした動画がロックされる様です。
不完全ですが投稿制限の回避方法を参考にしてください。