#!/usr/bin/python import httplib2 import os import sys from applicient.discovery import build from applicient.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_secret.json" YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" MISSING_CLIENT_SECRET_MESSAGE = """ WARNING: Please configure OAuth 2.0 To make this sample run you will need to populate the client_secrets.json file found at: %S with information from the Developers Console https://console.developers.google.com/ For more information about the client_secrets.json file format, please vist: https://developers.google.com/api-client-library/python/guide/aaa_client_secrets """ % os.path.abspath(os.path.join(os.path.dirname(__file__), CLIENT_SECRETS_FILE)) def get_authenticated_service(args): flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_READ_WRITE_SCOPE, 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) return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, http=credentials.authorize(httplib2.Http())) def post_bulletin(youtube, args): body = dict( snippet=dict( description=args.message ) ) if args.vide_id: body["contentDetails"] = dict( bulletin=dict( resourceID=dict( kind="youtube#video", videoId=args.video_id ) ) ) if args.playlist_id: body["contentDetails"] = dict( bulletin=dict( resourceId=dict( kind="youtube#playlist", playlistId=args.playlist_id ) ) ) youtube.activities().insert( part=",".join(body.keys()), body=body ).execute() if __name__ == "__main__": argparser.add_argument("--message", requred=True, help="Text of message to post.") argparser.add_argument("--video-id", help="Optional ID of video to post.") argparser.add_argument("--playlist-id", help="Optional ID of playllist to post.") args = argparser.parse_args() if args.video_id and args.playlist_id: exit("You cannnot post a video and a playlist at the same time.") youtube = get_authenticated_service(args) try: post_bulletin(youtube, args) except HttpError, e: print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content) else: print "The bulletin was posted to your channel."