傳送訊息

本指南說明 Google Chat 應用程式傳送訊息的不同方式:

  • 回應使用者互動,藉此即時傳送文字和資訊卡訊息。
  • Message 資源呼叫 create 方法,以非同步的方式傳送文字和資訊卡訊息。
  • 發起或回覆訊息串。
  • 傳送並命名訊息。

Message 資源代表 Google Chat 中的文字資訊卡訊息。您可以呼叫對應的方法,在 Google Chat API 中 creategetupdatedelete 訊息。如要進一步瞭解文字和資訊卡訊息,請參閱「Google Chat 訊息總覽」。

Google Chat 應用程式也可以建立訊息來即時回應使用者互動,而不必在 Google Chat API 的 Message 資源上呼叫 create 方法,以便以非同步的方式傳送簡訊或資訊卡訊息。使用者互動的回應不需要驗證,且支援其他類型的訊息,包括互動式對話方塊和連結預覽。詳情請參閱「接收及回應與 Google Chat 應用程式的互動」。

必要條件

Node.js

Python

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

    pip3 install --upgrade google-api-python-client google-auth
    
  • 已啟用並設定 Google Chat API 的 Google Cloud 專案。相關步驟請參閱「建構 Google Chat 應用程式」。
  • 授權讓 Chat 應用程式傳送非同步訊息。不需要進行授權設定即可即時傳送訊息。

Apps Script

  • 擁有可存取 Google ChatGoogle Workspace 帳戶。
  • 已發布的 Chat 應用程式。如要建構 Chat 應用程式,請按照這個quickstart操作。
  • 授權讓 Chat 應用程式傳送非同步訊息。不需要進行授權設定即可即時傳送訊息。

傳送簡訊

本節說明透過下列兩種方式傳送簡訊:

  • 回應使用者互動,即時傳送簡訊。
  • 以非同步方式呼叫 Google Chat API,傳送簡訊。

即時傳送簡訊

在這個範例中,當 Chat 應用程式新增至聊天室時,就會建立並傳送簡訊。如要瞭解新手上路使用者的最佳做法,請參閱「透過實用的新手上路指引讓人員和聊天室開始使用」。

如要在使用者將 Chat 應用程式新增至聊天室時傳送簡訊,Chat 應用程式會回應 ADDED_TO_SPACE 互動事件。如要以簡訊回應 ADDED_TO_SPACE 互動事件,請使用以下程式碼:

Node.js

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
exports.onMessage = function onMessage(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send(
      'Hello! This function is meant to be used in a Google Chat space.');
  }

  // Send an onboarding message when added to a Chat space
  if (req.body.type === 'ADDED_TO_SPACE') {
    res.json({
      'text': 'Hi, Cymbal at your service. I help you manage your calendar
      from Google Chat. Take a look at your schedule today by typing
      `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To
      learn what else I can do, type `/help`.'
    });
  }
};

Apps Script

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
function onAddToSpace(event) {

  return {
    'text': 'Hi, Cymbal at your service. I help you manage your calendar
    from Google Chat. Take a look at your schedule today by typing
    `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To learn
    what else I can do, type `/help`.'
  }
}

程式碼範例會傳回下列文字訊息:

新手上路訊息範例。

非同步傳送簡訊

下節說明如何使用應用程式驗證和使用者驗證,以非同步方式傳送簡訊。

如要傳送簡訊,請在要求中傳遞以下內容:

  • 應用程式驗證時,請指定 chat.bot 授權範圍。在使用者驗證的情況下,請指定 chat.messages.create 授權範圍。
  • 呼叫 Message 資源上的 create 方法

透過應用程式驗證傳送簡訊

以下說明如何使用應用程式驗證傳送簡訊:

Python

  1. 在工作目錄中,建立名為 chat_create_text_message_app.py 的檔案。
  2. chat_create_text_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)
    
    # Create a Chat message.
    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',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. 在程式碼中,將 SPACE 替換為聊天室名稱,您可以在 Chat API 的 spaces.list() 方法或聊天室網址取得這項資訊。

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

    python3 chat_create_text_message_app.py
    

Chat API 會傳回 Message 的執行個體,詳細說明已送出訊息。

傳送使用者驗證簡訊

下列可讓您透過使用者驗證功能傳送簡訊:

Python

  1. 在工作目錄中,建立名為 chat_create_text_message_user.py 的檔案。
  2. chat_create_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.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',
    
            # The message to create.
            body={'text': 'Hello, world!'}
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在程式碼中,將 SPACE 替換為聊天室名稱,您可以在 Chat API 的 spaces.list() 方法或聊天室網址取得。

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

    python3 chat_create_text_message_user.py
    

Chat API 會傳回 Message 的執行個體,詳細說明已送出訊息。

傳送卡片訊息

本節說明以下列兩種方式傳送卡片訊息:

  • 回應使用者互動,即時傳送卡片訊息。
  • 以非同步方式呼叫 Google Chat API,傳送卡片訊息。


使用資訊卡建構工具設計及預覽資訊卡。

開啟資訊卡建構工具

即時傳送卡片訊息

即時通訊應用程式可以建立資訊卡訊息,回應使用者互動,例如使用者傳送 Chat 應用程式的訊息,或將 Chat 應用程式新增至聊天室。如要進一步瞭解如何回應使用者互動,請參閱「接收及回應 Chat 應用程式互動事件」。

在此範例中,使用者傳送訊息給 Chat 應用程式,而 Chat 應用程式會傳送顯示使用者名稱和顯示圖片的資訊卡訊息以回應:

Chat 應用程式回覆的資訊卡包含傳送者的顯示名稱和顯示圖片。

Node.js

節點/avatar-app/index.js
/**
 * Google Cloud Function that responds to messages sent from a
 * Google Chat room.
 *
 * @param {Object} req Request sent from Google Chat room
 * @param {Object} res Response to send back
 */
exports.helloChat = function helloChat(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send('Hello! This function is meant to be used in a Google Chat ' +
      'Room.');
  }

  const sender = req.body.message.sender.displayName;
  const image = req.body.message.sender.avatarUrl;

  const data = createMessage(sender, image);

  res.send(data);
};

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} imageUrl the URL for the sender's avatar
 * @return {Object} a card with the user's avatar.
 */
function createMessage(displayName, imageUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`,
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '},
  };

  const avatarImageWidget = {
    image: {imageUrl},
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget,
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

Python

python/avatar-app/main.py
from typing import Any, Mapping

import flask
import functions_framework


# Google Cloud Function that responds to messages sent in
# Google Chat.
#
# @param {Object} req Request sent from Google Chat.
# @param {Object} res Response to send back.
@functions_framework.http
def hello_chat(req: flask.Request) -> Mapping[str, Any]:
  if req.method == "GET":
    return "Hello! This function must be called from Google Chat."

  request_json = req.get_json(silent=True)

  display_name = request_json["message"]["sender"]["displayName"]
  avatar = request_json["message"]["sender"]["avatarUrl"]

  response = create_message(name=display_name, image_url=avatar)

  return response


# Creates a card with two widgets.
# @param {string} name the sender's display name.
# @param {string} image_url the URL for the sender's avatar.
# @return {Object} a card with the user's avatar.
def create_message(name: str, image_url: str) -> Mapping[str, Any]:
  avatar_image_widget = {"image": {"imageUrl": image_url}}
  avatar_text_widget = {"textParagraph": {"text": "Your avatar picture:"}}
  avatar_section = {"widgets": [avatar_text_widget, avatar_image_widget]}

  header = {"title": f"Hello {name}!"}

  cards = {
      "text": "Here's your avatar",
      "cardsV2": [
          {
              "cardId": "avatarCard",
              "card": {
                  "name": "Avatar Card",
                  "header": header,
                  "sections": [avatar_section],
              },
          }
      ]
  }

  return cards

Apps Script

apps-script/avatar-app/hello-chat.gs
/**
 * Responds to a MESSAGE event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onMessage(event) {
  const displayName = event.message.sender.displayName;
  const avatarUrl = event.message.sender.avatarUrl;

  return createMessage(displayName, avatarUrl);
}

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} avatarUrl the URL for the sender's avatar
 * @return {Object} a card with the sender's avatar.
 */
function createMessage(displayName, avatarUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '}
  };

  const avatarImageWidget = {
    image: {imageUrl: avatarUrl}
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

以非同步方式傳送卡片訊息

如要傳送卡片訊息,請在要求中傳遞以下內容:

  • 應用程式驗證時,請指定 chat.bot 授權範圍。您無法以使用者驗證方式傳送卡片訊息。
  • 呼叫 Message 資源上的 create 方法

以下是資訊卡訊息範例:

透過 Chat API 傳送的卡片訊息。

以下說明如何透過應用程式驗證傳送卡片訊息:

Python

  1. 在工作目錄中,建立名為 chat_create_card_message.py 的檔案。
  2. chat_create_card_message.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)
    
    # Create a Chat message.
    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',
    
        # The message to create.
        body=
        {
          'cardsV2': [{
            'cardId': 'createCardMessage',
            'card': {
              'header': {
                'title': 'A card message!',
                'subtitle': 'Created with the Chat 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(result)
    
  3. 在程式碼中,將 SPACE 替換為聊天室名稱,您可以在 Chat API 的 spaces.list 方法或聊天室網址取得這項資訊。

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

    python3 chat_create_card_message.py
    

發起或回覆訊息串

如要發起訊息執行緒,請傳送訊息,並將 thread.name 留空;Google Chat 會在建立執行緒時填入訊息。(選用) 如要自訂執行緒名稱,請指定 thread.threadKey 欄位。

如要回覆訊息討論串,請傳送指定執行緒 threadKeyname 欄位的訊息。如果執行緒是由使用者或其他 Chat 應用程式建立,您必須使用 thread.name 欄位。

找不到相符的執行緒,您可以設定 messageReplyOption 欄位,指定訊息是否應啟動新的執行緒,還是無法發布。

如果已設定 messageReplyOption,您還必須設定 thread.namethread.threadKey

以下說明如何啟動或回覆 threadKey 欄位定義為 nameOfThread 的執行緒:

Python

  1. 在工作目錄中,建立名為 chat_create_message_thread.py 的檔案。
  2. chat_create_message_thread.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)
    
    # Create a Chat message.
    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',
    
        # Whether to start a thread or reply to an existing one.
        #
        # Required when threading is enabled in a space unless starting a
        # thread.  Ignored in other space types. Threading is enabled when
        # space.spaceThreadingState is THREADED_MESSAGES.
        #
        # REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD replies to an existing thread
        # if one exists, otherwise it starts a new one.
        messageReplyOption='REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD',
    
        # The message body.
        body={
    
            # The message to create.
            'text': 'Start or reply to another message in a thread!',
    
            # The thread to start or reply to.
            'thread': {
                'threadKey': 'nameOfThread'
            }
        }
    
    ).execute()
    
    print(result)
    
  3. 在程式碼中,將 SPACE 替換為聊天室名稱,您可以在 Chat API 的 spaces.list 方法或聊天室網址取得這項資訊。

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

    python3 chat_create_message_thread.py
    

Chat API 會傳回 Message 的執行個體,詳細說明已送出訊息。

為訊息命名

本節說明如何透過設定訊息的自訂 ID 為訊息命名。您可以使用自訂 ID 取得、更新或刪除訊息。自訂 ID 可讓您指定訊息,而不需要儲存訊息資源名稱中的系統指派的 ID (顯示於 name 欄位中)。建立訊息時,資源名稱會在回應主體中產生。

例如,使用 get() 方法擷取訊息時,您可以使用資源名稱指定要擷取的訊息。資源名稱的格式為 spaces/{space}/messages/{message},其中 {message} 代表系統指派的 ID。如果您已為訊息命名,可將 {message} 的值替換為自訂 ID。

如要為訊息命名,請在建立訊息時在 messageId 欄位中指定自訂 ID。messageId 欄位會設定 Message 資源的 clientAssignedMessageId 欄位值。

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

  • 開頭為 client-。例如,client-custom-name 是有效的自訂 ID,但 custom-name 則不是。
  • 最多包含 63 個字元,且只能使用小寫英文字母、數字和連字號。
  • 聊天室中不得重複。Chat 應用程式無法為不同訊息使用相同的自訂 ID。

以下說明如何傳送含有自訂 ID 的訊息:

Python

  1. 在工作目錄中,建立名為 chat_create_named_message.py 的檔案。
  2. chat_create_named_message.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)
    
    # Create a Chat message with a custom name.
    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',
    
        # Custom name for the message used to facilitate later operations.
        messageId='client-NAME',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. 在程式碼中,替換以下內容:

    • SPACE:要張貼訊息的聊天室 ID,您可以透過 Chat API 的 spaces.list 方法或聊天室網址取得。
    • NAME:訊息的自訂名稱。
  4. 在工作目錄中,建構並執行範例:

    python3 chat_create_named_message.py
    

Chat API 會傳回 Message 的執行個體。

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

您可以選擇使用配件小工具附加訊息。配件小工具會顯示在郵件中的任何文字或資訊卡後方。您可以使用這些小工具,透過多種方式提示使用者與訊息互動,包括:

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

如要新增配件小工具,請在訊息中加入 accessoryWidgets[] 物件,並指定一或多個您要納入的 AccessoryWidgets。訊息必須讓聊天室中的所有成員看到 (您無法將配件小工具新增至私人訊息)。

下圖顯示 Chat 應用程式附加含有配件小工具的文字訊息,讓使用者可針對 Chat 應用程式的體驗評分。

配件小工具範例

下列程式碼範例顯示這則訊息的 JSON。使用者點選其中一個按鈕時,互動會觸發處理評分的對應函式,例如 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 應用程式可透過私人方式傳送文字和資訊卡訊息,讓聊天室中的單一使用者只能看到該訊息。如要以不公開的方式傳送訊息,請在訊息中指定 privateMessageViewer 欄位。只有 Chat 應用程式可以傳送私人訊息。如要非同步傳送私人訊息,您必須使用應用程式驗證機制。

詳情請參閱「傳送私人訊息給 Google Chat 使用者」。

疑難排解

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

雖然 Chat UI 可能不會顯示錯誤訊息,但我們提供描述性的錯誤訊息和記錄資料,協助您修正啟用 Chat 應用程式錯誤記錄功能時發生的錯誤。如要瞭解如何查看、偵錯及修正錯誤,請參閱「疑難排解及修正 Google Chat 錯誤」。