LiveChatMessages: list

Lists live chat messages for a specific chat.

When you make your first request to retrieve chat messages, the API returns some or all of the chat history, depending on the length of that history. Messages in the response are ordered from oldest to newest.
  • The nextPageToken in the response provides a token that, in your next request, will identify the next set of results that your API client should retrieve.
  • The pollingIntervalMillis property indicates how long your API client should wait before requesting additional results.
When you request additional results, you set the pageToken parameter to the nextPageToken value and the API server returns additional chat messages, if available. Again, within that result set, messages are ordered from oldest to newest. Try it now.

Request

HTTP request

GET https://www.googleapis.com/youtube/v3/liveChat/messages

Parameters

The following table lists the parameters that this query supports. All of the parameters listed are query parameters.

Parameters
Required parameters
liveChatId string
The liveChatId parameter specifies the ID of the chat whose messages will be returned. The live chat ID associated with a broadcast is returned in the liveBroadcast resource's snippet.liveChatId property.
part string
The part parameter specifies the liveChatMessage resource parts that the API response will include. Supported values are id, snippet, and authorDetails.
Optional parameters
hl string
The hl parameter instructs the API to retrieve a localized currency display string for a specific application language that the YouTube website supports. For example, in English, currency would be displayed as $1.50, but in French, it would be displayed as 1,50$.

The parameter value must be a language code included in the list returned by the i18nLanguages.list method.
maxResults unsigned integer
The maxResults parameter specifies the maximum number of messages that should be returned in the result set. Acceptable values are 200 to 2000, inclusive. The default value is 500.
pageToken string
The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken property identify other pages that could be retrieved.
profileImageSize unsigned integer
The profileImageSize parameter specifies the size of the user profile pictures that should be returned in the result set. The images are square. The default value is 88, meaning pictures will be 88px by 88px. Acceptable values are in the range 16 to 720, inclusive.

Request body

Do not provide a request body when calling this method.

Response

If successful, this method returns a response body with the following structure:

{
  "kind": "youtube#liveChatMessageListResponse",
  "etag": etag,
  "nextPageToken": string,
  "pollingIntervalMillis": unsigned integer,
  "offlineAt": datetime,
  "pageInfo": {
    "totalResults": integer,
    "resultsPerPage": integer
  },
  "items": [
    liveChatMessage Resource
  ]
}

Properties

The following table defines the properties that appear in this resource:

Properties
kind string
Identifies the API resource's type. The value will be youtube#liveChatMessageListResponse.
etag etag
The Etag of this resource.
nextPageToken string
The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set.
pollingIntervalMillis unsigned integer
The amount of time, in milliseconds, that the client should wait before polling again for new live chat messages.
offlineAt datetime
The date and time when the underlying live stream went offline. This property is only present if the stream is already offline. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.
pageInfo object
The pageInfo object encapsulates paging information for the result set.
pageInfo.totalResults integer
The total number of results in the result set.
pageInfo.resultsPerPage integer
The number of results included in the API response.
items[] list
A list of live chat messages. Each item in the list is a liveChatMessage resource.

Examples

Note: The following code samples may not represent all supported programming languages. See the client libraries documentation for a list of supported languages.

Java

This sample lists live chat messages from the specified video or from the live broadcast for the authorized user's channel.

This example uses the Java client library.

/*
 * Copyright (c) 2017 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.live;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.YouTubeScopes;
import com.google.api.services.youtube.model.LiveChatMessage;
import com.google.api.services.youtube.model.LiveChatMessageAuthorDetails;
import com.google.api.services.youtube.model.LiveChatMessageListResponse;
import com.google.api.services.youtube.model.LiveChatMessageSnippet;
import com.google.api.services.youtube.model.LiveChatSuperChatDetails;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Lists live chat messages and SuperChat details from a live broadcast.
 *
 * The videoId is often included in the video's url, e.g.:
 * https://www.youtube.com/watch?v=L5Xc93_ZL60
 *                                 ^ videoId
 * The video URL may be found in the browser address bar, or by right-clicking a video and selecting
 * Copy video URL from the context menu.
 *
 * @author Jim Rogers
 */
public class ListLiveChatMessages {

    /**
     * Common fields to retrieve for chat messages
     */
    private static final String LIVE_CHAT_FIELDS =
        "items(authorDetails(channelId,displayName,isChatModerator,isChatOwner,isChatSponsor,"
            + "profileImageUrl),snippet(displayMessage,superChatDetails,publishedAt)),"
            + "nextPageToken,pollingIntervalMillis";

    /**
     * Define a global instance of a Youtube object, which will be used
     * to make YouTube Data API requests.
     */
    private static YouTube youtube;

    /**
     * Lists live chat messages and SuperChat details from a live broadcast.
     *
     * @param args videoId (optional). If the videoId is given, live chat messages will be retrieved
     * from the chat associated with this video. If the videoId is not specified, the signed in
     * user's current live broadcast will be used instead.
     */
    public static void main(String[] args) {

        // This OAuth 2.0 access scope allows for read-only access to the
        // authenticated user's account, but not other types of account access.
        List<String> scopes = Lists.newArrayList(YouTubeScopes.YOUTUBE_READONLY);

        try {
            // Authorize the request.
            Credential credential = Auth.authorize(scopes, "listlivechatmessages");

            // This object is used to make YouTube Data API requests.
            youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-listchatmessages-sample").build();

            // Get the liveChatId
            String liveChatId = args.length == 1
                ? GetLiveChatId.getLiveChatId(youtube, args[0])
                : GetLiveChatId.getLiveChatId(youtube);
            if (liveChatId != null) {
                System.out.println("Live chat id: " + liveChatId);
            } else {
                System.err.println("Unable to find a live chat id");
                System.exit(1);
            }

            // Get live chat messages
            listChatMessages(liveChatId, null, 0);
        } catch (GoogleJsonResponseException e) {
            System.err
                .println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                    + e.getDetails().getMessage());
            e.printStackTrace();

        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
            e.printStackTrace();
        } catch (Throwable t) {
            System.err.println("Throwable: " + t.getMessage());
            t.printStackTrace();
        }
    }

    /**
     * Lists live chat messages, polling at the server supplied interval. Owners and moderators of a
     * live chat will poll at a faster rate.
     *
     * @param liveChatId The live chat id to list messages from.
     * @param nextPageToken The page token from the previous request, if any.
     * @param delayMs The delay in milliseconds before making the request.
     */
    private static void listChatMessages(
        final String liveChatId,
        final String nextPageToken,
        long delayMs) {
        System.out.println(
            String.format("Getting chat messages in %1$.3f seconds...", delayMs * 0.001));
        Timer pollTimer = new Timer();
        pollTimer.schedule(
            new TimerTask() {
                @Override
                public void run() {
                    try {
                        // Get chat messages from YouTube
                        LiveChatMessageListResponse response = youtube
                            .liveChatMessages()
                            .list(liveChatId, "snippet, authorDetails")
                            .setPageToken(nextPageToken)
                            .setFields(LIVE_CHAT_FIELDS)
                            .execute();

                        // Display messages and super chat details
                        List<LiveChatMessage> messages = response.getItems();
                        for (int i = 0; i < messages.size(); i++) {
                            LiveChatMessage message = messages.get(i);
                            LiveChatMessageSnippet snippet = message.getSnippet();
                            System.out.println(buildOutput(
                                snippet.getDisplayMessage(),
                                message.getAuthorDetails(),
                                snippet.getSuperChatDetails()));
                        }

                        // Request the next page of messages
                        listChatMessages(
                            liveChatId,
                            response.getNextPageToken(),
                            response.getPollingIntervalMillis());
                    } catch (Throwable t) {
                        System.err.println("Throwable: " + t.getMessage());
                        t.printStackTrace();
                    }
                }
            }, delayMs);
    }

    /**
     * Formats a chat message for console output.
     *
     * @param message The display message to output.
     * @param author The author of the message.
     * @param superChatDetails SuperChat details associated with the message.
     * @return A formatted string for console output.
     */
    private static String buildOutput(
        String message,
        LiveChatMessageAuthorDetails author,
        LiveChatSuperChatDetails superChatDetails) {
        StringBuilder output = new StringBuilder();
        if (superChatDetails != null) {
            output.append(superChatDetails.getAmountDisplayString());
            output.append("SUPERCHAT RECEIVED FROM ");
        }
        output.append(author.getDisplayName());
        List<String> roles = new ArrayList<String>();
        if (author.getIsChatOwner()) {
            roles.add("OWNER");
        }
        if (author.getIsChatModerator()) {
            roles.add("MODERATOR");
        }
        if (author.getIsChatSponsor()) {
            roles.add("SPONSOR");
        }
        if (roles.size() > 0) {
            output.append(" (");
            String delim = "";
            for (String role : roles) {
                output.append(delim).append(role);
                delim = ", ";
            }
            output.append(")");
        }
        if (message != null && !message.isEmpty()) {
            output.append(": ");
            output.append(message);
        }
        return output.toString();
    }
}

Errors

The following table identifies error messages that the API could return in response to a call to this method. Please see the error message documentation for more detail.

Error type Error detail Description
forbidden (403) forbidden You do not have the permissions required to retrieve messages for the specified live chat.
forbidden (403) liveChatDisabled Live chat is not enabled for the specified broadcast.
forbidden (403) liveChatEnded The specified live chat is no longer live.
notFound (404) liveChatNotFound The live chat that you are trying to retrieve cannot be found. Check the value of the request's liveChatId parameter to ensure that it is correct.
rateLimitExceeded rateLimitExceeded The request was sent too quickly after the previous request. This error occurs when API requests to retrieve messages are being sent more frequently than YouTube's refresh rates, which unnecessarily wastes bandwidth and quota.

Try it!

Use the API Explorer to call this method on live data and see the API request and response.