更新消息

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

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

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

前提条件

Python

  • Python 3.6 或更高版本
  • pip 软件包管理工具
  • 最新的 Google 客户端库。若要安装或更新这些应用 在命令行界面中运行以下命令:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

通过用户身份验证更新短信,或在卡片消息前添加短信

要更新 短信 替换为 用户身份验证,通过 在您的请求中:

  • 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 updated message.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中进行以下替换:

    • SPACE:聊天室名称,您可以从中获取 该 spaces.list 方法 或通过聊天室网址发送。
    • MESSAGE:消息名称,您可以获取 从异步创建消息后返回的响应正文中 或者通过 自定义名称 分配给消息。
  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:聊天室名称,您可以从中获取 该 spaces.list 方法 或通过聊天室网址发送。
    • MESSAGE:消息名称,您可以获取 从异步创建消息后返回的响应正文中 或者通过 自定义名称 分配给消息。
  4. 在您的工作目录中,构建并运行该示例:

    python3 chat_update_text_message_app.py
    

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

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

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

如果更新后的消息 短信、 然后,一条信息卡会附加到短信中(该消息会继续显示)。如果 更新后的消息本身 card,则所显示的卡片是 已更新。

下面说明了如何将消息更新为 卡片消息

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:聊天室名称,您可以从中获取 该 spaces.list 方法 或通过聊天室网址发送。

    • MESSAGE:消息名称,您可以获取 从异步创建消息后返回的响应正文中 或者通过 自定义名称 分配给消息。

  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 updated message.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中进行以下替换:

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

    python3 chat_update_text_message_user.py