特定のチャンネルに対するお知らせメッセージを投稿します(リクエストを送信するユーザーは、チャンネルの代理で行動する権限を与えられていることが必要です)。
注: activity
リソースには、動画の評価やお気に入りへの動画の追加といった操作に関する情報が含まれますが、これらの activity
リソースを生成するには別の API メソッドを使う必要があります。たとえば動画を評価する場合は API の videos.rate()
メソッド、お気に入りに追加する場合は playlistItems.insert()
メソッドを使います。
今すぐ試すまたは例を見る。
リクエスト
HTTP リクエスト
POST https://www.googleapis.com/youtube/v3/activities
承認
このリクエストは、最低でも以下のスコープの 1 つによって承認される必要があります(認証と承認の詳細については、こちらをご覧ください)。
スコープ |
---|
https://www.googleapis.com/auth/youtube |
パラメータ
下記の表は、このクエリでサポートされているパラメータの一覧です。このリストのパラメータはすべてクエリ パラメータです。
パラメータ | ||
---|---|---|
必須パラメータ | ||
part |
string この操作では、 part パラメータは 2 つの目的で使用されます。書き込み操作で設定されるプロパティの特定と API レスポンスに含まれるプロパティの特定です。このパラメータに指定できる part 名は snippet と contentDetails です。 |
リクエストの本文
リクエストの本文にはアクティビティ リソースを指定します。 このリソースでは、次の点に注意してください。
-
以下のプロパティの値を指定する必要があります。
snippet.description
-
以下のプロパティの値を設定することができます。
snippet.description
contentDetails.bulletin.resourceId
レスポンス
成功すると、このメソッドはレスポンスの本文でアクティビティ リソースを返します。
例
注: 以下のコード サンプルは、サポートされているプログラミング言語すべてについて表したものではありません。サポートされている言語の一覧については、クライアント ライブラリのドキュメントを参照してください。
Java
この例では、Java クライアント ライブラリを使用しています。
-
ChannelBulletin.java
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_channelbulletin_sample; import java.io.File; import java.util.Calendar; import java.util.List; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.model.Activity; import com.google.api.services.youtube.model.ActivityContentDetails; import com.google.api.services.youtube.model.ActivityContentDetails.Bulletin; import com.google.api.services.youtube.model.ActivitySnippet; import com.google.api.services.youtube.model.Channel; import com.google.api.services.youtube.model.ChannelListResponse; import com.google.api.services.youtube.model.ResourceId; import com.google.common.collect.Lists; /** * Creates a video bulletin that is posted to the user's channel feed. * * @author Jeremy Walker */ public class ChannelBulletin { /** Global instance of the HTTP transport. */ private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); /** Global instance of the JSON factory. */ private static final JsonFactory JSON_FACTORY = new JacksonFactory(); /** Global instance of YouTube object to make all API requests. */ private static YouTube youtube; /* * Global instance of the video id we want to post as a bulletin into our channel feed. You will * probably pull this from a search or your app. */ private static String VIDEO_ID = "L-oNKK1CrnU"; /** * Authorizes the installed application to access user's protected data. * * @param scopes list of scopes needed to run upload. */ private static Credential authorize(List<String> scopes) throws Exception { // Load client secrets. GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( JSON_FACTORY, ChannelBulletin.class.getResourceAsStream("/client_secrets.json")); // Checks that the defaults have been replaced (Default = "Enter X here"). if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) { System.out.println( "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential" + "into youtube-cmdline-channelbulletin-sample/src/main/resources/client_secrets.json"); System.exit(1); } // Set up file credential store. FileCredentialStore credentialStore = new FileCredentialStore( new File(System.getProperty("user.home"), ".credentials/youtube-api-channelbulletin.json"), JSON_FACTORY); // Set up authorization code flow. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore) .build(); // Build the local server and bind it to port 8080 LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build(); // Authorize. return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user"); } /** * Authorizes user, runs Youtube.Channnels.List to get the default channel, and posts a bulletin * with a video id to the user's default channel. * * @param args command line args (not used). */ public static void main(String[] args) { // Scope required to upload to YouTube. List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube"); try { // Authorization. Credential credential = authorize(scopes); // YouTube object used to make all API requests. youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName( "youtube-cmdline-channelbulletin-sample").build(); /* * Now that the user is authenticated, the app makes a channel list request to get the * authenticated user's channel. https://developers.google.com/youtube/v3/docs/channels/list */ YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails"); channelRequest.setMine("true"); /* * Limits the results to only the data we need making your app more efficient. */ channelRequest.setFields("items/contentDetails"); ChannelListResponse channelResult = channelRequest.execute(); /* * Gets the list of channels associated with the user. */ List<Channel> channelsList = channelResult.getItems(); if (channelsList != null) { // Gets user's default channel id (first channel in list). String channelId = channelsList.get(0).getId(); /* * We create the snippet to set the channel we will post to and the description that goes * along with our bulletin. */ ActivitySnippet snippet = new ActivitySnippet(); snippet.setChannelId(channelId); Calendar cal = Calendar.getInstance(); snippet.setDescription("Bulletin test video via YouTube API on " + cal.getTime()); /* * We set the kind of the ResourceId to video (youtube#video). Please note, you could set * the type to a playlist (youtube#playlist) and use a playlist id instead of a video id. */ ResourceId resource = new ResourceId(); resource.setKind("youtube#video"); resource.setVideoId(VIDEO_ID); Bulletin bulletin = new Bulletin(); bulletin.setResourceId(resource); // We construct the ActivityContentDetails now that we have the Bulletin. ActivityContentDetails contentDetails = new ActivityContentDetails(); contentDetails.setBulletin(bulletin); /* * Finally, we construct the activity we will write to YouTube via the API. We set the * snippet (covers description and channel we are posting to) and the content details * (covers video id and type). */ Activity activity = new Activity(); activity.setSnippet(snippet); activity.setContentDetails(contentDetails); /* * We specify the parts (contentDetails and snippet) we will write to YouTube. Those also * cover the parts that are returned. */ YouTube.Activities.Insert insertActivities = youtube.activities().insert("contentDetails,snippet", activity); // This returns the Activity that was added to the user's YouTube channel. Activity newActivityInserted = insertActivities.execute(); if (newActivityInserted != null) { System.out.println( "New Activity inserted of type " + newActivityInserted.getSnippet().getType()); System.out.println(" - Video id " + newActivityInserted.getContentDetails().getBulletin().getResourceId().getVideoId()); System.out.println( " - Description: " + newActivityInserted.getSnippet().getDescription()); System.out.println(" - Posted on " + newActivityInserted.getSnippet().getPublishedAt()); } else { System.out.println("Activity failed."); } } else { System.out.println("No channels are assigned to this user."); } } catch (GoogleJsonResponseException e) { e.printStackTrace(); System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); } catch (Throwable t) { t.printStackTrace(); } } }
-
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.google.api.services.samples.youtube.cmdline</groupId> <artifactId>youtube-cmdline-channelbulletin-sample</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>youtube-cmdline-channelbulletin-sample</name> <url>http://maven.apache.org</url> <properties> <project.youtube.version>v3-rev8-1.12.0-beta</project.youtube.version> <project.http.version>1.12.0-beta</project.http.version> <project.oauth.version>1.12.0-beta</project.oauth.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <repositories> <repository> <id>google-api-services</id> <url>http://google-api-client-libraries.appspot.com/mavenrepo</url> </repository> </repositories> <dependencies> <!-- YouTube Data V3 support --> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-youtube</artifactId> <version>${project.youtube.version}</version> </dependency> <dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client-jackson2</artifactId> <version>${project.http.version}</version> </dependency> <dependency> <groupId>com.google.oauth-client</groupId> <artifactId>google-oauth-client-jetty</artifactId> <version>${project.oauth.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_channelbulletin_sample.ChannelBulletin</mainClass> </configuration> </plugin> <!-- Forces Maven to use Java 1.6 --> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument></compilerArgument> </configuration> </plugin> </plugins> </build> </project>
-
client_secrets.json
{ "installed": { "client_id": "Enter your client id here", "client_secret": "Enter your client secret here" } }
Python
この例では、Python クライアント ライブラリを使用しています。
#!/usr/bin/python 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 # The CLIENT_SECRETS_FILE variable specifies the name of a file that contains # the OAuth 2.0 information for this application, including its client_id and # client_secret. You can acquire an OAuth 2.0 client ID and client secret from # the Google API Console at # https://console.cloud.google.com/. # Please ensure that you have enabled the YouTube Data API for your project. # For more information about using OAuth2 to access the YouTube Data API, see: # https://developers.google.com/youtube/v3/guides/authentication # For more information about the client_secrets.json file format, see: # https://developers.google.com/api-client-library/python/guide/aaa_client_secrets CLIENT_SECRETS_FILE = "client_secrets.json" # This OAuth 2.0 access scope allows for full read/write access to the # authenticated user's account. YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" # This variable defines a message to display if the CLIENT_SECRETS_FILE is # missing. MISSING_CLIENT_SECRETS_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 API Console https://console.cloud.google.com/ For more information about the client_secrets.json file format, please visit: 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())) # This method calls the API's youtube.activities.insert method to post the # channel bulletin. def post_bulletin(youtube, args): body = dict( snippet=dict( description=args.message ) ) if args.video_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", required=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 playlist to post.") args = argparser.parse_args() # You can post a message with or without an accompanying video or playlist. # However, you can't post a video and a playlist at the same time. if args.video_id and args.playlist_id: exit("You cannot 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."
Ruby
この例では、Ruby クライアント ライブラリを使用しています。
#!/usr/bin/ruby require 'rubygems' gem 'google-api-client', '>0.7' require 'google/api_client' require 'google/api_client/client_secrets' require 'google/api_client/auth/file_storage' require 'google/api_client/auth/installed_app' require 'trollop' # This OAuth 2.0 access scope allows for full read/write access to the # authenticated user's account. YOUTUBE_SCOPE = 'https://www.googleapis.com/auth/youtube' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' def get_authenticated_service client = Google::APIClient.new( :application_name => $PROGRAM_NAME, :application_version => '1.0.0' ) youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION) file_storage = Google::APIClient::FileStorage.new("#{$PROGRAM_NAME}-oauth2.json") if file_storage.authorization.nil? client_secrets = Google::APIClient::ClientSecrets.load flow = Google::APIClient::InstalledAppFlow.new( :client_id => client_secrets.client_id, :client_secret => client_secrets.client_secret, :scope => [YOUTUBE_SCOPE] ) client.authorization = flow.authorize(file_storage) else client.authorization = file_storage.authorization end return client, youtube end def main opts = Trollop::options do opt :message, 'Required text of message to post.', :type => String opt :video_id, 'Optional ID of video to post.', :type => String opt :playlist_id, 'Optional ID of playlist to post.', :type => String end # You can post a message with or without an accompanying video or playlist. # However, you can't post a video and a playlist at the same time. if opts[:video_id] and opts[:playlist_id] Trollop::die 'You cannot post a video and a playlist at the same time' end Trollop::die :message, 'is required' unless opts[:message] client, youtube = get_authenticated_service begin body = { :snippet => { :description => opts[:message] } } if opts[:video_id] body[:contentDetails] = { :bulletin => { :resourceId => { :kind => 'youtube#video', :videoId => opts[:video_id] } } } end if opts[:playlist_id] body[:contentDetails] = { :bulletin => { :resourceId => { :kind => 'youtube#playlist', :playlistId => opts[:playlist_id] } } } end # Call the youtube.activities.insert method to post the channel bulletin. client.execute!( :api_method => youtube.activities.insert, :parameters => { :part => body.keys.join(',') }, :body_object => body ) puts "The bulletin was posted to your channel." rescue Google::APIClient::TransmissionError => e puts e.result.body end end main
エラー
次の表は、このメソッドを呼び出したときに API からレスポンスとして返される可能性のあるエラー メッセージの一覧です。詳細については、エラー メッセージのドキュメントを参照してください。
エラー タイプ | エラーの詳細 | 説明 |
---|---|---|
badRequest |
bulletinTextRequired |
お知らせメッセージの投稿にテキストを指定するには、リクエストで snippet オブジェクトの description プロパティを使用する必要があります。 |
notFound |
playlistNotFound |
お知らせメッセージの投稿と動画を関連付けようとしていますが、その動画が見つかりません。contentDetails.bulletinPosted.playlistId プロパティの値を確認してください。 |
notFound |
videoNotFound |
お知らせメッセージの投稿と動画を関連付けようとしていますが、その動画が見つかりません。contentDetails.bulletinPosted.videoId プロパティの値を確認してください。 |
userRateLimitExceeded |
rateLimitExceeded |
リクエストを完了できません。既に割り当てを超えています。 |
実際に試してみる
API Explorer を使用し、ライブ データに対してこのメソッドを呼び出して、API リクエストとレスポンスを確認してください。