Google Chat का इस्तेमाल करने वालों से इंटरैक्ट करने के लिए, स्लैश कमांड सेट अप करना

इस पेज पर बताया गया है कि Google Chat ऐप्लिकेशन के लिए, स्लैश कमांड कैसे सेट अप किए जा सकते हैं.

स्लैश कमांड एक आम तरीका है, जिससे उपयोगकर्ता Chat ऐप्लिकेशन को शुरू करते हैं और उससे इंटरैक्ट करते हैं. स्लैश कमांड की मदद से, उपयोगकर्ता चैट ऐप्लिकेशन की मुख्य सुविधाओं को खोज सकते हैं और उन्हें इस्तेमाल कर सकते हैं.

Chat ऐप्लिकेशन के बारे में जानकारी पाने के लिए, उपयोगकर्ता स्लैश कमांड का इस्तेमाल करते हैं. इसके लिए, उपयोगकर्ता पहले स्लैश (/) और फिर एक छोटा टेक्स्ट कमांड टाइप करते हैं. जैसे, /about.

स्लैश कमांड की विंडो
पहली इमेज: यह विंडो तब दिखती है, जब उपयोगकर्ता Google Chat में स्लैश टाइप करते हैं.

स्लैश कमांड सेट अप करने चाहिए या नहीं और उपयोगकर्ताओं के इंटरैक्शन को डिज़ाइन करने का तरीका जानने के लिए, Google Chat को डिज़ाइन करने से जुड़े सिद्धांत देखें.

ज़रूरी शर्तें

Node.js

  • Google Workspace खाता होना चाहिए, जिससे Google Chat को ऐक्सेस किया जा सके.
  • Chat ऐप्लिकेशन. Chat ऐप्लिकेशन बनाने के लिए, इस क्विकस्टार्ट का पालन करें.

Apps Script

  • Google Workspace खाता होना चाहिए, जिससे Google Chat को ऐक्सेस किया जा सके.
  • Chat ऐप्लिकेशन. Chat ऐप्लिकेशन बनाने के लिए, इस क्विकस्टार्ट का पालन करें.

Python

  • Google Workspace खाता होना चाहिए, जिससे Google Chat को ऐक्सेस किया जा सके.
  • Chat ऐप्लिकेशन. Chat ऐप्लिकेशन बनाने के लिए, इस क्विकस्टार्ट का पालन करें.

स्लैश कमांड सेट अप करना

स्लैश कमांड सेट अप करने के लिए, यह तरीका अपनाएं:

  1. अपने स्लैश कमांड के लिए, एक नाम दें.
  2. Google Chat API में स्लैश कमांड कॉन्फ़िगर करें.
  3. टेक्स्ट या कार्ड मैसेज जैसे स्लैश कमांड के लिए, कोई जवाब बनाएं.

इस सेक्शन में, स्लैश कमांड सेट अप करने का तरीका बताया गया है.

अपने स्लैश कमांड को नाम दें

उपयोगकर्ता, Chat ऐप्लिकेशन में स्लैश कमांड का नाम लिखकर, चैट ऐप्लिकेशन में क्लिक करते हैं. नाम के नीचे भी कम शब्दों में जानकारी दिखती है. इससे लोगों को कमांड इस्तेमाल करने के बारे में ज़्यादा जानकारी दी जाती है:

स्लैश कमांड का नाम और जानकारी
दूसरी इमेज: स्लैश कमांड का नाम और ब्यौरा.

अपने स्लैश कमांड के लिए नाम और ब्यौरा चुनते समय, इन सुझावों को ध्यान में रखें:

  • अपने स्लैश कमांड को कोई नाम देने के लिए:

    • छोटे, जानकारी देने वाले और कार्रवाई करने लायक शब्दों या वाक्यांशों का इस्तेमाल करें, ताकि उपयोगकर्ता आसानी से आदेश दे पाएं. उदाहरण के लिए, /createAReminder बोलने के बजाय, /remindMe का इस्तेमाल करें.
    • अगर आपके निर्देश में एक से ज़्यादा शब्द हैं, तो पहले शब्द के लिए सभी छोटे अक्षरों का इस्तेमाल करके और फिर दूसरे शब्दों के पहले अक्षर को बड़ा करके निर्देश पढ़ने में उपयोगकर्ताओं की मदद करें. उदाहरण के लिए, /updatecontact के बजाय /updateContact इस्तेमाल करें.
    • देखें कि आपको अपने निर्देश के लिए, कोई यूनीक नाम इस्तेमाल करना है या सामान्य नाम. अगर आपका निर्देश किसी सामान्य इंटरैक्शन या सुविधा के बारे में बताता है, तो आप किसी सामान्य नाम का इस्तेमाल कर सकते हैं, जिसे लोग पहचानते हैं और जिनकी उम्मीद करते हैं, जैसे कि /settingsया /feedback. इसके अलावा, यूनीक कमांड नाम का इस्तेमाल करने की कोशिश करें, क्योंकि अगर दूसरे Chat ऐप्लिकेशन के लिए आपके कमांड का नाम एक ही है, तो उपयोगकर्ता को आपके कमांड को ढूंढने और उसका इस्तेमाल करने के लिए, मिलते-जुलते निर्देशों को फ़िल्टर करना होगा.
  • अपने स्लैश कमांड की जानकारी देने के लिए:

    • ब्यौरे को छोटा और साफ़ रखें, ताकि उपयोगकर्ताओं को पता रहे कि निर्देश देने पर क्या उम्मीद की जानी चाहिए.
    • उपयोगकर्ताओं को बताएं कि निर्देश के लिए, फ़ॉर्मैट करने की कोई ज़रूरी शर्त है या नहीं. उदाहरण के लिए, अगर कोई ऐसा /remindMe निर्देश बनाया जाता है जिसके लिए आर्ग्युमेंट टेक्स्ट की ज़रूरत होती है, तो जानकारी को Remind me to do [something] at [time] जैसी किसी जानकारी पर सेट करें.

Google Chat API में अपने स्लैश कमांड को कॉन्फ़िगर करना

स्लैश कमांड बनाने के लिए, आपको Google Chat API के लिए अपने Chat ऐप्लिकेशन के कॉन्फ़िगरेशन में, कमांड के बारे में जानकारी देनी होगी.

Google Chat API में स्लैश कमांड कॉन्फ़िगर करने के लिए, यह तरीका अपनाएं:

  1. Google Cloud कंसोल में, मेन्यू > एपीआई और सेवाएं > चालू एपीआई और सेवाएं > Google Chat API पर क्लिक करें

    Google Chat API के पेज पर जाएं

  2. कॉन्फ़िगरेशन पर क्लिक करें.

  3. स्लैश कमांड में जाकर, स्लैश कमांड जोड़ें पर क्लिक करें.

  4. निर्देश के लिए नाम, कमांड आईडी, और जानकारी डालें:

    1. नाम: निर्देश के लिए डिसप्ले नेम: और यह कि उपयोगकर्ता आपके ऐप्लिकेशन को शुरू करने के लिए क्या टाइप करते हैं. यह एक स्लैश से शुरू होना चाहिए और इसमें सिर्फ़ टेक्स्ट होना चाहिए. साथ ही, यह 50 वर्णों तक का हो सकता है.
    2. ब्यौरा: वह टेक्स्ट जिसमें निर्देश को इस्तेमाल और फ़ॉर्मैट करने का तरीका बताया गया है. ब्यौरे में ज़्यादा से ज़्यादा 50 वर्ण हो सकते हैं.
    3. कमांड आईडी: 1 से 1,000 तक की कोई संख्या. इसका इस्तेमाल आपका Chat ऐप्लिकेशन, स्लैश कमांड की पहचान करने और जवाब देने के लिए करता है.
  5. ज़रूरी नहीं: अगर आप चाहते हैं कि Chat ऐप्लिकेशन, डायलॉग के ज़रिए निर्देश का जवाब दे, तो डायलॉग खोलें चेकबॉक्स चुनें.

  6. सेव करें पर क्लिक करें.

स्लैश कमांड को अब Chat ऐप्लिकेशन के लिए कॉन्फ़िगर किया जा चुका है.

स्लैश कमांड का जवाब देना

जब उपयोगकर्ता कोई ऐसा Chat मैसेज बनाते हैं जिसमें स्लैश कमांड होता है, तो आपके Chat ऐप्लिकेशन को एक MESSAGE इंटरैक्शन इवेंट मिलता है. इवेंट पेलोड में स्लैश कमांड के बारे में जानकारी होती है. इसमें slashCommand और slashCommandMetadata फ़ील्ड भी शामिल होते हैं. इन फ़ील्ड का इस्तेमाल कमांड आईडी की पहचान करने और पसंद के मुताबिक जवाब देने के लिए किया जाता है.

नीचे दिए गए उदाहरण में, MESSAGE इंटरैक्शन इवेंट के लिए JSON पेलोड दिखाया गया है. इसमें स्लैश कमांड /vote शामिल है:

    {
      ...
      "message": {
        ...
        "text": "/vote yes",
        "argumentText": " yes",
        "slashCommand": {
          "commandId": 2
        },
        "annotations": [
          {
            "length": 5,
            "startIndex": 0,
            "type": "SLASH_COMMAND",
            "slashCommand": {
              "commandName":"/vote",
              "commandId":1,
              "type": "INVOKE",
              "bot": {
                "avatarUrl": "https://www.example.com/images/vote-app-icon.png",
                "displayName": "Voter Chat App",
                "name": "users/1234567890987654321",
                "type": "BOT"
              }
            }
          }
        ]
      }
    }

स्लैश कमांड का जवाब देने के लिए, यह पता लगाया जा सकता है कि इवेंट पेलोड में slashCommand फ़ील्ड मौजूद है या नहीं. अगर हां, तो कमांड का जवाब दें. यहां दिए गए कोड सैंपल में, स्लैश कमांड वाले MESSAGE इंटरैक्शन इवेंट को जवाब देने का तरीका बताया गया है:

Node.js

/**
* Responds to a MESSAGE event in Google Chat.
*
* @param {Object} event the event object from Chat API.
*
* @return {object} function in response to a slash command.
*/

exports.onMessage = function onMessage(req, res) {

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

  // Checks for the presence of event.message.slashCommand.
  if (event.message.slashCommand) {
    switch (event.message.slashCommand.commandId) {
      case ID: // The ID for your slash command
        res.runFunction; // The response to the slash command.
    }
  }

Apps Script

/**
* Responds to a MESSAGE event in Google Chat.
*
* @param {Object} event the event object from Chat API.
*
* @return {object} function in response to a slash command.
*/

function onMessage(event) {

  // Checks for the presence of event.message.slashCommand
  if (event.message.slashCommand) {
    switch (event.message.slashCommand.commandId) {
      case ID: // The ID for your slash command
        return runFunction; // The response to the slash command.
    }
  }
}

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 a slash command.

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

  Returns:
      Mapping[str, Any]: function 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 == ID:
      return runFunction

कोड का इस्तेमाल करने के लिए, इन्हें बदलें:

सभी उदाहरण: Rolodex Chat ऐप्लिकेशन का इस्तेमाल करके संपर्क सेट अप करना

इस उदाहरण में Chat ऐप्लिकेशन दिखाया गया है जो इन स्लैश कमांड का जवाब देता है:

  • /help निर्देश एक मैसेज भेजता है, जिसमें बताया जाता है कि Chat ऐप्लिकेशन का इस्तेमाल कैसे किया जाता है. कमांड आईडी को 1 पर सेट किया गया है.
  • /createContact निर्देश से एक डायलॉग बॉक्स खुलता है, जहां लोग किसी संपर्क की जानकारी डाल सकते हैं. निर्देश आईडी, 2 पर सेट किया गया है.

इस सैंपल को चलाने से पहले, Google Chat API में स्लैश कमांड कॉन्फ़िगर करने के लिए दिया गया तरीका अपनाएं.

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.
  const 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 lets users 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 lets users 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

apps-script/dialogs/rolodex.gs
/**
* 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") {
    const contactName = fetchFormValue(event, "contactName");
    const address = fetchFormValue(event, "address");
    return openSequentialDialog(contactName, address);
  }

  if (event.common.invokedFunction === "receiveDialog") {
    const parameters = event.common.parameters;
    parameters["contactType"] = fetchFormValue(event, "contactType");
    parameters["notes"] = fetchFormValue(event, "notes");
    return receiveDialog(parameters);
  }
}

/**
 * Extracts form input value for a given widget
 * 
 * @param {Object} event the event object from Google Chat
 * @param {String} widgetName the widget name
 * @returns the form input value for the widget
 */
function fetchFormValue(event, widgetName) {
  const widget = event.common.formInputs[widgetName];
  if (widget) {
    return widget[""]["stringInputs"]["value"][0];
  }
}

/**
* Opens and starts a dialog that lets users 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 lets users add more contact details.
*
* @param {String} contactName the contact name from the previous dialog.
* @param {String} address the address from the previous dialog.
*
* @return {Object} open a dialog.
*/
function openSequentialDialog(contactName, address) {
  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": "contactName",
                                  "value": contactName
                                },
                                {
                                  "key": "address",
                                  "value": address
                                }
                              ]
                            }
                          }
                        }
                      ]
                    },
                    "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} parameters the form input values.
*
* @return {Object} open a Dialog in Google Chat.
*/
function receiveDialog(parameters) {

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

    // Otherwise the Chat 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": {
            "statusCode": "OK",
            "userFacingMessage": "Success " + JSON.stringify(parameters)
          }
        }
      }
    };
  }
}

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 lets users 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!"
        }
      }
    }