Inviare messaggi privati agli utenti di Google Chat

In questa pagina viene spiegato come creare e inviare messaggi privati come app Google Chat.

Un messaggio privato è un messaggio dell'app di Chat visibile solo a un utente di Chat specificato. Puoi utilizzare i messaggi privati in spazi con più persone in modo che possano interagire in privato con le app di Chat. Ad esempio, l'app Chat può inviare privatamente messaggi per:

  • Rispondere a un comando slash. Ad esempio, se un utente richiama il comando slash /about dell'app di Chat in uno spazio, l'app Chat può rispondere con un messaggio privato che spiega cosa fa l'app Chat e come utilizzarla.
  • Notifica o invia informazioni rilevanti per un solo utente. Ad esempio, informa un utente che gli è stata assegnata un'attività o ricordagli di completarla.
  • Invia un messaggio di errore. Ad esempio, se un utente omette il testo dell'argomento richiesto per un comando slash, l'app Chat può inviare un messaggio privato per spiegare l'errore e aiutare l'utente a formattare il comando.

Quando un'app di chat invia un messaggio privato, il messaggio mostra un'etichetta che informa l'utente che il messaggio è visibile solo a lui:

Messaggio privato per l'app di chat di Cymbal Labs. Il messaggio indica che l'app di chat è stata creata da Cymbal Labs e condivide un link alla documentazione e un link per contattare il team di assistenza.
Figura 1: quando un'app di chat invia un messaggio privato, l'utente visualizza un messaggio con l'etichetta Only visible to you.

Prerequisiti

Node.js

Nota: gli esempi di codice Node.js in questa guida sono scritti per essere eseguiti come funzione di Google Cloud Functions.

Python

Nota: gli esempi di codice Python in questa guida sono scritti per essere eseguiti come funzione di Google Cloud Functions utilizzando Python 3.10.

Apps Script

Invia un messaggio privato

Per inviare un messaggio in privato come app di chat, devi specificare il campo privateMessageViewer nel messaggio al momento della creazione. Puoi creare messaggi privati nello stesso modo in cui crei qualsiasi messaggio: rispondendo a un'interazione dell'utente o chiamando in modo asincrono il metodo create() dell'API Google Chat nella risorsa Message. Per la procedura di invio di messaggi di testo o di schede, vedi Inviare un messaggio.

L'esempio seguente mostra il formato JSON per un messaggio privato con scritto Hello private world!:

{
    "text": "Hello private world!",
    "privateMessageViewer": "USER"
}

In questo esempio, USER rappresenta l'utente di Chat che può visualizzare il messaggio, formattato come risorsa User. Se rispondi a un'interazione utente, puoi specificare l'oggetto User dall'evento di interazione. Per un esempio, consulta la sezione seguente Rispondere privatamente a un comando slash.

Altrimenti, per specificare il visualizzatore di un messaggio privato, puoi utilizzare il campo name della risorsa User:

{
    "text": "Hello private world!",
    "privateMessageViewer": {
      "name": "users/USER_ID"
    }
}

In questo esempio, utilizzerai il campo name per specificare il nome della risorsa User del visualizzatore in Google Chat. Sostituisci USER_ID con un ID univoco per l'utente, ad esempio 12345678987654321 o hao@cymbalgroup.com.

Per maggiori informazioni su come specificare gli utenti, consulta Identificare e specificare gli utenti di Google Chat.

Rispondere privatamente a un comando slash

Il seguente codice mostra un esempio di app di chat che risponde a un comando slash con un messaggio privato.

L'app Chat elabora un evento di interazione MESSAGE e risponde al comando slash /help con un messaggio privato che spiega come utilizzarlo:

Node.js

/**
* Responds to a MESSAGE event in Google Chat.
*
* @param {!Object} req Request sent from Google Chat app
* @param {!Object} res Response to send back
*
* @return {!Object} respond to slash command
*/
exports.onMessage = function onMessage(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    return res.send('Hello! This function is meant to be used in Google Chat app.');
  }

  const event = req.body;

  // Checks for the presence of event.message.slashCommand.
  // If the slash command is "/help", responds with a private text message.
  if (event.message.slashCommand) {
    switch (event.message.slashCommand.commandId) {
      case '1':  // /help
        return res.json({
          privateMessageViewer: event.user,
          text: 'This Chat app was created by Cymbal Labs. To get help with this app, <https://cymbalgroup.com/docs|see our documentation> or <https://cymbalgroup.com/support|contact our support team>.'
        });
    }
  }

  // If the Chat app doesn't detect a slash command, it responds
  // with a private text message
  return res.json({
    privateMessageViewer: event.user,
    text: 'Try a slash command.'
  });
};

Apps Script

/**
* Responds to a MESSAGE event in Google Chat.
*
* @param {Object} event the event object from Google Chat
*/
function onMessage(event) {
  if (event.message.slashCommand) {
    switch (event.message.slashCommand.commandId) {
      case 1: // Responds to /help
        return {
          "privateMessageViewer": event.user,
          "text": "This Chat app was created by Cymbal Labs. To get help with this app, <https://cymbalgroup.com/docs|see our documentation> or <https://cymbalgroup.com/support|contact our support team>."
        };
    }
  }
  else {
    return { "text": "Try a slash command.", "privateMessageViewer": event.user };
  }
}

Python

from typing import Any, Mapping

import flask
import functions_framework

@functions_framework.http
def main(req: flask.Request) -> Mapping[str, Any]:
  """Responds to a MESSAGE event in Google Chat.

  Args:
      req (flask.Request): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a card's button click.
  """
  if req.method == 'GET':
    return 'Hello! This function must be called from Google Chat.'

  request = req.get_json(silent=True)

  # Checks for the presence of event.message.slashCommand.
  # If the slash command is "/help", responds with a private text message.
  if request.get('message', {}).get('slashCommand'):
    command_id = request.get('message', {}).get('slashCommand').get('commandId')
    if command_id == '1':  # /help
      return {
          'privateMessageViewer': request.get('user'),
          'text': (
              'This Chat app was created by Cymbal Labs. To get help with this'
              ' app, <https://cymbalgroup.com/docs|see our documentation> or'
              ' <https://cymbalgroup.com/support|contact our support team>.'
          ),
      }

  return {
      'privateMessageViewer': request.get('user'),
      'text': 'Try a slash command.',
  }

Limitazioni

Per inviare un messaggio privato, il messaggio non può contenere o utilizzare quanto segue:

  • Allegati.
  • Azioni relative agli accessori.
  • Messaggi parzialmente privati. Ad esempio, un'app di chat non può inviare un messaggio con testo e una scheda in cui il testo sia visibile a un solo utente, ma la scheda è visibile a tutti nello spazio.
  • Autenticazione utente. Solo le app di chat possono inviare messaggi privati, pertanto l'app Chat non può autenticarsi come utente per inviare messaggi in privato.

Aggiornare o eliminare i messaggi privati

Per aggiornare o eliminare i messaggi di Google Chat, devi chiamare l'API Chat. Non puoi cambiare il visualizzatore del messaggio privato o renderlo pubblico. Pertanto, quando aggiorni i messaggi privati, devi omettere il campo privateMessageViewer nella chiamata API (il campo viene visualizzato solo come output).

Per aggiornare un messaggio privato, vedi Aggiornare un messaggio. Per eliminare un messaggio privato, vedi Eliminare un messaggio.