שליחת הודעות באמצעות Google Chat API

במדריך הזה מוסבר איך להשתמש בשיטה create() במשאב Message של Google Chat API כדי לבצע את הפעולות הבאות:

  • שליחת הודעות שמכילות טקסט, כרטיסים ווידג'טים אינטראקטיביים.
  • שליחת הודעות באופן פרטי למשתמש ספציפי ב-Chat.
  • להתחיל שרשור או לענות לשרשור.
  • נותנים שם להודעה, כדי שתוכלו לציין אותה בבקשות אחרות ל-Chat API.

הגודל המקסימלי של ההודעה (כולל טקסט או כרטיסים) הוא 32,000 בייטים. כדי לשלוח הודעה שחורגת מהגודל הזה, אפליקציית Chat צריכה לשלוח במקום זאת כמה הודעות.

בנוסף לקריאה ל-Chat API כדי ליצור הודעות, אפליקציות ל-Chat יכולות ליצור ולשלוח הודעות כדי להגיב לאינטראקציות של משתמשים, כמו פרסום הודעת פתיחה אחרי שמשתמש מוסיף את האפליקציה ל-Chat למרחב. כשמשיבים לאינטראקציות, אפליקציות צ'אט יכולות להשתמש בסוגים אחרים של תכונות העברת הודעות, כולל דיאלוגים אינטראקטיביים וממשקי תצוגה מקדימה של קישורים. כדי לענות למשתמש, אפליקציית Chat מחזירה את ההודעה באופן סינכרוני, בלי לקרוא ל-Chat API. כדי לקבל מידע על שליחת הודעות בתגובה לאינטראקציות, אפשר לעיין במאמר קבלת תגובות לאינטראקציות עם אפליקציית Google Chat.

איך מוצגות ב-Chat הודעות שנוצרו באמצעות Chat API

אפשר להתקשר לשיטת create() באמצעות אימות אפליקציה ואימות משתמש. ב-Chat, השיוך של שולח ההודעה משתנה בהתאם לסוג האימות שבו אתם משתמשים.

כשמבצעים אימות כאפליקציית Chat, ההודעה נשלחת מאפליקציית Chat.

שליחת קריאה לשיטה create()‎ עם אימות אפליקציה.
תרשים 1: כשמשתמשים באימות אפליקציה, אפליקציית Chat שולחת את ההודעה. כדי לציין שהשולח הוא לא אדם, ליד השם שלו מופיע הסמל App ב-Chat.

כשמבצעים אימות כמשתמש, אפליקציית Chat שולחת את ההודעה בשם המשתמש. בנוסף, ב-Chat מופיע שם האפליקציה כדי לציין שהיא שלחה את ההודעה.

קוראים לשיטת create()‎ עם אימות משתמש.
איור 2: באימות משתמשים, המשתמש שולח את ההודעה, וב-Chat מוצג השם של אפליקציית Chat ליד השם של המשתמש.

סוג האימות קובע גם אילו תכונות וממשקים של הודעות אפשר לכלול בהודעה. באמצעות אימות אפליקציות, אפליקציות ל-Chat יכולות לשלוח הודעות שמכילות טקסט עשיר, ממשקים מבוססי-כרטיסים ווידג'טים אינטראקטיביים. מכיוון שמשתמשי 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); }  main().catch(console.error);

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 של המרחב. אפשר לקבל את המזהה על ידי הפעלת השיטה ListSpaces() או מכתובת ה-URL של המרחב.

הוספת ווידג'טים אינטראקטיביים לחלק התחתון של ההודעה

בדוגמת הקוד הראשונה במדריך הזה, ההודעה באפליקציית הצ'אט כוללת כפתור שאפשר ללחוץ עליו בתחתית ההודעה, שנקרא ווידג'ט של אביזר. ווידג'טים של אביזרים מופיעים אחרי כל טקסט או כרטיסים בהודעה. אתם יכולים להשתמש בווידג'טים האלה כדי לעודד את המשתמשים ליצור אינטראקציה עם המסר שלכם בדרכים רבות, כולל:

  • לדרג את הדיוק או את רמת שביעות הרצון מההודעה.
  • מדווחים על בעיה בהודעה או באפליקציית Chat.
  • פותחים קישור לתוכן קשור, כמו תיעוד.
  • אפשר לסגור או להשהות הודעות דומות מאפליקציית Chat למשך תקופה מסוימת.

כדי להוסיף ווידג'טים של אביזרים, צריך לכלול את השדה accessoryWidgets[] בגוף הבקשה ולציין ווידג'ט אחד או יותר שרוצים לכלול.

בתמונה הבאה מוצגת אפליקציית Chat שמצרפת לווידג'טים של אביזרים להודעת טקסט, כדי שהמשתמשים יוכלו לדרג את החוויה שלהם עם אפליקציית Chat.

ווידג&#39;ט של אביזרים.
איור 5: הודעה באפליקציה ל-Chat עם טקסט ווידג'טים של אביזרים.

בדוגמה הבאה מוצג גוף הבקשה שיוצרת הודעת טקסט עם שני לחצני אביזר. כשמשתמש לוחץ על לחצן, הפונקציה המתאימה (למשל 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 בגוף הבקשה. כדי לציין את המשתמש, מגדירים את הערך למשאב User שמייצג את המשתמש ב-Chat. אפשר גם להשתמש בשדה name של מקור User, כמו בדוגמה הבאה:

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

כדי להשתמש בדוגמה הזו, מחליפים את USER_ID במזהה ייחודי של המשתמש, כמו 12345678987654321 או [email protected]. מידע נוסף על ציון משתמשים זמין במאמר זיהוי וציון של משתמשי Google Chat.

כדי לשלוח הודעה באופן פרטי, צריך להשמיט מהבקשה את הפרטים הבאים:

שליחת הודעת טקסט בשם משתמש

בקטע הזה מוסבר איך לשלוח הודעות בשם משתמש באמצעות אימות משתמש. באימות משתמשים, תוכן ההודעה יכול לכלול רק טקסט ואסור לכלול תכונות של העברת הודעות שזמינות רק באפליקציות ל-Chat, כולל ממשקי כרטיסים ווידג'טים אינטראקטיביים.

הודעה שנשלחה עם אימות משתמש
איור 3. אפליקציית Chat שולחת הודעת טקסט בשם משתמש.

כדי לקרוא לשיטה CreateMessage() באמצעות אימות משתמשים, צריך לציין את השדות הבאים בבקשה:

  • היקף הרשאה שתומך באימות משתמשים עבור השיטה הזו. בדוגמה הבאה נעשה שימוש בהיקף chat.messages.create.
  • מקור Space שבו רוצים לפרסם את ההודעה. המשתמש המאומת צריך להיות חבר במרחב.
  • משאב Message שצריך ליצור. כדי להגדיר את תוכן ההודעה, צריך לכלול את השדה text.

אפשר גם לכלול את הפרטים הבאים:

בדוגמת הקוד הבאה אפשר לראות איך אפליקציית 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); }  main().catch(console.error);

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 של המרחב. אפשר לקבל את המזהה על ידי הפעלת השיטה ListSpaces() או מכתובת ה-URL של המרחב.

התחלת שרשור או הוספת תשובה לשרשור

במרחבים שבהם השיחות מחולקות לשרשורים, אתם יכולים לציין אם הודעה חדשה תתחיל שרשור או תהיה תשובה לשרשור קיים.

כברירת מחדל, הודעות שנוצרות באמצעות Chat API מתחילות שרשור חדש. כדי שתוכלו לזהות את השרשור ולהשיב לו מאוחר יותר, אתם יכולים לציין מפתח שרשור בבקשה:

  • בגוף הבקשה, מציינים את השדה thread.threadKey.
  • מציינים את פרמטר השאילתה messageReplyOption כדי לקבוע מה קורה אם המפתח כבר קיים.

כדי ליצור הודעה שמוסיפה תשובה לשרשור קיים:

  • בגוף הבקשה, מציינים את השדה thread. אם הגדרתם, תוכלו לציין את threadKey שיצרתם. בכל מקרה אחר, צריך להשתמש nameבנושא של השרשור.
  • מציינים את פרמטר השאילתה messageReplyOption.

הקוד הבא מציג דוגמה לאופן שבו אפליקציית Chat יכולה לשלוח הודעת טקסט שמתחילה או מגיבה לשרשור נתון שמזוהה על ידי מפתח של מרחב נתון בשם משתמש מאומת:

Node.js

chat/client-libraries/cloud/create-message-user-cred-thread-key.js
import {createClientWithUserCredentials} from './authentication-utils.js'; const {MessageReplyOption} = require('@google-apps/chat').protos.google.chat.v1.CreateMessageRequest;  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: 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); }  main().catch(console.error);

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 של המרחב. אפשר לקבל את המזהה על ידי הפעלת השיטה ListSpaces() או מכתובת ה-URL של המרחב.

איך נותנים שם להודעה

כדי לאחזר או לציין הודעה בקריאות עתידיות ל-API, אפשר לתת שם להודעה על ידי הגדרת השדה messageId בבקשה. כשנותנים שם להודעה, אפשר לציין את ההודעה בלי לשמור את המזהה שהמערכת הקצתה לה מתוך שם המשאב של ההודעה (שמוצג בשדה name).

לדוגמה, כדי לאחזר הודעה באמצעות השיטה get(), צריך להשתמש בשם המשאב כדי לציין איזו הודעה לאחזר. שם המשאב מעוצב כ-spaces/{space}/messages/{message}, כאשר {message} מייצג את המזהה שהוקצה על ידי המערכת או את השם המותאם אישית שהגדרתם כשנוצר ההודעה.

כדי לתת שם להודעה, מציינים מזהה מותאם אישית בשדה messageId כשיוצרים את ההודעה. הערך בשדה messageId מוגדר בשדה clientAssignedMessageId של המשאב Message.

אפשר לתת שם להודעה רק כשיוצרים אותה. אי אפשר לתת שם למזהה בהתאמה אישית או לשנות אותו בהודעות קיימות. המזהה המותאם אישית צריך לעמוד בדרישות הבאות:

  • מתחיל ב-client-. לדוגמה, client-custom-name הוא מזהה מותאם אישית תקין, אבל custom-name לא.
  • השם יכול להכיל עד 63 תווים, רק אותיות קטנות, מספרים ומקפים.
  • ייחודי במרחב. אפליקציית Chat לא יכולה להשתמש באותו מזהה מותאם אישית להודעות שונות.

בדוגמת הקוד הבאה אפשר לראות איך אפליקציית Chat יכולה לשלוח הודעת טקסט עם מזהה למרחב מסוים בשם משתמש מאומת:

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 message with user credential with 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); }  main().catch(console.error);

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 של המרחב. אפשר לקבל את המזהה על ידי הפעלת השיטה ListSpaces() או מכתובת ה-URL של המרחב.
  • 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 של המרחב. אפשר לקבל את המזהה באמצעות קריאה לשיטה ListSpaces() (rpc, rest) או מכתובת ה-URL של המרחב.
  • QUOTED_MESSAGE_NAME: משאב ההודעה name (rpc, rest) של ההודעה שרוצים לצטט בפורמט spaces/{space}/messages/{message}.
  • QUOTED_MESSAGE_LAST_UPDATE_TIME: חותמת הזמן של העדכון האחרון של ההודעה שרוצים לצטט. אם ההודעה לא נערכה אף פעם, הערך שלה תואם לערך של createTime (rpc, ‏ rest). אם ההודעה נערכה, הערך שלה תואם לערך של lastUpdateTime (rpc, ‏ rest).

פתרון בעיות

כשמוחזרת שגיאה מאפליקציית Google Chat או מכרטיס, מוצגת בממשק של Chat ההודעה 'משהו השתבש'. או 'לא ניתן לעבד את הבקשה שלך'. לפעמים בממשק המשתמש של Chat לא מוצגת הודעת שגיאה, אבל אפליקציית Chat או הכרטיס מפיקים תוצאה לא צפויה. לדוגמה, יכול להיות שהודעה בכרטיס לא תופיע.

יכול להיות שלא תוצג הודעת שגיאה בממשק המשתמש של Chat, אבל אם הפעלתם את רישום השגיאות באפליקציות של Chat, תוכלו לראות הודעות שגיאה תיאוריות ונתוני יומן שיעזרו לכם לתקן את השגיאות. לקבלת עזרה בצפייה בשגיאות, באיתור באגים ובתיקון שלהן, אפשר לעיין במאמר פתרון בעיות ב-Google Chat.