Send a message‪

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

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

המשאב Message מייצג הודעת טקסט או כרטיס ב-Google Chat. אפשר create, get, update או delete הודעה ב-Google Chat API על ידי קריאה לשיטות המתאימות. למידע נוסף על הודעות טקסט וכרטיסים, תוכלו לקרוא את הסקירה הכללית על הודעות ב-Google Chat.

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

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

Node.js

Python

  • Python 3.6 ואילך
  • הכלי pip לניהול חבילות
  • ספריות הלקוח העדכניות של Google ל-Python. כדי להתקין או לעדכן אותם, מריצים את הפקודה הבאה בממשק שורת הפקודה:

    pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
    
  • אפליקציית Chat שפורסמה. כדי ליצור ולפרסם אפליקציית Chat, קראו את המאמר איך יוצרים אפליקציית Google Chat.

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

Apps Script

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

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

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

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

שליחה של הודעת טקסט בזמן אמת

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

כדי לשלוח הודעת טקסט כשמשתמש מוסיף את אפליקציית Chat למרחב משותף, אפליקציית Chat מגיבה לאירוע אינטראקציה של ADDED_TO_SPACE. כדי להגיב באמצעות הודעת טקסט לאירועי אינטראקציה של ADDED_TO_SPACE, צריך להשתמש בקוד הבא:

Node.js

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
exports.onMessage = function onMessage(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send(
      'Hello! This function is meant to be used in a Google Chat space.');
  }

  // Send an onboarding message when added to a Chat space
  if(req.body.type === 'ADDED_TO_SPACE') {
    res.json({
      'text': 'Hi, Cymbal at your service. I help you manage your calendar
      from Google Chat. Take a look at your schedule today by typing
      `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To
      learn what else I can do, type `/help`.'
    });
  }
};

Apps Script

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
function onAddToSpace(event) {

  return {
    'text': 'Hi, Cymbal at your service. I help you manage your calendar
    from Google Chat. Take a look at your schedule today by typing
    `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To learn
    what else I can do, type `/help`.'
  }
}

דוגמת הקוד מחזירה את הודעת הטקסט הבאה:

דוגמה להודעת הצטרפות.

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

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

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

  • כשמשתמשים באימות אפליקציות, צריך לציין את היקף ההרשאות chat.bot. כשמשתמשים באימות משתמשים, מציינים את היקף ההרשאות chat.messages.create.
  • קוראים ל-method create במשאב Message.

שליחת הודעת טקסט עם אימות אפליקציות

כדי לשלוח הודעת טקסט באמצעות אימות אפליקציות:

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_create_text_message_app.py.
  2. יש לכלול את הקוד הבא ב-chat_create_text_message_app.py:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. מחליפים את SPACE בשם של המרחב המשותף בקוד. אפשר לקבל אותו מה-method spaces.list() ב-Chat API או מכתובת ה-URL של המרחב המשותף.

  4. בספריית העבודה, בונים ומריצים את הדוגמה:

    python3 chat_create_text_message_app.py
    

ה-Chat API מחזיר מופע של Message עם פרטים על ההודעה שנשלחת.

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

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

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_create_text_message_user.py.
  2. יש לכלול את הקוד הבא ב-chat_create_text_message_user.py:

    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then creates a text message in a Chat space.
        '''
    
        # Start with no credentials.
        creds = None
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                        'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().create(
    
            # The space to create the message in.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE',
    
            # The message to create.
            body={'text': 'Hello, world!'}
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. מחליפים את SPACE בשם של המרחב המשותף בקוד. אפשר לקבל אותו מה-method spaces.list() ב-Chat API או מכתובת ה-URL של המרחב המשותף.

  4. בספריית העבודה, בונים ומריצים את הדוגמה:

    python3 chat_create_text_message_user.py
    

ה-Chat API מחזיר מופע של Message עם פרטים על ההודעה שנשלחת.

שליחת הודעות בכרטיס

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

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

שליחת הודעה בכרטיס בזמן אמת

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

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

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

Node.js

צומת/avatar-app/index.js
/**
 * Google Cloud Function that responds to messages sent from a
 * Google Chat room.
 *
 * @param {Object} req Request sent from Google Chat room
 * @param {Object} res Response to send back
 */
exports.helloChat = function helloChat(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send('Hello! This function is meant to be used in a Google Chat ' +
      'Room.');
  }

  const sender = req.body.message.sender.displayName;
  const image = req.body.message.sender.avatarUrl;

  const data = createMessage(sender, image);

  res.send(data);
};

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} imageUrl the URL for the sender's avatar
 * @return {Object} a card with the user's avatar.
 */
function createMessage(displayName, imageUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`,
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '},
  };

  const avatarImageWidget = {
    image: {imageUrl},
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget,
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

Python

python/avatar-app/main.py
from typing import Any, Mapping

import flask
import functions_framework


# Google Cloud Function that responds to messages sent in
# Google Chat.
#
# @param {Object} req Request sent from Google Chat.
# @param {Object} res Response to send back.
@functions_framework.http
def hello_chat(req: flask.Request) -> Mapping[str, Any]:
  if req.method == "GET":
    return "Hello! This function must be called from Google Chat."

  request_json = req.get_json(silent=True)

  display_name = request_json["message"]["sender"]["displayName"]
  avatar = request_json["message"]["sender"]["avatarUrl"]

  response = create_message(name=display_name, image_url=avatar)

  return response


# Creates a card with two widgets.
# @param {string} name the sender's display name.
# @param {string} image_url the URL for the sender's avatar.
# @return {Object} a card with the user's avatar.
def create_message(name: str, image_url: str) -> Mapping[str, Any]:
  avatar_image_widget = {"image": {"imageUrl": image_url}}
  avatar_text_widget = {"textParagraph": {"text": "Your avatar picture:"}}
  avatar_section = {"widgets": [avatar_text_widget, avatar_image_widget]}

  header = {"title": f"Hello {name}!"}

  cards = {
      "text": "Here's your avatar",
      "cardsV2": [
          {
              "cardId": "avatarCard",
              "card": {
                  "name": "Avatar Card",
                  "header": header,
                  "sections": [avatar_section],
              },
          }
      ]
  }

  return cards

Apps Script

apps-script/avatar-app/hello-chat.gs
/**
 * Responds to a MESSAGE event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onMessage(event) {
  const displayName = event.message.sender.displayName;
  const avatarUrl = event.message.sender.avatarUrl;

  return createMessage(displayName, avatarUrl);
}

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} avatarUrl the URL for the sender's avatar
 * @return {Object} a card with the sender's avatar.
 */
function createMessage(displayName, avatarUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '}
  };

  const avatarImageWidget = {
    image: {imageUrl: avatarUrl}
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

שליחה אסינכרונית של הודעת כרטיס

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

  • כשמשתמשים באימות אפליקציות, צריך לציין את היקף ההרשאות chat.bot. אי אפשר לשלוח הודעות בכרטיס עם אימות משתמשים.
  • קוראים ל-method create במשאב Message.

לפניכם דוגמה להודעה עם כרטיס:

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

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

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_create_card_message.py.
  2. יש לכלול את הקוד הבא ב-chat_create_card_message.py:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body=
        {
          'cardsV2': [{
            'cardId': 'createCardMessage',
            'card': {
              'header': {
                'title': 'A card message!',
                'subtitle': 'Created with the Chat API',
                'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
                'imageType': 'CIRCLE'
              },
              'sections': [
                {
                  'widgets': [
                    {
                      'buttonList': {
                        'buttons': [
                          {
                            'text': 'Read the docs!',
                            'onClick': {
                              'openLink': {
                                'url': 'https://developers.google.com/chat'
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }]
        }
    
    ).execute()
    
    print(result)
    
  3. מחליפים את SPACE בשם של המרחב המשותף בקוד. אפשר לקבל אותו מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.

  4. בספריית העבודה, בונים ומריצים את הדוגמה:

    python3 chat_create_card_message.py
    

התחלה של שרשור הודעות או מענה להן

כדי להתחיל שרשור הודעות, צריך לשלוח הודעה ולהשאיר את השדה thread.name ריק. Google Chat מאכלס אותו כשיוצרים את השרשור. אם רוצים להתאים אישית את שם ה-thread, צריך לציין את השדה thread.threadKey.

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

אם לא נמצא שרשור תואם, אפשר להגדיר אם ההודעה תתחיל שרשור חדש או תיכשל בפרסום, באמצעות השדה messageReplyOption.

כך מתחילים שרשור או משיבים לשרשור שבו השדה threadKey מוגדר בתור nameOfThread:

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_create_message_thread.py.
  2. יש לכלול את הקוד הבא ב-chat_create_message_thread.py:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Whether to start a thread or reply to an existing one.
        #
        # Required when threading is enabled in a space unless starting a
        # thread.  Ignored in other space types. Threading is enabled when
        # space.spaceThreadingState is THREADED_MESSAGES.
        #
        # REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD replies to an existing thread
        # if one exists, otherwise it starts a new one.
        messageReplyOption='REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD',
    
        # The message body.
        body={
    
            # The message to create.
            'text': 'Start or reply to another message in a thread!',
    
            # The thread to start or reply to.
            'thread': {
                'threadKey': 'nameOfThread'
            }
        }
    
    ).execute()
    
    print(result)
    
  3. מחליפים את SPACE בשם של המרחב המשותף בקוד. אפשר לקבל אותו מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.

  4. בספריית העבודה, בונים ומריצים את הדוגמה:

    python3 chat_create_message_thread.py
    

ה-Chat API מחזיר מופע של Message עם פרטים על ההודעה שנשלחת.

שליחת הודעה ומתן שם להודעות

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

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

על שמות מותאמים אישית יש לעמוד בדרישות הבאות:

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

כדי לשלוח הודעה ולתת לה שם:

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_create_named_message.py.
  2. יש לכלול את הקוד הבא ב-chat_create_named_message.py:

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message with a custom name.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Custom name for the message used to facilitate later operations.
        messageId='client-custom-name',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. מחליפים את SPACE בשם של המרחב המשותף בקוד. אפשר לקבל אותו מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.

  4. בספריית העבודה, בונים ומריצים את הדוגמה:

    python3 chat_create_named_message.py
    

ה-Chat API מחזיר מופע של Message עם פרטים על ההודעה שנשלחת.

פתרון בעיות

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

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