Aggiornare un messaggio

Questa guida spiega come utilizzare il metodo patch nella risorsa Message dell'API Google Chat per aggiornare un SMS o un messaggio di schede in uno spazio. Aggiorna un messaggio per modificare gli attributi del messaggio, come il testo scritto o i contenuti di una scheda. Puoi anche anteporre un messaggio a un messaggio o aggiungere una scheda a un SMS.

L'API Chat supporta anche il metodo update, ma ti consigliamo vivamente di chiamare il metodo patch perché utilizza una richiesta HTTP PATCH, mentre update utilizza una richiesta HTTPPUT. Per scoprire di più, consulta la sezione PATCH e PUT dell'AIP-134.

La risorsa Message rappresenta un messaggio di testo o scheda in Google Chat. Puoi create, get, update o delete un messaggio nell'API Google Chat chiamando i metodi corrispondenti. Per saperne di più sui messaggi di testo e delle schede, consulta la panoramica dei messaggi di Google Chat.

Prerequisiti

Python

  • Python 3.6 o versioni successive
  • Lo strumento di gestione dei pacchetti pip
  • Le librerie client di Google più recenti per Python. Per installarli o aggiornarli, esegui questo comando nell'interfaccia a riga di comando:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib google-auth
    
  • Un progetto Google Cloud in cui l'API Google Chat è abilitata e configurata. Per i passaggi da seguire, consulta Creare un'app Google Chat.
  • Autorizzazione configurata per l'app di Chat:

Aggiorna un SMS o anteponi un SMS a un messaggio con scheda, con l'autenticazione utente

Per aggiornare un messaggio di testo con autenticazione utente, trasmetti quanto segue nella richiesta:

  • L'ambito dell'autorizzazione chat.messages.
  • Il name del messaggio da aggiornare.
  • updateMask='text'
  • Un elemento body che specifica il messaggio aggiornato.

Se il messaggio aggiornato è un messaggio con scheda, l'SMS viene anteposto al messaggio della scheda (che continua a essere visualizzato).

Ecco come aggiornare un messaggio di testo o anteporre un SMS a un messaggio con scheda con l'autenticazione dell'utente:

Python

  1. Nella directory di lavoro, crea un file denominato chat_update_text_message_user.py.
  2. Includi il seguente codice in 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. Sostituisci quanto segue nel codice:

    • SPACE: il nome di uno spazio, che puoi ottenere dal metodo spaces.list nell'API Chat o dall'URL di uno spazio.
    • MESSAGE: nome del messaggio, che puoi ottenere dal corpo della risposta restituito dopo aver creato un messaggio in modo asincrono con l'API Chat o con il nome personalizzato assegnato al messaggio al momento della creazione.
  4. Nella directory di lavoro, crea ed esegui l'esempio:

    python3 chat_update_text_message_user.py
    

Aggiorna un SMS o anteponi un SMS a un messaggio con scheda, con l'autenticazione dell'app

Per aggiornare un messaggio di testo con autenticazione app, trasmetti quanto segue nella richiesta:

  • L'ambito dell'autorizzazione chat.bot.
  • Il name del messaggio da aggiornare.
  • updateMask='text'
  • Un elemento body che specifica il messaggio aggiornato.

Se il messaggio aggiornato è un messaggio con scheda, l'SMS viene anteposto al messaggio della scheda (che continua a essere visualizzato).

Per aggiornare un messaggio di testo in un SMS o anteporre un SMS a un messaggio con scheda con l'autenticazione delle app:

Python

  1. Nella directory di lavoro, crea un file denominato chat_update_text_message_app.py.
  2. Includi il seguente codice in 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. Sostituisci quanto segue nel codice:

    • SPACE: il nome di uno spazio, che puoi ottenere dal metodo spaces.list nell'API Chat o dall'URL di uno spazio.
    • MESSAGE: nome del messaggio, che puoi ottenere dal corpo della risposta restituito dopo aver creato un messaggio in modo asincrono con l'API Chat o con il nome personalizzato assegnato al messaggio al momento della creazione.
  4. Nella directory di lavoro, crea ed esegui l'esempio:

    python3 chat_update_text_message_app.py
    

Aggiorna un messaggio di carte o aggiungi un messaggio di carte a un SMS

Per aggiornare un messaggio della scheda, trasmetti quanto segue nella richiesta:

  • L'ambito dell'autorizzazione chat.bot. Per aggiornare un messaggio della carta è necessaria l'autenticazione delle app.
  • Il name del messaggio da aggiornare.
  • updateMask='cardsV2'
  • Un elemento body che specifica il messaggio aggiornato.

Se il messaggio aggiornato è un messaggio di testo, al messaggio viene aggiunta una scheda (che continua a essere visualizzata). Se il messaggio aggiornato è di per sé una scheda, la scheda visualizzata viene aggiornata.

Per convertire un messaggio in un messaggio con scheda:

Python

  1. Nella directory di lavoro, crea un file denominato chat_update_card_message.py.
  2. Includi il seguente codice in 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. Sostituisci quanto segue nel codice:

    • SPACE: il nome di uno spazio, che puoi ottenere dal metodo spaces.list nell'API Chat o dall'URL di uno spazio.

    • MESSAGE: nome del messaggio, che puoi ottenere dal corpo della risposta restituito dopo aver creato un messaggio in modo asincrono con l'API Chat o con il nome personalizzato assegnato al messaggio al momento della creazione.

  4. Nella directory di lavoro, crea ed esegui l'esempio:

    python3 chat_update_card_message.py
    

L'API Chat restituisce un'istanza di Message che descrive in dettaglio il messaggio aggiornato.

Aggiornare un messaggio con più percorsi di campo contemporaneamente

Quando un messaggio viene aggiornato, puoi aggiornare contemporaneamente più percorsi di campi del messaggio. Ad esempio, in una richiesta di messaggio di aggiornamento, puoi specificare contemporaneamente una modifica ai percorsi dei campi text e cardsv2, in modo da aggiornare sia il testo sia la scheda del messaggio. Se il messaggio include solo testo e nessuna scheda, viene aggiunta una scheda al messaggio. Per ulteriori informazioni sui percorsi dei campi supportati, consulta la sezione Parametri updateMask.

Per aggiornare sia text che card di un messaggio con autenticazione utente, trasmetti quanto segue nella richiesta:

  • L'ambito dell'autorizzazione chat.messages.
  • Il name del messaggio da aggiornare.
  • Un updateMask che specifica i percorsi dei campi del messaggio da aggiornare, separati da virgole: updateMask='text', 'cardsV2'.

  • Un body che specifica il messaggio aggiornato, inclusi tutti i percorsi dei campi aggiornati.

Ecco come aggiornare i percorsi dei campi text e cardsV2 in un messaggio con autenticazione utente:

Python

  1. Nella directory di lavoro, crea un file denominato chat_update_text_message_user.py.
  2. Includi il seguente codice in 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. Sostituisci quanto segue nel codice:

    • SPACE: il nome di uno spazio, che puoi ottenere dal metodo spaces.list nell'API Chat o dall'URL di uno spazio.
    • MESSAGE: nome del messaggio, che puoi ottenere dal corpo della risposta restituito dopo aver creato un messaggio in modo asincrono con l'API Chat o con il nome personalizzato assegnato al messaggio al momento della creazione.
  4. Nella directory di lavoro, crea ed esegui l'esempio:

    python3 chat_update_text_message_user.py