Invia un messaggio

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

  • Invia SMS e messaggi con le schede in tempo reale rispondendo a un'interazione utente.
  • Invia messaggi e messaggi con schede in modo asincrono chiamando il metodo create nella risorsa Message.
  • Avvia o rispondi a un thread di messaggi.
  • Invia un messaggio e assegnagli un nome.

La risorsa Message rappresenta un messaggio di SMS o carta 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 sulle schede, vedi Panoramica dei messaggi di Google Chat.

Anziché chiamare il metodo create nella risorsa Message dell'API Google Chat per inviare un messaggio di testo o di carte 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, incluse finestre di dialogo interattive e anteprime dei link. Per maggiori dettagli, vedi Ricevere e rispondere alle interazioni con l'app Google Chat.

Prerequisiti

Node.js

Python

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

    pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
    
  • Un'app Chat pubblicata. Per creare e pubblicare un'app Chat, consulta Creare un'app Google Chat.

  • Autorizzazione configurata per l'app Chat per l'invio di messaggi asincroni. Non è necessaria alcuna configurazione di autorizzazione per inviare messaggi in tempo reale.

Apps Script

Invia messaggi

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

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

Invia un SMS in tempo reale

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

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

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:

Esempio di messaggio di onboarding.

Invia un messaggio in modo asincrono

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

Per inviare un SMS, inserisci quanto segue nella richiesta:

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

Invia un messaggio con l'autenticazione delle app

Ecco come inviare un messaggio 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 httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # 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 oppure 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 descrive in dettaglio il messaggio inviato.

Inviare un messaggio con l'autenticazione degli utenti

Ecco come inviare un messaggio con l'autenticazione 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 membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. Nel codice, sostituisci SPACE con un nome dello 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 descrive in dettaglio il messaggio inviato.

Invia messaggi con le schede

In questa sezione viene descritto come inviare messaggi relativi alle schede nei seguenti due modi:

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

Invia un messaggio con le carte in tempo reale

Le app di chat possono creare messaggi di schede per rispondere a un'interazione 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 quest'ultima risponde inviando un messaggio di carta che mostra il nome e l'immagine dell'avatar dell'utente:

Un'app di chat che risponde con una scheda che mostra il nome visualizzato e l'immagine dell'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

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 con scheda, inserisci quanto segue nella richiesta:

  • Con l'autenticazione delle app, specifica l'ambito di autorizzazione chat.bot. Non puoi inviare un messaggio relativo a una carta con l'autenticazione utente.
  • Chiama il metodo create nella risorsa Message.

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

Un messaggio con scheda inviato con l'API Chat.

Ecco come inviare un messaggio relativo alle carte con l'autenticazione 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 httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # 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 oppure 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, inviane uno e lascia vuoto il campo thread.name: viene completato da Google Chat 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 specifichi il campo threadKey o name del thread. Se il thread è stato creato da una persona o da un'altra app di Chat, devi utilizzare il campo thread.name.

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

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 httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # 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 oppure 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 descrive in dettaglio il messaggio inviato.

Inviare un messaggio e assegnargli un nome

Questa sezione spiega come inviare un messaggio con un nome personalizzato. Puoi utilizzare i nomi dei messaggi per ricevere, aggiornare o eliminare i messaggi. L'assegnazione di un nome personalizzato consente anche a un'app di chat di richiamare il messaggio senza salvare il messaggio name dal corpo della risposta restituito al momento dell'invio.

L'assegnazione di un nome personalizzato non sostituisce il campo name generato, ovvero il nome della risorsa del messaggio. Imposta invece il nome personalizzato come campo clientAssignedMessageId, a cui puoi fare riferimento durante l'elaborazione delle operazioni successive, come l'aggiornamento o l'eliminazione del messaggio.

I nomi personalizzati hanno i seguenti requisiti:

  • Inizia con client-. Ad esempio, client-custom-name è un nome personalizzato valido, mentre custom-name non lo è.
  • Contenere solo lettere minuscole, numeri e trattini.
  • Non superare i 63 caratteri di lunghezza.
  • Se specifichi un nome personalizzato utilizzato durante l'invio di un messaggio, viene restituito un errore, ma altri metodi come update e delete funzionano come previsto.

Per inviare e assegnare un nome a un messaggio, procedi nel seguente modo:

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 httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # 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-custom-name',
    
        # 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 oppure dall'URL di uno spazio.

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

    python3 chat_create_named_message.py
    

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

Risolvi il problema

Quando un'app o una scheda Google Chat restituisce un errore, nell'interfaccia di Chat viene visualizzato il messaggio "Si è verificato un problema" o "Impossibile elaborare la richiesta". A volte nell'interfaccia utente di Chat non viene visualizzato alcun messaggio di errore, ma l'app o la scheda di Chat generano un risultato imprevisto; ad esempio, un messaggio della 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 assistenza sulla visualizzazione, il debug e la correzione degli errori, vedi Risolvere i problemi e correggere gli errori di Google Chat.