刪除訊息中的回應

本指南將說明如何在 Google Chat API 的 Reaction 資源上使用 delete 方法,刪除訊息中的回應,例如 👍?、🚲?, 首次發文。 刪除回應並不會刪除該訊息。

Reaction 資源代表一個表情符號,可供使用者回應訊息,例如 👍?、🚲?, 和 ♀。

必要條件

Python

  • Python 3.6 或更高版本
  • pip 套件管理工具
  • 最新的 Python 專用 Google 用戶端程式庫。如要安裝或更新,請在指令列介面中執行下列指令:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • 已啟用並設定 Google Chat API 的 Google Cloud 專案。相關步驟請參閱「建構 Google Chat 應用程式」。
  • 已為 Chat 應用程式設定授權。如要刪除回應,您必須使用 chat.messages.reactionschat.messages 授權範圍的使用者驗證

刪除回應

如要刪除訊息中的回應,請在要求中傳送以下內容:

  • 指定 chat.messages.reactionschat.messages 授權範圍。
  • 呼叫 Reaction 資源上的 delete 方法
  • name 設為要刪除的回應的資源名稱。

下方範例會從訊息中刪除 😀? 的回應:

Python

  1. 在工作目錄中,建立名為 chat_reaction_delete.py 的檔案。
  2. chat_reaction_delete.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.reactions"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then deletes a reaction to 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)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().reactions().delete(
    
            # The reaction to delete.
            #
            # 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.
            #
            # Replace REACTION with a reaction name.
            # Obtain the reaction name from the reaction resource of Chat API.
            name = 'spaces/SPACE/messages/MESSAGE/reactions/REACTION'
    
        ).execute()
    
    if __name__ == '__main__':
        main()
    
  3. 在程式碼中,替換以下內容:

    • SPACE:聊天室名稱,您可以透過 Chat API 的 spaces.list 方法或聊天室網址取得。
    • MESSAGE:訊息名稱。您可以使用 Chat API 以非同步方式建立訊息後,從傳回的回應主體取得此名稱,或是在建立訊息時指派給該訊息的自訂名稱
    • REACTION:回應名稱,您可以透過 Chat API 的 spaces.messages.reactions.list 方法取得,或透過 Chat API 建立非同步回應後傳回的回應主體取得此名稱。
  4. 在工作目錄中,建構並執行範例:

    python3 chat_reaction_delete.py
    

如果成功,回應主體會空白,表示回應已刪除。