Создайте домашнюю страницу для приложения Google Chat

This page explains how to build a homepage for direct messages with your Google Chat app. A homepage, referred to as app home in the Google Chat API, is a customizable card interface that appears in the Home tab of direct message spaces between a user and a Chat app.

Домашняя карточка приложения с двумя виджетами.
Рисунок 1 : Пример главной страницы, которая отображается в личных сообщениях в приложении «Чат».

На главной странице приложения вы можете делиться советами по взаимодействию с приложением «Чат» или предоставлять пользователям доступ к внешним сервисам или инструментам из приложения «Чат» и разрешать им их использование.


Используйте конструктор карточек для разработки и предварительного просмотра сообщений и пользовательских интерфейсов для чат-приложений:

Откройте конструктор карточек.

Предварительные требования

Node.js

Приложение Google Chat, которое получает и обрабатывает события взаимодействия . Чтобы создать интерактивное приложение чата с использованием HTTP-сервиса, выполните следующие действия в этом кратком руководстве .

Python

Приложение Google Chat, которое получает и обрабатывает события взаимодействия . Чтобы создать интерактивное приложение чата с использованием HTTP-сервиса, выполните следующие действия в этом кратком руководстве .

Java

Приложение Google Chat, которое получает и обрабатывает события взаимодействия . Чтобы создать интерактивное приложение чата с использованием HTTP-сервиса, выполните следующие действия в этом кратком руководстве .

Apps Script

Приложение Google Chat, которое получает и обрабатывает события взаимодействия . Чтобы создать интерактивное приложение чата в Apps Script, выполните следующие действия в этом кратком руководстве .

Настройте домашний экран для вашего приложения чата.

To support app home, you must configure your Chat app to receive APP_HOME interaction events , Your Chat app receives this event whenever a user clicks the Home tab from a direct message with the Chat app.

Чтобы обновить параметры конфигурации в консоли Google Cloud, выполните следующие действия:

  1. В консоли Google Cloud перейдите в «Меню» > «API и сервисы» > «Включенные API и сервисы» > «Google Chat API» > «Конфигурация» . Перейдите в раздел «Конфигурация Chat API».
  2. В разделе «Интерактивные функции» перейдите в раздел «Функциональность» и выберите «Домашняя страница приложения поддержки» .
  3. Если ваше приложение для чата использует HTTP-сервис, перейдите в настройки подключения и укажите конечную точку в поле «URL-адрес домашней страницы приложения» . Вы можете использовать тот же URL-адрес, который указали в поле «URL-адрес конечной точки HTTP» .
  4. Нажмите « Сохранить ».

Создайте главную карточку приложения

When a user opens app home, your Chat app must handle the APP_HOME interaction event by returning an instance of RenderActions with pushCard navigation and a Card . To create an interactive experience, the card can contain interactive widgets such as buttons or text inputs that the Chat app can process and respond to with additional cards, or a dialog.

In the following example, the Chat app displays an initial app home card that displays the time the card was created and a button. When a user clicks the button, the Chat app returns an updated card that displays the time the updated card was created.

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

Реализуйте функцию onAppHome , которая вызывается после всех событий взаимодействия APP_HOME :

В этом примере отправляется сообщение в виде карточки, возвращая JSON-объект с именем карточки . Вы также можете использовать службу создания карточек 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"
      }}
    }]}}
  ]}]};
}

Реагируйте на действия, происходящие на главной странице приложения.

If your initial app home card contains interactive widgets, such as buttons or selection inputs, your Chat app must handle the related interaction events by returning an instance of RenderActions with updateCard navigation. To learn more about handling interactive widgets, see Process information inputted by users .

In the previous example, the initial app home card included a button. Whenever a user clicks the button, a CARD_CLICKED interaction event triggers the function updateAppHome to refresh the app home card, as shown in the following code:

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

В этом примере отправляется сообщение в виде карточки, возвращая JSON-объект с именем карточки . Вы также можете использовать службу создания карточек Apps Script .

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

Открыть диалоги

Ваше приложение «Чат» также может отвечать на сообщения на главной странице приложения, открывая диалоговые окна .

Диалоговое окно с различными виджетами.
Рисунок 3 : Диалоговое окно, предлагающее пользователю добавить контакт.

To open a dialog from app home, process the related interaction event by returning renderActions with updateCard navigation that contains a Card object. In the following example, a Chat app responds to a button click from an app home card by processing the CARD_CLICKED interaction event and opening a dialog:

{ renderActions: { action: { navigations: [{ updateCard: { sections: [{
  header: "Add new contact",
  widgets: [{ "textInput": {
    label: "Name",
    type: "SINGLE_LINE",
    name: "contactName"
  }}, { textInput: {
    label: "Address",
    type: "MULTIPLE_LINE",
    name: "address"
  }}, { decoratedText: {
    text: "Add to favorites",
    switchControl: {
      controlType: "SWITCH",
      name: "saveFavorite"
    }
  }}, { decoratedText: {
    text: "Merge with existing contacts",
    switchControl: {
      controlType: "SWITCH",
      name: "mergeContact",
      selected: true
    }
  }}, { buttonList: { buttons: [{
    text: "Next",
    onClick: { action: { function: "openSequentialDialog" }}
  }]}}]
}]}}]}}}

Для закрытия диалога обработайте следующие события взаимодействия:

  • CLOSE_DIALOG : Закрывает диалоговое окно и возвращает на главную страницу приложения «Чат».
  • CLOSE_DIALOG_AND_EXECUTE : Закрывает диалоговое окно и обновляет главную страницу приложения.

В следующем примере кода используется CLOSE_DIALOG для закрытия диалогового окна и возврата на главную страницу приложения:

{ renderActions: { action: {
  navigations: [{ endNavigation: { action: "CLOSE_DIALOG" }}]
}}}

Для сбора информации от пользователей можно также создавать последовательные диалоги. Чтобы узнать, как создавать последовательные диалоги, см. раздел «Открытие диалогов и ответы на них» .