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

במדריך הזה מוסבר איך לקרוא ל-API של Google Chat messages.create() לביצוע אחת מהפעולות הבאות:

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

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

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

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

אפשר לבצע קריאה ל-method messages.create() באמצעות אימות אפליקציות ואימות משתמשים. אפליקציית Chat משייכת את שולח ההודעה באופן שונה בהתאם לסוג האימות שבו אתם משתמשים.

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

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

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

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

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

במדריך הזה מוסבר איך להשתמש בכל אחד מסוגי האימות כדי לשלוח הודעה באמצעות Chat API.

דרישות מוקדמות

Node.js

Python

Java

Apps Script

שליחת הודעה בתור אפליקציית Chat

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

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

כדי להפעיל את messages.create() באמצעות אימות אפליקציות, צריך לציין השדות הבאים בבקשה:

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

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

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

  • מה מידת הדיוק או שביעות הרצון של הודעה?
  • מדווחים על בעיה בהודעה או באפליקציית 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 API, צריך לציין את privateMessageViewer בגוף הבקשה. כדי לציין את המשתמש, צריך להגדיר את הערך כ- משאב User מייצג את המשתמש ב-Chat. אפשר גם להשתמש השדה name של משאב User, כמו בדוגמה הבאה:

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

כדי להשתמש בדוגמה הזו, צריך להחליף את USER_ID עם מזהה ייחודי של המשתמש, כמו 12345678987654321 או hao@cymbalgroup.com. למידע נוסף על ציון משתמשים, ראה זיהוי וציון משתמשים ב-Google Chat.

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

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

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

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

כדי להפעיל את messages.create() באמצעות אימות משתמש, צריך לציין את השדות הבאים בבקשה:

  • היקף ההרשאה שתומך באימות משתמשים בשיטה הזו. הדוגמה הבאה משתמשת ההיקף 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 השדה הזה. אפשר לקבל את התעודה המזהה בטלפון שיטת spaces.list() או מכתובת ה-URL של המרחב המשותף.

התחלת שרשור או כתיבת תשובה בשרשור

במרחבים משותפים שבהם נעשה שימוש בשרשורים: אפשר להגדיר אם הודעה חדשה תתחיל שרשור או תענה בשרשור קיים.

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

  • בגוף הבקשה, יש לציין את 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 השדה הזה. אפשר לקבל את התעודה המזהה בטלפון שיטת spaces.list() או מכתובת ה-URL של המרחב המשותף.

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

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

לדוגמה, כדי לאחזר הודעה באמצעות ה-method 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 השדה הזה. אפשר לקבל את התעודה המזהה בטלפון שיטת spaces.list() או מכתובת ה-URL של המרחב המשותף.
  • MESSAGE-ID: שם ההודעה שמתחילה עם custom-. חייב להיות ייחודי משמות אחרים של הודעות שנוצרו על ידי אפליקציית Chat במרחב המשותף שצוין.

פתרון בעיות

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

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