使用 Google Chat API 傳送訊息

本指南說明如何使用 Google Chat API Message 資源的 create() 方法,執行下列任一操作:

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

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

除了呼叫 Chat API 建立訊息,Chat 應用程式也可以建立及傳送訊息,回覆使用者互動,例如在使用者將 Chat 應用程式新增至聊天室後,發布歡迎訊息。回覆互動時,Chat 應用程式可以使用其他類型的訊息功能,包括互動式對話方塊和連結預覽介面。如要回覆使用者,Chat 應用程式會同步傳回訊息,而不需呼叫 Chat API。如要瞭解如何傳送訊息來回覆互動,請參閱「透過 Google Chat 應用程式接收及回覆互動」。

Chat 如何顯示及歸因於使用 Chat API 建立的訊息

您可以使用應用程式驗證使用者驗證呼叫 create() 方法。Chat 會根據您使用的驗證類型,以不同方式標示訊息傳送者。

以 Chat 應用程式的身分驗證後,Chat 應用程式就會傳送訊息。

使用應用程式驗證呼叫 create() 方法。
圖 1:透過應用程式驗證,Chat 應用程式會傳送訊息。為標示傳送者不是真人,Chat 會在名稱旁顯示 App

以使用者身分驗證時,Chat 應用程式會代表使用者傳送訊息。即時通訊也會顯示應用程式名稱,將訊息歸因於即時通訊應用程式。

使用使用者驗證呼叫 create() 方法。
圖 2:使用者通過驗證後傳送訊息,Chat 會在使用者名稱旁顯示 Chat 應用程式名稱。

驗證類型也會決定您可以在訊息中加入哪些訊息功能和介面。透過應用程式驗證,Chat 應用程式可以傳送含有 RTF 文字、資訊卡式介面和互動式小工具的訊息。由於 Chat 使用者只能在訊息中傳送文字,因此使用使用者驗證建立訊息時,只能加入文字。如要進一步瞭解 Chat API 提供的訊息功能,請參閱「Google Chat 訊息總覽」。

本指南說明如何使用任一驗證類型,透過 Chat API 傳送訊息。

必要條件

Node.js

Python

Java

Apps Script

以 Chat 應用程式身分傳送訊息

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

透過應用程式驗證傳送的訊息
圖 4 Chat 應用程式傳送的訊息包含文字、資訊卡和配件按鈕。

如要使用應用程式驗證呼叫 CreateMessage() 方法,您必須在要求中指定下列欄位:

  • chat.bot 授權範圍
  • 要在其中發布訊息的 Space 資源。Chat 應用程式必須是該空間的成員。
  • 要建立的 Message 資源。如要定義訊息內容,可以加入 富文字 (text)、 一或多個資訊卡介面 (cardsV2), 或兩者皆是。

視需要加入下列項目:

以下程式碼範例說明 Chat 應用程式如何傳送以 Chat 應用程式身分發布的訊息,其中包含文字、資訊卡,以及訊息底部的可點選按鈕:

Node.js

chat/client-libraries/cloud/create-message-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';  // This sample shows how to create message with app credential async function main() {   // Create a client   const chatClient = createClientWithAppCredentials();    // Initialize request argument(s)   const request = {     // Replace SPACE_NAME here.     parent: 'spaces/SPACE_NAME',     message: {       text:         '👋🌎 Hello world! I created this message by calling ' +         "the Chat API's `messages.create()` method.",       cardsV2: [         {           card: {             header: {               title: 'About this message',               imageUrl:                 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg',             },             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.',                     },                   },                 ],               },             ],           },         },       ],       accessoryWidgets: [         {           buttonList: {             buttons: [               {                 text: 'View documentation',                 icon: {materialIcon: {name: 'link'}},                 onClick: {                   openLink: {                     url: 'https://developers.google.com/workspace/chat/create-messages',                   },                 },               },             ],           },         },       ],     },   };    // Make the request   const response = await chatClient.createMessage(request);    // Handle the response   console.log(response); }  await main();

Python

chat/client-libraries/cloud/create_message_app_cred.py
from authentication_utils import create_client_with_app_credentials from google.apps import chat_v1 as google_chat  # This sample shows how to create message with app credential def create_message_with_app_cred():     # Create a client     client = create_client_with_app_credentials()      # Initialize request argument(s)     request = google_chat.CreateMessageRequest(         # Replace SPACE_NAME here.         parent = "spaces/SPACE_NAME",         message = {             "text": '👋🌎 Hello world! I created this message by calling ' +                     'the Chat API\'s `messages.create()` method.',             "cards_v2" : [{ "card": {                 "header": {                     "title": 'About this message',                     "image_url": 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'                 },                 "sections": [{                     "header": "Contents",                     "widgets": [{ "text_paragraph": {                             "text": '🔡 <b>Text</b> which can include ' +                                     'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'                         }}, { "text_paragraph": {                             "text": '🖼️ A <b>card</b> to display visual elements' +                                     'and request information such as text 🔤, ' +                                     'dates and times 📅, and selections ☑️.'                         }}, { "text_paragraph": {                             "text": '👉🔘 An <b>accessory widget</b> which adds ' +                                     'a button to the bottom of a message.'                         }}                     ]}, {                         "header": "What's next",                         "collapsible": True,                         "widgets": [{ "text_paragraph": {                                 "text": "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."                             }}, { "text_paragraph": {                                 "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."                             }                         }]                     }                 ]             }}],             "accessory_widgets": [{ "button_list": { "buttons": [{                 "text": 'View documentation',                 "icon": { "material_icon": { "name": 'link' }},                 "on_click": { "open_link": {                     "url": 'https://developers.google.com/workspace/chat/create-messages'                 }}             }]}}]         }     )      # Make the request     response = client.create_message(request)      # Handle the response     print(response)  create_message_with_app_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java
import com.google.apps.card.v1.Button; import com.google.apps.card.v1.ButtonList; import com.google.apps.card.v1.Card; import com.google.apps.card.v1.Icon; import com.google.apps.card.v1.MaterialIcon; import com.google.apps.card.v1.OnClick; import com.google.apps.card.v1.OpenLink; import com.google.apps.card.v1.TextParagraph; import com.google.apps.card.v1.Widget; import com.google.apps.card.v1.Card.CardHeader; import com.google.apps.card.v1.Card.Section; import com.google.chat.v1.AccessoryWidget; import com.google.chat.v1.CardWithId; import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.Message;  // This sample shows how to create message with app credential. public class CreateMessageAppCred {    public static void main(String[] args) throws Exception {     try (ChatServiceClient chatServiceClient =         AuthenticationUtils.createClientWithAppCredentials()) {       CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()         // Replace SPACE_NAME here.         .setParent("spaces/SPACE_NAME")         .setMessage(Message.newBuilder()           .setText( "👋🌎 Hello world! I created this message by calling " +                     "the Chat API\'s `messages.create()` method.")           .addCardsV2(CardWithId.newBuilder().setCard(Card.newBuilder()             .setHeader(CardHeader.newBuilder()               .setTitle("About this message")               .setImageUrl("https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg"))             .addSections(Section.newBuilder()               .setHeader("Contents")               .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(                 "🔡 <b>Text</b> which can include " +                 "hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.")))               .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(                 "🖼️ A <b>card</b> to display visual elements " +                 "and request information such as text 🔤, " +                 "dates and times 📅, and selections ☑️.")))               .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(                 "👉🔘 An <b>accessory widget</b> which adds " +                 "a button to the bottom of a message."))))             .addSections(Section.newBuilder()               .setHeader("What's next")               .setCollapsible(true)               .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(                 "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>.")))               .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(                 "🔄 <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."))))))           .addAccessoryWidgets(AccessoryWidget.newBuilder()             .setButtonList(ButtonList.newBuilder()               .addButtons(Button.newBuilder()                 .setText("View documentation")                 .setIcon(Icon.newBuilder()                   .setMaterialIcon(MaterialIcon.newBuilder().setName("link")))                 .setOnClick(OnClick.newBuilder()                   .setOpenLink(OpenLink.newBuilder()                     .setUrl("https://developers.google.com/workspace/chat/create-messages")))))));       Message response = chatServiceClient.createMessage(request.build());        System.out.println(JsonFormat.printer().print(response));     }   } }

Apps Script

chat/advanced-service/Main.gs
/**  * This sample shows how to create message with app credential  *   * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'  * used by service accounts.  */ function createMessageAppCred() {   // Initialize request argument(s)   // TODO(developer): Replace SPACE_NAME here.   const parent = 'spaces/SPACE_NAME';   const message = {     text: '👋🌎 Hello world! I created this message by calling ' +           'the Chat API\'s `messages.create()` method.',     cardsV2 : [{ card: {       header: {         title: 'About this message',         imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'       },       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."             }           }]         }       ]     }}],     accessoryWidgets: [{ buttonList: { buttons: [{       text: 'View documentation',       icon: { materialIcon: { name: 'link' }},       onClick: { openLink: {         url: 'https://developers.google.com/workspace/chat/create-messages'       }}     }]}}]   };   const parameters = {};    // Make the request   const response = Chat.Spaces.Messages.create(     message, parent, parameters, getHeaderWithAppCredentials()   );    // Handle the response   console.log(response); }

如要執行這個範例,請將 SPACE_NAME 替換為空間的 name 欄位中的 ID。您可以呼叫 ListSpaces() 方法或從空間的網址取得 ID。

在郵件底部新增互動式小工具

在本指南的第一個程式碼範例中,Chat 應用程式訊息會在訊息底部顯示可點選的按鈕,也就是配件小工具。配件小工具會顯示在郵件中的任何文字或資訊卡後方。您可以透過這些小工具,提示使用者以多種方式與訊息互動,包括:

  • 評估訊息的準確度或滿意度。
  • 回報訊息或 Google Chat 應用程式的問題。
  • 開啟相關內容的連結,例如文件。
  • 在特定時間內,關閉或暫緩顯示 Google 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 應用程式傳送私人訊息時,訊息會顯示標籤,通知使用者只有他們能查看該訊息。

如要使用 Chat API 私下傳送訊息,請在要求主體中指定 privateMessageViewer 欄位。如要指定使用者,請將值設為代表 Chat 使用者的 User 資源。您也可以使用 User 資源的 name 欄位,如下列範例所示:

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

如要使用這個範例,請將 USER_ID 替換為使用者的專屬 ID,例如 12345678987654321[email protected]。如要進一步瞭解如何指定使用者,請參閱「識別及指定 Google Chat 使用者」。

如要私下傳送訊息,請在要求中省略下列項目:

代表使用者傳送簡訊

本節說明如何使用使用者驗證,代表使用者傳送訊息。如果使用使用者驗證,訊息內容只能包含文字,且必須省略僅適用於 Chat 應用程式的訊息功能,包括資訊卡介面和互動式小工具。

透過使用者驗證傳送的訊息
圖 3. Chat 應用程式代表使用者傳送簡訊。

如要使用使用者驗證呼叫 CreateMessage() 方法,您必須在要求中指定下列欄位:

  • 支援此方法使用者驗證的授權範圍。下列範例使用 chat.messages.create 範圍。
  • 要在其中發布訊息的 Space 資源。已通過驗證的使用者必須是聊天室成員。
  • 要建立的 Message 資源。如要定義訊息內容,請務必加入 text 欄位。

視需要加入下列項目:

  • messageId 欄位,可讓您為訊息命名,以便在其他 API 要求中使用。
  • thread.threadKeymessageReplyOption 欄位,可發起或回覆討論串。如果空間未使用執行緒,系統會忽略這個欄位。

以下程式碼範例說明 Chat 應用程式如何代表已驗證的使用者,在指定空間中傳送訊息:

Node.js

chat/client-libraries/cloud/create-message-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';  const USER_AUTH_OAUTH_SCOPES = [   'https://www.googleapis.com/auth/chat.messages.create', ];  // This sample shows how to create message with user credential async function main() {   // Create a client   const chatClient = await createClientWithUserCredentials(     USER_AUTH_OAUTH_SCOPES,   );    // Initialize request argument(s)   const request = {     // Replace SPACE_NAME here.     parent: 'spaces/SPACE_NAME',     message: {       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>.',     },   };    // Make the request   const response = await chatClient.createMessage(request);    // Handle the response   console.log(response); }  await main();

Python

chat/client-libraries/cloud/create_message_user_cred.py
from authentication_utils import create_client_with_user_credentials from google.apps import chat_v1 as google_chat  SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]  def create_message_with_user_cred():     # Create a client     client = create_client_with_user_credentials(SCOPES)      # Initialize request argument(s)     request = google_chat.CreateMessageRequest(         # Replace SPACE_NAME here.         parent = "spaces/SPACE_NAME",         message = {             "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>.'         }     )      # Make the request     response = client.create_message(request)      # Handle the response     print(response)  create_message_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java
import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.Message;  // This sample shows how to create message with user credential. public class CreateMessageUserCred {    private static final String SCOPE =     "https://www.googleapis.com/auth/chat.messages.create";    public static void main(String[] args) throws Exception {     try (ChatServiceClient chatServiceClient =         AuthenticationUtils.createClientWithUserCredentials(           ImmutableList.of(SCOPE))) {       CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()         // Replace SPACE_NAME here.         .setParent("spaces/SPACE_NAME")         .setMessage(Message.newBuilder()           .setText( "👋🌎 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>."));       Message response = chatServiceClient.createMessage(request.build());        System.out.println(JsonFormat.printer().print(response));     }   } }

Apps Script

chat/advanced-service/Main.gs
/**  * This sample shows how to create message with user credential  *   * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'  * referenced in the manifest file (appsscript.json).  */ function createMessageUserCred() {   // Initialize request argument(s)   // TODO(developer): Replace SPACE_NAME here.   const parent = 'spaces/SPACE_NAME';   const message = {     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>.'   };    // Make the request   const response = Chat.Spaces.Messages.create(message, parent);    // Handle the response   console.log(response); }

如要執行這個範例,請將 SPACE_NAME 替換為空間的 name 欄位中的 ID。您可以呼叫 ListSpaces() 方法或從空間的網址取得 ID。

發起或回覆討論串

如果聊天室使用討論串,您可以指定新訊息要發起討論串,還是回覆現有討論串。

根據預設,使用 Chat API 建立的訊息會啟動新的討論串。如要識別及回覆執行緒,可以在要求中指定執行緒鍵:

如要建立回覆現有討論串的訊息,請按照下列步驟操作:

  • 在要求主體中加入 thread 欄位。如果已設定,您可以指定您建立的 threadKey。否則,您必須使用該執行緒的 name
  • 指定查詢參數 messageReplyOption

下列程式碼範例說明 Chat 應用程式如何代表已驗證的使用者,傳送文字訊息來發起或回覆特定討論串,該討論串由特定聊天室的鍵值識別:

Node.js

chat/client-libraries/cloud/create-message-user-cred-thread-key.js
import {protos} from '@google-apps/chat'; import {createClientWithUserCredentials} from './authentication-utils.js';  const USER_AUTH_OAUTH_SCOPES = [   'https://www.googleapis.com/auth/chat.messages.create', ];  // This sample shows how to create message with user credential with thread key async function main() {   // Create a client   const chatClient = await createClientWithUserCredentials(     USER_AUTH_OAUTH_SCOPES,   );    // Initialize request argument(s)   const request = {     // Replace SPACE_NAME here.     parent: 'spaces/SPACE_NAME',     // Creates the message as a reply to the thread specified by thread_key     // If it fails, the message starts a new thread instead     messageReplyOption:       protos.google.chat.v1.CreateMessageRequest.MessageReplyOption         .REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,     message: {       text: 'Hello with user credential!',       thread: {         // Thread key specifies a thread and is unique to the chat app         // that sets it         threadKey: 'THREAD_KEY',       },     },   };    // Make the request   const response = await chatClient.createMessage(request);    // Handle the response   console.log(response); }  await main();

Python

chat/client-libraries/cloud/create_message_user_cred_thread_key.py
from authentication_utils import create_client_with_user_credentials from google.apps import chat_v1 as google_chat  import google.apps.chat_v1.CreateMessageRequest.MessageReplyOption  SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]  # This sample shows how to create message with user credential with thread key def create_message_with_user_cred_thread_key():     # Create a client     client = create_client_with_user_credentials(SCOPES)      # Initialize request argument(s)     request = google_chat.CreateMessageRequest(         # Replace SPACE_NAME here         parent = "spaces/SPACE_NAME",         # Creates the message as a reply to the thread specified by thread_key.         # If it fails, the message starts a new thread instead.         message_reply_option = MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,         message = {             "text": "Hello with user credential!",             "thread": {                 # Thread key specifies a thread and is unique to the chat app                 # that sets it.                 "thread_key": "THREAD_KEY"             }         }     )      # Make the request     response = client.create_message(request)      # Handle the response     print(response)  create_message_with_user_cred_thread_key()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadKey.java
import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.CreateMessageRequest.MessageReplyOption; import com.google.chat.v1.Message; import com.google.chat.v1.Thread;  // This sample shows how to create message with a thread key with user // credential. public class CreateMessageUserCredThreadKey {    private static final String SCOPE =     "https://www.googleapis.com/auth/chat.messages.create";    public static void main(String[] args) throws Exception {     try (ChatServiceClient chatServiceClient =         AuthenticationUtils.createClientWithUserCredentials(           ImmutableList.of(SCOPE))) {       CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()         // Replace SPACE_NAME here.         .setParent("spaces/SPACE_NAME")         // Creates the message as a reply to the thread specified by thread_key.         // If it fails, the message starts a new thread instead.         .setMessageReplyOption(           MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD)         .setMessage(Message.newBuilder()           .setText("Hello with user credentials!")           // Thread key specifies a thread and is unique to the chat app           // that sets it.           .setThread(Thread.newBuilder().setThreadKey("THREAD_KEY")));       Message response = chatServiceClient.createMessage(request.build());        System.out.println(JsonFormat.printer().print(response));     }   } }

Apps Script

chat/advanced-service/Main.gs
/**  * This sample shows how to create message with user credential with thread key  *   * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'  * referenced in the manifest file (appsscript.json).  */ function createMessageUserCredThreadKey() {   // Initialize request argument(s)   // TODO(developer): Replace SPACE_NAME here.   const parent = 'spaces/SPACE_NAME';   // Creates the message as a reply to the thread specified by thread_key   // If it fails, the message starts a new thread instead   const messageReplyOption = 'REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD';   const message = {     text: 'Hello with user credential!',     thread: {       // Thread key specifies a thread and is unique to the chat app       // that sets it       threadKey: 'THREAD_KEY'     }   };    // Make the request   const response = Chat.Spaces.Messages.create(message, parent, {     messageReplyOption: messageReplyOption   });    // Handle the response   console.log(response); }

如要執行這個範例,請替換下列項目:

  • THREAD_KEY:空間中的現有討論串金鑰,或是討論串的專屬名稱 (如要建立新討論串)。
  • SPACE_NAME:來自聊天室 name 欄位的 ID。您可以呼叫 ListSpaces() 方法或從空間的網址取得 ID。

為訊息命名

如要在日後的 API 呼叫中擷取或指定訊息,可以透過在要求中設定 messageId 欄位來為訊息命名。命名訊息後,您就能指定訊息,不必儲存訊息資源名稱中系統指派的 ID (以 name 欄位表示)。

舉例來說,如要使用 get() 方法擷取訊息,請使用資源名稱指定要擷取的訊息。資源名稱的格式為 spaces/{space}/messages/{message},其中 {message} 代表系統指派的 ID,或是您在建立訊息時設定的自訂名稱。

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

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

  • 開頭為「client-」。舉例來說,client-custom-name 是有效的自訂 ID,但 custom-name 則不是。
  • 最多 63 個字元,只能使用小寫英文字母、數字和連字號。
  • 在空間中不得重複。Chat 應用程式無法為不同訊息使用相同的自訂 ID。

以下程式碼範例說明 Chat 應用程式如何代表已驗證的使用者,將含有 ID 的訊息傳送至指定聊天室:

Node.js

chat/client-libraries/cloud/create-message-user-cred-message-id.js
import {createClientWithUserCredentials} from './authentication-utils.js';  const USER_AUTH_OAUTH_SCOPES = [   'https://www.googleapis.com/auth/chat.messages.create', ];  // This sample shows how to create a message with user credentials and a custom // message id async function main() {   // Create a client   const chatClient = await createClientWithUserCredentials(     USER_AUTH_OAUTH_SCOPES,   );    // Initialize request argument(s)   const request = {     // Replace SPACE_NAME here.     parent: 'spaces/SPACE_NAME',     // Message id lets chat apps get, update or delete a message without needing     // to store the system assigned ID in the message's resource name     messageId: 'client-MESSAGE-ID',     message: {text: 'Hello with user credential!'},   };    // Make the request   const response = await chatClient.createMessage(request);    // Handle the response   console.log(response); }  await main();

Python

chat/client-libraries/cloud/create_message_user_cred_message_id.py
from authentication_utils import create_client_with_user_credentials from google.apps import chat_v1 as google_chat  SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]  # This sample shows how to create message with user credential with message id def create_message_with_user_cred_message_id():     # Create a client     client = create_client_with_user_credentials(SCOPES)      # Initialize request argument(s)     request = google_chat.CreateMessageRequest(         # Replace SPACE_NAME here         parent = "spaces/SPACE_NAME",         # Message id let chat apps get, update or delete a message without needing         # to store the system assigned ID in the message's resource name.         message_id = "client-MESSAGE-ID",         message = {             "text": "Hello with user credential!"         }     )      # Make the request     response = client.create_message(request)      # Handle the response     print(response)  create_message_with_user_cred_message_id()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredMessageId.java
import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.Message;  // This sample shows how to create message with message id specified with user // credential. public class CreateMessageUserCredMessageId {    private static final String SCOPE =     "https://www.googleapis.com/auth/chat.messages.create";    public static void main(String[] args) throws Exception {     try (ChatServiceClient chatServiceClient =         AuthenticationUtils.createClientWithUserCredentials(           ImmutableList.of(SCOPE))) {       CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()         // Replace SPACE_NAME here.         .setParent("spaces/SPACE_NAME")         .setMessage(Message.newBuilder()           .setText("Hello with user credentials!"))         // Message ID lets chat apps get, update or delete a message without         // needing to store the system assigned ID in the message's resource         // name.         .setMessageId("client-MESSAGE-ID");       Message response = chatServiceClient.createMessage(request.build());        System.out.println(JsonFormat.printer().print(response));     }   } }

Apps Script

chat/advanced-service/Main.gs
/**  * This sample shows how to create message with user credential with message id  *   * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'  * referenced in the manifest file (appsscript.json).  */ function createMessageUserCredMessageId() {   // Initialize request argument(s)   // TODO(developer): Replace SPACE_NAME here.   const parent = 'spaces/SPACE_NAME';   // Message id lets chat apps get, update or delete a message without needing   // to store the system assigned ID in the message's resource name   const messageId = 'client-MESSAGE-ID';   const message = { text: 'Hello with user credential!' };    // Make the request   const response = Chat.Spaces.Messages.create(message, parent, {     messageId: messageId   });    // Handle the response   console.log(response); }

如要執行這個範例,請替換下列項目:

  • SPACE_NAME:來自聊天室 name 欄位的 ID。您可以呼叫 ListSpaces() 方法或從空間的網址取得 ID。
  • MESSAGE-ID:訊息名稱,開頭為 custom-。不得與 Chat 應用程式在指定空間中建立的任何其他訊息名稱重複。

引用訊息

您可以呼叫 CreateMessage() (rpc, rest) 並在要求中設定 quotedMessageMetadata (rpc, rest),引用其他訊息。

你可以在討論串或主要對話中引用訊息,但無法引用其他討論串中的訊息。

以下程式碼說明如何建立引用其他訊息的訊息:

Node.js

import {createClientWithUserCredentials} from './authentication-utils.js';  const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];  // This sample shows how to create a message that quotes another message. async function main() {    // Create a client   const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);    // Initialize request argument(s)   const request = {      // TODO(developer): Replace SPACE_NAME .     parent: 'spaces/SPACE_NAME',      message: {       text: 'I am responding to a quoted message!',        // quotedMessageMetadata lets chat apps respond to a message by quoting it.       quotedMessageMetadata: {          // TODO(developer): Replace QUOTED_MESSAGE_NAME         // and QUOTED_MESSAGE_LAST_UPDATE_TIME.         name: 'QUOTED_MESSAGE_NAME',         lastUpdateTime: 'QUOTED_MESSAGE_LAST_UPDATE_TIME'       }     }   };    // Make the request   const response = await chatClient.createMessage(request);    // Handle the response   console.log(response); }  main().catch(console.error); 

Python

from authentication_utils import create_client_with_user_credentials from google.apps import chat_v1 as google_chat from google.protobuf.timestamp_pb2 import Timestamp  SCOPES = ['https://www.googleapis.com/auth/chat.messages.create']  # This sample shows how to create a message that quotes another message. def create_message_quote_message():     '''Creates a message that quotes another message.'''      # Create a client     client = create_client_with_user_credentials(SCOPES)      # Create a timestamp from the RFC-3339 string.     # TODO(developer): Replace QUOTED_MESSAGE_LAST_UPDATE_TIME.     last_update_time = Timestamp()     last_update_time.FromJsonString('QUOTED_MESSAGE_LAST_UPDATE_TIME')      # Initialize request argument(s)     request = google_chat.CreateMessageRequest(          # TODO(developer): Replace SPACE_NAME.         parent='spaces/SPACE_NAME',          # Create the message.         message = google_chat.Message(             text='I am responding to a quoted message!',              # quotedMessageMetadata lets chat apps respond to a message by quoting it.             quoted_message_metadata=google_chat.QuotedMessageMetadata(                  name='QUOTED_MESSAGE_NAME',                 last_update_time=last_update_time             )         )     )      # Make the request     response = client.create_message(request)      # Handle the response     print(response)  create_message_quote_message() 

Java

import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateMessageRequest; import com.google.chat.v1.Message; import com.google.chat.v1.QuotedMessageMetadata; import com.google.protobuf.util.Timestamps; import com.google.workspace.api.chat.samples.utils.AuthenticationUtils; import java.text.ParseException;  // This sample shows how to create a message that quotes another message. public class CreateMessageQuoteMessage {   public static void main(String[] args) throws Exception, ParseException {     // Create a client.     ChatServiceClient chatClient = AuthenticationUtils.createClientWithUserCredentials();      // Initialize request argument(s).     // TODO(developer): Replace SPACE_NAME, QUOTED_MESSAGE_NAME,     // and QUOTED_MESSAGE_LAST_UPDATE_TIME here.     String parent = "spaces/SPACE_NAME";     String quotedMessageName = "QUOTED_MESSAGE_NAME";     String lastUpdateTime = "QUOTED_MESSAGE_LAST_UPDATE_TIME";      QuotedMessageMetadata quotedMessageMetadata =         QuotedMessageMetadata.newBuilder()             .setName(quotedMessageName)             .setLastUpdateTime(Timestamps.parse(lastUpdateTime))             .build();      Message message = Message.newBuilder()         .setText("I am responding to a quoted message!")         .setQuotedMessageMetadata(quotedMessageMetadata)         .build();      CreateMessageRequest request =         CreateMessageRequest.newBuilder()             .setParent(parent)             .setMessage(message)             .build();      // Make the request.     Message response = chatClient.createMessage(request);      // Handle the response.     System.out.println(response);   } } 

Apps Script

/**  * Creates a message that quotes another message.  *  * Relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'  * referenced in the manifest file (appsscript.json).  */ function createMessageQuoteMessage() {    // Initialize request argument(s)   // TODO(developer): Replace SPACE_NAME here.   const parent = 'spaces/SPACE_NAME';    const message = {      // The text content of the message.     text: 'I am responding to a quoted message!',      // quotedMessageMetadata lets chat apps respond to a message by quoting it.     //     // TODO(developer): Replace QUOTED_MESSAGE_NAME     // and QUOTED_MESSAGE_LAST_UPDATE_TIME .     quotedMessageMetadata: {       name: 'QUOTED_MESSAGE_NAME',       lastUpdateTime: 'QUOTED_MESSAGE_LAST_UPDATE_TIME',     }   };    // Make the request   const response = Chat.Spaces.Messages.create(message, parent);    // Handle the response   console.log(response); } 

如要執行這個範例,請替換下列項目:

  • SPACE_NAME:來自聊天室 name 欄位的 ID。您可以呼叫 ListSpaces() (rpcrest) 方法,或從空間的網址取得 ID。
  • QUOTED_MESSAGE_NAME:訊息資源 name (rpcrest),格式為 spaces/{space}/messages/{message},用於引用訊息。
  • QUOTED_MESSAGE_LAST_UPDATE_TIME:要引用訊息的上次更新時間。如果訊息從未經過編輯,則對應 createTime (rpcrest)。如果訊息經過編輯,則對應 lastUpdateTime (rpcrest)。

疑難排解

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

即使 Chat 使用者介面未顯示錯誤訊息,只要開啟 Chat 應用程式的錯誤記錄功能,系統就會提供說明性錯誤訊息和記錄資料,協助您修正錯誤。如需查看、偵錯及修正錯誤的相關協助,請參閱「排解及修正 Google Chat 錯誤」。