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 a un utente un'interazione.
  • Invia messaggi di testo e schede in modo asincrono chiamando il metodo create su la risorsa Message.
  • Avviare o rispondere a un thread di messaggi.
  • Invia un messaggio e assegnagli un nome.

La Message risorsa rappresenta un testo o scheda in Google Chat. Puoi create, get, update o delete un messaggio nell'API Google Chat chiamando metodi corrispondenti. Per ulteriori informazioni su SMS e messaggi di schede, 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 possono invece inviare più messaggi.

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

Prerequisiti

Node.js

Python

  • Un'app di Google Workspace account con accesso a Google Chat.
  • Python 3.6 o versioni successive
  • Il pip strumento di gestione dei pacchetti
  • Le librerie client di Google più recenti per Python. Per installarle o aggiornarle, 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, vedi Crea un'app Google Chat.
  • Autorizzazione configurata per l'invio da parte dell'app Chat e asincroni. Non è richiesta alcuna configurazione di autorizzazione per l'invio in tempo reale.

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 aggiunto a uno spazio. Per conoscere le best practice per per gli utenti, vedi Inizia a utilizzare le persone e gli spazi con un onboarding utile.

Per inviare un messaggio quando un utente aggiunge la tua app Chat in uno spazio, la tua app Chat risponde a un ADDED_TO_SPACE evento di interazione. Per rispondere a ADDED_TO_SPACE eventi di interazione 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 autenticazione delle app e degli utenti.

Per inviare un messaggio, inserisci quanto segue nella richiesta:

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

Invia un messaggio di testo con l'autenticazione delle app

Per inviare un messaggio di testo con autenticazione 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 che puoi ottenere 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 Message che descrive in dettaglio il messaggio inviato.

Invia un messaggio con autenticazione utente

Per inviare un messaggio di testo con 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 message.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. Nel codice, sostituisci SPACE con il nome di uno spazio, che che puoi ottenere spaces.list() nel dall'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 Message che descrive 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 a un utente un'interazione, ad esempio quando un utente invia all'app Chat un o aggiunge l'app Chat a uno spazio. Per scoprire di più su come rispondere alle interazioni degli utenti, consulta Ricevere e rispondere a Interazione con l'app di chat eventi.

In questo esempio, un utente invia un messaggio a un'app di Chat e l'app Chat risponde inviando un messaggio a riguardo 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'avatar del mittente
dell'immagine.

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 JSON card. Puoi utilizzare anche 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, inserisci quanto segue nella tua richiesta:

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

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 che puoi ottenere 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 esci thread.name vuoto; Google Chat lo compila durante la creazione del thread. Se vuoi, per personalizzare il nome del thread, specificare thread.threadKey .

Per rispondere a un thread di messaggi, invia un messaggio che specifichi Campo threadKey o name. Se il thread è stato creato da una persona o un'altra persona App di chat, devi utilizzare il campo thread.name.

Se non viene trovato alcun thread corrispondente, puoi specificare Impostando l'impostazione per indicare se un messaggio deve iniziare un nuovo thread o se non viene pubblicato messageReplyOption .

Se 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 che puoi ottenere 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 Message che descrive 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 per creare un nuovo messaggio email. Puoi utilizzare gli ID personalizzati per recuperare, aggiornare o eliminare i messaggi. ID personalizzati consente di specificare un messaggio senza dover archiviare l'ID assegnato dal sistema il nome della risorsa del messaggio (rappresentato nel campo name). La risorsa viene generato nel tag corpo della risposta quando crei il messaggio.

Ad esempio, per recuperare un messaggio con il metodo get(), devi utilizzare il il nome della risorsa per specificare quale messaggio recuperare. Il nome della risorsa è nel 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 messageId campo quando crei il messaggio. Il campo messageId consente di impostare il valore del parametro 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 requisiti:

  • Inizia con client-. Ad esempio, client-custom-name è un'entità personalizzata ID, ma custom-name non lo è.
  • Contiene fino a 63 caratteri e solo lettere minuscole, numeri e e trattini.
  • Sia univoco all'interno di uno spazio. Un'app di Chat non può utilizzare 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 spostarlo pubblicare il messaggio, che si può ottenere 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 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 chiedere agli utenti di interagire con il tuo messaggio in vari modi, tra cui: le seguenti:

  • 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 alla documentazione.
  • Ignorare o posticipare messaggi simili dall'app Chat per un determinato periodo di tempo.

Per aggiungere widget accessori, includi i accessoryWidgets[] oggetto nel messaggio e specificare 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 SMS con widget accessori per consentire agli utenti di 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 uno dei pulsanti, l'interazione attiva la funzione corrispondente (come 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 SMS e messaggi in privato in modo che è visibile a un solo 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 utilizzare l'autenticazione delle app.

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

Risoluzione dei problemi

Quando un'app Google Chat o card restituisce un errore, L'interfaccia di Chat mostra il messaggio "Si è verificato un problema". o "Impossibile elaborare la richiesta". A volte, l'UI di Chat non mostra alcun messaggio di errore, ma l'app Chat o la scheda restituisce un risultato inaspettato; Ad esempio, il messaggio di una scheda potrebbe non vengono visualizzate.

Anche se un messaggio di errore potrebbe non essere visualizzato nella UI di Chat, messaggi di errore descrittivi e dati di log che ti aiuteranno a correggere gli errori quando il logging degli errori per le app di chat è attivo. Per assistenza con la visualizzazione, il debug e la correzione degli errori, consulta Risolvere i problemi e correggere gli errori di Google Chat.