איך מעדכנים הודעות?

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

Chat API תומך גם בשיטה update, אבל מומלץ מאוד לקרוא ל-method patch, כי היא משתמשת בבקשת HTTP PATCH בזמן ש-update משתמש בבקשת HTTP PUT. למידע נוסף, קראו את הקטע PATCH ו-PUT של AIP-134.

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

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

Python

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

    pip3 install --upgrade google-api-python-client google-auth-oauthlib google-auth
    
  • פרויקט ב-Google Cloud עם ממשק Google Chat API פעיל ומוגדר. במאמר איך יוצרים אפליקציה ל-Google Chat מוסבר איך עושים זאת.
  • אילו הרשאות הוגדרו לאפליקציית Chat:

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

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

  • היקף ההרשאה של chat.messages.
  • name של ההודעה שיש לעדכן.
  • updateMask='text'
  • body שמציין את ההודעה המעודכנת.

אם ההודעה המעודכנת היא הודעת כרטיס, הודעת הטקסט מצורפת להודעה בכרטיס (שממשיכה להופיע).

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

Python

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

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    
    # 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"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates a message.
        '''
    
        # 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)
    
        # Update a Chat message.
        result = chat.spaces().messages().patch(
    
          # The message to update, and the updated message.
          #
          # Replace SPACE with a space name.
          # Obtain the space name from the spaces resource of Chat API,
          # or from a space's URL.
          #
          # Replace MESSAGE with a message name.
          # Obtain the message name from the response body returned
          # after creating a message asynchronously with Chat REST API.
          name='spaces/SPACE/messages/MESSAGE',
          updateMask='text',
          body={'text': 'Updated message!'}
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. בקוד, מחליפים את מה שכתוב בשדות הבאים:

    • SPACE: שם למרחב המשותף, שאותו אפשר לקבל מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.
    • MESSAGE: שם ההודעה, שאותו אפשר לקבל מגוף התשובה שהוחזר אחרי שיצרתם הודעה באופן אסינכרוני באמצעות Chat API, או באמצעות השם המותאם אישית שהוקצה להודעה כשיוצרים אותה.
  4. בספריית העבודה, יוצרים ומריצים את הדוגמה:

    python3 chat_update_text_message_user.py
    

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

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

  • היקף ההרשאה של chat.bot.
  • name של ההודעה שיש לעדכן.
  • updateMask='text'
  • body שמציין את ההודעה המעודכנת.

אם ההודעה המעודכנת היא הודעת כרטיס, הודעת הטקסט מצורפת להודעה בכרטיס (שממשיכה להופיע).

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

Python

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

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = (
        service_account.Credentials.from_service_account_file('credentials.json')
        .with_scopes(SCOPES)
    )
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Update a Chat message.
    result = chat.spaces().messages().patch(
    
      # The message to update, and the updated message.
      #
      # Replace SPACE with a space name.
      # Obtain the space name from the spaces resource of Chat API,
      # or from a space's URL.
      #
      # Replace MESSAGE with a message name.
      # Obtain the message name from the response body returned
      # after creating a message asynchronously with Chat REST API.
      name='spaces/SPACE/messages/MESSAGE',
      updateMask='text',
      body={'text': 'Updated message!'}
    
    ).execute()
    
    # Print Chat API's response in your command line interface.
    print(result)
    
  3. בקוד, מחליפים את מה שכתוב בשדות הבאים:

    • SPACE: שם למרחב המשותף, שאותו אפשר לקבל מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.
    • MESSAGE: שם ההודעה, שאותו אפשר לקבל מגוף התשובה שהוחזר אחרי שיצרתם הודעה באופן אסינכרוני באמצעות Chat API, או באמצעות השם המותאם אישית שהוקצה להודעה כשיוצרים אותה.
  4. בספריית העבודה, יוצרים ומריצים את הדוגמה:

    python3 chat_update_text_message_app.py
    

עדכון הודעת כרטיס או צירוף הודעת כרטיס להודעת טקסט

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

  • היקף ההרשאה של chat.bot. כדי לעדכן הודעה בכרטיס, צריך אימות אפליקציות.
  • name של ההודעה שיש לעדכן.
  • updateMask='cardsV2'
  • body שמציין את ההודעה המעודכנת.

אם ההודעה המעודכנת היא הודעת טקסט, מצורף כרטיס להודעת הטקסט (שממשיכת להופיע). אם ההודעה המעודכנת היא כרטיס, הכרטיס המוצג מתעדכן.

כך מעדכנים הודעה להודעת כרטיס:

Python

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

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = (
        service_account.Credentials.from_service_account_file('credentials.json')
        .with_scopes(SCOPES)
    )
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Update a Chat message.
    result = chat.spaces().messages().patch(
    
      # The message to update, and the updated message.
      #
      # Replace SPACE with a space name.
      # Obtain the space name from the spaces resource of Chat API,
      # or from a space's URL.
      #
      # Replace MESSAGE with a message name.
      # Obtain the message name from the response body returned
      # after creating a message asynchronously with Chat REST API.
      name='spaces/SPACE/messages/MESSAGE',
      updateMask='cardsV2',
      body=
      {
        'cardsV2': [{
          'cardId': 'updateCardMessage',
          'card': {
            'header': {
              'title': 'An Updated Card Message!',
              'subtitle': 'Updated with Chat REST 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 Chat API's response in your command line interface.
    print(result)
    
  3. בקוד, מחליפים את מה שכתוב בשדות הבאים:

    • SPACE: שם למרחב המשותף, שאותו אפשר לקבל מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.

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

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

    python3 chat_update_card_message.py
    

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

עדכון הודעה עם כמה נתיבי שדות בו-זמנית

כשמעדכנים הודעה, אפשר לעדכן כמה נתיבים של שדות הודעה בו-זמנית. לדוגמה, בבקשה לעדכון של הודעת עדכון, אתם יכולים לציין שינוי בנתיב השדה text ו-cardsv2 בו-זמנית, וכך גם הטקסט וגם הכרטיס של ההודעה יעודכנו. אם ההודעה כוללת רק טקסט ללא כרטיס, יתווסף כרטיס להודעה. מידע נוסף על נתיבי השדות הנתמכים זמין במאמר פרמטרים של updateMask.

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

  • היקף ההרשאה של chat.messages.
  • name של ההודעה שיש לעדכן.
  • השדה updateMask שמציין את הנתיבים של שדות ההודעה שצריך לעדכן, מופרדים על ידי פסיקים: updateMask='text', 'cardsV2'.

  • body שמציין את ההודעה המעודכנת, כולל כל נתיבי השדות המעודכנים.

כך מעדכנים את נתיבי השדות text ו-cardsV2 בהודעה באמצעות אימות משתמשים:

Python

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

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    
    # 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"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates a message.
        '''
    
        # 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)
    
        # Update a Chat message.
        result = chat.spaces().messages().patch(
    
          # The message to update, and the updated message.
          #
          # Replace SPACE with a space name.
          # Obtain the space name from the spaces resource of Chat API,
          # or from a space's URL.
          #
          # Replace MESSAGE with a message name.
          # Obtain the message name from the response body returned
          # after creating a message asynchronously with Chat REST API.
          name='spaces/SPACE/messages/MESSAGE',
          updateMask='text,cardsV2',
          body=
          {'text': 'Updated message!',
                'cardsV2': [{
                  'cardId': 'updateCardMessage',
                  'card': {
                    'header': {
                      'title': 'An Updated Card Message!',
                      'subtitle': 'Updated with Chat REST 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()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. בקוד, מחליפים את מה שכתוב בשדות הבאים:

    • SPACE: שם למרחב המשותף, שאותו אפשר לקבל מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.
    • MESSAGE: שם ההודעה, שאותו אפשר לקבל מגוף התשובה שהוחזר אחרי שיצרתם הודעה באופן אסינכרוני באמצעות Chat API, או באמצעות השם המותאם אישית שהוקצה להודעה כשיוצרים אותה.
  4. בספריית העבודה, יוצרים ומריצים את הדוגמה:

    python3 chat_update_text_message_user.py