Ouvrir les boîtes de dialogue interactives

Ce guide explique comment implémenter des boîtes de dialogue pour votre application Chat.

Les boîtes de dialogue sont des interfaces fenêtrées basées sur des fiches que les applications Chat ouvrent pour interagir avec les utilisateurs. Pour aider les utilisateurs à effectuer des processus en plusieurs étapes, les applications peuvent ouvrir des boîtes de dialogue séquentielles.

Les boîtes de dialogue sont utiles pour de nombreux types d'interactions utilisateur:

  • Collecte d'informations auprès des utilisateurs
  • Authentifier les utilisateurs avec des services Web
  • Configurer les paramètres de l'application Chat

Prérequis

Node.js

Apps Script

Python

Fonctionnement des boîtes de dialogue

Lorsqu'un utilisateur clique sur un bouton d'une fiche ou envoie une commande à barre oblique, l'application Chat peut ouvrir une boîte de dialogue pour interagir avec l'utilisateur.

Cliquer sur un bouton sur une fiche pour ouvrir une boîte de dialogue
Figure 1: Cliquer sur un bouton sur une fiche pour ouvrir une boîte de dialogue
Cliquer sur un bouton sur une fiche pour ouvrir une boîte de dialogue
Figure 2: Exécuter une commande à barre oblique pour ouvrir une boîte de dialogue.

Cette boîte de dialogue facilite l'interaction des utilisateurs en leur permettant de saisir des informations à l'aide de widgets (champs de saisie de texte, par exemple). Lorsque vous collectez de nombreuses informations auprès des utilisateurs, les applications Chat peuvent ouvrir des boîtes de dialogue séquentielles.

Boîte de dialogue présentant différents widgets.
Figure 3: Boîte de dialogue ouverte invitant l'utilisateur à ajouter un contact.
Boîte de dialogue présentant différents widgets.
Figure 4: Une deuxième boîte de dialogue invite l'utilisateur à fournir plus d'informations.

Une fois l'opération terminée, l'application Chat reçoit les valeurs saisies par les utilisateurs dans la boîte de dialogue au format JSON. Informez les utilisateurs que leur interaction a abouti en répondant par SMS ou par carte.

Ouvrir une boîte de dialogue

Votre application Chat peut ouvrir une boîte de dialogue en réponse à un utilisateur:

Lorsqu'un utilisateur demande une boîte de dialogue, votre application Chat reçoit un message Event Google Chat dans lequel:

  • isDialogEvent : true.
  • DialogEventType indique si un utilisateur ouvre une boîte de dialogue (REQUEST_DIALOG), clique sur un bouton dans une boîte de dialogue (SUBMIT_DIALOG) ou annule une boîte de dialogue (CANCEL_DIALOG).

Par exemple, lorsqu'un utilisateur ouvre une boîte de dialogue, votre application Chat reçoit un message Event de ce type de la part de Google Chat:

JSON

{
  "type": enum (EventType),
  "eventTime": string,
  "threadKey": string,
  "message": {
    object (Message)
  },
  "user": {
    object (User)
  },
  "space": {
    object (Space)
  },
  "action": {
    object (FormAction)
  },
  "configCompleteRedirectUrl": string,
  "isDialogEvent": true,
  "dialogEventType": "REQUEST_DIALOG",
  "common": {
    object (CommonEventObject)
  }
}

L'application de chat peut ouvrir une boîte de dialogue en renvoyant uneActionResponse"type": "DIALOG" DialogAction avec une description JSON de la boîte de dialogue:

JSON

{
  "action_response": {
    "type": "DIALOG",
    "dialog_action": {
      "dialog": {
        "body": {
          "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"
                          }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          ]
        }
      }
    }
  }
}

Ouvrir une boîte de dialogue en réponse à un clic sur un bouton sur une fiche

Lorsqu'un utilisateur clique sur un bouton d'une fiche, votre application reçoit un élément Event dans lequel:

Pour ouvrir une boîte de dialogue:

  • onClick.action.function comme nom d'une fonction qui ouvre une boîte de dialogue. Cette fonction doit renvoyer :
  • onClick.action.interaction en tant que OPEN_DIALOG. Cette propriété indique à Google Chat que l'application souhaite ouvrir une boîte de dialogue.

Dans cet exemple, une application de chat répond à un Event MESSAGE avec une fiche comportant un bouton qui ouvre une boîte de dialogue:

Node.js

/**
* Responds to messages that have links whose URLs
* match URL patterns configured for link previews.
*
* @param {Object} event The event object from Chat
* API.
*
* @return {Object} Response from the Chat app
* attached to the message with the previewed link.
*/
exports.onMessage = function onMessage(req, res) {

  // Store the Google Chat event as a variable.
  var event = req.body;

  if (req.method === "GET" || !event.message) {
    res.send("Hello! This function is meant to be used in a Google Chat " +
      "Space.");
  }

  // Responds with a card that prompts the user to add a contact
  else {
    res.json({
      "cardsV2": [{
        "cardId": "addContact",
        "card": {
          "header": {
            "title": "Rolodex",
            "subtitle": "Manage your contacts!",
            "imageUrl": "https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png",
            "imageType": "CIRCLE"
          },
          "sections": [
            {
              "widgets": [
                {
                  "buttonList": {
                    "buttons": [
                      {
                        "text": "Add Contact",
                        "onClick": {
                          "action": {
                            "function": "openDialog",
                            "interaction": "OPEN_DIALOG"
                          }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          ]
        }
      }]

    });
  }

  // Respond to button clicks on attached cards
  if(event.type === "CARD_CLICKED") {

    if (event.common.invokedFunction == "openDialog") {
      res.openDialog(event);
};

/**
 * Opens and starts a dialog that allows users to add details about a contact.
 *
 * @param {object} event the event object from Google Chat.
 *
 * @return {object} open a dialog.
 */
function openDialog(event) {
  res.json({
    "action_response": {
        "type": "DIALOG",
        "dialog_action": {
          "dialog": {
            "body": {
              "sections": [
                {
                  "header": "Add new contact",
                  "widgets": [
                    {
                      "textInput": {
                        "label": "Name",
                        "type": "SINGLE_LINE",
                        "name": "name"
                      }
                    },
                    {
                      "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"
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }
        }
    }
  });
};

Apps Script

/**
 * Responds to a MESSAGE event in Google Chat with a card with a button
 * that opens a dialog.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in response to a card's button click.
 */
function onMessage(event) {
  return {
    "cardsV2": [{
      "cardId": "addContact",
      "card": {
        "header": {
          "title": "Rolodex",
          "subtitle": "Manage your contacts!",
          "imageUrl": "https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png",
          "imageType": "CIRCLE"
        },
        "sections": [
          {
            "widgets": [
              {
                "buttonList": {
                  "buttons": [
                    {
                      "text": "Add Contact",
                      "onClick": {
                        "action": {
                          "function": "openDialog",
                          "interaction": "OPEN_DIALOG"
                        }
                      }
                    }
                  ]
                },
                "horizontalAlignment": "CENTER"
              }
            ]
          }
        ]
      }
    }]
  };
}

/**
 * Responds to a CARD_CLICKED event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onCardClick(event) {
  if (event.common.invokedFunction == "openDialog") {
    return openDialog(event);
  }
}

/**
 * Opens a dialog in Google Chat.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in Google Chat.
 */
function openDialog(event) {
  return {
    "action_response": {
      "type": "DIALOG",
      "dialog_action": {
        "dialog": {
          "body": {
            "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"
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  };
}

Python

from typing import Any, Mapping

import flask
import functions_framework

@functions_framework.http
def main(req: flask.Request) -> Mapping[str, Any]:
  """Responds to a MESSAGE event in Google Chat that includes the /createContact
     slash command by opening a dialog.

  Args:
      req (flask.Request): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a card's button click.
  """

  if req.method == 'GET':
    return 'Sorry, this function must be called from a Google Chat.'

  request = req.get_json(silent=True)

  if request.get('type') == 'CARD_CLICKED':
    if request.get('common', dict()).get('invokedFunction') == 'open_dialog':
      return open_dialog(request)

  else:
    return {
      'cardsV2': [{
        'cardId': 'addContact',
        'card': {
          'header': {
            'title': 'Rolodex',
            'subtitle': 'Manage your contacts!',
            'imageUrl': 'https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png',
            'imageType': 'CIRCLE'
          },
          'sections': [
            {
              'widgets': [
                {
                  'buttonList': {
                    'buttons': [
                      {
                        'text': 'Add Contact',
                        'onClick': {
                          'action': {
                            'function': 'open_dialog',
                            'interaction': 'OPEN_DIALOG'
                          }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          ]
        }
      }]
    }

def open_dialog(request: Mapping[str, Any]) -> Mapping[str, Any]:
  """Opens a dialog in Google Chat.

  Args:
      request (Mapping[str, Any]): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a card's button click.
  """
  return {
    'action_response': {
      'type': 'DIALOG',
      'dialog_action': {
        'dialog': {
          'body': {
            'sections': [
              {
                'header': 'Add new contact',
                'widgets': [
                  {
                    'textInput': {
                      'label': 'Name',
                      'type': 'SINGLE_LINE',
                      'name': 'name'
                    }
                  },
                  {
                    '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': 'open_sequential_dialog'
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }

Ouvrir une boîte de dialogue en réponse à une commande à barre oblique

Lorsqu'un utilisateur ouvre une boîte de dialogue avec une commande à barre oblique, votre application reçoit un Event où:

Pour ouvrir une boîte de dialogue:

Dans cet exemple, une application de chat répond à la commande à barre oblique /createContact en ouvrant une boîte de dialogue:

Node.js

/**
* Responds to messages that have links whose URLs
* match URL patterns configured for link previews.
*
* @param {Object} event The event object from Chat
* API.
*
* @return {Object} Response from the Chat app
* attached to the message with the previewed link.
*/
exports.onMessage = function onMessage(req, res) {

  // Store the Google Chat event as a variable.
  var event = req.body;

  if (req.method === "GET" || !event.message) {
    res.send("Hello! This function is meant to be used in a Google Chat " +
      "Space.");
  }

  // Checks for the presence of event.message.slashCommand.
  // If the slash command is "/help", responds with a text message.
  // If the slash command is "/createContact", opens a dialog.
  if (event.message.slashCommand) {
    switch (event.message.slashCommand.commandId) {
      case 1: // /help
        res.json({"text": "Contact bot helps you update your address book!"});
      case 2:  // /createContact
        res.openDialog(event);
    }
  }
};

/**
 * Opens and starts a dialog that allows users to add details about a contact.
 *
 * @param {object} event the event object from Google Chat.
 *
 * @return {object} open a dialog.
 */
function openDialog(event) {
  res.json({
    "action_response": {
        "type": "DIALOG",
        "dialog_action": {
          "dialog": {
            "body": {
              "sections": [
                {
                  "header": "Add new contact",
                  "widgets": [
                    {
                      "textInput": {
                        "label": "Name",
                        "type": "SINGLE_LINE",
                        "name": "name"
                      }
                    },
                    {
                      "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"
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }
        }
    }
  });
};

Apps Script

/**
 * Responds to a MESSAGE event in Google Chat that includes the /createContact
 * slash command by opening a dialog.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in response to a slash command.
 */
function onMessage(event) {

  // Checks for the presence of event.message.slashCommand.
  // If the slash command is "/help", responds with a text message.
  // If the slash command is "/createContact", opens a dialog.
  if (event.message.slashCommand) {
    switch (event.message.slashCommand.commandId) {
      case 1: // /help
        return {"text": "Contact bot helps you update your address book!"}
      case 2:  // /createContact
        return openDialog(event);
    }
  }
}

/**
 * Opens a dialog in Google Chat.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in Google Chat.
 */
function openDialog(event) {
  return {
    "action_response": {
      "type": "DIALOG",
      "dialog_action": {
        "dialog": {
          "body": {
            "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"
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  };
}

Python

from typing import Any, Mapping

import flask
import functions_framework

@functions_framework.http
def main(req: flask.Request) -> Mapping[str, Any]:
  """Responds to a MESSAGE event in Google Chat that includes the /createContact
     slash command by opening a dialog.

  Args:
      req (flask.Request): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a slash command.
  """
  if req.method == 'GET':
    return 'Sorry, this function must be called from a Google Chat.'

  request = req.get_json(silent=True)

  if slash_command := request.get('message', dict()).get('slashCommand'):
    command_id = slash_command['commandId']
    if command_id == 1:
      return {'text': 'Contact bot helps you update your address book!'}

    elif command_id == 2:
      return open_dialog(request)

def open_dialog(request: Mapping[str, Any]) -> Mapping[str, Any]:
  """Opens a dialog in Google Chat.

  Args:
      request (Mapping[str, Any]): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a slash command.
  """
  return {
    'action_response': {
      'type': 'DIALOG',
      'dialog_action': {
        'dialog': {
          'body': {
            'sections': [
              {
                'header': 'Add new contact',
                'widgets': [
                  {
                    'textInput': {
                      'label': 'Name',
                      'type': 'SINGLE_LINE',
                      'name': 'name'
                    }
                  },
                  {
                    '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': 'open_sequential_dialog'
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }

Associer plusieurs interfaces de carte

Lorsque les interactions de l'utilisateur nécessitent plusieurs fiches, vous pouvez ouvrir une nouvelle carte à partir de la même boîte de dialogue en renvoyant une autre boîte de dialogue.

Lorsque les utilisateurs cliquent sur un bouton dans une boîte de dialogue, votre application reçoit un Event où:

Étant donné qu'une boîte de dialogue est déjà ouverte, ne spécifiez pas onClick.action.interaction comme vous le faites lorsque vous ouvrez une boîte de dialogue à partir d'une fiche de conversation. Remplacez plutôt onClick.action.function par le nom d'une fonction qui ouvre une boîte de dialogue.

Dans cet exemple, une application de chat répond à un Event CARD_CLICKED à partir d'un bouton de boîte de dialogue:

Node.js

// Respond to button clicks on attached cards
if(event.type === "CARD_CLICKED") {

  // Open the first dialog.
  if (event.common.invokedFunction == "openDialog") {
    res.openDialog(event);
  }

  // Open the second dialog.
  if (event.common.invokedFunction == "openSequentialDialog") {
    res.openSequentialDialog(event);
  }
}

/**
* Opens and starts a dialog that allows users to add details about a contact.
*
* @param {object} event the event object from Google Chat.
*
* @return {object} open a dialog.
*/
function openDialog(event) {
  res.json({
    "action_response": {
        "type": "DIALOG",
        "dialog_action": {
          "dialog": {
            "body": {
              "sections": [
                {
                  "header": "Add new contact",
                  "widgets": [
                    {
                      "textInput": {
                        "label": "Name",
                        "type": "SINGLE_LINE",
                        "name": "name"
                      }
                    },
                    {
                      "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"
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }
        }
    }
  });
};

/**
* Opens a second dialog that allows users to add more contact details.
*
* @param {object} event the event object from Google Chat.
*
* @return {object} open a dialog.
*/
function openSequentialDialog(event) {
res.json({
  "action_response": {
      "type": "DIALOG",
      "dialog_action": {
        "dialog": {
          "body": {
            "sections": [
              {
                "header": "Add new contact",
                "widgets": [
                  {
                    "textInput": {
                      "label": "Notes",
                      "type": "MULTIPLE_LINE",
                      "name": "notes"
                    }
                  },
                  {
                    "selectionInput": {
                      "type": "RADIO_BUTTON",
                      "label": "Contact type",
                      "name": "contactType",
                      "items": [
                        {
                          "text": "Work",
                          "value": "Work",
                          "selected": false
                        },
                        {
                          "text": "Personal",
                          "value": "Personal",
                          "selected": false
                        }
                      ]
                    }
                  },
                  {
                    "buttonList": {
                      "buttons": [
                        {
                          "text": "Submit",
                          "onClick": {
                            "action": {
                              "function": "confirmDialogSuccess",
                              "parameters": [
                                {
                                  "key": "confirmDialogSuccess",
                                  "value": "confirmDialogSuccess"
                                }
                              ]
                            }
                          }
                        }
                      ]
                    },
                    "horizontalAlignment": "END"
                  }
                ]
              }
            ]
          }
        }
      }
  }
});

Apps Script

/**
 * Responds to a CARD_CLICKED event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onCardClick(event) {

  // When a user clicks a card, the app checks to see which function to run.
  if (event.common.invokedFunction == "openDialog") {
    return openDialog(event);
  }

  if (event.common.invokedFunction == "openSequentialDialog") {
    return openSequentialDialog(event);
  }
}

/**
 * Opens and starts a dialog that allows users to add details about a contact.
 *
 * @param {object} event the event object from Google Chat.
 *
 * @return {object} open a dialog.
 */
function openDialog(event) {
  return {
    "action_response": {
        "type": "DIALOG",
        "dialog_action": {
          "dialog": {
            "body": {
              "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": {

                                // Specifies which function to run
                                // in response to the card click.
                                "function": "openSequentialDialog"
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }
        }
    }
  };
}

/**
 * Opens a second dialog that allows users to add more contact details.
 *
 * @param {object} event the event object from Google Chat.
 *
 * @return {object} open a dialog.
 */
function openSequentialDialog(event) {
  return {
    "action_response": {
        "type": "DIALOG",
        "dialog_action": {
          "dialog": {
            "body": {
              "sections": [
                {
                  "header": "Add new contact",
                  "widgets": [
                    {
                      "textInput": {
                        "label": "Notes",
                        "type": "MULTIPLE_LINE",
                        "name": "notes"
                      }
                    },
                    {
                      "selectionInput": {
                        "type": "RADIO_BUTTON",
                        "label": "Contact type",
                        "name": "contactType",
                        "items": [
                          {
                            "text": "Work",
                            "value": "Work",
                            "selected": false
                          },
                          {
                            "text": "Personal",
                            "value": "Personal",
                            "selected": false
                          }
                        ]
                      }
                    },
                    {
                      "buttonList": {
                        "buttons": [
                          {
                            "text": "Submit",
                            "onClick": {
                              "action": {

                                // Specifies which function to run
                                // in response to the card click.
                                "function": "receiveDialog",
                                "parameters": [
                                  {
                                    "key": "receiveDialog",
                                    "value": "receiveDialog"
                                  }
                                ]
                              }
                            }
                          }
                        ]
                      },
                      "horizontalAlignment": "END"
                    }
                  ]
                }
              ]
            }
          }
        }
    }
  };
}

Python

from typing import Any, Mapping

import flask
import functions_framework

@functions_framework.http
def main(req: flask.Request) -> Mapping[str, Any]:
  """Responds to a MESSAGE event in Google Chat that includes the /createContact
     slash command by opening a dialog.

  Args:
      req (flask.Request): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a card's button click.
  """

  if req.method == 'GET':
    return 'Sorry, this function must be called from a Google Chat.'

  request = req.get_json(silent=True)

  if request.get('type') == 'CARD_CLICKED':
    if invoked_function := request.get('common', dict()).get('invokedFunction'):
      if invoked_function == 'open_dialog':
        return open_dialog(request)

      elif invoked_function == 'open_sequential_dialog':
        return open_dialog(request)

def open_dialog(request: Mapping[str, Any]) -> Mapping[str, Any]:
  """Opens a dialog in Google Chat.

  Args:
      request (Mapping[str, Any]): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a card's button click.
  """
  return {
    'action_response': {
      'type': 'DIALOG',
      'dialog_action': {
        'dialog': {
          'body': {
            'sections': [
              {
                'header': 'Add new contact',
                'widgets': [
                  {
                    'textInput': {
                      'label': 'Name',
                      'type': 'SINGLE_LINE',
                      'name': 'name'
                    }
                  },
                  {
                    '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': 'open_sequential_dialog'
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }

def open_sequential_dialog(request: Mapping[str, Any]) -> Mapping[str, Any]:
  """Opens a second dialog that allows users to add more contact details.

  Args:
      request (Mapping[str, Any]): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a card's button click.
  """
  return {
    'action_response': {
      'type': 'DIALOG',
      'dialog_action': {
        'dialog': {
          'body': {
            'sections': [
              {
                'header': 'Add new contact',
                'widgets': [
                  {
                    'textInput': {
                      'label': 'Notes',
                      'type': 'MULTIPLE_LINE',
                      'name': 'notes'
                    }
                  },
                  {
                    'selectionInput': {
                      'type': 'RADIO_BUTTON',
                      'label': 'Contact type',
                      'name': 'contactType',
                      'items': [
                        {
                          'text': 'Work',
                          'value': 'Work',
                          'selected': False
                        },
                        {
                          'text': 'Personal',
                          'value': 'Personal',
                          'selected': False
                        }
                      ]
                    }
                  },
                  {
                    'buttonList': {
                      'buttons': [
                        {
                          'text': 'Submit',
                          'onClick': {
                            'action': {
                              'function': 'receiveDialog',
                              'parameters': [
                                {
                                  'key': 'receiveDialog',
                                  'value': 'receiveDialog'
                                }
                              ]
                            }
                          }
                        }
                      ]
                    },
                    'horizontalAlignment': 'END'
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }

Recevoir des données de formulaire à partir de boîtes de dialogue

Lorsque les utilisateurs cliquent sur un bouton dans une boîte de dialogue, les données qu'ils ont saisies sont envoyées à l'application Chat, qui reçoit alors un message Event dans lequel:

Les données que les utilisateurs saisissent dans la boîte de dialogue sont disponibles sur Event en tant que Event.common.formInputs, une carte dans laquelle les clés sont des ID de chaîne attribués à chaque widget de dialogue et des valeurs représentent les entrées utilisateur pour chaque widget. Différents objets représentent différents types de données d'entrée. Par exemple, Event.common.formInputs.stringInputs représentent des entrées de chaîne.

Lorsqu'un utilisateur envoie une boîte de dialogue, votre application Chat reçoit un message Event de ce type de la part de Google Chat:

JSON

{
  "type": enum (EventType),
  "eventTime": string,
  "threadKey": string,
  "message": {
    object (Message)
  },
  "user": {
    object (User)
  },
  "space": {
    object (Space)
  },
  "action": {
    object (FormAction)
  },
  "configCompleteRedirectUrl": string,

  // Indicates that this event is dialog-related.
  "isDialogEvent": true,

  // Indicates that a user clicked a button, and all data
  // they entered in the dialog is included in Event.common.formInputs.
  "dialogEventType": "SUBMIT_DIALOG",
  "common": {
    "userLocale": string,
    "hostApp": enum (HostApp),
    "platform": enum (Platform),
    "timeZone": {
      object (TimeZone)
    },

    // Represents user data entered in a dialog
    "formInputs": {

      // Represents string data entered in a dialog, like text input fields
      // and check boxes
      "stringInputs": {

        // An array of strings entered by the user in a dialog.
        "value": [
          string
        ]
      }
    },
    "parameters": {
      string: string,
      ...
    },
    "invokedFunction": string
  }
}

Votre application peut accéder à la première valeur saisie par l'utilisateur au niveau de event.common.formInputs.NAME.stringInputs.value[0], où NAME est le champ name d'un widget TextInput.

Après avoir reçu les données du formulaire de la boîte de dialogue, l'application Chat doit accuser réception de la confirmation, répondre à l'aide d'un SMS ou d'une carte, ou bien renvoyer une erreur. Pour cela, il suffit de renvoyer un message ActionResponse:

  • Pour accuser réception, vous devez répondre avec un message ActionResponse contenant "actionStatus": "OK".
  • Pour répondre par SMS ou par carte, répondez en envoyant un ActionResponse avec un ResponseType de NEW_MESSAGE, UPDATE_MESSAGE ou UPDATE_USER_MESSAGE_CARDS. Pour en savoir plus, consultez Répondre à une boîte de dialogue.
  • Pour renvoyer une erreur, répondez avec un message ActionResponse contenant "actionStatus": "ERROR MESSAGE".

L'exemple suivant vérifie la présence d'une valeur "name". S'il est absent, l'application renvoie une erreur. Si elles sont présentes, l'application accuse réception des données du formulaire et ferme la boîte de dialogue.

Node.js

/**
 * Checks for a form input error, the absence of
 * a "name" value, and returns an error if absent.
 * Otherwise, confirms successful receipt of a dialog.
 *
 * Confirms successful receipt of a dialog.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in Google Chat.
 */
function receiveDialog(event) {

  // Checks to make sure the user entered a name
  // in a dialog. If no name value detected, returns
  // an error message.
  if (event.common.formInputs.WIDGET_NAME.stringInputs.value[0] == "") {
    return {
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": {
            "statusCode": "OK", 
            "userFacingMessage": "Don't forget to name your new contact!"
        }
      }
    };

  // Otherwise the app indicates that it received
  // form data from the dialog. Any value other than "OK"
  // gets returned as an error. "OK" is interpreted as
  // code 200, and the dialog closes.
  } else {
    res.json({
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "OK"
        }
      }
    });
  }
}

Apps Script

/**
 * Checks for a form input error, the absence of
 * a "name" value, and returns an error if absent.
 * Otherwise, confirms successful receipt of a dialog.
 *
 * Confirms successful receipt of a dialog.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in Google Chat.
 */
function receiveDialog(event) {

  // Checks to make sure the user entered a name
  // in a dialog. If no name value detected, returns
  // an error message.
  if (event.common.formInputs.WIDGET_NAME[""].stringInputs.value[0]) {
    return {
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "Don't forget to name your new contact!"
        }
      }
    };

  // Otherwise the app indicates that it received
  // form data from the dialog. Any value other than "OK"
  // gets returned as an error. "OK" is interpreted as
  // code 200, and the dialog closes.
  } else {
    return {
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "OK"
        }
      }
    };
  }
}

Python

def receive_dialog(event: Mapping[str, Any]) -> Mapping[str, Any]:
  """Checks for a form input error, the absence of a "name" value, and returns
     an error if absent. Otherwise, confirms successful receipt of a dialog.

  Args:
      event (Mapping[str, Any]): the event object from Chat API.

  Returns:
      Mapping[str, Any]: the response.
  """

  if common := event.get('common'):
    if form_inputs := common.get('formInputs'):
      if contact_name := form_inputs.get('WIDGET_NAME'):
        if string_inputs := contact_name.get('stringInputs'):
          if name := string_inputs.get('value')[0]:
            return {
              'actionResponse': {
                'type': 'DIALOG',
                'dialogAction': {
                  'actionStatus': 'OK'
                }
              }
            }
          else:
            return {
              'actionResponse': {
                'type': 'DIALOG',
                'dialogAction': {
                  'actionStatus': 'Don\'t forget to name your new contact!'
                }
              }
            }

Répondre à une boîte de dialogue

Vous pouvez répondre à une boîte de dialogue par un nouveau message ou une mise à jour d'un message existant.

Répondre à une boîte de dialogue avec un nouveau message

Pour répondre à un envoi de formulaire de boîte de dialogue par un nouveau message, l'application Chat renvoie un ActionResponse de type NEW_MESSAGE, ainsi qu'un balisage indiquant le contenu du nouveau message. À la réception de cette réponse, la boîte de dialogue se ferme et le nouveau message est publié.

Le code suivant est un exemple de réponse JSON à une boîte de dialogue qui est envoyée par une application de chat pour créer un message de réponse:

JSON

{
  "actionResponse": "NEW_MESSAGE",
  "text": "This message is a reply to a dialog form submission.",
  "cardsV2": [
    {
      "cardId" : "reply-card-id",
      "card" : {
        "header": {
          "title": "Reply card title"
        },
        "sections": [
          {
            "widgets" : [
              {
                "textParagraph": {
                  "text": "Reply card message"
                }
              }
            ]
          }
        ]
      }
    }
  ]
}

L'application Chat peut également répondre de manière asynchrone via un SMS ou une fiche. Pour ce faire, authentifiez-vous avec un compte de service, puis envoyez une réponse asynchrone en appelant spaces.messages.create à l'aide de l'API Google Chat.

Répondre à une boîte de dialogue en mettant à jour un message

Lorsque vous répondez à une boîte de dialogue avec un message mis à jour, vous pouvez modifier un message existant dans l'application ou l'aperçu d'un lien.

Messages de l'application

Pour répondre à l'envoi d'un formulaire de boîte de dialogue par une mise à jour d'un message existant envoyé par l'application Chat, le message ActionResponse de type UPDATE_MESSAGE est renvoyé. La réponse inclut un balisage qui indique le contenu du message mis à jour. À la réception de cette réponse, la boîte de dialogue se ferme et le message est mis à jour avec le nouveau contenu.

Le code suivant est un exemple de réponse JSON à une boîte de dialogue qui est envoyée par une application de chat pour mettre à jour un message existant:

JSON

{
  "actionResponse": "UPDATE_MESSAGE",
  "text": "This message has been updated with new content in response to a dialog form submission.",
  "cardsV2": [
    {
      "cardId" : "updated-card-id",
      "card" : {
        "header": {
          "title": "Updated card title"
        },
        "sections": [
          {
            "widgets" : [
              {
                "textParagraph": {
                  "text": "Updated card message"
                }
              }
            ]
          }
        ]
      }
    }
  ]
}

L'application Chat peut également mettre à jour un message d'application de manière asynchrone à l'aide de l' API Google Chat.

Pour mettre à jour les aperçus de lien avec un nouveau contenu en réponse aux envois de formulaire de boîte de dialogue, l'application Chat renvoie un ActionResponse de type UPDATE_USER_MESSAGE_CARDS. La réponse inclut le balisage des nouvelles fiches avec lesquelles les aperçus des liens sont mis à jour. À la réception de cette réponse, la boîte de dialogue se ferme et les aperçus des liens sont mis à jour avec les nouvelles fiches.

Le code suivant est un exemple de réponse JSON à une boîte de dialogue qui est envoyée par une application de chat. Il permet de mettre à jour un aperçu de lien avec une nouvelle fiche:

JSON

{
  "actionResponse": "UPDATE_USER_MESSAGE_CARDS",
  "cardsV2": [
    {
      "cardId" : "updated-card-id",
      "card" : {
        "header": {
          "title": "Updated card title"
        },
        "sections": [
          {
            "widgets" : [
              {
                "textParagraph": {
                  "text": "Updated card message"
                }
              }
            ]
          }
        ]
      }
    }
  ]
}

Exemple complet: Rolodex, le contact qui gère l'application Chat

Dans cet exemple, une application Chat ouvre une boîte de dialogue permettant à l'utilisateur d'ajouter des détails sur un contact, tels que son nom, son adresse e-mail et son adresse:

Node.js

/**
* Responds to messages that have links whose URLs
* match URL patterns configured for link previews.
*
* @param {Object} event The event object from Chat
* API.
*
* @return {Object} Response from the Chat app
* attached to the message with the previewed link.
*/
exports.onMessage = function onMessage(req, res) {

  // Store the Google Chat event as a variable.
  var event = req.body;

  if (req.method === "GET" || !event.message) {
    res.send("Hello! This function is meant to be used in a Google Chat " +
      "Space.");
  }

  // Checks for the presence of event.message.slashCommand.
  // If the slash command is "/help", responds with a text message.
  // If the slash command is "/createContact", opens a dialog.
  if (event.message.slashCommand) {
    switch (event.message.slashCommand.commandId) {
      case 1: // /help
        res.json({"text": "Contact bot helps you update your address book!"});
      case 2:  // /createContact
        res.openDialog(event);
    }
  }

  // If the Chat app doesn"t detect a slash command, it responds
  // with a card that prompts the user to add a contact
  else {
    res.json({
      "cardsV2": [{
        "cardId": "addContact",
        "card": {
          "header": {
            "title": "Rolodex",
            "subtitle": "Manage your contacts!",
            "imageUrl": "https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png",
            "imageType": "CIRCLE"
          },
          "sections": [
            {
              "widgets": [
                {
                  "buttonList": {
                    "buttons": [
                      {
                        "text": "Add Contact",
                        "onClick": {
                          "action": {
                            "function": "openDialog",
                            "interaction": "OPEN_DIALOG"
                          }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          ]
        }
      }]

    });
  }

  // Respond to button clicks on attached cards
  if(event.type === "CARD_CLICKED") {

    if (event.common.invokedFunction == "openDialog") {
      res.openDialog(event);
    }

    if (event.common.invokedFunction == "openSequentialDialog") {
      res.openSequentialDialog(event);
    }

    if (event.common.invokedFunction == "confirmDialogSuccess") {
      res.confirmDialogSuccess(event);
    }

  }

};

/**
 * Opens and starts a dialog that allows users to add details about a contact.
 *
 * @param {object} event the event object from Google Chat.
 *
 * @return {object} open a dialog.
 */
function openDialog(event) {
  res.json({
    "action_response": {
        "type": "DIALOG",
        "dialog_action": {
          "dialog": {
            "body": {
              "sections": [
                {
                  "header": "Add new contact",
                  "widgets": [
                    {
                      "textInput": {
                        "label": "Name",
                        "type": "SINGLE_LINE",
                        "name": "name"
                      }
                    },
                    {
                      "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"
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }
        }
    }
  });
};

/**
 * Opens a second dialog that allows users to add more contact details.
 *
 * @param {object} event the event object from Google Chat.
 *
 * @return {object} open a dialog.
 */
function openSequentialDialog(event) {
  res.json({
    "action_response": {
        "type": "DIALOG",
        "dialog_action": {
          "dialog": {
            "body": {
              "sections": [
                {
                  "header": "Add new contact",
                  "widgets": [
                    {
                      "textInput": {
                        "label": "Notes",
                        "type": "MULTIPLE_LINE",
                        "name": "notes"
                      }
                    },
                    {
                      "selectionInput": {
                        "type": "RADIO_BUTTON",
                        "label": "Contact type",
                        "name": "contactType",
                        "items": [
                          {
                            "text": "Work",
                            "value": "Work",
                            "selected": false
                          },
                          {
                            "text": "Personal",
                            "value": "Personal",
                            "selected": false
                          }
                        ]
                      }
                    },
                    {
                      "buttonList": {
                        "buttons": [
                          {
                            "text": "Submit",
                            "onClick": {
                              "action": {
                                "function": "confirmDialogSuccess",
                                "parameters": [
                                  {
                                    "key": "confirmDialogSuccess",
                                    "value": "confirmDialogSuccess"
                                  }
                                ]
                              }
                            }
                          }
                        ]
                      },
                      "horizontalAlignment": "END"
                    }
                  ]
                }
              ]
            }
          }
        }
    }
  });
}

/**
 * Checks for a form input error, the absence of
 * a "name" value, and returns an error if absent.
 * Otherwise, confirms successful receipt of a dialog.
 *
 * Confirms successful receipt of a dialog.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in Google Chat.
 */
function receiveDialog(event) {

  // Checks to make sure the user entered a name
  // in a dialog. If no name value detected, returns
  // an error message.
  if (event.common.formInputs.contactName.stringInputs.value[0] == "") {
    return {
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": {
            "statusCode": "OK", 
            "userFacingMessage": "Don't forget to name your new contact!"
        }
      }
    };

  // Otherwise the app indicates that it received
  // form data from the dialog. Any value other than "OK"
  // gets returned as an error. "OK" is interpreted as
  // code 200, and the dialog closes.
  } else {
    res.json({
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "OK"
        }
      }
    });
  }
}

Apps Script

/**
 * Responds to a MESSAGE event in Google Chat.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in response to a slash command
 * or a card"s button click.
 */
function onMessage(event) {

  // Checks for the presence of event.message.slashCommand.
  // If the slash command is "/help", responds with a text message.
  // If the slash command is "/createContact", opens a dialog.
  if (event.message.slashCommand) {
    switch (event.message.slashCommand.commandId) {
      case 1: // /help
        return {"text": "Contact bot helps you update your address book!"}
      case 2:  // /createContact
        return openDialog(event);
    }
  }

  // If the Chat app doesn"t detect a slash command, it responds
  // with a card that prompts the user to add a contact
  else {
    return {
      "cardsV2": [{
        "cardId": "addContact",
        "card": {
          "header": {
            "title": "Rolodex",
            "subtitle": "Manage your contacts!",
            "imageUrl": "https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png",
            "imageType": "CIRCLE"
          },
          "sections": [
            {
              "widgets": [
                {
                  "buttonList": {
                    "buttons": [
                      {
                        "text": "Add Contact",
                        "onClick": {
                          "action": {
                            "function": "openDialog",
                            "interaction": "OPEN_DIALOG"
                          }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          ]
        }
      }]

    };
  }
}

/**
 * Responds to a CARD_CLICKED event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onCardClick(event) {

  if (event.common.invokedFunction == "openDialog") {
    return openDialog(event);
  }

  if (event.common.invokedFunction == "openSequentialDialog") {
    return openSequentialDialog(event);
  }

  if (event.common.invokedFunction == "receiveDialog") {
    return receiveDialog(event);
  }
}

/**
 * Opens and starts a dialog that allows users to add details about a contact.
 *
 *
 * @return {object} open a dialog.
 */
function openDialog(event) {
  return {
    "action_response": {
        "type": "DIALOG",
        "dialog_action": {
          "dialog": {
            "body": {
              "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"
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }
        }
    }
  };
}

/**
 * Opens a second dialog that allows users to add more contact details.
 *
 * @param {object} event the event object from Google Chat.
 *
 * @return {object} open a dialog.
 */
function openSequentialDialog(event) {
  return {
    "action_response": {
        "type": "DIALOG",
        "dialog_action": {
          "dialog": {
            "body": {
              "sections": [
                {
                  "header": "Add new contact",
                  "widgets": [
                    {
                      "textInput": {
                        "label": "Notes",
                        "type": "MULTIPLE_LINE",
                        "name": "notes"
                      }
                    },
                    {
                      "selectionInput": {
                        "type": "RADIO_BUTTON",
                        "label": "Contact type",
                        "name": "contactType",
                        "items": [
                          {
                            "text": "Work",
                            "value": "Work",
                            "selected": false
                          },
                          {
                            "text": "Personal",
                            "value": "Personal",
                            "selected": false
                          }
                        ]
                      }
                    },
                    {
                      "buttonList": {
                        "buttons": [
                          {
                            "text": "Submit",
                            "onClick": {
                              "action": {
                                "function": "receiveDialog",
                                "parameters": [
                                  {
                                    "key": "receiveDialog",
                                    "value": "receiveDialog"
                                  }
                                ]
                              }
                            }
                          }
                        ]
                      },
                      "horizontalAlignment": "END"
                    }
                  ]
                }
              ]
            }
          }
        }
    }
  };
}

/**
 * Checks for a form input error, the absence of
 * a "name" value, and returns an error if absent.
 * Otherwise, confirms successful receipt of a dialog.
 *
 * Confirms successful receipt of a dialog.
 *
 * @param {Object} event the event object from Chat API.
 *
 * @return {object} open a Dialog in Google Chat.
 */
function receiveDialog(event) {

  // Checks to make sure the user entered a name
  // in a dialog. If no name value detected, returns
  // an error message.
  if (event.common.formInputs.contactName.stringInputs.value[0] == "") {
    return {
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "Don't forget to name your new contact!"
        }
      }
    };

  // Otherwise the app indicates that it received
  // form data from the dialog. Any value other than "OK"
  // gets returned as an error. "OK" is interpreted as
  // code 200, and the dialog closes.
  } else {
    return {
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "OK"
        }
      }
    };
  }
}

Python

from typing import Any, Mapping

import flask
import functions_framework

@functions_framework.http
def main(req: flask.Request) -> Mapping[str, Any]:
  """Responds to a MESSAGE event in Google Chat that includes the /createContact
     slash command by opening a dialog.

  Args:
      req (flask.Request): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a card's button click.
  """

  if req.method == 'GET':
    return 'Sorry, this function must be called from a Google Chat.'

  request = req.get_json(silent=True)

  if request.get('type') == 'CARD_CLICKED':
    invoked_function = request.get('common', dict()).get('invokedFunction')
    if invoked_function == 'open_dialog':
      return open_dialog(request)

    elif invoked_function == 'open_sequential_dialog':
      return open_dialog(request)

    elif invoked_function == "receive_dialog":
      return receive_dialog(request)

  else:
    return {
      'cardsV2': [{
        'cardId': 'addContact',
        'card': {
          'header': {
            'title': 'Rolodex',
            'subtitle': 'Manage your contacts!',
            'imageUrl': 'https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png',
            'imageType': 'CIRCLE'
          },
          'sections': [
            {
              'widgets': [
                {
                  'buttonList': {
                    'buttons': [
                      {
                        'text': 'Add Contact',
                        'onClick': {
                                'action': {
                                  'function': 'open_dialog',
                                  'interaction': 'OPEN_DIALOG'
                                }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          ]
        }
      }]
    }

def open_dialog(request: Mapping[str, Any]) -> Mapping[str, Any]:
  """Opens a dialog in Google Chat.

  Args:
      request (Mapping[str, Any]): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a card's button click.
  """
  return {
    'action_response': {
      'type': 'DIALOG',
      'dialog_action': {
        'dialog': {
          'body': {
            'sections': [
              {
                'header': 'Add new contact',
                'widgets': [
                  {
                    'textInput': {
                      'label': 'Name',
                      'type': 'SINGLE_LINE',
                      'name': 'name'
                    }
                  },
                  {
                    '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': 'open_sequential_dialog'
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }

def open_sequential_dialog(request: Mapping[str, Any]) -> Mapping[str, Any]:
  """Opens a second dialog that allows users to add more contact details.

  Args:
      request (Mapping[str, Any]): the event object from Chat API.

  Returns:
      Mapping[str, Any]: open a Dialog in response to a card's button click.
  """
  return {
    'action_response': {
      'type': 'DIALOG',
      'dialog_action': {
        'dialog': {
              'body': {
                'sections': [
                  {
                    'header': 'Add new contact',
                    'widgets': [
                      {
                        'textInput': {
                          'label': 'Notes',
                          'type': 'MULTIPLE_LINE',
                          'name': 'notes'
                        }
                      },
                      {
                        'selectionInput': {
                          'type': 'RADIO_BUTTON',
                          'label': 'Contact type',
                          'name': 'contactType',
                          'items': [
                            {
                              'text': 'Work',
                              'value': 'Work',
                              'selected': False
                            },
                            {
                              'text': 'Personal',
                              'value': 'Personal',
                              'selected': False
                            }
                          ]
                        }
                      },
                      {
                        'buttonList': {
                          'buttons': [
                            {
                              'text': 'Submit',
                              'onClick': {
                                'action': {
                                  'function': 'receive_dialog',
                                  'parameters': [
                                    {
                                      'key': 'receiveDialog',
                                      'value': 'receiveDialog'
                                    }
                                  ]
                                }
                              }
                            }
                          ]
                        },
                        'horizontalAlignment': 'END'
                      }
                    ]
                  }
                ]
              }
        }
      }
    }
  }

def receive_dialog(event: Mapping[str, Any]) -> Mapping[str, Any]:
  """Checks for a form input error, the absence of a "name" value, and returns
     an error if absent. Otherwise, confirms successful receipt of a dialog.

  Args:
      event (Mapping[str, Any]): the event object from Chat API.

  Returns:
      Mapping[str, Any]: the response.
  """

  if event.get('common', dict()) \
      .get('formInputs', dict()).get('contactName', dict()) \
          .get('stringInputs').get('value', list()):
    return {
      'actionResponse': {
        'type': 'DIALOG',
        'dialogAction': {
          'actionStatus': 'OK'
        }
      }
    }
  else:
    return {
      'actionResponse': {
        'type': 'DIALOG',
        'dialogAction': {
          'actionStatus': "Don't forget to name your new contact!"
        }
      }
    }

Limites et considérations

Prenez en compte les limites et considérations suivantes concernant les boîtes de dialogue:

  • Les fiches v1, qui sont obsolètes, ne sont pas compatibles avec les boîtes de dialogue. Utilisez plutôt les fiches v2.
  • Les suggestions de saisie semi-automatique générées par le serveur ne sont pas compatibles, contrairement aux suggestions renvoyées avec la réponse de la boîte de dialogue.
  • onChangeAction : propriété de certains widgets de carte, comme SwitchControl, qui spécifie un Action à effectuer lors du changement de widget, comme un basculement d'un contacteur.

Boîtes de dialogue de débogage

Lorsque vous mettez en œuvre des boîtes de dialogue, vous devrez peut-être déboguer votre application Chat en lisant les journaux de l'application. Pour lire les journaux, accédez à l'explorateur de journaux sur Google Cloud Console.