Invia un messaggio

Questa guida illustra i diversi modi in cui le app Google Chat possono inviare messaggi:

  • Invia messaggi di testo e schede in tempo reale rispondendo all'interazione di un utente.
  • Invia messaggi di testo e schede in modo asincrono chiamando il metodo create nella risorsa Message.
  • Avviare o rispondere a un thread di messaggi.
  • Invia un messaggio e assegnagli un nome.

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 scoprire di più sugli SMS e sui messaggi scheda, vedi Panoramica dei messaggi di Google Chat.

La dimensione massima del messaggio (compreso testo o schede) è di 32.000 byte. Se un messaggio supera queste dimensioni, l'app Chat può inviare più messaggi.

Anziché chiamare il metodo create sulla risorsa Message dell'API Google Chat per inviare un messaggio di testo o una scheda in modo asincrono, le app Google Chat possono anche creare messaggi per rispondere alle interazioni degli utenti in tempo reale. Le risposte alle interazioni degli utenti non richiedono l'autenticazione e supportano altri tipi di messaggi, tra cui le finestre di dialogo interattive e le anteprime dei link. Per maggiori dettagli, consulta Ricevere e rispondere alle interazioni con l'app Google Chat.

Prerequisiti

Node.js

Python

  • Un account Google Workspace con accesso a Google Chat.
  • 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
    
  • Un progetto Google Cloud con l'API Google Chat abilitata e configurata. Per i passaggi da seguire, vedi Creare un'app Google Chat.
  • Autorizzazione configurata per l'invio di messaggi asincroni da parte dell'app Chat. Per inviare messaggi in tempo reale non è necessaria alcuna configurazione di autorizzazione.

Apps Script

Invia messaggi

In questa sezione viene descritto come inviare messaggi di testo nei due modi seguenti:

  • Invia un messaggio in tempo reale rispondendo a un'interazione dell'utente.
  • Invia un messaggio chiamando l'API Google Chat in modo asincrono.

Invia un messaggio in tempo reale

In questo esempio, l'app Chat crea e invia un messaggio ogni volta che viene aggiunta a uno spazio. Per scoprire le best practice per l'onboarding degli utenti, consulta Iniziare a utilizzare le persone e gli spazi con un onboarding utile.

Per inviare un messaggio quando un utente aggiunge la tua app Chat a uno spazio, l'app Chat risponde a un evento di interazione ADDED_TO_SPACE. Per rispondere agli eventi di interazione con ADDED_TO_SPACE con un messaggio, utilizza il seguente codice:

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`.'
  }
}

L'esempio di codice restituisce il seguente messaggio di testo:

Esempio di messaggio di onboarding.

Invia un messaggio in modo asincrono

La sezione seguente spiega come inviare un messaggio in modo asincrono con l'autenticazione delle app e quella degli utenti.

Per inviare un messaggio, inserisci quanto segue nella richiesta:

  • Con l'autenticazione delle app, specifica l'ambito dell'autorizzazione chat.bot. Con l'autenticazione dell'utente, specifica l'ambito dell'autorizzazione chat.messages.create.
  • Chiama il metodo create sulla risorsa Message.

Invia un messaggio di testo con l'autenticazione delle app

Per inviare un messaggio di testo con l'autenticazione delle app:

Python

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

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # 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', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # 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. Nel codice, sostituisci SPACE con il nome di uno spazio, che puoi ottenere dal metodo spaces.list() nell'API Chat o dall'URL di uno spazio.

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

    python3 chat_create_text_message_app.py
    

L'API Chat restituisce un'istanza di Message che mostra in dettaglio il messaggio inviato.

Invia un messaggio con autenticazione utente

Ecco come inviare un messaggio con l'autenticazione dell'utente:

Python

  1. Nella directory di lavoro, crea un file denominato chat_create_text_message_user.py.
  2. Includi il seguente codice in 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 message.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. Nel codice, sostituisci SPACE con il nome di uno spazio, che puoi ottenere dal metodo spaces.list() nell'API Chat o dall'URL di uno spazio.

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

    python3 chat_create_text_message_user.py
    

L'API Chat restituisce un'istanza di Message che mostra in dettaglio il messaggio inviato.

Invia messaggi relativi alle schede

Questa sezione descrive come inviare i messaggi relativi alle schede nei due modi seguenti:

  • Invia un messaggio nella scheda in tempo reale rispondendo a un'interazione dell'utente.
  • Invia un messaggio scheda chiamando l'API Google Chat in modo asincrono.

Invia un messaggio di carta in tempo reale

Le app di chat possono creare messaggi di schede per rispondere all'interazione di un utente, ad esempio quando un utente invia un messaggio all'app Chat o aggiunge l'app Chat a uno spazio. Per scoprire di più su come rispondere alle interazioni degli utenti, consulta Ricevere e rispondere agli eventi di interazione con l'app Chat.

In questo esempio, un utente invia un messaggio a un'app di Chat e l'app Chat risponde inviando un messaggio di scheda che mostra il nome e l'immagine avatar dell'utente:

Un'app di Chat che risponde con una scheda con il nome visualizzato e l'immagine avatar del mittente.

Node.js

node/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

Questo esempio invia un messaggio di una scheda restituendo card JSON. Puoi anche utilizzare il servizio di schede 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],
      }
    }],
  };
}

Inviare un messaggio della scheda in modo asincrono

Per inviare un messaggio nella scheda, trasmetti quanto segue nella richiesta:

  • Con l'autenticazione delle app, specifica l'ambito dell'autorizzazione chat.bot. Non puoi inviare un messaggio scheda con l'autenticazione utente.
  • Chiama il metodo create sulla risorsa Message.

Di seguito è riportato un esempio di messaggio di una scheda:

Messaggio della scheda inviato con l'API Chat.

Per inviare un messaggio relativo a una carta di credito con l'autenticazione delle app:

Python

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

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # 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', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # 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. Nel codice, sostituisci SPACE con il nome di uno spazio, che puoi ottenere dal metodo spaces.list nell'API Chat o dall'URL di uno spazio.

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

    python3 chat_create_card_message.py
    

Avviare o rispondere a un thread di messaggi

Per avviare un thread di messaggi, invia un messaggio e lascia vuoto il campo thread.name; Google Chat lo compila durante la creazione del thread. Se vuoi, per personalizzare il nome del thread, specifica il campo thread.threadKey.

Per rispondere a un thread di messaggi, invia un messaggio che specifica il campo threadKey o name del thread. Se il thread è stato creato da una persona o da un'altra app Chat, devi utilizzare il campo thread.name.

Se non viene trovato alcun thread corrispondente, puoi specificare se un messaggio deve avviare un nuovo thread o non pubblicarlo impostando il campo messageReplyOption.

Se il criterio messageReplyOption è impostato, devi impostare anche thread.name o thread.threadKey.

Ecco come avviare o rispondere a un thread con il campo threadKey definito come nameOfThread:

Python

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

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # 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', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # 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. Nel codice, sostituisci SPACE con il nome di uno spazio, che puoi ottenere dal metodo spaces.list nell'API Chat o dall'URL di uno spazio.

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

    python3 chat_create_message_thread.py
    

L'API Chat restituisce un'istanza di Message che mostra in dettaglio il messaggio inviato.

Assegna un nome a un messaggio

Questa sezione spiega come assegnare un nome a un messaggio impostando un ID personalizzato per il messaggio. Puoi utilizzare gli ID personalizzati per recuperare, aggiornare o eliminare i messaggi. Gli ID personalizzati ti consentono di specificare un messaggio senza dover archiviare l'ID assegnato dal sistema dal nome della risorsa del messaggio (rappresentato nel campo name). Il nome della risorsa viene generato nel corpo della risposta quando crei il messaggio.

Ad esempio, per recuperare un messaggio con il metodo get(), puoi utilizzare il nome della risorsa per specificare quale messaggio recuperare. Il nome della risorsa ha il formato spaces/{space}/messages/{message}, dove {message} rappresenta l'ID assegnato dal sistema. Se hai assegnato un nome al messaggio, puoi sostituire il valore di {message} con l'ID personalizzato.

Per assegnare un nome a un messaggio, specifica un ID personalizzato nel campo messageId quando lo crei. Il campo messageId imposta il valore del campo clientAssignedMessageId della risorsa Message.

Puoi assegnare un nome a un messaggio solo quando lo crei. Non puoi assegnare un nome o modificare un ID personalizzato per i messaggi esistenti. L'ID personalizzato deve soddisfare i seguenti requisiti:

  • Inizia con client-. Ad esempio, client-custom-name è un ID personalizzato valido, mentre custom-name non lo è.
  • Contiene fino a 63 caratteri e solo lettere minuscole, numeri e trattini.
  • Sia univoco all'interno di uno spazio. Un'app di Chat non può usare lo stesso ID personalizzato per messaggi diversi.

Per inviare un messaggio con un ID personalizzato:

Python

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

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # 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', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # 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-NAME',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. Nel codice, sostituisci quanto segue:

    • SPACE: l'ID dello spazio in cui vuoi pubblicare il messaggio, che puoi ottenere dal metodo spaces.list nell'API Chat o dall'URL di uno spazio.
    • NAME: il nome personalizzato del messaggio.
  4. Nella directory di lavoro, crea ed esegui l'esempio:

    python3 chat_create_named_message.py
    

L'API Chat restituisce un'istanza di Message.

Aggiungere widget interattivi nella parte inferiore di un messaggio

Facoltativamente, puoi aggiungere messaggi con widget di accessori. I widget accessori vengono visualizzati dopo il testo o le schede di un messaggio. Puoi utilizzare questi widget per richiedere agli utenti di interagire con il tuo messaggio in molti modi, tra cui:

  • Valuta l'accuratezza o la soddisfazione di un messaggio.
  • Segnala un problema relativo al messaggio o all'app Chat.
  • Apri un link ai contenuti correlati, ad esempio la documentazione.
  • Ignora o posticipa messaggi simili dall'app Chat per un periodo di tempo specifico.

Per aggiungere widget accessori, includi l'oggetto accessoryWidgets[] nel messaggio e specifica uno o più AccessoryWidgets che vuoi includere. Il messaggio deve essere visibile a tutti nello spazio (non puoi aggiungere widget accessori ai messaggi privati).

L'immagine seguente mostra un'app di Chat che aggiunge un messaggio di testo con widget accessori in modo che gli utenti possano valutare la loro esperienza con l'app Chat.

Esempi di widget di accessori

Il seguente esempio di codice mostra il JSON per questo messaggio. Quando un utente fa clic su uno dei pulsanti, l'interazione attiva la funzione corrispondente (ad esempio doUpvote) che elabora la valutazione.


 "text": "Rate your experience with this Chat app.",
 "accessoryWidgets": [
   {
     "buttonList": {
       "buttons": [
         {
           "icon": {
             "material_icon": {
               "name": "thumb_up"
             }
           },
           "color": {
             "red": 0,
             "blue": 255,
             "green": 0
           },
           "onClick": {
             "action": {
               "function": "doUpvote",
             }
           }
         },
         {
           "icon": {
             "material_icon": {
               "name": "thumb_down"
             }
           },
           "color": {
             "red": 0,
             "blue": 255,
             "green": 0
           },
           "onClick": {
             "action": {
               "function": "doDownvote",
             }
           }
         }
       ]
     }
   }
 ]

Invia messaggi privatamente

Le app di chat possono inviare messaggi di testo e schede in privato in modo che il messaggio sia visibile solo a un utente nello spazio. Per inviare un messaggio in privato, devi specificare il campo privateMessageViewer nel messaggio. Solo le app di Chat possono inviare messaggi privati. Per inviare un messaggio privato in modo asincrono, devi usare l'autenticazione app.

Per maggiori dettagli, vedi Inviare messaggi privati agli utenti di Google Chat.

Risolvi il problema

Quando un'app o una scheda Google Chat restituisce un errore, l'interfaccia di Chat mostra il messaggio "Si è verificato un problema". o "Impossibile elaborare la richiesta". A volte nella UI di Chat non viene visualizzato alcun messaggio di errore, ma l'app o la scheda Chat produce un risultato imprevisto. Ad esempio, il messaggio di una scheda potrebbe non essere visualizzato.

Anche se un messaggio di errore potrebbe non essere visualizzato nell'interfaccia utente di Chat, sono disponibili messaggi di errore descrittivi e dati di log per aiutarti a correggere gli errori quando il logging degli errori per le app di Chat è attivato. Per informazioni su visualizzazione, debug e correzione degli errori, vedi Risolvere i problemi e correggere gli errori di Google Chat.