本指南說明 Google Chat 應用程式傳送訊息的各種方式:
- 回應使用者互動,藉此即時傳送文字和資訊卡訊息。
- 呼叫
Message
資源上的create
方法,以非同步方式傳送文字和資訊卡訊息。 - 發起或回覆訊息串。
- 傳送訊息並為訊息命名。
Message
資源代表 Google Chat 中的文字或資訊卡訊息。您可以呼叫對應的方法,在 Google Chat API 中 create
、get
、update
或 delete
訊息。如要進一步瞭解文字和資訊卡訊息,請參閱 Google Chat 訊息總覽。
訊息大小上限 (包括任何文字或資訊卡) 為 32,000 個位元組。 如果訊息超過此大小,Chat 應用程式可以改為傳送多則訊息。
Google Chat 應用程式也可以建立訊息,即時回應使用者互動,而不是在 Google Chat API 的 Message
資源上呼叫 create
方法,以非同步方式傳送文字或卡片訊息。針對使用者互動的回應不需要驗證,且支援其他類型的訊息,包括互動式對話方塊和連結預覽。詳情請參閱「接收及回應您與 Google Chat 應用程式的互動」。
先備知識
Node.js
- 可存取 Google Chat 的 Google Workspace 帳戶。
- 已啟用並設定 Google Chat API 的 Google Cloud 專案。如需詳細步驟,請參閱「建構 Google Chat 應用程式」。
- 為 Chat 應用程式設定授權以傳送非同步訊息。您不需要進行授權設定,就能即時傳送訊息。
Python
- 可存取 Google Chat 的 Google 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 Chat 的 Google 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
- 在工作目錄中,建立名為
chat_create_text_message_app.py
的檔案。 在
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)
在程式碼中,將
SPACE
替換為聊天室名稱,您可以從 Chat API 的spaces.list()
方法或聊天室網址取得。在工作目錄中建構並執行範例:
python3 chat_create_text_message_app.py
Chat API 會傳回 Message
的執行個體,詳述傳送的訊息。
傳送含使用者驗證的簡訊
以下說明如何使用使用者驗證傳送簡訊:
Python
- 在工作目錄中,建立名為
chat_create_text_message_user.py
的檔案。 在
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()
在程式碼中,將
SPACE
替換為聊天室名稱,您可以從 Chat API 的spaces.list()
方法或聊天室網址取得。在工作目錄中建構並執行範例:
python3 chat_create_text_message_user.py
Chat API 會傳回 Message
的執行個體,詳述傳送的訊息。
傳送卡片訊息
本節將說明如何以下列兩種方式傳送卡片訊息:
- 回應使用者互動,即時傳送資訊卡訊息。
- 以非同步方式呼叫 Google Chat API,傳送卡片訊息。
即時傳送卡片訊息
即時通訊應用程式可以建立資訊卡訊息來回應使用者互動,例如在使用者傳送 Chat 應用程式訊息,或將 Chat 應用程式新增至聊天室時。如要進一步瞭解如何回應使用者互動,請參閱「接收及回應 Chat 應用程式互動事件」。
在此範例中,使用者傳送訊息至 Chat 應用程式,而 Chat 應用程式會傳送顯示使用者名稱和顯示圖片的資訊卡訊息來回應:
非同步傳送卡片訊息
如要傳送資訊卡訊息,請在要求中傳送以下內容:
- 透過應用程式驗證功能,請指定
chat.bot
授權範圍。您無法透過使用者驗證機制傳送卡片訊息。 - 呼叫
Message
資源上的create
方法。
以下是資訊卡訊息的範例:
如何透過應用程式驗證功能傳送卡片訊息:
Python
- 在工作目錄中,建立名為
chat_create_card_message.py
的檔案。 在
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)
在程式碼中,將
SPACE
替換為聊天室名稱,您可以從 Chat API 的spaces.list
方法或聊天室網址取得。在工作目錄中建構並執行範例:
python3 chat_create_card_message.py
發起或回覆訊息串
如要發起訊息執行緒,請傳送訊息並將 thread.name
留空;Google Chat 會在建立執行緒時填入訊息串。或者,如要自訂執行緒名稱,請指定 thread.threadKey
欄位。
如要回覆訊息串,請傳送指出執行緒的 threadKey
或 name
欄位的訊息。如果執行緒是由使用者或其他 Chat 應用程式建立,您必須使用 thread.name
欄位。
如果找不到相符的執行緒,您可以透過設定 messageReplyOption
欄位,指定訊息應發起新的執行緒,還是無法發布。
如果已設定 messageReplyOption
,您也必須設定 thread.name
或 thread.threadKey
。
如何使用定義為 nameOfThread
的 threadKey
欄位來發起或回覆討論串:
Python
- 在工作目錄中,建立名為
chat_create_message_thread.py
的檔案。 在
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)
在程式碼中,將
SPACE
替換為聊天室名稱,您可以從 Chat API 的spaces.list
方法或聊天室網址取得。在工作目錄中建構並執行範例:
python3 chat_create_message_thread.py
Chat API 會傳回 Message
的執行個體,詳述傳送的訊息。
輸入訊息名稱
本節說明如何設定訊息的自訂 ID,藉此為訊息命名。您可以使用自訂 ID 取得、更新或刪除訊息。自訂 ID 可讓您指定訊息,而無須儲存訊息資源名稱 (如 name
欄位) 中系統指派的 ID。建立訊息時,資源名稱會在回應主體中產生。
舉例來說,如要使用 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
- 在工作目錄中,建立名為
chat_create_named_message.py
的檔案。 在
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)
請在程式碼中替換下列內容:
SPACE
:要發布訊息的聊天室 ID,您可以從 Chat API 的spaces.list
方法或聊天室網址取得。NAME
:訊息的自訂名稱。
在工作目錄中建構並執行範例:
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",
}
}
}
]
}
}
]
私下傳送訊息
即時通訊應用程式可私下傳送文字和資訊卡訊息,確保只有聊天室中的一位使用者看得到訊息。如要以私人方式傳送訊息,請在訊息中指定 privateMessageViewer
欄位。只有 Chat 應用程式可以傳送私人訊息,如要以非同步方式傳送私人訊息,您必須使用應用程式驗證。
詳情請參閱「傳送私人訊息給 Google Chat 使用者」。
疑難排解
當 Google Chat 應用程式或資訊卡傳回錯誤時,Chat 介面會顯示「發生錯誤」的訊息。或「無法處理你的要求」。Chat UI 有時不會顯示任何錯誤訊息,但 Chat 應用程式或資訊卡卻產生非預期的結果,例如資訊卡可能不會顯示。
雖然 Chat UI 可能不會顯示錯誤訊息,但可以在啟用 Chat 擴充應用程式的錯誤記錄功能時,查看描述性的錯誤訊息和記錄資料,協助您修正錯誤。如要瞭解如何查看、偵錯及修正錯誤,請參閱「疑難排解及修正 Google Chat 錯誤」。