获取消息详情

本指南介绍了如何使用 Google Chat API 的 Message 资源中的 get() 方法返回有关文本或卡片消息的详细信息。

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

前提条件

Node.js

Python

Java

Apps 脚本

获取包含用户身份验证的消息

如需获取有关具有用户身份验证的消息的详细信息,请在请求中传递以下内容:

  • 指定 chat.messages.readonlychat.messages 授权范围。
  • 调用 GetMessage() 方法。
  • name 设置为要获取的消息的资源名称。

以下示例获取了包含用户身份验证的消息:

Node.js

chat/client-libraries/cloud/get-message-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 get message 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 and MESSAGE_NAME here     name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME',   };    // Make the request   const response = await chatClient.getMessage(request);    // Handle the response   console.log(response); }  await main();

Python

chat/client-libraries/cloud/get_message_user_cred.py
from authentication_utils import create_client_with_user_credentials import google.oauth2.credentials  from google.apps import chat_v1 as google_chat  SCOPES = ["https://www.googleapis.com/auth/chat.messages.readonly"]  # This sample shows how to get message with user credential def get_message_with_user_cred():     # Create a client     client = create_client_with_user_credentials(SCOPES)      # Initialize request argument(s)     request = google_chat.GetMessageRequest(         # Replace SPACE_NAME and MESSAGE_NAME here         name = "spaces/SPACE_NAME/messages/MESSAGE_NAME",     )      # Make the request     response = client.get_message(request)      # Handle the response     print(response)  get_message_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageUserCred.java
import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.GetMessageRequest; import com.google.chat.v1.Message;  // This sample shows how to get message with user credential. public class GetMessageUserCred {    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))) {       GetMessageRequest.Builder request = GetMessageRequest.newBuilder()         // replace SPACE_NAME and MESSAGE_NAME here         .setName("spaces/SPACE_NAME/members/MESSAGE_NAME");       Message response = chatServiceClient.getMessage(request.build());        System.out.println(JsonFormat.printer().print(response));     }   } }

Apps 脚本

chat/advanced-service/Main.gs
/**  * This sample shows how to get message 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 getMessageUserCred() {   // Initialize request argument(s)   // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here   const name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME';    // Make the request   const response = Chat.Spaces.Messages.get(name);    // Handle the response   console.log(response); }

如需运行此示例,请替换以下内容:

  • SPACE_NAME:来自空间 name 的 ID。您可以通过调用 ListSpaces() 方法或从会议室的网址中获取 ID。
  • MESSAGE_NAME:消息的 name 中的 ID。您可以通过以下方式获取 ID:使用 Chat API 异步创建消息后返回的响应正文,或者创建消息时分配给消息的自定义名称

Chat API 会返回一个 Message 实例,其中包含指定消息的详细信息。

接收包含应用身份验证的消息

如需获取有关具有应用身份验证的消息的详细信息,请在请求中传递以下内容:

以下示例获取了包含应用身份验证的消息:

Node.js

chat/client-libraries/cloud/get-message-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';  // This sample shows how to get message with app credential async function main() {   // Create a client   const chatClient = createClientWithAppCredentials();    // Initialize request argument(s)   const request = {     // Replace SPACE_NAME and MESSAGE_NAME here     name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME',   };    // Make the request   const response = await chatClient.getMessage(request);    // Handle the response   console.log(response); }  await main();

Python

chat/client-libraries/cloud/get_message_app_cred.py
from authentication_utils import create_client_with_app_credentials from google.apps import chat_v1 as google_chat  # This sample shows how to get message with app credential def get_message_with_app_cred():     # Create a client     client = create_client_with_app_credentials()      # Initialize request argument(s)     request = google_chat.GetMessageRequest(         # Replace SPACE_NAME and MESSAGE_NAME here         name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME',     )      # Make the request     response = client.get_message(request=request)      # Handle the response     print(response)  get_message_with_app_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/GetMessageAppCred.java
import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.GetMessageRequest; import com.google.chat.v1.Message;  // This sample shows how to get message with app credential. public class GetMessageAppCred {    public static void main(String[] args) throws Exception {     try (ChatServiceClient chatServiceClient =         AuthenticationUtils.createClientWithAppCredentials()) {       GetMessageRequest.Builder request = GetMessageRequest.newBuilder()         // replace SPACE_NAME and MESSAGE_NAME here         .setName("spaces/SPACE_NAME/members/MESSAGE_NAME");       Message response = chatServiceClient.getMessage(request.build());        System.out.println(JsonFormat.printer().print(response));     }   } }

Apps 脚本

chat/advanced-service/Main.gs
/**  * This sample shows how to get message with app credential  *   * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'  * used by service accounts.  */ function getMessageAppCred() {   // Initialize request argument(s)   // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here   const name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME';   const parameters = {};    // Make the request   const response = Chat.Spaces.Messages.get(name, parameters, getHeaderWithAppCredentials());    // Handle the response   console.log(response); }

如需运行此示例,请替换以下内容:

  • SPACE_NAME:来自空间 name 的 ID。您可以通过调用 ListSpaces() 方法或从会议室的网址中获取 ID。
  • MESSAGE_NAME:消息的 name 中的 ID。您可以通过以下方式获取 ID:使用 Chat API 异步创建消息后返回的响应正文,或者创建消息时分配给消息的自定义名称

Chat API 会返回一个 Message 实例,其中包含指定消息的详细信息。

以获得管理员批准的 Chat 应用的身份获取消息

使用 chat.app.* 授权范围进行应用身份验证需要管理员批准一次。

如需使用 Chat REST API 通过应用身份验证获取有关消息的详细信息,请在请求中传递以下内容:

  • 调用 GetMessage() 方法。
  • 指定 chat.app.messages.readonly 授权范围。
  • name 设置为要获取的消息的资源名称。

创建 API 密钥

如需调用开发者预览版 API 方法,您必须使用非公开的开发者预览版 API 发现文档。如需对请求进行身份验证,您必须传递 API 密钥。

如需创建 API 密钥,请打开应用的 Google Cloud 项目并执行以下操作:

  1. 在 Google Cloud 控制台中,依次前往菜单 > API 和服务 > 凭据

    进入“凭据”页面

  2. 依次点击创建凭据 > API 密钥
  3. 系统会显示您的新 API 密钥。
    • 点击“复制”图标 即可复制 API 密钥,以便在应用的代码中使用。您还可以在项目的凭据的“API 密钥”部分中找到 API 密钥。
    • 为防止未经授权的使用,我们建议您限制 API 密钥可用于哪些位置和 API。如需了解详情,请参阅添加 API 限制

编写调用 Chat API 的脚本

以下是使用应用身份验证和管理员批准以及 Chat REST API 获取消息详细信息的方法:

Python

  1. 在工作目录中,创建一个名为 chat_messages_get_admin_app.py 的文件。
  2. chat_messages_get_admin_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 gets details about a message.     '''      # 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, discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY')      # Use the service endpoint to call Chat API.     result = chat.spaces().messages().get(          # The message to get details about.         #         # Replace SPACE_NAME with a space name.         # Obtain the space name from the spaces resource of Chat API,         # or from a space's URL.         name='spaces/SPACE_NAME/messages/MESSAGE_NAME',      ).execute()      # Print Chat API's response in your command line interface.     print(result)  if __name__ == '__main__':     main() 
  3. 在代码中,替换以下内容:

    • API_KEY:您创建的用于构建 Chat API 服务端点的 API 密钥。
    • SPACE_NAME:来自空间 name 的 ID。 您可以通过调用 ListSpaces() 方法或从空间的网址中获取 ID。
    • MESSAGE_NAME:消息的 name 中的 ID。您可以通过以下方式获取 ID:使用 Chat API 异步创建消息后返回的响应正文,或者创建消息时分配给消息的自定义名称
  4. 在工作目录中,构建并运行示例:

    python3 chat_messages_get_admin_app.py

Chat API 会返回一个 Message 实例,其中包含指定消息的详细信息。