列出消息

本指南将介绍如何使用 list() 方法,以查看分页、Message 聊天室中可过滤的消息列表。

在 Chat API 中,Chat 消息由 Message 资源。 Chat 用户只能发送包含文字的消息, 聊天应用可以使用许多其他即时通讯功能,包括 显示静态或交互式界面,从 以及以私密方式传递消息。详细了解消息功能 功能的详细信息,请参阅 Google Chat 消息概览

前提条件

Node.js

  • Google Chat 聊天室。要使用 Google Chat API 创建一个,请参阅 创建聊天室。要在 Chat 中创建账号,请按以下步骤操作: 请访问 帮助中心文档

Python

  • Google Chat 聊天室。如需使用 Google Chat API 创建聊天室,请参阅创建聊天室。如需在 Chat 中创建聊天室,请参阅帮助中心文档

Java

Apps 脚本

  • Google Chat 聊天室。如需使用 Google Chat API 创建聊天室,请参阅创建聊天室。要在 Chat 中创建账号,请按以下步骤操作: 请访问 帮助中心文档

<ph type="x-smartling-placeholder">

列出消息

如需列出需要用户身份验证的消息,请在请求中传递以下内容:

  • 指定 chat.messages.readonlychat.messages 授权范围。
  • 调用 ListMessages() 方法。

以下示例列出了 Chat 聊天室中的消息:

Node.js

chat/client-libraries/cloud/list-messages-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.readonly'];

// This sample shows how to list messages with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here
    parent: 'spaces/SPACE_NAME'
  };

  // Make the request
  const pageResult = chatClient.listMessagesAsync(request);

  // Handle the response. Iterating over pageResult will yield results and
  // resolve additional pages automatically.
  for await (const response of pageResult) {
    console.log(response);
  }
}

main().catch(console.error);

Python

chat/client-libraries/cloud/list_messages_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.readonly"]

# This sample shows how to list messages with user credential
def list_messages_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.ListMessagesRequest(
        # Replace SPACE_NAME here
        parent = 'spaces/SPACE_NAME',
        # Number of results that will be returned at once
        page_size = 100
    )

    # Make the request
    page_result = client.list_messages(request)

    # Handle the response. Iterating over page_result will yield results and
    # resolve additional pages automatically.
    for response in page_result:
        print(response)

list_messages_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.ListMessagesRequest;
import com.google.chat.v1.ListMessagesResponse;
import com.google.chat.v1.Message;

// This sample shows how to list messages with user credential.
public class ListMessagesUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.readonly";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      ListMessagesRequest.Builder request = ListMessagesRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        // Number of results that will be returned at once.
        .setPageSize(10);

      // Iterate over results and resolve additional pages automatically.
      for (Message response :
          chatServiceClient.listMessages(request.build()).iterateAll()) {
        System.out.println(JsonFormat.printer().print(response));
      }
    }
  }
}

Apps 脚本

chat/advanced-service/Main.gs
/**
 * This sample shows how to list messages with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.readonly'
 * referenced in the manifest file (appsscript.json).
 */
function listMessagesUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here
  const parent = 'spaces/SPACE_NAME';

  // Iterate through the response pages using page tokens
  let responsePage;
  let pageToken = null;
  do {
    // Request response pages
    responsePage = Chat.Spaces.Messages.list(parent, {
      pageSize: 10,
      pageToken: pageToken
    });
    // Handle response pages
    if (responsePage.messages) {
      responsePage.messages.forEach((message) => console.log(message));
    }
    // Update the page token to the next one
    pageToken = responsePage.nextPageToken;
  } while (pageToken);
}

如需运行此示例,请将 SPACE_NAME 替换为聊天室的 name 字段中的 ID。可通过调用 ListSpaces() 方法或聊天室的网址来执行此操作。

Chat API 会返回在指定聊天室中发送的消息列表。如果请求中没有消息, Chat API 响应会返回一个空对象。使用 REST/HTTP 接口时,响应包含一个空 JSON 对象 {}