Creare una home page per un'app Google Chat

Questa pagina spiega come creare una home page per i messaggi diretti con la tua app Google Chat. Una home page, chiamata Home app nell'API Google Chat, è un'interfaccia a schede personalizzabile che viene visualizzata nella scheda Home degli spazi di messaggi diretti 1:1 tra un utente e un'app di chat.

Scheda della home page dell'app con due widget.
Figura 1: un esempio di home page visualizzata nei messaggi diretti con un'app di chat.

A differenza di altre applicazioni host di Google Workspace, i componenti aggiuntivi che estendono Chat non mostrano una home page nel riquadro di accesso rapido a destra e non utilizzano addOns.common.homepageTrigger nel manifest. Invece, Chat mostra la tua home page come scheda nella scheda Home di un messaggio diretto 1:1 con l'app Chat ed è configurata nella console Google Cloud.

Puoi utilizzare la home page dell'app per condividere suggerimenti per interagire con l'app Chat, visualizzare una dashboard utente personalizzata o consentire agli utenti di accedere e configurare un servizio o strumento esterno da Chat.


Utilizza Card Builder per progettare e visualizzare in anteprima le interfacce utente e di messaggistica per le app di chat:

Apri il generatore di schede

Prerequisiti

HTTP

Un'app Google Chat che riceve e risponde alle interazioni degli utenti. Per crearne uno, completa la guida rapida HTTP.

Apps Script

Un'app Google Chat che riceve e risponde alle interazioni degli utenti. Per crearne uno, completa la guida rapida di Apps Script.

Configurare la home page dell'app per l'app di chat

Per supportare App Home, attiva Supporta App Home e configura il trigger di App Home nella console Google Cloud. La tua app Chat riceve un evento trigger Home app ogni volta che un utente apre la scheda Home in un messaggio diretto 1:1 con l'app Chat.

Per configurare App Home nella console Google Cloud:

  1. Nella console Google Cloud, vai a Menu > API e servizi > API Google Chat > Configurazione.

    Vai alla configurazione dell'API Chat

  2. Nella sezione Funzionalità interattive, assicurati che l'opzione Attiva funzionalità interattive sia attivata, quindi, nella sezione Funzionalità, seleziona la casella di controllo Supporta la home page dell'app.

  3. In Impostazioni di connessione > Trigger, specifica l'handler di App Home nel campo App Home in base all'architettura dell'app di chat:

    • HTTP: inserisci l'URL dell'endpoint HTTPS che gestisce le richieste della home page dell'app (o seleziona Utilizza un URL dell'endpoint HTTP comune per tutti i trigger in modo che l'URL dell'endpoint HTTP comune riceva tutti gli eventi).
    • Google Apps Script: inserisci il nome della funzione di callback di Google Apps Script che crea e restituisce la scheda della home page (il valore predefinito è onAppHome).
  4. Fai clic su Salva.

Gestire l'oggetto evento Home dell'app

Quando un utente apre la scheda Home di un messaggio diretto 1:1 con la tua app Chat, Chat invia un oggetto evento all'endpoint o alla funzione di callback di App Home.

A differenza degli eventi di interazione con lo spazio o con i messaggi, l'oggetto evento iniziale di App Home non include un payload di interazione unione (ad esempio messagePayload). Contiene i seguenti campi:

  • commonEventObject: Include clientPlatform, hostApp ("CHAT"), userLocale e userTimezone.
  • chat.user: l'utente di Chat che ha aperto la scheda Home.
  • chat.eventTime: il timestamp relativo al momento in cui l'utente ha aperto la scheda Home.

Creare una scheda della home page dell'app

Quando un utente apre la scheda Home, gestisci l'evento di attivazione Home app restituendo un oggetto RenderActions con un'azione di navigazione pushCard e un Card. Per creare un'esperienza interattiva, la scheda può contenere widget interattivi come pulsanti o input di testo.

HTTP

{
  "action": {
    "navigations": [
      {
        "pushCard": {
          "header": {
            "title": "Welcome to App Home"
          },
          "sections": [
            {
              "widgets": [
                {
                  "textParagraph": {
                    "text": "Manage your settings and view your dashboard here."
                  }
                },
                {
                  "buttonList": {
                    "buttons": [
                      {
                        "text": "Refresh",
                        "onClick": {
                          "action": {
                            "function": "https://example.com/updateAppHome"
                          }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

Apps Script

/**
 * Builds and returns the App Home card when a user opens the Home tab.
 *
 * @param {Object} event The event object from Google Chat.
 * @return {ActionResponse} The RenderActions response pushing the homepage card.
 */
function onAppHome(event) {
  const card = CardService.newCardBuilder()
      .setHeader(
          CardService.newCardHeader().setTitle('Welcome to App Home'))
      .addSection(
          CardService.newCardSection()
              .addWidget(
                  CardService.newTextParagraph().setText(
                      'Manage your settings and view your dashboard here.'))
              .addWidget(
                  CardService.newButtonSet().addButton(
                      CardService.newTextButton()
                          .setText('Refresh')
                          .setOnClickAction(
                              CardService.newAction().setFunctionName(
                                  'updateAppHome')))))
      .build();

  return CardService.newActionResponseBuilder()
      .setNavigation(CardService.newNavigation().pushCard(card))
      .build();
}

Rispondere alle interazioni con l'app Home

Se la scheda della schermata iniziale dell'app contiene widget interattivi, come pulsanti o input di moduli, un clic su un pulsante invia un oggetto evento contenente chat.buttonClickedPayload (insieme a commonEventObject.parameters e commonEventObject.formInputs) alla funzione o all'endpoint di azione configurato del pulsante.

Per aggiornare la scheda Home app in risposta a un'interazione dell'utente, restituisci un oggetto RenderActions con un'azione di navigazione updateCard. Per scoprire di più sulla lettura dei dati inseriti nei moduli dai widget interattivi, consulta Leggere i dati inseriti nei moduli dagli utenti sulle schede.

HTTP

{
  "action": {
    "navigations": [
      {
        "updateCard": {
          "header": {
            "title": "Welcome to App Home"
          },
          "sections": [
            {
              "widgets": [
                {
                  "textParagraph": {
                    "text": "Last updated: 2026-10-02T23:00:00Z"
                  }
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

Apps Script

/**
 * Updates the App Home card when a user clicks the Refresh button.
 *
 * @param {Object} event The event object from Google Chat.
 * @return {ActionResponse} The RenderActions response updating the homepage card.
 */
function updateAppHome(event) {
  const updatedCard = CardService.newCardBuilder()
      .setHeader(
          CardService.newCardHeader().setTitle('Welcome to App Home'))
      .addSection(
          CardService.newCardSection().addWidget(
              CardService.newTextParagraph().setText(
                  'Last updated: ' + new Date().toTimeString())))
      .build();

  return CardService.newActionResponseBuilder()
      .setNavigation(CardService.newNavigation().updateCard(updatedCard))
      .build();
}

Aprire le finestre di dialogo da App Home

L'app Chat può anche rispondere alle interazioni in App Home aprendo dialoghi.

Una finestra di dialogo con una serie di widget diversi.
Figura 2: una finestra di dialogo che chiede a un utente di aggiungere un contatto.

Per scoprire come aprire, aggiornare e chiudere le finestre di dialogo utilizzando RenderActions (pushCard, updateCard e endNavigation: "CLOSE_DIALOG"), consulta Aprire finestre di dialogo interattive.

App di chat che non sono componenti aggiuntivi: crea una home page per un'app di chat

Se gestisci un'app Chat che non è un componente aggiuntivo di Google Workspace, Chat invia un APP_HOMEevento di interazione quando un utente apre la scheda Home e invia eventi di interazione CARD_CLICKED o SUBMIT_FORM quando un utente interagisce con i widget nella scheda Home dell'app.

Per eseguire l'upgrade di un'app di Chat che non è un componente aggiuntivo al framework dei componenti aggiuntivi di Google Workspace, consulta Convertire un'app di Google Chat in un componente aggiuntivo di Google Workspace.

Creare una scheda della home page dell'app in un'app di chat che non sia un componente aggiuntivo

In un'app di chat che non è un componente aggiuntivo, gestisci l'evento di interazione APP_HOME restituendo una risposta contenente un campo renderActions di primo livello con pushCard navigazione:

Node.js

node/app-home/index.js
app.post('/', async (req, res) => {
  let event = req.body.chat;

  let body = {};
  if (event.type === 'APP_HOME') {
    // App home is requested
    body = { action: { navigations: [{
      pushCard: getHomeCard()
    }]}}
  } else if (event.type === 'SUBMIT_FORM') {
    // The update button from app home is clicked
    commonEvent = req.body.commonEventObject;
    if (commonEvent && commonEvent.invokedFunction === 'updateAppHome') {
      body = updateAppHome()
    }
  }

  return res.json(body);
});

// Create the app home card
function getHomeCard() {
  return { sections: [{ widgets: [
    { textParagraph: {
      text: "Here is the app home 🏠 It's " + new Date().toTimeString()
    }},
    { buttonList: { buttons: [{
      text: "Update app home",
      onClick: { action: {
        function: "updateAppHome"
      }}
    }]}}
  ]}]};
}

Python

python/app-home/main.py
@app.route('/', methods=['POST'])
def post() -> Mapping[str, Any]:
  """Handle requests from Google Chat

  Returns:
      Mapping[str, Any]: the response
  """
  event = request.get_json()
  match event['chat'].get('type'):

    case 'APP_HOME':
      # App home is requested
      body = { "action": { "navigations": [{
        "pushCard": get_home_card()
      }]}}

    case 'SUBMIT_FORM':
      # The update button from app home is clicked
      event_object = event.get('commonEventObject')
      if event_object is not None:
        if 'update_app_home' == event_object.get('invokedFunction'):
          body = update_app_home()

    case _:
      # Other response types are not supported
      body = {}

  return json.jsonify(body)


def get_home_card() -> Mapping[str, Any]:
  """Create the app home card

  Returns:
      Mapping[str, Any]: the card
  """
  return { "sections": [{ "widgets": [
    { "textParagraph": {
      "text": "Here is the app home 🏠 It's " +
        datetime.datetime.now().isoformat()
    }},
    { "buttonList": { "buttons": [{
      "text": "Update app home",
      "onClick": { "action": {
        "function": "update_app_home"
      }}
    }]}}
  ]}]}

Java

java/app-home/src/main/java/com/google/chat/app/home/App.java
// Process Google Chat events
@PostMapping("/")
@ResponseBody
public GenericJson onEvent(@RequestBody JsonNode event) throws Exception {
  switch (event.at("/chat/type").asText()) {
    case "APP_HOME":
      // App home is requested
      GenericJson navigation = new GenericJson();
      navigation.set("pushCard", getHomeCard());

      GenericJson action = new GenericJson();
      action.set("navigations", List.of(navigation));

      GenericJson response = new GenericJson();
      response.set("action", action);
      return response;
    case "SUBMIT_FORM":
      // The update button from app home is clicked
      if (event.at("/commonEventObject/invokedFunction").asText().equals("updateAppHome")) {
        return updateAppHome();
      }
  }

  return new GenericJson();
}

// Create the app home card
GoogleAppsCardV1Card getHomeCard() {
  return new GoogleAppsCardV1Card()
    .setSections(List.of(new GoogleAppsCardV1Section()
      .setWidgets(List.of(
        new GoogleAppsCardV1Widget()
          .setTextParagraph(new GoogleAppsCardV1TextParagraph()
            .setText("Here is the app home 🏠 It's " + new Date())),
        new GoogleAppsCardV1Widget()
          .setButtonList(new GoogleAppsCardV1ButtonList().setButtons(List.of(new GoogleAppsCardV1Button()
            .setText("Update app home")
            .setOnClick(new GoogleAppsCardV1OnClick()
              .setAction(new GoogleAppsCardV1Action()
                .setFunction("updateAppHome"))))))))));
}

Apps Script

Questo esempio invia un messaggio della scheda restituendo JSON della scheda. Puoi anche utilizzare il servizio di schede Apps Script.

apps-script/app-home/app-home.gs
/**
 * Responds to a APP_HOME event in Google Chat.
 */
function onAppHome() {
  return { action: { navigations: [{
    pushCard: getHomeCard()
  }]}};
}

/**
 * Returns the app home card.
 */
function getHomeCard() {
  return { sections: [{ widgets: [
    { textParagraph: {
      text: "Here is the app home 🏠 It's " + new Date().toTimeString()
    }},
    { buttonList: { buttons: [{
      text: "Update app home",
      onClick: { action: {
        function: "updateAppHome"
      }}
    }]}}
  ]}]};
}

Rispondere alle interazioni di App Home in un'app di chat che non è un componente aggiuntivo

In un'app di chat che non è un componente aggiuntivo, gestisci gli eventi di interazione CARD_CLICKED o SUBMIT_FORM da una scheda della home page dell'app restituendo una risposta contenente un campo renderActions di primo livello con la navigazione updateCard:

Node.js

node/app-home/index.js
// Update the app home
function updateAppHome() {
  return { renderActions: { action: { navigations: [{
    updateCard: getHomeCard()
  }]}}}
};

Python

python/app-home/main.py
def update_app_home() -> Mapping[str, Any]:
  """Update the app home

  Returns:
      Mapping[str, Any]: the update card render action
  """
  return { "renderActions": { "action": { "navigations": [{
    "updateCard": get_home_card()
  }]}}}

Java

java/app-home/src/main/java/com/google/chat/app/home/App.java
// Update the app home
GenericJson updateAppHome() {
  GenericJson navigation = new GenericJson();
  navigation.set("updateCard", getHomeCard());

  GenericJson action = new GenericJson();
  action.set("navigations", List.of(navigation));

  GenericJson renderActions = new GenericJson();
  renderActions.set("action", action);

  GenericJson response = new GenericJson();
  response.set("renderActions", renderActions);
  return response;
}

Apps Script

Questo esempio invia un messaggio della scheda restituendo JSON della scheda. Puoi anche utilizzare il servizio di schede Apps Script.

apps-script/app-home/app-home.gs
/**
 * Updates the home app.
 */
function updateAppHome() {
  return { renderActions: { action: { navigations: [{
    updateCard: getHomeCard()
  }]}}};
}