Aggiornare un messaggio

Questa guida spiega come utilizzare il metodo patch nella risorsa Message di l'API Google Chat per aggiornare un messaggio di testo o una scheda in uno spazio. Aggiorna un un messaggio per modificarne gli attributi, come il testo scritto, o il contenuto . Puoi anche anteporre un messaggio a una o aggiungere una scheda a un messaggio di testo.

L'API Chat supporta anche Metodo update, ma consigliamo vivamente di chiamare il metodo Metodo patch perché utilizza una richiesta HTTP PATCH update utilizza un PUT Richiesta HTTP. Per saperne di più, consulta Sezione PATCH e PUT dell'AIP-134.

Nell'API Chat, un messaggio di Chat è rappresentato dalla Message risorsa. Anche se gli utenti di Chat possono inviare solo messaggi contenenti testo, Le app di chat possono utilizzare molte altre funzionalità di messaggistica, tra cui: Mostrare interfacce utente statiche o interattive, raccogliendo informazioni da utenti e distribuire i messaggi in privato. Per scoprire di più sui messaggi disponibili per l'API Chat, consulta le 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 installarle o aggiornarle, esegui questo comando nell'interfaccia a riga di comando:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

Aggiorna un messaggio di testo o anteponi un SMS a un messaggio della scheda mediante l'autenticazione utente

Per aggiornare un messaggio di testo con autenticazione dell'utente, quanto segue nella tua richiesta:

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

Se il messaggio aggiornato è un messaggio nella scheda, il messaggio di testo viene anteposto a quello della scheda (che continua a essere visualizzato).

Per aggiornare un messaggio di testo o anteponi un SMS a un messaggio nella scheda 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',
          body={'text': 'Updated message!'}
    
        ).execute()
    
        # Prints details about the updated message.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. Nel codice, sostituisci quanto segue:

    • SPACE: il nome di uno spazio, che puoi ottenere il Metodo spaces.list nell'API Chat o dall'URL di uno spazio.
    • MESSAGE: il nome di un messaggio, che puoi ottenere dal corpo della risposta restituito dopo la creazione del messaggio in modo asincrono. con l'API Chat o con nome personalizzato e 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 messaggio di testo o anteponi un messaggio a un messaggio della carta con l'autenticazione delle app

Per aggiornare un messaggio di testo con autenticazione delle app, inserisci quanto segue nella tua richiesta:

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

Se il messaggio aggiornato è un messaggio scheda, il messaggio di testo viene anteposto a quello della scheda (che continua a essere visualizzato).

Per aggiornare un messaggio di testo a un messaggio di testo o anteporre un messaggio a un messaggio nella scheda con 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. Nel codice, sostituisci quanto segue:

    • SPACE: il nome di uno spazio, che puoi ottenere il Metodo spaces.list nell'API Chat o dall'URL di uno spazio.
    • MESSAGE: il nome di un messaggio, che puoi ottenere dal corpo della risposta restituito dopo la creazione del messaggio in modo asincrono. con l'API Chat o con nome personalizzato e 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 il messaggio di una scheda o aggiungi un messaggio della scheda a un messaggio di testo

Per aggiornare un messaggio nella scheda, inserisci quanto segue nella tua richiesta:

  • L'ambito dell'autorizzazione chat.bot. L'aggiornamento del messaggio di una scheda richiede autenticazione delle app.
  • name del messaggio da aggiornare.
  • updateMask='cardsV2'
  • Un elemento body che specifica il messaggio aggiornato.

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

Ecco come aggiornare un messaggio in un messaggio nella 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. Nel codice, sostituisci quanto segue:

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

    • MESSAGE: il nome di un messaggio, che puoi ottenere dal corpo della risposta restituito dopo la creazione del messaggio in modo asincrono. con l'API Chat o con nome personalizzato e 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 Message che descrive in dettaglio il messaggio aggiornato.

Aggiornare un messaggio con più percorsi di campo contemporaneamente

Quando un messaggio viene aggiornato, puoi aggiornare più percorsi dei campi dei messaggi nella nel tempo. Ad esempio, in una richiesta di aggiornamento di un messaggio, puoi specificare una modifica contemporaneamente, vengono aggiornati sia i percorsi dei campi text che quelli di cardsv2. testo e scheda del messaggio. Se il messaggio include solo testo e nessuna scheda, viene visualizzata una scheda vengono aggiunte al messaggio. Per saperne di più sui percorsi dei campi supportati, vedi Parametri updateMask.

Per aggiornare sia text e card di un messaggio con l'autenticazione degli utenti, inserisci quanto segue nella tua richiesta:

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

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

Ecco come aggiornare i percorsi dei campi text e cardsV2 in una 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 updated message.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. Nel codice, sostituisci quanto segue:

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

    python3 chat_update_text_message_user.py