列出消息

本指南介绍了如何使用 Google Chat API 的 Message 资源中的 list() 方法来查看聊天室中可过滤的已分页消息列表。

在 Chat API 中,聊天消息由 Message 资源表示。虽然 Chat 用户只能发送包含文字的消息,但 Chat 扩展应用可以使用许多其他消息功能,包括显示静态或互动式界面、从用户处收集信息以及私密地传递消息。如需详细了解 Chat API 提供的消息传递功能,请参阅 Google Chat 消息概览

前提条件

Node.js

Python

Java

Apps 脚本

以用户身份列出消息

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

  • 指定 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);
  }
}

await main();

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) {
      for (const message of responsePage.messages) {
        console.log(message);
      }
    }
    // Update the page token to the next one
    pageToken = responsePage.nextPageToken;
  } while (pageToken);
}

如需运行此示例,请将 SPACE_NAME 替换为空间name字段中的 ID。您可以通过调用 ListSpaces() 方法或从空间的网址中获取 ID。

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

以 Chat 应用的身份列出消息

应用身份验证需要管理员批准一次。

如需使用 Chat REST API 列出空间中的消息,请在请求中传递以下内容:应用身份验证

  • 指定以下授权范围之一:
    • https://www.googleapis.com/auth/chat.app.messages.readonly
  • messages 资源调用 list 方法
  • 传递要列出消息的聊天室的 name

编写调用 Chat API 的脚本

以下是使用应用身份验证Chat REST API 列出消息的方法:

Python

  1. 在工作目录中,创建一个名为 chat_messages_list_app.py 的文件。
  2. chat_messages_list_app.py 中添加以下代码:

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.app.messages.readonly"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then lists messages from a specified space.
        '''
    
        # Specify service account details.
        creds = (
            service_account.Credentials.from_service_account_file('credentials.json')
            .with_scopes(SCOPES)
        )
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().list(
    
            # The space to list messages from.
            #
            # Replace SPACE_NAME with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE_NAME'
    
        ).execute()
    
        # Print Chat API's response in your command line interface.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中,替换以下内容:

    • SPACE_NAME:聊天室名称,您可以通过 Chat API 中的 spaces.list 方法或从聊天室的网址获取该名称。
  4. 在工作目录中,构建并运行示例:

    python3 chat_messages_list_app.py

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