Creare una home page per un'app Google Chat

Questa pagina spiega come creare una home page per App Google Chat. La home page dell'app è un'interfaccia di carte personalizzabile che un'app di Chat invia a un utente quando apre una pagina con l'app Chat.

Scheda della home page dell'app con due widget.

Ad esempio, puoi configurare il messaggio della scheda Home dell'app in modo che includa suggerimenti per l'interazione con App di chat con comandi slash. Per gli utenti finali, la home page dell'app disponibile nel messaggio diretto di un'app di Chat solo se lo sviluppatore di app attiva la funzionalità.


Utilizza Card Builder per progettare e visualizzare l'anteprima di messaggi delle schede JSON per le app di chat:

Apri il generatore di schede

Prerequisiti

Python

Un'app di Google Chat abilitata per le funzionalità interattive. Per creare un un'app di chat interattiva utilizzando un servizio HTTP, completa questa guida rapida.

Apps Script

Un'app di Google Chat abilitata per le funzionalità interattive. Per creare un app di Chat interattiva in Apps Script, completa questa guida rapida.

Node.js

Un'app di Google Chat abilitata per le funzionalità interattive. Per creare un un'app di chat interattiva utilizzando un servizio HTTP, completa questa guida rapida.

Java

Un'app di Google Chat abilitata per le funzionalità interattive. Per creare un un'app di chat interattiva utilizzando un servizio HTTP, completa questa guida rapida.

Configura l'API Chat

Per supportare la home page dell'app, devi aggiornare la configurazione dell'API Chat nella console Google Cloud.

Python

  1. Nella console Google Cloud, vai a Menu > Altri prodotti > Google Workspace > Libreria prodotti > API Google Chat.

    Vai all'API Google Chat

  2. Fai clic su Gestisci, quindi sulla scheda Configurazione.

  3. Seleziona la casella di controllo Support App Home.

  4. Aggiungi un URL nel campo URL della home page dell'app. Questo valore è solitamente lo stesso URL come URL dell'app. Questo URL viene chiamato APP_HOME eventi.

  5. Fai clic su Salva.

Apps Script

  1. Nella console Google Cloud, vai a Menu > Altri prodotti > Google Workspace > Libreria prodotti > API Google Chat.

    Vai all'API Google Chat

  2. Fai clic su Gestisci, quindi sulla scheda Configurazione.

  3. Seleziona la casella di controllo Support App Home.

  4. Fai clic su Salva.

Node.js

  1. Nella console Google Cloud, vai a Menu > Altri prodotti > Google Workspace > Libreria prodotti > API Google Chat.

    Vai all'API Google Chat

  2. Fai clic su Gestisci, quindi sulla scheda Configurazione.

  3. Seleziona la casella di controllo Support App Home.

  4. Aggiungi un URL nel campo URL della home page dell'app. Questo valore è solitamente lo stesso URL come URL dell'app. Questo URL viene chiamato APP_HOME eventi.

  5. Fai clic su Salva.

Java

  1. Nella console Google Cloud, vai a Menu > Altri prodotti > Google Workspace > Libreria prodotti > API Google Chat.

    Vai all'API Google Chat

  2. Fai clic su Gestisci, quindi sulla scheda Configurazione.

  3. Seleziona la casella di controllo Support App Home.

  4. Aggiungi un URL nel campo URL della home page dell'app. Questo valore è solitamente lo stesso URL come URL dell'app. Questo URL viene chiamato APP_HOME eventi.

  5. Fai clic su Salva.

Home page di Build app

La scheda della home page dell'app viene avviata quando un utente apre un messaggio diretto dalla app di chat e può essere aggiornata in risposta Un evento interattivo come un clic su un pulsante, l'invio di un modulo o la chiusura di una finestra di dialogo.

Nell'esempio seguente, l'app Chat mostra una scheda iniziale della home page dell'app che mostra l'ora in cui è stata creata e un pulsante. Quando un utente fa clic sul pulsante, l'app Chat restituisce una scheda aggiornata che mostra l'ora in cui è stata creata.

Crea la carta iniziale per la home page dell'app

Per creare la home page dell'app, l'app Chat deve gestire APP_HOME eventi di interazione e restituiscono un'istanza di RenderActions con navigazione pushCard.

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"
      }}
    }]}}
  ]}]}

Apps Script

Implementa la funzione onAppHome che viene richiamata dopo tutti gli eventi APP_HOME:

Questo esempio invia un messaggio di una scheda restituendo JSON card. Puoi utilizzare anche 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"
      }}
    }]}}
  ]}]};
}

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"
      }}
    }]}}
  ]}]};
}

Java

java/app-home/src/main/java/com/google/chat/app/home/App.java
/**
 * Process Google Chat events
 *
 * @param event Event from chat.
 * @return GenericJson
 * @throws Exception
 */
@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() {
  GoogleAppsCardV1TextParagraph textParagraph = new GoogleAppsCardV1TextParagraph();
  textParagraph.setText("Here is the app home 🏠 It's " + new Date());

  GoogleAppsCardV1Widget textParagraphWidget = new GoogleAppsCardV1Widget();
  textParagraphWidget.setTextParagraph(textParagraph);

  GoogleAppsCardV1Action action = new GoogleAppsCardV1Action();
  action.setFunction("updateAppHome");

  GoogleAppsCardV1OnClick onClick = new GoogleAppsCardV1OnClick();
  onClick.setAction(action);

  GoogleAppsCardV1Button button = new GoogleAppsCardV1Button();
  button.setText("Update app home");
  button.setOnClick(onClick);

  GoogleAppsCardV1ButtonList buttonList = new GoogleAppsCardV1ButtonList();
  buttonList.setButtons(List.of(button));

  GoogleAppsCardV1Widget buttonListWidget = new GoogleAppsCardV1Widget();
  buttonListWidget.setButtonList(buttonList);

  GoogleAppsCardV1Section section = new GoogleAppsCardV1Section();
  section.setWidgets(List.of(textParagraphWidget, buttonListWidget));

  GoogleAppsCardV1Card card = new GoogleAppsCardV1Card();
  card.setSections(List.of(section));

  return card;
}

Aggiorna la scheda Home dell'app

Se la scheda iniziale dell'app iniziale contiene widget interattivi, ad esempio pulsanti o input di selezione, l'app Chat deve gestire gli eventi di interazione correlati restituendo un'istanza RenderActions con navigazione updateCard. Per scoprire di più sulla gestione delle richieste interattive, widget, vedi Elabora le informazioni inserite dagli utenti.

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()
  }]}}}

Apps Script

Questo esempio invia un messaggio di una scheda restituendo JSON card. Puoi utilizzare anche Servizio di schede Apps Script.

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

Node.js

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

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;
}

Limitazioni

In generale, navigation è non è disponibile per le app di chat. Non puoi restituire una pila di carte. Solo pushCard (per la risposta iniziale) e updateCard (per gli aggiornamenti) sono disponibile per le app di chat.