Ottenere dettagli sullo stato di lettura del thread di un utente

Questa guida spiega come utilizzare il metodo getThreadReadState nella risorsa ThreadReadState dell'API Google Chat per ottenere dettagli sullo stato di lettura di un utente all'interno di un thread di messaggi. Per ottenere lo stato di lettura di un messaggio in uno spazio, consulta Ottenere i dettagli sullo stato di lettura dello spazio di un utente.

La risorsa ThreadReadState è una risorsa singleton che rappresenta i dettagli dell'ultimo messaggio letto di un utente specificato in un thread di 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
    
  • 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. Per ottenere i dettagli sullo stato di lettura di un utente all'interno di uno spazio, è necessaria l'autenticazione dell'utente con l'ambito di autorizzazione chat.users.readstate o chat.users.readstate.readonly.

Node.js

  • Node.js e npm
  • Le librerie client di Google più recenti per Node.js. Per installarle, esegui questo comando nell'interfaccia a riga di comando:

    npm install @google-cloud/local-auth @googleapis/chat
    
  • 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. Per ottenere i dettagli sullo stato di lettura di un utente all'interno di uno spazio, è necessaria l'autenticazione dell'utente con l'ambito di autorizzazione chat.users.readstate o chat.users.readstate.readonly.

Apps Script

  • Un account Google Workspace con accesso a Google Chat.
  • Un'app di Chat pubblicata. Per creare un'app di Chat, segui questa quickstart.
  • Autorizzazione configurata per l'app di Chat. Per ottenere i dettagli sullo stato di lettura di un utente all'interno di uno spazio, è necessaria l'autenticazione dell'utente con l'ambito di autorizzazione chat.users.readstate o chat.users.readstate.readonly.

Recupera lo stato di lettura del thread dell'utente chiamante

Per ottenere dettagli sullo stato di lettura di un utente all'interno di un thread di messaggi, includi quanto segue nella richiesta:

  • Specificare l'ambito di autorizzazione chat.users.readstate o chat.users.readstate.readonly.
  • Chiama il metodo getThreadReadState nella risorsa ThreadReadState.
  • Passa il valore name dello stato di lettura del thread per ottenere, che include un ID utente o un alias e un ID spazio. Ottenere lo stato di lettura del thread supporta solo il recupero dello stato di lettura dell'utente chiamante, che può essere specificato impostando una delle seguenti opzioni:
    • L'alias me. Ad esempio, users/me/spaces/SPACE/threads/THREAD/threadReadState.
    • L'indirizzo email Workspace dell'utente chiamante. Ad esempio, users/user@example.com/spaces/SPACEthreads/THREAD/threadReadState.
    • L'ID utente dell'utente chiamante. Ad esempio, users/USER/spaces/SPACE/threads/THREAD/threadReadState.

L'esempio seguente restituisce lo stato di lettura del thread dell'utente che ha effettuato la chiamata:

Python

  1. Nella directory di lavoro, crea un file denominato chat_threadReadState_get.py.
  2. Includi il seguente codice in chat_threadReadState_get.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.users.readstate.readonly"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then gets the thread read state for the calling user.
        '''
    
        # 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.users().spaces().threads().getThreadReadState(
    
            # The thread read state to get.
            #
            # Replace USER with the calling user's ID, Workspace email,
            # or the alias me.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            #
            # Replace THREAD with a thread name.
            # Obtain the thread name from the messages resource of Chat API.
            name='users/me/spaces/SPACE/threads/THREAD/threadReadState'
    
          ).execute()
    
        # Prints the API's response.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. Sostituisci quanto segue nel codice:

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

    python3 chat_threadReadState_get.py
    

Node.js

  1. Nella directory di lavoro, crea un file denominato chat_threadReadState_get.js.
  2. Includi il seguente codice in chat_threadReadState_get:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Authenticates with Chat API via user credentials,
    * then gets the thread read state for the calling user.
    * @return {!Promise<!Object>}
    */
    async function getThreadReadState() {
    
      /**
      * Authenticate with Google Workspace
      * and get user authorization.
      */
      const scopes = [
        'https://www.googleapis.com/auth/chat.users.readstate.readonly',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      /**
      * Build a service endpoint for Chat API.
      */
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      /**
      * Use the service endpoint to call Chat API.
      */
      return await chatClient.users.spaces.threads.getThreadReadState({
    
        /**
        * The thread read state to get.
        *
        * Replace USER with the calling user's ID, Workspace email,
        * or the alias me.
        *
        * Replace SPACE with a space name.
        * Obtain the space name from the spaces resource of Chat API,
        * or from a space's URL.
        */
        name: 'users/me/spaces/SPACE/threads/THREADS/threadReadState'
      });
    }
    
    /**
    * Use the service endpoint to call Chat API.
    */
    getThreadReadState().then(console.log);
    
  3. Sostituisci quanto segue nel codice:

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

    node chat_threadReadState_get.js
    

Apps Script

Questo esempio chiama l'API Chat utilizzando il servizio Chat avanzato.

  1. Aggiungi l'ambito dell'autorizzazione chat.users.readstate.readonly al file appsscript.json del progetto Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.users.readstate.readonly"
    ]
    
  2. Aggiungi una funzione come questa al codice del progetto Apps Script:

    /**
    * Authenticates with Chat API via user credentials,
    * then gets the thread read state for the calling user.
    * @param {string} threadReadStateName The resource name of the thread read state.
    */
    function getThreadReadState(threadReadStateName) {
      try {
        Chat.Users.Spaces.Threads.getThreadReadState(threadReadStateName);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to get read state with error %s', err.message);
      }
    }
    

L'API Google Chat ottiene lo stato di lettura del thread specificato e restituisce un'istanza della risorsa ThreadReadState.