在訊息中加入回應

本指南說明如何針對 Reaction 資源使用 create 方法 Google Chat API 的快速回應,可對訊息新增回應,例如 👍?、🚲? 與 Θ。

Reaction 項資源 所代表的表情符號,例如 👍?、🚲? 和 CANNOT TRANSLATE

必要條件

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.reactions.createchat.messages.reactionschat.messages授權範圍。

對訊息新增回應

如要回應訊息,請在 要求:

  • 指定 chat.messages.reactions.createchat.messages.reactionschat.messages 個授權範圍。
  • create 方法Reaction 項資源
  • parent 設為要回應的訊息資源名稱。
  • body (要求主體) 設為 Reaction 在當中,unicode 欄位是以萬國碼 (Unicode) 表示的標準表情符號 字串。

以下範例使用 😀? 表情符號回應訊息:

Python

  1. 在工作目錄中,建立名為 chat_reaction_create.py 的檔案。
  2. chat_reaction_create.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.create"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then creates 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().create(
    
            # The message to create a reaction to.
            #
            # 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.
            parent = 'spaces/SPACE/messages/MESSAGE',
    
            # The reaction to the message.
            body = {
    
                'emoji': {
    
                    # A standard emoji represented by a unicode string.
                    'unicode': '😀'
                }
    
            }
    
        ).execute()
    
        # Prints details about the created reaction.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 請在程式碼中替換下列內容:

    • SPACE:也就是空間的 name 訊息也會張貼,您可以在 spaces.list 方法 或聊天室網址傳送

    • MESSAGE:訊息名稱,您可以取得 建立非同步訊息後傳回的回應主體 透過 Chat API 或 自訂名稱 是在建立訊息時指派的

  4. 在工作目錄中建構並執行範例:

    python3 chat_reaction_create.py
    

Chat API 會傳回 Reaction敬上 即可詳細描述系統建立的回應