Creare un'app Google Chat come webhook

Questa pagina descrive come impostare un webhook per inviare messaggi asincroni a un Spazio di Chat che utilizza trigger esterni. Ad esempio, puoi configurare un'applicazione di monitoraggio per avvisare il personale sempre disponibile Chatta quando un server non è disponibile. Per inviare un messaggio sincrono con un'app di Chat, vedi Inviare un messaggio.

Con questo tipo di architettura gli utenti non possono interagire con il webhook o con l'esterno perché la comunicazione è unidirezionale. I webhook non sono conversazionali. Non può rispondere o ricevere messaggi dagli utenti o Eventi di interazione con l'app di Chat. Per rispondere ai messaggi: sviluppare un'app di Chat anziché un webhook.

Anche se un webhook non è tecnicamente un'app di Chat: i webhook collegano le applicazioni utilizzando Richieste HTTP: in questa pagina si parla di app di Chat per semplificazione. Ogni webhook funziona solo nello spazio di Chat in in cui è registrato. I webhook in arrivo funzionano nei messaggi diretti, ma solo quando tutti gli utenti hanno App di chat attivate. Non puoi pubblicare webhook su Google Workspace Marketplace.

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

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

Nel diagramma precedente, un'app di Chat include quanto segue flusso di informazioni:

  1. La logica dell'app Chat riceve informazioni servizi di terze parti esterni, come un sistema di project management o un per la vendita di biglietti.
  2. La logica dell'app di Chat è ospitata in un cloud sistema on-premise in grado di inviare messaggi utilizzando un URL webhook a un uno spazio di Chat specifico.
  3. Gli utenti possono ricevere messaggi dall'app Chat in spazio di Chat specifico, ma non riesci a interagire con Chat.

Prerequisiti

Python

Node.js

Java

Apps Script

Crea un webhook

Per creare un webhook, registralo nello spazio di Chat in cui vuoi ricevere messaggi e scrivere uno script che li invii.

Registra il webhook in arrivo

  1. In un browser, apri Chatta. 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 sull'icona Espandi la freccia Altro, quindi fai clic 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, quindi fai clic su Copia link.

Scrivi lo script del webhook

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

Seleziona una lingua per scoprire come creare uno script webhook:

Python

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

  2. Incolla il codice seguente in quickstart.py:

    python/webhook/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 che hai copiato durante la registrazione del webhook.

Node.js

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

  2. Incolla il codice seguente in index.js:

    node/webhook/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"
      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 che hai copiato durante la registrazione del webhook.

Java

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

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

    java/webhook/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>java-webhook-app</artifactId>
      <version>0.1.0</version>
    
      <name>java-webhook-app</name>
      <url>https://github.com/googleworkspace/google-chat-samples/tree/main/java/webhook</url>
    
      <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. Incolla il codice seguente in App.java:

    java/webhook/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/AAAAGCYeSRY/messages";
      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 durante la registrazione del webhook.

Apps Script

  1. In un browser, vai a Apps Script.

  2. Fai clic su Nuovo progetto

  3. Incolla il seguente codice:

    apps-script/webhook/webhook.gs
    function webhook() {
      const url = "https://chat.googleapis.com/v1/spaces/SPACE_ID/messages"
      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 durante la registrazione del webhook.

Esegui lo script webhook

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

Python

  python3 quickstart.py

Node.js

  node index.js

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 l'ha registrato.

Avviare o rispondere a un thread di messaggi

  1. Specifica spaces.messages.thread.threadKey nel corpo della richiesta. A seconda che tu abbia iniziato rispondendo a un thread, utilizza i seguenti valori per threadKey:

    • Se avvii un thread, imposta threadKey su una stringa arbitraria, ma annota questo valore per pubblicare una risposta nel thread.

    • Se rispondi a un thread, specifica il valore threadKey impostato quando thread è stato avviato. Ad esempio, per pubblicare una risposta al thread in cui messaggio iniziale utilizzato MY-THREAD, imposta MY-THREAD.

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

    • Rispondi a un thread o avvia un nuovo thread. Aggiungi il parametro messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD parametro in l'URL webhook. Il passaggio di questo parametro URL fa sì che Chat per cercare un thread esistente utilizzando il valore threadKey specificato. Se uno , il messaggio viene pubblicato come risposta a quel thread. Se nessuna è trovato, il messaggio avvia un nuovo thread corrispondente 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 per cercare un thread esistente utilizzando il valore threadKey specificato. Se uno , il messaggio viene pubblicato come risposta a quel thread. Se nessuna è trovato, il messaggio non viene inviato.

    Per scoprire di più, visita la pagina messageReplyOption.

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

Python

python/webhook/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()

Node.js

node/webhook/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));

Apps Script

apps-script/webhook/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);
}