เปิดและตอบกล่องโต้ตอบ

หน้านี้จะอธิบายวิธีที่แอป Chat สามารถเปิดและตอบข้อความโต้ตอบ

กล่องโต้ตอบเป็นอินเทอร์เฟซแบบการ์ดในโหมดหน้าต่าง ซึ่งแอป Chat จะเปิดขึ้นเพื่อโต้ตอบกับผู้ใช้ แอป Chat จะเปิดกล่องโต้ตอบตามลำดับเพื่อช่วยให้ผู้ใช้ดำเนินการตามกระบวนการแบบหลายขั้นตอนได้

กล่องโต้ตอบมีประโยชน์สำหรับการโต้ตอบของผู้ใช้ประเภทต่อไปนี้

  • การรวบรวมข้อมูลจากผู้ใช้
  • การตรวจสอบสิทธิ์ผู้ใช้ด้วยบริการผ่านเว็บ
  • การกำหนดการตั้งค่าแอป Chat

การเปิด การส่ง หรือยกเลิกกล่องโต้ตอบต้องใช้การตอบกลับแบบพร้อมกันจากแอป Chat ด้วย DialogEventType แอป Chat ที่สร้างด้วยสถาปัตยกรรมแบบไม่พร้อมกัน เช่น เมธอด Pub/Sub หรือข้อความ create ไม่รองรับกล่องโต้ตอบ หากแอป Chat ใช้สถาปัตยกรรมแบบไม่พร้อมกัน ให้ใช้ข้อความการ์ดแทนกล่องโต้ตอบ

ข้อกำหนดเบื้องต้น

Node.js

  • บัญชี Google Workspace ที่มีสิทธิ์เข้าถึง Google Chat
  • แอป Chat หากต้องการสร้าง แอป Chat ให้ทำตาม quickstartนี้
  • หากเปิดกล่องโต้ตอบเพื่อตอบสนองต่อคำสั่งเครื่องหมายทับ คำสั่งเครื่องหมายทับ ซึ่งกำหนดค่าด้วยการเลือกเปิดกล่องโต้ตอบ

ระบบจะเขียนตัวอย่างโค้ด Node.js ให้เรียกใช้เป็น Cloud Function

Apps Script

  • บัญชี Google Workspace ที่มีสิทธิ์เข้าถึง Google Chat
  • แอป Chat หากต้องการสร้าง แอป Chat ให้ทำตาม quickstartนี้
  • หากเปิดกล่องโต้ตอบเพื่อตอบสนองต่อคำสั่งเครื่องหมายทับ คำสั่งเครื่องหมายทับ ซึ่งกำหนดค่าด้วยการเลือกเปิดกล่องโต้ตอบ

Python

  • บัญชี Google Workspace ที่มีสิทธิ์เข้าถึง Google Chat
  • แอป Chat หากต้องการสร้าง แอป Chat ให้ทำตาม quickstartนี้
  • หากเปิดกล่องโต้ตอบเพื่อตอบสนองต่อคำสั่งเครื่องหมายทับ คำสั่งเครื่องหมายทับ ซึ่งกำหนดค่าด้วยการเลือกเปิดกล่องโต้ตอบ

ระบบจะเขียนตัวอย่างโค้ด Python เพื่อเรียกใช้เป็น Cloud Function โดยใช้ Python 3.9

เปิดกล่องโต้ตอบ

แอป Chat สามารถเปิดกล่องโต้ตอบเพื่อให้ผู้ใช้คลิกปุ่มบนข้อความในการ์ด

คลิกปุ่มบนการ์ดเพื่อเปิดกล่องโต้ตอบ
ภาพที่ 1: การคลิกปุ่มบนการ์ดเพื่อเปิดกล่องโต้ตอบ

แอป Chat สามารถเปิดกล่องโต้ตอบเพื่อตอบกลับผู้ใช้ที่ออกคำสั่งเครื่องหมายทับ

คลิกปุ่มบนการ์ดเพื่อเปิดกล่องโต้ตอบ
ภาพที่ 2: การออกคำสั่งเครื่องหมายทับเพื่อเปิดกล่องโต้ตอบ

เมื่อผู้ใช้เปิดกล่องโต้ตอบ แอป Chat จะได้รับเหตุการณ์การโต้ตอบพร้อมข้อมูลต่อไปนี้

  • isDialogEvent คือtrue
  • DialogEventType จะระบุการดำเนินการอย่างใดอย่างหนึ่งต่อไปนี้ที่ผู้ใช้ทำ

    • REQUEST_DIALOG: เปิดกล่องโต้ตอบแล้ว
    • SUBMIT_DIALOG: คลิกปุ่มในกล่องโต้ตอบ
    • CANCEL_DIALOG: ยกเลิกกล่องโต้ตอบแล้ว

ตัวอย่างเช่น เมื่อผู้ใช้เปิดกล่องโต้ตอบ แอป 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)
  }
}

แอป Chat สามารถเปิดกล่องโต้ตอบโดยแสดงผล ActionResponse ของ "type": "DIALOG" พร้อม DialogAction ที่มีคำอธิบาย JSON ของกล่องโต้ตอบ ดังนี้

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

เปิดกล่องโต้ตอบตามการคลิกปุ่มการ์ด

หากต้องการให้ปุ่มการ์ดเปิดกล่องโต้ตอบ ให้ระบุสิ่งต่อไปนี้

  • onClick.action.function เป็นชื่อฟังก์ชันที่เปิดกล่องโต้ตอบ
  • onClick.action.interaction ในฐานะ OPEN_DIALOG พร็อพเพอร์ตี้นี้จะบอก Chat ว่าแอป Chat ต้องการเปิดกล่องโต้ตอบ

เมื่อผู้ใช้คลิกปุ่มบนการ์ด แอป Chat จะได้รับเหตุการณ์การโต้ตอบที่มีข้อมูลต่อไปนี้

  • EventType คือCARD_CLICKED
  • DialogEventType คือ REQUEST_DIALOG
  • common.invokedFunction คือชื่อของฟังก์ชันจากพร็อพเพอร์ตี้ onClick ของปุ่มการ์ดที่คลิก

หากต้องการเปิดกล่องโต้ตอบ ให้ตอบกลับด้วยข้อมูลต่อไปนี้

  • ActionResponse จาก "type": "DIALOG"
  • DialogAction ที่มีคำอธิบาย JSON ของกล่องโต้ตอบ

ในตัวอย่างนี้ แอป Chat จะตอบสนองต่อเหตุการณ์การโต้ตอบ MESSAGE ด้วยการ์ดที่มีปุ่มที่เปิดกล่องโต้ตอบ

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.");
  }

  // 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") {
      openDialog(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"
                                }
                              }
                            }
                          ]
                        }
                      }
                    ]
                  }
                ]
              }
            }
          }
        }
      });
    };
  }
}

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

เปิดกล่องโต้ตอบเพื่อตอบกลับคำสั่งเครื่องหมายทับ

เมื่อผู้ใช้เปิดกล่องโต้ตอบที่มีคำสั่งเครื่องหมายทับที่กำหนดค่าไว้สำหรับเปิดกล่องโต้ตอบ แอป Chat จะได้รับเหตุการณ์การโต้ตอบพร้อมด้วยข้อมูลต่อไปนี้

หากต้องการเปิดกล่องโต้ตอบ ให้ตอบกลับด้วยข้อมูลต่อไปนี้

  • ActionResponse จาก "type": "DIALOG"
  • DialogAction ที่มีคำอธิบาย JSON ของกล่องโต้ตอบ

ในตัวอย่างนี้ แอป Chat จะตอบสนองต่อคำสั่งเครื่องหมายทับ /createContact ด้วยการเปิดกล่องโต้ตอบ

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

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

เปิดกล่องโต้ตอบตามลำดับ

เมื่อการโต้ตอบของผู้ใช้ต้องใช้กล่องโต้ตอบมากกว่า 1 กล่องโต้ตอบ คุณสามารถเปิดกล่องโต้ตอบอีกกล่องหนึ่งได้โดยแสดงกล่องโต้ตอบถัดไปในลำดับเพื่อตอบสนองต่อ SUBMIT_DIALOG DialogEventType

กล่องโต้ตอบที่มีวิดเจ็ตหลากหลายแบบ
ภาพที่ 3: กล่องโต้ตอบที่เปิดอยู่ที่แจ้งให้ผู้ใช้เพิ่มรายชื่อติดต่อ

ในปุ่มการ์ดที่อัปเดตกล่องโต้ตอบ ให้แสดงผล onClick.action.function เป็นชื่อของฟังก์ชันที่จะเปิดกล่องโต้ตอบถัดไปและไม่ระบุ onClick.action.interaction

กล่องโต้ตอบที่มีวิดเจ็ตหลากหลายแบบ
ภาพที่ 4: กล่องโต้ตอบที่ 2 จะแจ้งให้ผู้ใช้ดูข้อมูลเพิ่มเติม

เมื่อเสร็จแล้ว แอป Chat จะได้รับค่าที่ผู้ใช้ป้อนในกล่องโต้ตอบเป็น JSON แจ้งให้ผู้ใช้ทราบว่าการโต้ตอบของผู้ใช้ประสบความสำเร็จโดยการตอบกลับด้วยข้อความหรือข้อความการ์ด

เมื่อผู้ใช้คลิกปุ่มในกล่องโต้ตอบ แอป Chat จะได้รับเหตุการณ์การโต้ตอบที่มีข้อมูลต่อไปนี้

ในตัวอย่างนี้ แอป Chat จะตอบสนองต่อเหตุการณ์การโต้ตอบ CARD_CLICKED จากการคลิกปุ่มกล่องโต้ตอบโดยการเปิดกล่องโต้ตอบอื่น ดังนี้

Node.js

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

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

  // Open the second dialog.
  if (event.common.invokedFunction === "openSequentialDialog") {
    openSequentialDialog(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"
                  }
                ]
              }
            ]
          }
        }
      }
    }
  });
}

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 Chat 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 lets users 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 lets users 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 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': 'receiveDialog',
                              'parameters': [
                                {
                                  'key': 'receiveDialog',
                                  'value': 'receiveDialog'
                                }
                              ]
                            }
                          }
                        }
                      ]
                    },
                    'horizontalAlignment': 'END'
                  }
                ]
              }
            ]
          }
        }
      }
    }
  }

เปิดกล่องโต้ตอบเพื่อตอบกลับข้อความการ์ดหน้าแรกของแอป

สำหรับข้อความการ์ดหน้าแรกของแอปเท่านั้น ให้ใช้ render_actions แทน action_response เพื่อเปิดกล่องโต้ตอบดังนี้

Apps Script

function openDialog() {
  return {
    render_actions: {
      action: {
        navigations: [{
          update_card: {
            "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"
                        }
                      }
                    }
                  ]
                }
              }]
            }]
          }
        }]
      }
    }
  }
}

รับข้อมูลแบบฟอร์มจากกล่องโต้ตอบ

เมื่อผู้ใช้คลิกปุ่มบนกล่องโต้ตอบ ระบบจะส่งข้อมูลที่ผู้ใช้ป้อนไปยังแอป Chat และแอป Chat ของคุณจะได้รับเหตุการณ์การโต้ตอบที่มีข้อมูลต่อไปนี้

ข้อมูลที่ผู้ใช้ป้อนในกล่องโต้ตอบจะปรากฏในเหตุการณ์การโต้ตอบในรูปแบบ Event.common.formInputs ซึ่งเป็นการแมปที่คีย์คือรหัสสตริงที่กำหนดให้กับวิดเจ็ตกล่องโต้ตอบแต่ละรายการและค่าที่แสดงอินพุตของผู้ใช้สําหรับวิดเจ็ตแต่ละรายการ ออบเจ็กต์ต่างๆ แสดงถึงข้อมูลอินพุต ที่ต่างกัน เช่น Event.common.formInputs.stringInputs แสดงถึงอินพุตสตริง

เมื่อผู้ใช้ส่งกล่องโต้ตอบ แอป Chat ของคุณจะได้รับเหตุการณ์การโต้ตอบดังนี้จาก 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 user data entered for a specific field in a dialog.
      "NAME": {

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

แอป Chat จะเข้าถึงค่าแรกที่ผู้ใช้ป้อนได้ใน event.common.formInputs.NAME.stringInputs.value[0] โดยที่ NAME คือช่อง name ของวิดเจ็ต TextInput

หลังจากได้รับข้อมูลของแบบฟอร์มกล่องโต้ตอบแล้ว แอป Chat ควรตอบกลับด้วย ActionResponse ดังนี้

  • หากต้องการตอบรับใบเสร็จที่ได้รับ ให้ตอบกลับด้วย ActionResponse ที่มี "actionStatus": "OK" การทำเช่นนี้จะปิดกล่องโต้ตอบโดยไม่โพสต์คำตอบ
  • หากต้องการตอบกลับด้วย SMS หรือข้อความการ์ด ให้ตอบกลับด้วย ActionResponse ที่มี ResponseType NEW_MESSAGE, UPDATE_MESSAGE หรือ UPDATE_USER_MESSAGE_CARDS โปรดดูข้อมูลเพิ่มเติมที่หัวข้อตอบกลับกล่องโต้ตอบ
  • หากต้องการแสดงผลข้อผิดพลาด ให้ตอบกลับด้วย ActionResponse ที่มี "actionStatus": "ERROR MESSAGE"

ตัวอย่างต่อไปนี้จะตรวจสอบการแสดงค่า name หากไม่พบตัวเลือกนี้ แอป Chat จะแสดงข้อผิดพลาด หากมีอยู่แล้ว แอป Chat จะรับทราบว่าได้รับข้อมูลแบบฟอร์มและปิดกล่องโต้ตอบ

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. Any "actionStatus" value other than "OK"
  // gets returned as an error.
  if (event.common.formInputs.WIDGET_NAME.stringInputs.value[0] === "") {
    res.json({
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "Don't forget to name your new contact!"
        }
      }
    });

    // Otherwise the Chat app indicates that it received
    // form data from the dialog. An "actionStatus" of "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. Any "actionStatus" value other than "OK"
  // gets returned as an error.
  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 Chat app indicates that it received
    // form data from the dialog. An "actionStatus" of "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!'
                }
              }
            }

ตอบกลับกล่องโต้ตอบ

คุณตอบกลับกล่องโต้ตอบด้วยข้อความใหม่หรืออัปเดตข้อความที่มีอยู่ได้

ตอบกล่องโต้ตอบด้วยข้อความใหม่

หากต้องการตอบกลับการส่งฟอร์มกล่องโต้ตอบด้วยข้อความใหม่ แอป Chat จะส่ง ActionResponse ประเภท NEW_MESSAGE กลับมาพร้อมกับมาร์กอัปเพื่อระบุเนื้อหาของข้อความใหม่ เมื่อได้รับการตอบกลับนี้ กล่องโต้ตอบจะปิดลงและโพสต์ข้อความใหม่

โค้ดต่อไปนี้เป็นตัวอย่างการตอบสนองของ JSON ต่อกล่องโต้ตอบที่แอป Chat ส่งเพื่อสร้างข้อความตอบกลับใหม่

JSON

{
  "actionResponse": {
    "type": "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"
                }
              }
            ]
          }
        ]
      }
    }
  ]
}

แอป Chat ยังตอบกลับแบบไม่พร้อมกันด้วยข้อความหรือการ์ดได้ด้วย

ตอบกล่องโต้ตอบด้วยข้อความที่อัปเดตแล้ว

เมื่อตอบกล่องโต้ตอบด้วยข้อความที่อัปเดต คุณจะอัปเดตข้อความในแอป Chat ที่มีอยู่หรืออัปเดตตัวอย่างลิงก์ได้

ข้อความแอปใน Chat

หากต้องการตอบกลับการส่งแบบฟอร์มในกล่องโต้ตอบด้วยการอัปเดตข้อความที่มีอยู่ซึ่งแอป Chat ส่ง ระบบจะแสดงผล ActionResponse ประเภท UPDATE_MESSAGE การตอบกลับจะมีมาร์กอัปซึ่งระบุเนื้อหาของข้อความที่อัปเดต เมื่อได้รับการตอบกลับนี้แล้ว กล่องโต้ตอบจะปิดขึ้นและระบบจะอัปเดตข้อความด้วยเนื้อหาใหม่

โค้ดต่อไปนี้คือตัวอย่างการตอบสนองของ JSON ไปยังกล่องโต้ตอบที่แอป Chat ส่งเพื่ออัปเดตข้อความในแอป Chat ที่มีอยู่

JSON

{
  "actionResponse": {
    "type": "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"
                }
              }
            ]
          }
        ]
      }
    }
  ]
}

นอกจากนี้ แอป Chat ยังอัปเดตข้อความแอป Chat แบบไม่พร้อมกันโดยใช้ Google Chat API ได้ด้วย

หากต้องการอัปเดต การแสดงตัวอย่างลิงก์ ด้วยเนื้อหาใหม่เพื่อตอบสนองต่อการส่งแบบฟอร์มในกล่องโต้ตอบ แอป Chat จะแสดงผล ActionResponse ประเภท UPDATE_USER_MESSAGE_CARDS การตอบกลับจะมีมาร์กอัปสำหรับข้อความการ์ดใหม่ที่มีการอัปเดตตัวอย่างลิงก์ หลังจากได้รับการตอบกลับนี้ กล่องโต้ตอบจะปิดลงและอัปเดตตัวอย่างลิงก์ด้วยข้อความการ์ดใหม่

ตัวอย่างการตอบสนอง JSON ต่อไปนี้จะอัปเดตตัวอย่างลิงก์ด้วยข้อความการ์ดใหม่

JSON

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

ตอบกลับกล่องโต้ตอบสำหรับข้อความการ์ดหน้าแรกของแอป

สำหรับข้อความการ์ดหน้าแรกของแอปเท่านั้น คุณปิดกล่องโต้ตอบได้ 2 วิธีดังนี้

  • CLOSE_DIALOG: ปิดกล่องโต้ตอบและกลับไปที่ข้อความการ์ดหน้าแรกของแอป
  • CLOSE_DIALOG_AND_EXECUTE: ปิดกล่องโต้ตอบและรีเฟรชข้อความการ์ดหน้าแรกของแอป

Python

ตัวอย่างโค้ดต่อไปนี้ใช้ CLOSE_DIALOG เพื่อปิดกล่องโต้ตอบและกลับไปที่ข้อความการ์ดหน้าแรกของแอป

def close_dialog():
  """Handles dismiss dialog request from Chat."""
  return {
      'render_actions': {
          'action': {
              'navigations': [{
                'end_navigation': {'action': 'CLOSE_DIALOG'}
              }]
          }
      }
  }

Apps Script

ตัวอย่างโค้ดต่อไปนี้ใช้ CLOSE_DIALOG เพื่อปิดกล่องโต้ตอบและกลับไปที่ข้อความการ์ดหน้าแรกของแอป

function closeDialog(event) {
  return {
    render_actions: {
      action:{
        navigations:[{
          end_navigation:{
            action: "CLOSE_DIALOG"
          }
        }]
      }
    }
  };
}

ตัวอย่างแบบสมบูรณ์: Rolodex รายชื่อติดต่อที่จัดการแอป Chat

ในตัวอย่างนี้ แอป Chat จะเปิดกล่องโต้ตอบเพื่อให้ผู้ใช้เพิ่มรายละเอียดเกี่ยวกับรายชื่อติดต่อได้ เช่น ชื่อ อีเมล และที่อยู่

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
        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") {
      openDialog(event);
    }

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

    if (event.common.invokedFunction === "confirmDialogSuccess") {
      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. Any "actionStatus" value other than "OK"
  // gets returned as an error.
  if (event.common.formInputs.contactName.stringInputs.value[0] === "") {
    res.json({
      "actionResponse": {
        "type": "DIALOG",
        "dialogAction": {
          "actionStatus": "Don't forget to name your new contact!"
        }
      }
    });

    // Otherwise the Chat app indicates that it received
    // form data from the dialog. An "actionStatus" of "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!"
        }
      }
    }

แก้ปัญหา

เมื่อแอป Google Chat หรือการ์ดแสดงผลข้อผิดพลาด อินเทอร์เฟซ Chat จะแสดงข้อความว่า "เกิดข้อผิดพลาด" หรือ "ดำเนินการตามคำขอของคุณไม่ได้" บางครั้ง UI ของ Chat ไม่แสดงข้อความแสดงข้อผิดพลาด แต่แอปหรือการ์ด Chat จะให้ผลลัพธ์ที่ไม่คาดคิด เช่น ข้อความการ์ดอาจไม่ปรากฏ

แม้ว่าข้อความแสดงข้อผิดพลาดอาจไม่แสดงใน UI ของ Chat แต่ก็จะมีข้อความแสดงข้อผิดพลาดที่สื่อความหมายและข้อมูลบันทึกที่จะช่วยคุณแก้ไขข้อผิดพลาดเมื่อเปิดการบันทึกข้อผิดพลาดสำหรับแอป Chat ไว้ หากต้องการความช่วยเหลือในการดู แก้ไขข้อบกพร่อง และแก้ไขข้อผิดพลาด โปรดดูหัวข้อแก้ปัญหาและแก้ไขข้อผิดพลาดของ Google Chat