使用 Google Chat API 傳送訊息

本指南說明如何呼叫 Google Chat API 的 messages.create()敬上 方法執行下列任一操作:

  • 傳送內含文字、資訊卡和互動式小工具的訊息,
  • 傳送私人訊息給特定的 Chat 使用者。
  • 發起或回覆訊息串。
  • 為訊息命名,方便你在其他 Chat API 中指定 要求。

除了呼叫 messages.create() 方法外,即時通訊應用程式 您可以建立並傳送訊息,回覆使用者互動,例如張貼 當使用者將 Chat 應用程式新增到 空白鍵。回覆互動時,即時通訊應用程式可以使用其他 多種訊息功能,包括互動式對話方塊和連結預覽 存取 API為了回覆使用者,Chat 應用程式會傳回 讀取訊息,不必呼叫 Chat API。學習 瞭解如何傳送訊息以回覆互動,請參閱 接收及回覆與 Google Chat 應用程式的互動

Chat 如何顯示和屬性使用 Chat API 建立的訊息

您可以使用以下項目呼叫 messages.create() 方法: 應用程式驗證使用者驗證。 Chat 會以不同方式區分訊息傳送者 取決於您使用的驗證類型。

當您以 Chat 應用程式的身分進行驗證時 Chat 應用程式會傳送訊息。

使用應用程式驗證來呼叫 messages.create() 方法。
圖 1:啟用應用程式驗證功能後,Chat 應用程式會傳送 訊息。請注意,傳送者不是使用者,Chat 會在對方名稱旁邊顯示 App

當您以使用者的身分進行驗證後,Chat 應用程式會將 傳送留言Chat 也會將 顯示訊息名稱的 Chat 擴充應用程式

透過使用者驗證呼叫 messages.create() 方法。
圖 2:啟用使用者驗證功能後,使用者傳送訊息,Chat 則會顯示 使用者名稱旁邊的 Chat 應用程式名稱。

驗證類型也會決定哪些訊息功能和介面 請附加在訊息中透過應用程式驗證功能 Chat 擴充應用程式可以傳送含有 RTF 格式的訊息, 卡片式介面和互動式小工具。 由於 Chat 使用者只能在訊息中傳送簡訊,您可以 僅在使用使用者驗證機制建立訊息時,才含有文字。 進一步瞭解訊息功能 如要瞭解 Chat API 可用的功能,請參閱 Google Chat 訊息總覽

本指南說明如何使用其中一種驗證類型傳送訊息 快速分享

必要條件

Python

  • Python 3.6 以上版本
  • pip 套件管理工具
  • 最新的 Google 用戶端程式庫。安裝或更新 在指令列介面中執行下列指令:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

代表使用者傳送簡訊

本節說明如何使用 使用者驗證。 採用使用者驗證功能時,郵件內容只能包含文字 而且如果訊息功能僅支援特定用途 即時通訊應用程式,包括資訊卡介面和互動式小工具。

訊息已在使用者驗證時傳送
圖 3. Chat 應用程式會在 使用者 ID

如要透過使用者驗證機制呼叫 messages.create(),您必須指定 要求中填入下列欄位:

  • 授權範圍 。下列範例使用 chat.messages.create 範圍。
  • 在其中的 Space 資源 這則訊息的效期。已驗證使用者必須是 空白鍵。
  • Message 要建立的資源如要定義訊息內容,您必須將 text敬上 ] 欄位。

您也可以選擇加入下列資訊:

  • messageId 欄位:可讓您 命名訊息,以便在其他 API 要求中使用。
  • thread.threadKeymessageReplyOption 欄位 發起或回覆討論串。如果聊天室沒有 但系統會忽略這個欄位。

如要代表使用者傳送簡訊,請按照下列步驟操作:

Python

  1. 在工作目錄中,建立名為 chat_create_message_user.py
  2. chat_create_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.create"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then creates a text message in a Chat space.
        '''
    
        # Start with no credentials.
        creds = None
    
        # 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().create(
    
            # The space to create the message in.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE',
    
            # Optional. Sets custom ID for the message to use in other requests.
            messageId='client-myfirstusermessage',
    
            # The text message to create.
            body={
              'text': '👋 🌎Hello world! Text messages can contain things like:\n\n'
    
              + '* Hyperlinks 🔗\n'
              + '* Emojis 😄🎉\n'
              + '* Mentions of other Chat users `@` \n\n'
    
              'For details, see the <https://developers.google.com/workspace/chat/format-messages|Chat API developer documentation>.'
          }
    
        ).execute()
    
        # Prints details about the created message.
        print(result)
    
    if __name__ == '__main__':
        main()
    

    SPACE 替換為聊天室的 ID name ] 欄位。您可以呼叫 spaces.list() 方法 或從聊天室網址複製

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

    python3 chat_create_message_user.py
    
  4. 如果系統提示您輸入網址,請開啟該網址進行授權。 根據您在 請求。

Chat 應用程式建立訊息,且通過驗證 使用者在聊天室中張貼訊息。在指令列介面中 Chat API 會傳回新的 Message 項資源。

以 Chat 應用程式的形式傳送訊息

本節說明如何傳送內含文字、資訊卡和 互動式配件小工具 應用程式驗證

訊息以應用程式驗證方式傳送
圖 4 Chat 應用程式傳送訊息給 文字、卡片和配件按鈕

如要使用應用程式驗證功能呼叫 messages.create(),您必須指定 要求中填入下列欄位:

  • chat.bot 授權範圍
  • 在其中的 Space 資源 這則訊息的效期。Chat 應用程式必須是 聊天室成員。
  • Message 要建立的資源如要定義訊息內容,您可以加上 RTF 格式 (text), 一或多個資訊卡介面 (cardsV2), 或兩者並行

您也可以選擇加入下列資訊:

訊息大小上限 (包括任何文字或資訊卡) 為 32,000 個位元組。 如要傳送超過此大小的訊息,你的 Chat 應用程式 就必須傳送多則訊息。

如要以 Chat 應用程式的形式傳送含有以下內容的訊息: 文字、資訊卡以及訊息底部的可點擊按鈕 步驟如下:

Python

  1. 在工作目錄中,建立名為 chat_create_message_app.py
  2. chat_create_message_app.py 中加入下列程式碼:

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # 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', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Specify the Chat space where the message is posted. Obtain the ID
    # from the resource name, or from the space's URL.
    SPACE = 'spaces/SPACE'
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The Chat space.
        parent=SPACE,
    
        # Optional. Sets custom ID for the message to use in other requests.
        messageId='client-myfirstappmessage',
    
        # The message to create with text, a card, and a button at the
        # bottom of the message.
        body=
        {
          'text': '👋 🌎Hello world! I created this message by calling the Chat API\'s `messages.create()` method.',
          'cardsV2': [{
            'cardId': 'myCardId',
            'card': {
              'header': {
                'title': 'About this message',
                'imageUrl': 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg',
                'imageType': 'CIRCLE'
              },
            "sections": [
                {
                "header": "Contents",
                "widgets": [
                    {
                    "textParagraph": {
                        "text": "🔡 <b>Text</b> which can include hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️."
                    }},
                    {
                    "textParagraph": {
                        "text": "🖼️ A <b>card</b> to display visual elements and request information such as text 🔤, dates and times 📅, and selections ☑️."
                    }},
                    {
                    "textParagraph": {
                        "text": "👉🔘 An <b>accessory widget</b> which adds a button to the bottom of a message."
                    }},
                  ]
                },
                {
                "header": "What's next",
                "collapsible": True,
                "widgets": [
                    {
                    "textParagraph": {
                        "text": "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
                    }},
                    {
                    "textParagraph": {
                        "text": "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> the message."
                    }},
                    {
                    "textParagraph": {
                        "text": '💡 <b>Pro tip</b>: To specify the message in other API requests, use its custom name: <i>' + SPACE + '/messages/client-myfirstappmessage</i>.'
                    }}
                  ]
                }
              ]}
          }],
          "accessoryWidgets":
          [
              {
                  "buttonList":
                  {
                      "buttons":
                      [
                          {
                              "text": "View documentation",
                              "altText": "Opens a new browser tab and navigates to the Google Chat developer documentation website.",
                              "icon":
                              {
                                  "material_icon":
                                  {
                                      "name": "link"
                                  }
                              },
                              "onClick":
                              {
                                  "openLink":
                                  {
                                      "url": "https://developers.google.com/workspace/chat/create-messages"
                                  }
                              }
                          }
                      ]
                  }
              }
          ]
        }
    
    ).execute()
    
    print(result)
    

    SPACE 替換為聊天室的 ID name ] 欄位。您可以呼叫 spaces.list() 方法 或從聊天室網址複製

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

    python3 chat_create_message_app.py
    

Chat 應用程式會在 空白鍵。在指令列介面中,Chat API 會傳回 新的執行個體 Message 項資源。

在訊息底部新增互動式小工具

在上一節的程式碼範例中 Chat 應用程式訊息的 (稱為配件小工具)。配件小工具 顯示在訊息中的任何文字或資訊卡後方。使用這些小工具 使用者可以透過多種方式與訊息互動,包括:

  • 為訊息的準確度或滿意度評分。
  • 回報與訊息或 Chat 應用程式相關的問題。
  • 開啟相關內容的連結,例如說明文件。
  • 關閉或延後 Chat 應用程式中的類似訊息 一段時間。

如要新增配件小工具,請在 accessoryWidgets[]敬上 ] 欄位,然後指定一或多個小工具 。

下圖顯示會附加的 Chat 應用程式 附有配件小工具的文字訊息,可讓使用者為自己的體驗評分 取得最新資訊

配件小工具。
圖 5:含有 文字和配件小工具

以下範例顯示會建立簡訊的要求主體 兩個配件按鈕使用者點選按鈕時, 函式 (例如 doUpvote) 會處理互動:


 "text": "Rate your experience with this Chat app.",
 "accessoryWidgets": [
   {
     "buttonList": {
       "buttons": [
         {
           "icon": {
             "material_icon": {
               "name": "thumb_up"
             }
           },
           "color": {
             "red": 0,
             "blue": 255,
             "green": 0
           },
           "onClick": {
             "action": {
               "function": "doUpvote",
             }
           }
         },
         {
           "icon": {
             "material_icon": {
               "name": "thumb_down"
             }
           },
           "color": {
             "red": 0,
             "blue": 255,
             "green": 0
           },
           "onClick": {
             "action": {
               "function": "doDownvote",
             }
           }
         }
       ]
     }
   }
 ]

傳送私人訊息

即時通訊應用程式可以在私人訊息中傳送訊息, 只有聊天室中的特定使用者看得到訊息。如果 Chat 應用程式會傳送私人訊息,也就是訊息 會顯示標籤,告知使用者該訊息僅供檢視。

如要使用 Chat API 傳送私人訊息,請指定 privateMessageViewer敬上 ] 欄位的值。如要指定使用者,請將值設為 所需的 User 資源 代表 Chat 使用者。您也可以使用 name 欄位, User 資源,如以下範例所示:

{
    "text": "Hello private world!",
    "privateMessageViewer": {
      "name": "users/USER_ID"
    }
}

取代 USER_ID 或使用者專屬 ID,例如 12345678987654321hao@cymbalgroup.com。如要進一步瞭解如何指定使用者,請參閱 識別並指定 Google Chat 使用者

如要傳送私人訊息,必須在要求中省略以下內容:

在討論串中發起或回覆

針對使用執行緒的聊天室, 您可以指定新訊息是發起討論串,或是回覆 或現有討論串

根據預設,您使用 Chat API 建立的訊息會啟動新的 。為了方便辨識及回覆討論串,可以指定 加入執行緒金鑰:

如何建立回覆現有討論串的訊息:

  • 在要求主體中,納入 thread 欄位。如果已經設定 請指定 threadKey敬上 每個專案的名稱否則,您必須使用 name敬上 執行緒之間的關係。
  • 指定查詢參數 messageReplyOption

以下 JSON 範例顯示了 使用 helloWorldThread 鍵發起或回覆討論串:

   {
     'thread': {
      'threadKey': 'helloWorldThread',
     },
     'text': '👋 🌎Hello world!'
   }

輸入訊息名稱

如要在日後的 API 呼叫中擷取或指定訊息,您可以為訊息命名 只要在 messages.create() 要求中設定 messageId 欄位即可。 為訊息命名後,您不需要儲存 系統從訊息資源名稱中指派的 ID (如 name敬上 ] 欄位)。

舉例來說,如要使用 get() 方法擷取訊息,您可以使用 指定要擷取哪些訊息的資源名稱。資源名稱是 格式為 spaces/{space}/messages/{message},其中 {message} 代表 您在建立 Deployment 時 撰寫新的電子郵件訊息

如要為訊息命名,請在 messageId敬上 ] 欄位輸入訊息內容。messageId 欄位會設定 clientAssignedMessageId 擁有多個欄位,Message)。

你只能在建立訊息時命名訊息。您無法為或 修改現有郵件的自訂 ID。自訂 ID 必須符合下列規定 規定:

  • 開頭為 client-。舉例來說,client-custom-name 是有效的自訂值 ID,但 custom-name 不是。
  • 長度上限為 63 個半形字元,且只能使用小寫英文字母、數字和 連字號
  • 聊天室中不得重複,Chat 應用程式無法使用 以便為不同訊息套用相同的自訂 ID。

疑難排解

Google Chat 應用程式或 card 會傳回錯誤, 即時通訊介面顯示「發生錯誤」的訊息。 或「無法處理你的要求」。有時使用 Chat UI 不會顯示任何錯誤訊息,但 Chat 應用程式或 資訊卡產生非預期的結果例如資訊卡訊息 顯示。

雖然 Chat UI 中可能不會顯示錯誤訊息, 提供描述性錯誤訊息和記錄資料,協助您修正錯誤 。如需觀看說明, 偵錯及修正錯誤,請參閱 疑難排解並修正 Google Chat 錯誤