更新消息

本指南介绍了如何在 Google Chat API 的 Message 资源中使用 patch 方法更新聊天室中的文本或卡片消息。更新消息以更改消息属性,例如消息内容或卡片的内容。您还可以在卡片消息前附加短信,或将卡片附加到短信中。

Chat API 还支持 update 方法,但我们强烈建议您调用 patch 方法,因为它使用的是 PATCH HTTP 请求,而 update 使用的是 PUT HTTP 请求。如需了解详情,请参阅 AIP-134 的 PATCHPUT 部分

Message 资源表示 Google Chat 中的文本卡片消息。您可以通过调用相应的方法,在 Google Chat API 中对消息执行 creategetupdatedelete 操作。如需详细了解文本和卡片消息,请参阅 Google Chat 消息概览

前提条件

Python

  • Python 3.6 或更高版本
  • pip 软件包管理工具
  • 适用于 Python 的最新 Google 客户端库。如需安装或更新它们,请在命令行界面中运行以下命令:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib google-auth
    
  • 一个启用了并配置了 Google Chat API 的 Google Cloud 项目。如需了解相关步骤,请参阅构建 Google Chat 应用
  • 为 Chat 应用配置授权:

使用用户身份验证功能更新短信或在卡片消息前附加短信

如需使用用户身份验证更新短信,请在请求中传递以下内容:

  • chat.messages 授权范围。
  • 要更新的消息的 name
  • updateMask='text'
  • 一个 body,用于指定更新后的消息。

如果更新的消息是卡片消息,文本消息将附加到卡片消息之前(将继续显示)。

以下是使用用户身份验证更新短信卡片消息前置短信的方法:

Python

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

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.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.messages"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates a message.
        '''
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                          'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Update a Chat message.
        result = chat.spaces().messages().patch(
    
          # The message to update, and the updated message.
          #
          # Replace SPACE with a space name.
          # Obtain the space name from the spaces resource of Chat API,
          # or from a space's URL.
          #
          # Replace MESSAGE with a message name.
          # Obtain the message name from the response body returned
          # after creating a message asynchronously with Chat REST API.
          name='spaces/SPACE/messages/MESSAGE',
          updateMask='text',
          body={'text': 'Updated message!'}
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中,替换以下内容:

    • SPACE:聊天室名称,可通过 Chat API 中的 spaces.list 方法或聊天室网址获取。
    • MESSAGE:消息名称,您可以从通过 Chat API 异步创建消息后返回的响应正文中获取,也可以使用在创建消息时分配给该消息的自定义名称获取。
  4. 在您的工作目录中,构建并运行示例:

    python3 chat_update_text_message_user.py
    

使用应用身份验证功能更新短信或在卡消息前添加短信

如需使用应用身份验证更新短信,请在请求中传递以下内容:

  • chat.bot 授权范围。
  • 要更新的消息的 name
  • updateMask='text'
  • 一个 body,用于指定更新后的消息。

如果更新的消息是卡片消息,那么文本消息将添加到卡片消息之前(将继续显示)。

下面介绍了如何通过应用身份验证短信更新为短信,或在卡片消息前面附加短信:

Python

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

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = (
        service_account.Credentials.from_service_account_file('credentials.json')
        .with_scopes(SCOPES)
    )
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Update a Chat message.
    result = chat.spaces().messages().patch(
    
      # The message to update, and the updated message.
      #
      # Replace SPACE with a space name.
      # Obtain the space name from the spaces resource of Chat API,
      # or from a space's URL.
      #
      # Replace MESSAGE with a message name.
      # Obtain the message name from the response body returned
      # after creating a message asynchronously with Chat REST API.
      name='spaces/SPACE/messages/MESSAGE',
      updateMask='text',
      body={'text': 'Updated message!'}
    
    ).execute()
    
    # Print Chat API's response in your command line interface.
    print(result)
    
  3. 在代码中,替换以下内容:

    • SPACE:聊天室名称,可通过 Chat API 中的 spaces.list 方法或聊天室网址获取。
    • MESSAGE:消息名称,您可以从通过 Chat API 异步创建消息后返回的响应正文中获取,也可以使用在创建消息时分配给该消息的自定义名称获取。
  4. 在您的工作目录中,构建并运行示例:

    python3 chat_update_text_message_app.py
    

更新卡片消息,或将卡片消息附加到短信中

如需更新卡片消息,请在请求中传递以下内容:

  • chat.bot 授权范围。更新卡消息需要执行应用身份验证
  • 要更新的消息的 name
  • updateMask='cardsV2'
  • 一个 body,用于指定更新后的消息。

如果更新的消息是短信,那么一张卡片会附加到短信中(系统会继续显示该卡片)。如果更新的消息本身就是卡片,则显示的卡片将会更新。

将消息更新为卡片消息的方法如下:

Python

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

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = (
        service_account.Credentials.from_service_account_file('credentials.json')
        .with_scopes(SCOPES)
    )
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Update a Chat message.
    result = chat.spaces().messages().patch(
    
      # The message to update, and the updated message.
      #
      # Replace SPACE with a space name.
      # Obtain the space name from the spaces resource of Chat API,
      # or from a space's URL.
      #
      # Replace MESSAGE with a message name.
      # Obtain the message name from the response body returned
      # after creating a message asynchronously with Chat REST API.
      name='spaces/SPACE/messages/MESSAGE',
      updateMask='cardsV2',
      body=
      {
        'cardsV2': [{
          'cardId': 'updateCardMessage',
          'card': {
            'header': {
              'title': 'An Updated Card Message!',
              'subtitle': 'Updated with Chat REST API',
              'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
              'imageType': 'CIRCLE'
            },
            'sections': [
              {
                'widgets': [
                  {
                    'buttonList': {
                      'buttons': [
                        {
                          'text': 'Read the docs!',
                          'onClick': {
                            'openLink': {
                              'url': 'https://developers.google.com/chat'
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }]
      }
    
    ).execute()
    
    # Print Chat API's response in your command line interface.
    print(result)
    
  3. 在代码中,替换以下内容:

    • SPACE:聊天室名称,可通过 Chat API 中的 spaces.list 方法或聊天室网址获取。

    • MESSAGE:消息名称,您可以从通过 Chat API 异步创建消息后返回的响应正文中获取,也可以使用在创建消息时分配给该消息的自定义名称获取。

  4. 在您的工作目录中,构建并运行示例:

    python3 chat_update_card_message.py
    

Chat API 会返回 Message 的实例,其中详细说明了已更新的消息。

同时更新包含多个字段路径的消息

更新消息后,您可以同时更新多个消息字段路径。例如,在更新消息请求中,您可以同时指定对 textcardsv2 字段路径的更改,这将更新消息的文本和卡片。如果消息仅包含文本而没有卡片,则系统会向消息中添加卡片。如需详细了解支持的字段路径,请参阅 updateMask 参数

如需使用用户身份验证更新消息的 textcard,请在请求中传递以下内容:

  • chat.messages 授权范围。
  • 要更新的消息的 name
  • 一个 updateMask,用于指定要更新的消息字段路径(以英文逗号分隔):updateMask='text', 'cardsV2'

  • 一个 body,用于指定更新后的消息,包括所有已更新的字段路径。

以下是使用用户身份验证更新消息中的 textcardsV2 字段路径的具体步骤:

Python

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

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.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.messages"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates a message.
        '''
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                          'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Update a Chat message.
        result = chat.spaces().messages().patch(
    
          # The message to update, and the updated message.
          #
          # Replace SPACE with a space name.
          # Obtain the space name from the spaces resource of Chat API,
          # or from a space's URL.
          #
          # Replace MESSAGE with a message name.
          # Obtain the message name from the response body returned
          # after creating a message asynchronously with Chat REST API.
          name='spaces/SPACE/messages/MESSAGE',
          updateMask='text,cardsV2',
          body=
          {'text': 'Updated message!',
                'cardsV2': [{
                  'cardId': 'updateCardMessage',
                  'card': {
                    'header': {
                      'title': 'An Updated Card Message!',
                      'subtitle': 'Updated with Chat REST API',
                      'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
                      'imageType': 'CIRCLE'
                    },
                    'sections': [
                      {
                        'widgets': [
                          {
                            'buttonList': {
                              'buttons': [
                                {
                                  'text': 'Read the docs!',
                                  'onClick': {
                                    'openLink': {
                                      'url': 'https://developers.google.com/chat'
                                    }
                                  }
                                }
                              ]
                            }
                          }
                        ]
                      }
                    ]
                  }
                }]
          }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中,替换以下内容:

    • SPACE:聊天室名称,可通过 Chat API 中的 spaces.list 方法或聊天室网址获取。
    • MESSAGE:消息名称,您可以从通过 Chat API 异步创建消息后返回的响应正文中获取,也可以使用在创建消息时分配给该消息的自定义名称获取。
  4. 在您的工作目录中,构建并运行示例:

    python3 chat_update_text_message_user.py