更新消息

本指南介绍了如何在 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-httplib2 google-auth-oauthlib oauth2client
    
  • 已发布的 Chat 应用。如需创建和发布 Chat 应用,请参阅构建 Google Chat 应用

  • 为 Chat 应用配置的授权:

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

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

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

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

下面展示了如何更新短信或使用用户身份验证功能在卡片消息前面添加文字消息:

Python

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

    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    # 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 httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
      'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # 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 httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
      'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # 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 的实例,其中详细说明了更新的消息。