사용자가 입력한 정보 처리

이 가이드에서는 사용자가 카드 메시지대화상자에 입력하는 정보를 수신하고 읽는 방법을 설명합니다. 사용자는 채팅 앱이 수신하고 읽고 응답할 수 있는 데이터를 입력할 수 있습니다. 사용자가 정보를 입력할 수 있는 위젯은 다음과 같습니다.

  • TextInput: 추천도 지원하는 자유 형식 텍스트 입력입니다.
  • 목록 항목 및 메뉴(예: 체크박스, 라디오 버튼, 드롭다운 메뉴)의 경우 SelectionInput
  • 날짜 및 시간 항목의 경우 DateTimePicker


카드 빌더를 사용하여 채팅 앱용 JSON 카드 메시지를 디자인하고 미리 볼 수 있습니다.

카드 빌더 열기

사용자로부터 데이터 입력을 받으면 채팅 앱에서 다음과 같은 작업을 할 수 있습니다.

  • 고객 서비스 케이스를 업데이트합니다.
  • 작업 주문을 만듭니다.
  • 웹 서비스를 사용하여 인증합니다.

데이터 수신 작동 방식

채팅 앱은 대화상자 또는 카드 메시지로 사용자에게 정보를 표시합니다. 이 예에서는 사용자에게 TextInputSelectionInput 위젯을 사용하여 연락처 정보를 입력하라는 메시지를 표시합니다.

다양한 위젯이 표시된 대화상자

완료되면 채팅 앱은 사용자가 JSON 형식으로 대화상자에 입력한 데이터와 상호작용 이벤트를 수신합니다. 각 항목의 의미는 다음과 같습니다.

사용자가 입력한 내용에 대한 데이터를 가져오려면 이벤트 페이로드에서 Event.common.formInputs 필드를 사용합니다. formInputs 필드는 키는 각 위젯에 할당된 문자열 ID이고 값은 각 위젯의 사용자 입력을 나타내는 맵입니다. 서로 다른 객체는 서로 다른 입력 데이터 유형을 나타냅니다. 예를 들어 Event.common.formInputs.stringInputs는 문자열 입력을 나타냅니다.

앱은 event.common.formInputs.NAME.stringInputs.value[0]에서 사용자가 입력한 첫 번째 값에 액세스할 수 있습니다. 여기서 NAMETextInput 위젯의 name 필드입니다.

카드에서 데이터 수신

사용자가 카드 메시지에 데이터를 입력하면 채팅 앱이 다음 예와 같은 채팅 앱 상호작용 이벤트를 수신합니다.

JSON

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

    // Represents user data entered in a card.
    "formInputs": {

      // Represents user data entered for a specific field in a card.
      "NAME": {

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

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

대화상자에서 데이터 수신

사용자가 대화상자에서 데이터를 제출하면 채팅 앱은 다음 예와 같은 다른 채팅 앱 상호작용 이벤트를 수신합니다.

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

카드 메시지 또는 대화상자에서 수집된 데이터에 응답하기

카드 메시지 또는 대화상자에서 데이터를 수신하면 채팅 앱은 수신 확인 또는 오류 반환으로 응답합니다. 둘 다 ActionResponse를 반환하는 방식으로 처리됩니다.

  • 수신이 완료되었음을 확인하려면 "actionStatus": "OK"가 있는 ActionResponse 매개변수로 응답합니다.
  • 오류를 반환하려면 "actionStatus": "ERROR MESSAGE"가 있는 ActionResponse 매개변수로 응답합니다.

다음 예에서는 name 값이 있는지 확인합니다. 이 항목이 없으면 앱이 오류를 반환합니다. 있는 경우 앱은 양식 데이터 수신을 확인하고 대화상자를 닫습니다.

Node.js

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

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

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

Apps Script

이 예에서는 카드 JSON을 반환하여 카드 메시지를 전송합니다. Apps Script 카드 서비스를 사용할 수도 있습니다.

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

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

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

Python

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

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

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

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

문제 해결

Google Chat 앱 또는 카드에서 오류를 반환하면 Chat 인터페이스에 '문제 발생' 또는 '요청을 처리할 수 없습니다'라는 메시지가 표시됩니다. 채팅 UI에는 오류 메시지가 표시되지 않지만 채팅 앱 또는 카드에서 예기치 않은 결과가 발생하는 경우가 있습니다. 예를 들어 카드 메시지가 표시되지 않을 수 있습니다.

Chat UI에 오류 메시지가 표시되지 않더라도 채팅 앱에 대한 오류 기록이 사용 설정되어 있을 때 오류를 수정하는 데 도움이 되는 자세한 오류 메시지와 로그 데이터가 제공됩니다. 오류를 확인, 디버깅, 수정하는 데 도움이 필요하면 Google Chat 오류 문제 해결 및 수정하기를 참고하세요.