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

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

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

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

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

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

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

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

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

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

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

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

בסקירה הכללית על הודעות ב-Google Chat מוסבר בהרחבה על התכונות שקשורות להודעות ב-Chat API.

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

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

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

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

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

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

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

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

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

לשלוח התראות מאולצות או הודעות שקטות

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

  • התראה כפויה: Chat תמיד שולח התראה לנמענים, בלי קשר להגדרת ההתראות שלהם או לסטטוס "נא לא להפריע" (DND). ב-Chat, ההודעה מודגשת ומוקפצת ברשימת הנמענים או ברשימת הבית, ומוצג תג.
  • שליחת הודעה שקטה: ב-Chat לא נשלחות התראות לנמענים. ב-Chat, ההודעה לא גורמת להדגשה או להקפצה של השיחה ברשימת המשתתפים או ברשימת השיחות במסך הבית של הנמענים, ולא מוצג תג. אם ההודעה השקטה היא ההודעה האחרונה בשיחה, התוכן שלה לא מוצג בתקציר בדף הבית.

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

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

להתראות מאולצות ולהודעות שקטות יש את המגבלות הבאות:

  • משתמשים חיצוניים: התראות מאולצות והודעות שקטות לא חלות על משתמשים חיצוניים (אורחים) במרחב. משתמשים חיצוניים מקבלים התראות בהתאם להגדרות שלהם.
  • תיוגים: אי אפשר לתייג משתמשים בהודעות שקטות. אם תתייגו מישהו בהודעה שקטה, התיוג יופיע כטקסט פשוט.
  • שרשורים: אי אפשר להתחיל שרשור או לענות להודעה בשרשור בהודעה שקטה.
  • סוג המרחב המשותף: אי אפשר להשתמש בהתראות כפויות ובהודעות שקטות בצ'אטים אישיים או במרחבים משותפים שבבעלות אנשים שאין להם חשבון Google Workspace.
  • התראות באימייל: הודעות שקטות לא מפעילות התראות באימייל. הודעות עם התראות מאולצות מפעילות התראות באימייל רק אם הן כוללות גם אזכור של משתמש ספציפי.

כדי לאלץ התראה או לשלוח הודעה שקטה, צריך לכלול את השדה createMessageNotificationOptions בבקשה ולהגדיר את notificationType לאחת מהאפשרויות הבאות:

ערך התנהגות
NOTIFICATION_TYPE_FORCE_NOTIFY הצגת התראה.
NOTIFICATION_TYPE_SILENT ההודעה נשלחת בלי התראה.

בדוגמה הבאה מוצג גוף ה-JSON של בקשה לשליחת הודעה עם התראה מאולצת:

{
  "text": "Critical update: the server is down!",
  "createMessageNotificationOptions": {
    "notificationType": "NOTIFICATION_TYPE_FORCE_NOTIFY"
  }
}

שליחת הודעת SMS בשם משתמש

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

ההודעה נשלחה עם אימות משתמש
איור 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);
}

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

ציטוט הודעה

כדי לצטט הודעה אחרת, אפשר להפעיל את 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 של המרחב. כדי לקבל את המזהה, אפשר להפעיל את ה-method‏ 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 מוסבר איך לראות, לנפות באגים ולתקן שגיאות.