傳送訊息

本指南將說明 Google Chat 應用程式傳送各種傳送方式 訊息:

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

Message 項資源 代表的 文字資訊卡 訊息。你可以 creategetupdatedelete,透過呼叫方式在 Google Chat API 中傳送訊息 對應的方法如要進一步瞭解簡訊和資訊卡訊息,請參閱 Google Chat 訊息總覽

訊息大小上限 (包括任何文字或資訊卡) 為 32,000 個位元組。 如果訊息超過此大小,表示 Chat 應用程式 可以傳送多則訊息。

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

必要條件

Node.js

Python

  • Google Workspace 擁有存取權的帳戶 Google Chat
  • 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 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 授權範圍。
  • create 方法Message 項資源

傳送附有應用程式驗證的簡訊

使用以下應用程式傳送簡訊的方法 應用程式驗證

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 替換成空格名稱, 您可以從中取得 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 message.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 將程式碼中的 SPACE 替換成空格名稱, 您可以從中取得 呼叫 spaces.list() 方法 Chat API 或聊天室網址。

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

    python3 chat_create_text_message_user.py
    

Chat API 會傳回 Message敬上 傳送詳細的訊息內容

傳送卡片訊息

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

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

即時傳送卡片訊息

即時通訊應用程式可以建立資訊卡訊息來回覆使用者 例如使用者傳送 Chat 應用程式 傳送訊息,或是將 Chat 應用程式加入聊天室。瞭解詳情 瞭解如何回應使用者互動,請參閱接收及回覆 Chat 應用程式互動 活動

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

即時通訊應用程式使用傳送者顯示名稱和顯示圖片的資訊卡
圖片。

Node.js

node/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

此範例會透過 資訊卡 JSON。 您也可以使用 Apps Script Card 服務

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 授權範圍。禁止事項 在使用者驗證時傳送卡片訊息
  • create 方法Message 項資源

以下是資訊卡訊息的範例:

透過 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 替換成空格名稱, 您可以從中取得 spaces.list 方法 或聊天室網址傳送

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

    python3 chat_create_card_message.py
    

發起或回覆訊息串

如要發起訊息串,請傳送訊息並離開 thread.name敬上 空白;Google Chat 會在建立討論串時填入資料。視需要 自訂執行緒名稱、指定 thread.threadKey敬上 ] 欄位。

如要回覆訊息串,請傳送指出該討論串的 threadKeyname 欄位。由使用者或其他人員建立的討論串 即時通訊應用程式,必須使用 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 替換成空格名稱, 您可以從中取得 spaces.list 方法 或聊天室網址傳送

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

    python3 chat_create_message_thread.py
    

Chat API 會傳回 Message敬上 傳送詳細的訊息內容

輸入訊息名稱

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

舉例來說,如要使用 get() 方法擷取訊息,您可以使用 指定要擷取哪些訊息的資源名稱。資源名稱是 格式為 spaces/{space}/messages/{message},其中 {message} 代表 系統指派的 ID如果您已經為訊息命名,可以 搭配自訂 ID 的 {message} 值。

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

你只能在建立訊息時命名訊息。您無法為或 修改現有郵件的自訂 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 或訊息,您可以從 spaces.list 方法 或聊天室網址傳送
    • NAME:訊息的自訂名稱。
  4. 在工作目錄中建構並執行範例:

    python3 chat_create_named_message.py
    

Chat API 會傳回 Message

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

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

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

如要新增配件小工具,請在 accessoryWidgets[]敬上 物件,並指定一或多個 AccessoryWidgets 你要加入的內容聊天室中的所有成員都必須查看這則訊息 (您無法將配件小工具加入私人訊息中)。

下圖顯示會附加的 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",
             }
           }
         }
       ]
     }
   }
 ]

私下傳送訊息

即時通訊應用程式可安全地傳送文字和卡片訊息,確保 只有聊天室中的一位使用者可以看到訊息。如何傳送私人訊息: 您在訊息中指定 privateMessageViewer 欄位。僅限 即時通訊應用程式可以傳送私人訊息。傳送私人訊息 就必須使用應用程式驗證

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

疑難排解

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

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