Creare un'app Google Chat come webhook

Questa pagina descrive come configurare un webhook per inviare messaggi asincroni in uno spazio di Chat utilizzando trigger esterni. Ad esempio, puoi configurare un'applicazione di monitoraggio per inviare una notifica al personale di reperibilità su Chat quando un server è inattivo. Per inviare un messaggio sincrono con un'app Chat, vedi Inviare un messaggio.

Con questo tipo di progettazione dell'architettura, gli utenti non possono interagire con il webhook o l'applicazione esterna connessa perché la comunicazione è unidirezionale. I webhook non sono conversazionali. Non possono rispondere a o ricevere messaggi da utenti o eventi di interazione con l'app Chat. Per rispondere ai messaggi, crea un'app Chat anziché un webhook.

Sebbene un webhook non sia tecnicamente un'app Chat (i webhook connettono le applicazioni utilizzando le richieste HTTP standard), in questa pagina viene fatto riferimento a esso come app Chat per semplificare la procedura. Ogni webhook funziona solo nello spazio di Chat in cui è registrato. I webhook in entrata funzionano nei messaggi diretti, ma solo quando tutte le app Chat sono attivate. Non puoi pubblicare webhook in Google Workspace Marketplace.

Il seguente diagramma mostra l'architettura di un webhook connesso a Chat:

Architettura per i webhook in entrata per inviare messaggi asincroni a Chat.

Nel diagramma precedente, un'app Chat ha il seguente flusso di informazioni:

  1. La logica dell'app Chat riceve informazioni da servizi di terze parti esterni, come un sistema di gestione dei progetti o uno strumento di gestione dei ticket.
  2. La logica dell'app Chat è ospitata in un sistema cloud o on-premise in grado di inviare messaggi utilizzando un URL webhook a uno spazio di Chat specifico.
  3. Gli utenti possono ricevere messaggi dall'app Chat in quello spazio di Chat specifico, ma non possono interagire con l'app Chat.

Prerequisiti

Node.js

Python

Java

Apps Script

Crea un webhook

Per creare un webhook, registralo nello spazio di Chat in cui vuoi ricevere i messaggi, quindi scrivi uno script che invii i messaggi.

Registra il webhook in entrata

  1. In un browser, apri Chat. I webhook non sono configurabili dall'app mobile Chat.
  2. Vai allo spazio in cui vuoi aggiungere un webhook.
  3. Accanto al titolo dello spazio, fai clic sulla freccia di espansione e poi su App e integrazioni.
  4. Fai clic su Aggiungi webhook.

  5. Nel campo Nome, inserisci Quickstart Webhook.

  6. Nel campo URL avatar, inserisci https://developers.google.com/chat/images/chat-product-icon.png.

  7. Fai clic su Salva.

  8. Per copiare l'URL webhook, fai clic su Altro e poi su Copia link.

    L'URL webhook contiene due parametri: key, un valore comune condiviso tra i webhook, e token che è un valore univoco che deve essere mantenuto segreto per preservare la sicurezza del webhook.

Scrivi lo script webhook

Lo script webhook di esempio invia un messaggio allo spazio in cui è registrato il webhook inviando una richiesta POST all'URL webhook. L' API Chat risponde con un'istanza di Message.

Seleziona una lingua per scoprire come creare uno script webhook:

Node.js

  1. Nella directory di lavoro, crea un file denominato index.js.

  2. In index.js, incolla il seguente codice:

    solutions/webhook-chat-app/index.js
    /**
     * Sends asynchronous message to Google Chat
     * @return {Object} response
     */
    async function webhook() {
      const url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN"
      const res = await fetch(url, {
        method: "POST",
        headers: {"Content-Type": "application/json; charset=UTF-8"},
        body: JSON.stringify({
          text: "Hello from a Node script!"
        })
      });
      return await res.json();
    }
    
    webhook().then(res => console.log(res));
  3. Sostituisci il valore della variabile url con l'URL webhook che hai copiato quando hai registrato il webhook.

Python

  1. Nella directory di lavoro, crea un file denominato quickstart.py.

  2. In quickstart.py, incolla il seguente codice:

    solutions/webhook-chat-app/quickstart.py
    from json import dumps
    from httplib2 import Http
    
    # Copy the webhook URL from the Chat space where the webhook is registered.
    # The values for SPACE_ID, KEY, and TOKEN are set by Chat, and are included
    # when you copy the webhook URL.
    
    def main():
        """Google Chat incoming webhook quickstart."""
        url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN"
        app_message = {
            "text": "Hello from a Python script!"
        }
        message_headers = {"Content-Type": "application/json; charset=UTF-8"}
        http_obj = Http()
        response = http_obj.request(
            uri=url,
            method="POST",
            headers=message_headers,
            body=dumps(app_message),
        )
        print(response)
    
    
    if __name__ == "__main__":
        main()
  3. Sostituisci il valore della variabile url con l'URL webhook che hai copiato quando hai registrato il webhook.

Java

  1. Nella directory di lavoro, crea un file denominato pom.xml.

  2. In pom.xml, copia e incolla quanto segue:

    solutions/webhook-chat-app/pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.chat.webhook</groupId>
      <artifactId>webhook-app</artifactId>
      <version>0.1.0</version>
      <name>webhook-app</name>
    
      <properties>
        <maven.compiler.target>11</maven.compiler.target>
        <maven.compiler.source>11</maven.compiler.source>
      </properties>
    
      <dependencies>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.1</version>
        </dependency>
      </dependencies>
    
      <build>
        <pluginManagement>
          <plugins>
            <plugin>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.8.0</version>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
    </project>
  3. Nella directory di lavoro, crea la seguente struttura di directory src/main/java.

  4. Nella directory src/main/java, crea un file denominato App.java.

  5. In App.java, incolla il seguente codice:

    solutions/webhook-chat-app/src/main/java/com/google/chat/webhook/App.java
    import com.google.gson.Gson;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.util.Map;
    import java.net.URI;
    
    public class App {
      private static final String URL = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN";
      private static final Gson gson = new Gson();
      private static final HttpClient client = HttpClient.newHttpClient();
    
      public static void main(String[] args) throws Exception {
        String message = gson.toJson(Map.of(
          "text", "Hello from Java!"
        ));
    
        HttpRequest request = HttpRequest.newBuilder(URI.create(URL))
          .header("accept", "application/json; charset=UTF-8")
          .POST(HttpRequest.BodyPublishers.ofString(message)).build();
    
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    
        System.out.println(response.body());
      }
    }
  6. Sostituisci il valore della variabile URL con l'URL webhook che hai copiato quando hai registrato il webhook.

Apps Script

  1. In un browser, vai ad Apps Script.

  2. Fai clic su Nuovo progetto.

  3. Incolla il seguente codice:

    solutions/webhook-chat-app/webhook.gs
    function webhook() {
      const url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN"
      const options = {
        "method": "post",
        "headers": {"Content-Type": "application/json; charset=UTF-8"},
        "payload": JSON.stringify({
          "text": "Hello from Apps Script!"
        })
      };
      const response = UrlFetchApp.fetch(url, options);
      console.log(response);
    }
  4. Sostituisci il valore della variabile url con l'URL webhook che hai copiato quando hai registrato il webhook.

Esegui lo script webhook

In un'interfaccia a riga di comando, esegui lo script:

Node.js

  node index.js

Python

  python3 quickstart.py

Java

  mvn compile exec:java -Dexec.mainClass=App

Apps Script

  • Fai clic su Esegui.

Quando esegui il codice, il webhook invia un messaggio allo spazio in cui lo hai registrato.

Avviare o rispondere a un thread di messaggi

  1. Specifica spaces.messages.thread.threadKey come parte del corpo della richiesta di messaggi. A seconda che tu stia avviando o rispondendo a un thread, utilizza i seguenti valori per threadKey:

    • Se stai avviando un thread, imposta threadKey su una stringa arbitraria, ma prendi nota di questo valore per pubblicare una risposta al thread.

    • Se rispondi a un thread, specifica il threadKey impostato all'avvio del thread. Ad esempio, per pubblicare una risposta al thread in cui il messaggio iniziale utilizzava MY-THREAD, imposta MY-THREAD.

  2. Definisci il comportamento del thread se il threadKey specificato non viene trovato:

    • Rispondi a un thread o avvia un nuovo thread. Aggiungi il parametro messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD all'URL webhook. Il passaggio di questo parametro URL fa sì che Chat cerchi un thread esistente utilizzando il threadKey specificato. Se ne viene trovato uno, il messaggio viene pubblicato come risposta a quel thread. Se non ne viene trovato nessuno, il messaggio avvia un nuovo thread corrispondente a quel threadKey.

    • Rispondi a un thread o non fare nulla. Aggiungi il parametro messageReplyOption=REPLY_MESSAGE_OR_FAIL all'URL webhook. Il passaggio di questo parametro URL fa sì che Chat cerchi un thread esistente utilizzando il threadKey specificato. Se ne viene trovato uno, il messaggio viene pubblicato come risposta a quel thread. Se non ne viene trovato nessuno, il messaggio non viene inviato.

    Per saperne di più, vedi messageReplyOption.

Il seguente esempio di codice avvia o risponde a un thread di messaggi:

Node.js

solutions/webhook-chat-app/thread-reply.js
/**
 * Sends asynchronous message to Google Chat
 * @return {Object} response
 */
async function webhook() {
  const url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
  const res = await fetch(url, {
    method: "POST",
    headers: {"Content-Type": "application/json; charset=UTF-8"},
    body: JSON.stringify({
      text: "Hello from a Node script!",
      thread: {
        threadKey: "THREAD_KEY_VALUE"
      }
    })
  });
  return await res.json();
}

webhook().then(res => console.log(res));

Python

solutions/webhook-chat-app/thread-reply.py
from json import dumps
from httplib2 import Http

# Copy the webhook URL from the Chat space where the webhook is registered.
# The values for SPACE_ID, KEY, and TOKEN are set by Chat, and are included
# when you copy the webhook URL.
#
# Then, append messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD to the
# webhook URL.


def main():
    """Google Chat incoming webhook that starts or replies to a message thread."""
    url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
    app_message = {
        "text": "Hello from a Python script!",
        # To start a thread, set threadKey to an arbitratry string.
        # To reply to a thread, specify that thread's threadKey value.
        "thread": {
            "threadKey": "THREAD_KEY_VALUE"
        },
    }
    message_headers = {"Content-Type": "application/json; charset=UTF-8"}
    http_obj = Http()
    response = http_obj.request(
        uri=url,
        method="POST",
        headers=message_headers,
        body=dumps(app_message),
    )
    print(response)


if __name__ == "__main__":
    main()

Java

solutions/webhook-chat-app/src/main/java/com/google/chat/webhook/AppThread.java
import com.google.gson.Gson;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import java.net.URI;

public class App {
  private static final String URL = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD";
  private static final Gson gson = new Gson();
  private static final HttpClient client = HttpClient.newHttpClient();

  public static void main(String[] args) throws Exception {
    String message = gson.toJson(Map.of(
      "text", "Hello from Java!",
      "thread", Map.of(
        "threadKey", "THREAD_KEY_VALUE"
      )
    ));

    HttpRequest request = HttpRequest.newBuilder(URI.create(URL))
      .header("accept", "application/json; charset=UTF-8")
      .POST(HttpRequest.BodyPublishers.ofString(message)).build();

    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

    System.out.println(response.body());
  }
}

Apps Script

solutions/webhook-chat-app/thread-reply.gs
function webhook() {
  const url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
  const options = {
    "method": "post",
    "headers": {"Content-Type": "application/json; charset=UTF-8"},
    "payload": JSON.stringify({
      "text": "Hello from Apps Script!",
      "thread": {
        "threadKey": "THREAD_KEY_VALUE"
      }
    })
  };
  const response = UrlFetchApp.fetch(url, options);
  console.log(response);
}

Gestisci gli errori

Le richieste webhook possono non riuscire per una serie di motivi, tra cui:

  • Richiesta non valida.
  • Il webhook o lo spazio che ospita il webhook è stato eliminato.
  • Problemi intermittenti come la connettività di rete o i limiti di quota.

Quando crei il webhook, devi gestire gli errori in modo appropriato:

L'API Google Chat restituisce gli errori come a google.rpc.Status, che include un errore HTTP code che indica il tipo di errore riscontrato: un errore client (serie 400) o un errore server (serie 500). Per esaminare tutti i mapping HTTP, vedi google.rpc.Code.

{
    "code": 503,
    "message": "The service is currently unavailable.",
    "status": "UNAVAILABLE"
}

Per scoprire come interpretare i codici di stato HTTP e gestire gli errori, vedi Errori.

Limitazioni e considerazioni

  • Quando crei un messaggio con un webhook nell'API Google Chat, la risposta non contiene il messaggio completo. La risposta popola solo i campi name e thread.name.
  • I webhook sono soggetti alla quota per spazio di spaces.messages.create: 1 richiesta al secondo, condivisa tra tutti i webhook nello spazio. Chat potrebbe anche rifiutare le richieste webhook che superano 1 query al secondo nello stesso spazio. Per maggiori informazioni sulle quote dell'API Chat, vedi Limiti di utilizzo.