지금까지 Kore.ai 가상 비서 플랫폼에서 경고 작업을 설정하는 방법을 여기에서 확인했습니다. 이 섹션에서는, REST 서비스의 API 요청을 구성하는 방법을 살펴봅니다.

다음 그림은 일반 탭에서 연결 유형웹 서비스로 지정되고 연결 모드REST로 설정된 경고 작업을 위한 경고 편집 – <작업 이름> 페이지에서 API 요청 탭의 예입니다.

연결 유형웹 서비스로 지정되고 연결 모드REST로 설정된 작업의 경우 다음을 정의해야 합니다.

  • 콘텐츠 유형 – Kore.ai 및 웹 애플리케이션 간에 교환되는 데이터 유형입니다. 자세한 내용은 아래를 참조하세요.
  • 인증 – 경고 작업에 필요한 경우, 기본 인증, OAuth 또는 API 키를 사용하여 API에 액세스하기 위해 인증을 정의해야 합니다. 자세한 내용은 여기를 참조하세요.
  • 매개변수 – API 요청을 처리하는 데 사용되는 매개변수를 하나 이상 정의합니다. 예: 사용자 프롬프트의 입력, 선택 항목에서 최종 사용자가 선택한 항목, URL 등. 자세한 내용은 아래를 참조하세요.
  • 이니셜라이저 – 웹 서비스가 코드를 실행할 때 또는 세션 변수가 설정될 때, API 요청이 실행되기 전에 사용자 컨텍스트 세부 정보를 수정할 때, 작업 인스턴스를 생성하기 전에 실행할 사용자 정의 JavaScript를 지정하거나 세션 변수를 설정합니다. 자세한 내용은 아래를 참조하세요.
  • 요청 – 봇에 대한 URL과 경로를 사용하여 웹 서비스에 API 호출을 수행하여 작업을 시작하고 웹 서비스에서 봇 플랫폼으로 데이터 페이로드 전달을 시작하는 데 사용되는 요청 체인을 정의합니다. 요청 체인은 전처리기, API 요청, 후처리기로 구성됩니다. 자세한 내용은 아래를 참조하세요.
  • 응답 샘플 – 작업 페이로드에서 수신할 것으로 예상되는 키/ 값 쌍을 정의합니다. 입력한 키는 최종 사용자에게 표시할 데이터를 처리하기 위해 드롭다운 선택 항목으로 사용할 수 있습니다. 자세한 내용은 아래를 참조하세요.
  • 게시물의 웹 사이트 링크 콘텐츠 미리 보기 – 작업 알림 메시지에 표시되는 웹 사이트 미리 보기 콘텐츠입니다. 자세한 내용은 아래를 참조하세요.

저장을 클릭하여 API 요청 설정을 저장합니다.

콘텐츠 유형 정의하기

콘텐츠 유형은 Kore.ai 및 봇 웹 사이트 또는 애플리케이션 간에 교환되는 데이터 유형 및 작업 페이로드 응답에서 예상되는 키-값 쌍을 설명합니다. API 요청(REST)을 위한 콘텐츠 유형을 정의하려면 콘텐츠 유형 탭을 확장하고 다음 옵션 중 하나를 선택합니다.

  • JSON – JavaScript Object Notation은 사람이 읽을 수 있는 텍스트를 사용하여 데이터 개체를 속성-값 쌍으로 전송하는 개방형 표준 포맷입니다. JSON을 사용하여 Kore.ai 서버와 봇 웹 애플리케이션 간에 데이터를 전송할 수 있습니다.
  • RSS – Rich Site Summary 또는 Really Simple Syndication은 블로그 항목, 뉴스 헤드라인, 오디오 및 동영상과 같이 자주 업데이트되는 정보를 게시하는 데 사용되는 표준화된 형식 집합입니다.
  • XML – Extensible Markup Language는 사람이 읽을 수 있고 기계가 읽을 수 있는 형식으로 문서를 인코딩하기 위한 규칙 집합을 정의한 마크업 언어입니다. 웹 서비스는 종종 XML 스키마를 사용하여 XML 데이터를 처리합니다.
  • URL 인코딩된 JSON – 예약된 문자에 대해 JSON 인코딩을 사용한 URL입니다.
  • CSV – 쉼표로 구분된 값 목록입니다.
  • 텍스트 – 텍스트 기반 키-값 쌍입니다.
  • Twitter 인코딩된 JSON – 예약된 문자에 대해 JSON 인코딩을 사용한 Twitter의 URL입니다.
  • Multipart/Form-data – 사용자가 양식에서 파일을 업로드할 수 있도록 하는 경우 HTTP POST 요청 메소드를 통해 파일을 전송하는 인코딩 유형입니다.
  • Multipart/Related – 같은 정보를 다른 본문 파트에 다른 형태로 표시할 때 사용됩니다. 본문 파트는 복잡도가 높은 순으로 정렬됩니다.
  • Oracle ADF – Oracle Application Development Framework용 입니다.

매개 변수 정의하기

API 요청(REST) 매개 변수를 정의하려면 다음 단계를 따르세요.

  1. 매개변수 섹션을 클릭한 다음 추가를 클릭합니다.  작업 매개변수 설정 대화 상자가 열립니다.
  2. 선택에 따라, 다음 표에 설명된 대로 관련 필드 값을 입력합니다.
    필드 이름 설명
    작업 매개 변수 유형

    다음 중 하나를 지정합니다.

    • 페이로드 매개변수 – 이 필드 유형을 사용하여 POST, PUT, GET, DELETE 등 HTTP 메소드의 페이로드 데이터를 나타냅니다. 예:
      {
         "taskId":"{payloadfield2}",
         "message":"{payloadfield1}"
      }
    • 쿼리 매개변수 – 이 필드는 URL 경로 또는 URL 내의 쿼리의 일부로 사용됩니다. 예:
      http://app.asana.com/api/workspaces/{queryfield1}/project/{queryfield2}?userId={queryfield3}
    매개 변수 이름 사용자에게 표시되는 작업 입력 필드의 제목입니다. 예: <i>계정 선택</i>
    프롬프트 메시지 매개변수 이름 아래에 표시되는 도움말 설명입니다. 예: 어떤 계정에 액세스하시겠습니까?
    매개 변수 키 수집하려는 최종 사용자 입력값을 나타내는 키입니다. 예: accountType.
    매개 변수 유형

    값에 할당할 요청 개체의 사용자 입력 수집을 위해 최종 사용자 인터페이스에 표시되는 작업 입력 필드의 유형을 지정합니다. 기본 설정은 텍스트 상자이지만 다음 중 하나에 맞게 사용자 정의할 수 있습니다.

    • 날짜 – 작업을 계정에 설정할 때 최종 사용자가 정의할 날짜 형식 구문을 선택할 수 있는 형식 필드를 표시합니다. 날짜 형식 선택 드롭다운 목록에서, 다음 중 하나를 선택합니다.
      • dd-MM-YYYY – 예: 16-05-1999
      • MM-dd-YYYY – 예: 05-16-1999
      • dd-MM-YY – 예: 16-05-99
      • YYYY-MM-dd – 예: 1999-05-16
    • URL – 올바른 URL 구문을 위한 필드 유효성 검사를 포함하여 최종 사용자가 URL을 입력할 수 있는 텍스트 상자를 표시합니다. 플레이스 홀더 필드에, 텍스트 상자에 표시되는 도움말 힌트를 입력합니다. 예: 여기에 웹 사이트의 URL 입력.
    • 텍스트 상자 – 최종 사용자가 작업 입력 필드로 텍스트를 입력하기 위한 텍스트 상자를 표시합니다. 일반적으로 몇 단어입니다. 플레이스 홀더 필드에서, 텍스트 필드에 표시되는 도움말 힌트를 입력합니다. 예: 꾸미려는 이름을 입력합니다.
    • 정적 드롭다운 – 최종 사용자에 대한 드롭다운 선택 목록을 표시합니다. 옵션 추가를 클릭하여 다음 매개변수를 사용하여 최종 사용자에게 표시할 항목 목록을 추가합니다.
      • 옵션 이름 – 최종 사용자에게 표시되는 옵션의 이름입니다.
      • 옵션값 – 애플리케이션에 반환된 옵션 이름을 나타내는 값입니다.
      • 기본값 – 하나 이상의 옵션이 정의된 경우 옵션의 기본값을 선택합니다.
      • 검색 가능 – 최종 사용자가 이 필드에 텍스트를 입력할 때 동적 검색 및 표시를 사용함으로 설정하거나 일치 항목이 없는 경우 자유 양식 입력을 허용하려면 선택합니다.

      저장을 클릭합니다. 추가 항목을 추가하려면, 옵션 추가를 다시 클릭합니다. 옵션의 조치 열에서 옵션을 편집하거나 삭제합니다.

    • 동적 드롭다운 – 봇의 URL 응답에 따라 실행 시 동적으로 채워진 드롭다운 목록을 표시합니다. 예: JIRA 작업 알림용 프로젝트 목록. 동적으로 채워진 드롭다운에 대해 다음 속성을 정의합니다.
      • 엔드포인트 URL – 봇 엔드포인트 URL입니다. 예: https://app.asana.com/api/1.0/workspaces.
      • 엔드포인트 콘텐츠 유형 – 지정된 엔드포인트 URL에서 예상되는 콘텐츠 유형입니다. 다음 중 하나입니다. JSON, RSS, XML, URL Encoded JSON, CCV, Text 또는 Twitter 인코딩된 JSON.
      • 엔드포인트 메소드 – 다음 중 하나입니다.
        • GET – 작업 필드의 HTTP 요청 GET 메소드를 지정합니다.
        • POST – 작업 필드의 HTTP 요청 POST 메소드를 지정합니다.
      • 응답 경로 – 원하는 드롭다운 목록 값이 포함된 응답의 경로입니다. 예: data.
      • 라벨 키 – 드롭다운 옵션의 라벨 키입니다. 예: name.
      • 옵션값 키 – 드롭다운 옵션 값의 키입니다. 예: id.
      • 페이로드 필드 추가 – 동적 드롭다운에 대한 옵션으로 응답 페이로드에서 하나 이상의 필드를 추가하려면 클릭합니다. 각 페이로드 필드에서, 페이로드 필드 키페이로드 필드 값을 입력한 다음 저장을 클릭합니다. 조치 열에서 페이로드 필드를 편집하거나 삭제합니다.
      • 검색 가능 – 최종 사용자가 이 필드에 텍스트를 입력할 때 동적 검색 및 표시를 사용함으로 설정하거나 일치 항목이 없는 경우 자유 양식 입력을 허용하려면 선택합니다.
    • 텍스트 영역 – 최종 사용자가 작업 입력 텍스트를 입력하기 위한 텍스트 영역을 표시합니다. 일반적으로 몇 문장입니다. 플레이스 홀더 필드에서, 텍스트 영역 내부에 표시되는 도움말 힌트를 입력합니다.
    • 타입 어헤드 – 작업에 정의된 URL 응답에 따라 사용자가 검색 결과와 일치하는 3개 이상의 문자를 입력할 때 실행 시 동적으로 채워진 드롭다운 선택 목록을 최종 사용자에게 표시합니다. 예: JIRA 작업 알림 메시지의 프로젝트 목록. 동적으로 채워진 드롭다운에 대해 다음 속성을 정의합니다.
      • 엔드포인트 URL – 봇 엔드포인트 URL입니다. 예: https://app.asana.com/api/1.0/workspaces.
      • 엔드포인트 콘텐츠 유형 – 지정된 엔드포인트 URL에서 예상되는 콘텐츠 유형입니다. 다음 중 하나입니다. JSON, RSS, XML, URL Encoded JSON, CCV, Text, Twitter Encoded JSON, Multipart/Form-data 또는 Multipart/Related.
      • 엔드포인트 메소드 – 다음 중 하나입니다.
        • GET – 작업 필드의 HTTP 요청 GET 메소드를 지정합니다.
        • POST – 작업 필드의 HTTP 요청 POST 메소드를 지정합니다.
      • 응답 경로 – 원하는 드롭다운 목록 값이 포함된 응답의 경로입니다. 예: data.
      • 라벨 키 – 드롭다운 옵션의 라벨 키입니다. 예: name.
      • 옵션값 키 – 드롭다운 옵션 값의 키입니다. 예: id.
      • 페이로드 필드 추가 – 타입 어헤드 필드에 대한 옵션으로 응답 페이로드에서 하나 이상의 필드를 추가하려면 클릭합니다. 각 타입 어헤드 필드 옵션에서, 페이로드 필드 키페이로드 필드 값을 입력한 다음 저장을 클릭합니다. 조치 열에서 페이로드 필드를 편집하거나 삭제합니다.
      • 편집 가능 – 타입 어헤드 검색 결과가 일치하지 않을 때 사용자가 필드에서 텍스트를 자유롭게 입력할 수 있습니다.
    • 이메일 – 최종 사용자가 이메일 주소를 입력할 수 있는 텍스트 상자를 표시합니다. 플레이스 홀더 필드에서, 텍스트 상자 내부에 최종 사용자에게 표시되는 유용한 힌트를 입력합니다.
    • 날짜 및 시간 – 최종 사용자가 시간과 함께 날짜를 입력할 수 있는 텍스트 상자를 표시합니다. 형식 필드에서, 날짜 텍스트 상자에 최종 사용자에게 표시할 예상되는 날짜 또는 시간 형식을 입력합니다. 날짜 형식 선택 드롭다운 목록에서, 시간 형식의 날짜를 선택합니다.
    • 시간대 – 운영 체제 설정에 따른 시간대 드롭다운 목록을 표시합니다.
    • 위치 – 최종 사용자가 지리적 위치를 입력할 수 있는 텍스트 상자를 표시합니다. 예: Orlando, FL 또는 32801.
    • 중첩된 양식 – 상위 입력 필드 아래에 중첩된 형식으로 최종 사용자 입력 필드를 표시합니다. 중첩된 양식 입력 필드에 대해 다음 필드를 지정합니다.
      • 배열 요소 유형 – 상위 입력 양식 요소의 데이터 유형을 선택합니다.
      • 중첩 양식 필드 추가 – 하나 이상의 중첩된 양식 필드를 추가하려면 클릭합니다.
    • 파일 업로드 – 검색할 최종 사용자 컨트롤을 표시하고 업로드할 파일을 선택합니다. 클릭되면, 파일 업로드 페이로드 키를 입력합니다. 파일 업로드 페이로드 키가 정의된 경우, 파일 업로드 페이로드 필드 값 드롭다운 목록에서 다음 유형 중 하나를 선택합니다.
      • 파일 이름
      • 파일 크기
      • 파일 콘텐츠 유형
    데이터 유형

    다음 사용자 입력 유형 중 하나를 선택합니다.

    • 문자열 – 사용자는 연속된 숫자, 문자 또는 특수 문자를 입력할 수 있습니다.
    • 숫자 – 사용자는 숫자를 입력할 수 있습니다. 특수 문자는 허용되지 않습니다.
    • 불리언 – 사용자는 true 또는 false의 부울 값을 입력할 수 있습니다.
    • 이메일 – 사용자는 유효한 이메일 주소를 입력할 수 있습니다.
    • 개체 – 봇의 데이터는 JSON 개체로 수신할 수 있습니다. 예: 다음과 같이 정의된 위치 세부정보  “location” : { “lat” : 17.4374614, “lng” : 78.4482878 } 요청 체인 또는 작업 요청에서 속성을 location.latlocation.lng로 참조할 수 있습니다.
    • Array – 사용자는 쉼표로 구분된 값 목록을 봇에 전달할 수 있습니다. 예: 구글 캘린더에서 데이터가 있는 여러 참석자는 다음과 같이 전달할 수 있습니다. “attendees”: [“user1”, “user2”, “user3”] 선택되면 사용자 입력 배열의 유형을 다음 중 하나로 지정합니다.
  • 문자열
  • 숫자
  • 불리언
  • 이메일
  • 배열
  • 날짜
  • 날짜 – 사용자는 전체 날짜를 입력하거나 날짜 선택기에서 날짜를 선택할 수 있습니다.

Is Multi Select를 사용하여 사용자는 하나 이상의 항목을 선택할 수 있습니다. 이 필드는 선택한 필드 유형에 따라 표시됩니다.

  • 고급 설정 탭을 클릭하여 작업 필드의 추가 옵션 설정을 정의합니다.

    필드 이름 설명
    가시성

    작업 입력 필드를 최종 사용자에게 표시할지 숨길지 여부를 지정합니다. 가시성 필드는 사용자 정의로 설정할 수도 있으며 데이터는 사용자로부터 캡처되지만 쿼리 매개 변수 또는 페이로드 필드로 사용되지 않습니다. 예: JIRA 봇을 사용하는 경우 아래와 같이 @mention 태그를 사용하여 티켓에 의견을 게시합니다. “@Mike, 이 문제를 살펴보세요” ‘의견 게시’를 위한 JIRA API는 다음과 같이 하나의 쿼리 필드와 하나의 페이로드 필드가 필요합니다.

    • 발급 ID
    • 의견

    가시성 필드를 사용자 정의로 설정하면 페이로드 필드 또는 쿼리 필드로 사용하지 않고 comment 필드 값에 추가할 데이터를 가져오기 위해 JIRA API를 사용하여 @Mike로 언급된 사용자의 사용자 정보를 캡처할 수 있습니다. 기본 가시성 필드 설정은 Visible입니다.

    필수 최종 사용자가 이 설정을 정의하여 작업 설정 구성을 저장하려는 경우 선택합니다.
    키 전치 해제 Kore.ai의 키 전치를 비활성화하려면 선택하세요. 기본적으로 Kore.ai는 키/값 쌍을 전치합니다. 예: Kore.ai는 “parameter”:”value”를 “parameter:{value:”actualValue”}로 전치합니다. 선택되면 키는 전치되지 않습니다.
    세션에서 가져오기

    이 필드의 사용자 입력값을 세션 변수로 저장하려면 선택합니다. 선택되면, 세션의 필드 값 필드가 표시됩니다. 기본 변수를 선택하거나 새 세션 변수 추가를 선택하여 새 변수를 정의합니다. 새 세션 변수를 생성하려면, 변수의 범위를 선택하고 변수를 저장할 를 정의해야 합니다. 범위 필드에서 다음 중 하나를 선택합니다.

    • EnterpriseContext – 엔터프라이즈 모든 사용자가 사용할 수 있는 키/값 쌍을 정의합니다.
    • BotContext – 봇의 모든 사용자가 사용할 수 있는 키/값 쌍을 정의합니다.
    • UserSession – 엔터프라이즈 내 모든 봇 사용자를 위한 키/값 쌍을 정의합니다.
    • BotUserSession – 사용자 입력을 기반으로 봇이 사용 가능한 키/값 쌍을 정의합니다.
  • 추가 및 계속을 클릭하여 작업 요청의 매개변수를 저장하고 다른 매개변수를 추가하거나, 추가 및 종료를 클릭하여 작업 요청의 매개변수를 저장하고 대화 상자를 닫습니다. 봇 사용자가 입력을 제공해야 하는 순서대로 여러 매개변수를 구성해야 합니다. 매개변수를 이동하려면  및  아이콘을 사용합니다.
    조치 작업 - API 요청 탭 - 매개 변수 섹션 - 정렬

이니셜라이저 정의하기

작업을 실행하려면, Kore.ai 세션별 변수를 사용하여 작업을 실행하기 전에 세션에 값을 입력하거나 가져와야 할 수 있습니다. 자세한 내용은, 작업에서 세션 변수 및 컨텍스트 변수 사용하기를 참조하세요. 일부 웹 서비스는 API 요청을 실행하기 전에 실행된 코드, 세션 변수 또는 사용자 컨텍스트 세부 정보 수정이 필요합니다. 예: 웹 서비스는 2단계 사용자 권한 부여가 필요할 수 있습니다. 첫 번째 단계는 사용자 인증이며 두 번째 단계는 파트너 인증입니다. 이 두 단계를 모두 검증한 후, 액세스 토큰이 부여되며 해당 웹 서비스에 대한 후속 API 호출 헤더에 사용됩니다. 이니셜라이저를 사용하여, 파트너 권한 부여를 완료하고 사용자 인증에서 액세스 토큰을 검색할 수 있습니다. 액세스 토큰은 사용자 정의 세션 변수로 저장할 수 있고 후속 API 호출을 위한 헤더로 설정할 수 있습니다.

작업 이니셜라이저 정의

작업 이니셜라이저를 설정하려면, 이니셜라이저 탭을 클릭하세요. 필요한 코드를 작성할 수 있는 JavaScript 편집기가 열립니다. 조치 작업 - API 요청 탭 - 이니셜라이저 섹션 JavaScript 편집기에서, 다음과 같이  및 범위를 정의합니다.

  • EnterpriseContext – 엔터프라이즈 내 모든 봇과 사용자가 사용할 수 있는 키-값 쌍입니다. 예: GitHub 봇의 경우 사용자는 하나 이상의 엔터프라이즈 저장소에 액세스해야 합니다. 이니셜라이저에서, 다음 JavaScript 코드를 사용하여 저장소 데이터를 Gitrepository(엔터프라이즈 컨텍스트)로 유지할 수 있습니다.
    var userRepository = {
    "title": _labels_[repository],
    "value": repository
    };
    EnterpriseContext.put('Gitrepository', userRepository, 200000);
  • BotContext – 특정 봇의 모든 사용자가 사용할 수 있는 키-값 쌍입니다. 예: 사용자의 위치에 따라 세션에서 금융 거래를 위한 기본 통화를 설정할 수 있습니다. 이니셜라이저에서 다음 JavaScript 코드를 사용하여 기본 통화 데이터를 currency(봇 컨텍스트)로 유지할 수 있습니다.
    var defaultCurrency = { TODO Custom JavaScript for location-based currency }
    BotContext.put('currency', defaultCurrency, 200000);
  • UserContext – 사용자의 모든 봇이 사용할 수 있는 키-값 쌍입니다. 이 키는 읽기 전용이며 시스템에서 다음과 같은 사용자 데이터로 제공됩니다.
    • _id – Kore.ai userId입니다.
    • emailId – userId에 연결된 이메일 주소입니다.
    • lastName – 사용자의 성입니다.
    • firstName – 사용자의 이름입니다.
    • profImage – 사용자의 이미지 또는 아바타 파일 이름입니다.
    • profColour – 사용자의 계정 색상입니다.
    • activationStatus – 사용자의 계정 상태입니다.
    • 직함 – 정의된 경우 사용자의 직함입니다.
    • orgId – 정의된 경우 사용자 계정의 조직 ID입니다.
  • UserSession – 엔터프라이즈 내 모든 봇의 특정 사용자가 사용할 수 있는 키-값 쌍을 정의합니다. 예: 상거래, 운송 및 가정 배달 서비스를 위한 사용자 집 주소와 같이 사용자 위치를 저장하여 모든 봇이 사용할 수 있도록 해야 합니다. 이니셜라이저에서, 다음 JavaScript 코드를 사용하여 기본 위치 데이터를 HomeLocation (사용자 세션)으로 유지할 수 있습니다.
    var location = {
     "title": labels[location],
     "value": {
     "latitude": location.latitude,
     "longitude": request.location.longitude
     }
    };
    UserSession.put('HomeLocation', location, '20000');
  • BotUserSession – 같은 특정 사용자의 입력을 기반으로 특정 봇이 사용 가능한 키-값 쌍을 정의합니다. 예: 하나 이상의 봇 작업에 대해 사용자 위치를 유지해야 합니다. 여행 봇의 경우 같은 집 주소와 목적지 주소를 기준으로 항공편과 호텔을 예약할 수 있습니다. 이니셜라이저에서 다음 JavaScript 코드를 사용하여 기본 집 및 목적지 데이터를 HomeLocation (봇 사용자 세션) 및 DestinationLocation (봇 사용자 세션)으로 유지할 수 있습니다.
    var homelocation = {
     "title": labels[request.sourceLocation],
     "value": {
     "latitude": request.sourceLocation.latitude,
     "longitude": request.sourceLocation.longitude
     }
    };
    BotUserSession.put('HomeLocation', homelocation, '20000');
    var destlocation = {
     "title": labels[request.destLocation],
     "value": {
     "latitude": request.destLocation.latitude,
     "longitude": request.destLocation.longitude
     }
    };
    BotUserSession.put('DestinationLocation', destlocation, '20000’);

GET 및 PUT 구문

다음 코드 예시에서는 각 컨텍스트 유형에 따라 키-값 쌍을 GET 또는 PUT하는 구문을 보여줍니다.

"EnterpriseContext" : {
       "get" : function(key){...},//get the specified key
       "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes
   },
   "BotContext" : {
       "get" : function(key){...},//get the specified key
       "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes
   },
   "UserContext" : {
       "get" : function(key){...},//get the specified key
   },
   "UserSession" : {
       "get" : function(key){...},//get the specified key
       "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes
   },
   "BotUserSession" : {
       "get" : function(key){...},//get the specified key
       "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes
   }

예:

    BotContext.put("topicSessionVariable","music",2000);
    UserSession.put("firstName","Mary",20000);
    UserContext.get("firstName");

예외 구문

인증 실패와 같은 작업 설정 전에 오류를 캡처하도록 사용자 정의 오류 메시지를 정의할 수도 있습니다. 예외가 캡처된 경우 작업 설정이 중지됩니다. 다음 구문을 사용하여 예외를 발생시킵니다.

{
    "exceptions": {
        "message": " Error Message"
    }
}

예,

var ex ={};
var exceptions={};
exceptions.message ='You can not proceed further with out valid permissions';
ex.exceptions = exceptions;
print(JSON.stringify(ex)); //print is mandatory.

이니셜라이저 섹션에서는, 세션 또는 기타 세션 값을 설정할 수 있지만, 값을 설정하거나 액세스할 수는 없습니다. 예:

var name = UserContext.get("firstName")+UserContext.get("lastName");
UserSession.put("fullName") = name;

앞의 코드 예시에서는, 작업의 고급 설정 섹션에서 세션에서 가져오기 필드로 정의된 작업 매개변수를 사용하여 세션에 값을 입력합니다. 는 사용자 정의된 UserSession 컨텍스트 변수에 대해 fullName으로 정의됩니다.

작업 이니셜라이저 예시

다음 코드는 API 요청에서 변수를 미리 채우는 사용자 ID 및 이메일 데이터를 얻기 위한 작업 이니셜라이저의 예입니다.

var x = UserContext.get("identities");
var isEmailFound = false;
for (var i = 0; i < x.length; i++) {
    if (x[i].type === "mapped") {
        var identity = x[i].val
        var arr = identity.split("/");
        var pattern = /^cs/i;
        var result = arr[0].match(pattern);
        if (result) {
            isEmailFound = true;
            UserSession.put("rtmEmail", arr[1], '20000');
        }
    }
}
if (!isEmailFound) {
    for (var j = 0; j < x.length; j++) {
        if (x[j].type === "email") {
            UserSession.put("rtmEmail", x[j].val, '20000');
        }
    }
}

요청 체인 정의하기

API 요청 탭의 요청 섹션에서, 전처리기, API 요청, 후처리기로 구성된 API 요청 체인을 정의할 수 있습니다. 처리기는 선택이지만, API 요청은 하나 이상 필요합니다.

API 요청

모든 작업에 대해 작업을 시작하려면 웹 서비스 호출을 위한 API 요청을 정의해야 합니다. 각 작업을 위해 최소한 하나의 API 요청은 필요합니다. 각 API 요청에 대해 웹 서비스에서 데이터 페이로드 전달을 시작하려면 하나 이상의 요청 URL 및 경로를 추가해야 합니다.

API 요청 설정하기
  1. API 요청 탭에서, 요청 탭을 확장한 다음 API 추가를 클릭합니다.
  2. 다음 절차에 설명된 대로 API 추가 대화 상자에 필드 값을 지정합니다.
  3. 이름 필드에서, API 요청의 이름을 입력합니다. 예: 내 API 요청.
  4. 메소드 드롭다운 목록에서, 작업에 사용되는 HTTP 메소드를 입력합니다. 다음 중 하나입니다.
    • POST– HTML 양식을 사용하여 고객 정보, 파일 업로드 등 서버에 데이터를 전송하는 데 사용됩니다.
    • PUT– 대상 리소스의 내용을 전송된 내용으로 대체합니다.
    • PATCH – 기존 대상 리소스의 내용에 전송된 내용을 추가합니다.
    • DELETE – 기존 대상 리소스의 내용을 삭제합니다.
    • GET – 기존 대상 리소스의 내용을 반환합니다.
  5. URL 필드에서 프로세스에 대한 봇 작업 응답의 URL을 지정합니다. 예: http://koremessenger.com/postURL. 다음 예시와 같이 URL에서 세션 변수를 사용할 수도 있습니다.
    https://mySite.crm.ondemand.com/sap/c4c/odata/v1/c4codata/ServiceRequestCollection?$filter=ID eq '{id}' and ReporterEmail eq '{userEmail}'&amp;$expand=ServiceRequestHistoricalVersion,ServiceRequestDescription
    참고 사항: 일부 URL에서는 종료시작 매개변수에 독자적인 Kore.ai 매개변수 값을 사용해야 합니다. Kore.ai 매개변수 값에 대한 자세한 내용은, 봇 추가하기에서 봇별 문서를 참조하세요.
  6. 커넥터를 사용한 액세스 필드에서, Kore.ai 커넥터 에이전트를 사용하여 Kore.ai 봇의 액세스를 활성화하려면 를 선택합니다. 이 옵션은 Kore.ai 커넥터 에이전트가 엔터프라이즈 온프레미스 네트워크에서 설정되어 사용함으로 설정한 경우에만 표시됩니다. 자세한 내용은, Kore.ai 커넥터 사용하기를 참조하세요.
  7. 헤더 탭의 콘텐츠 유형 필드에서, 샘플 응답 데이터에 대해 지원되는 다음 데이터 유형 중 하나를 선택합니다.
    • JSON – JavaScript Object Notation은 사람이 읽을 수 있는 텍스트를 사용하여 데이터 개체를 속성-값 쌍으로 전송하는 개방형 표준 포맷입니다. JSON을 사용하여 Kore.ai 서버와 봇 웹 애플리케이션 간에 데이터를 전송할 수 있습니다.
    • RSS – Rich Site Summary 또는 Really Simple Syndication은 블로그 항목, 뉴스 헤드라인, 오디오 및 동영상과 같이 자주 업데이트되는 정보를 게시하는 데 사용되는 표준화된 형식 집합입니다.
    • XML – Extensible Markup Language는 사람이 읽을 수 있고 기계가 읽을 수 있는 형식으로 문서를 인코딩하기 위한 규칙 집합을 정의한 마크업 언어입니다. 웹 서비스는 종종 XML 스키마를 사용하여 XML 데이터를 처리합니다.
    • URL 인코딩된 JSON – 예약된 문자에 대해 JSON 인코딩을 사용한 URL입니다.
    • CSV – 쉼표로 구분된 값 목록입니다.
    • 텍스트 – 텍스트 기반 키-값 쌍입니다.
    • Twitter 인코딩된 JSON – 예약된 문자에 대해 JSON 인코딩을 사용한 Twitter의 URL입니다.
    • Multipart/Form-data – 사용자가 양식에서 파일을 업로드할 수 있도록 하는 경우 HTTP POST 요청 메소드를 통해 파일을 전송하는 인코딩 유형입니다.
    • Multipart/Related – 같은 정보를 다른 본문 파트에 다른 형태로 표시할 때 사용됩니다. 본문 파트는 복잡도가 높은 순으로 정렬됩니다.
    • Oracle ADF – Oracle Application Development Framework용 입니다.
  8. 권한 부여 헤더 섹션에서 키를 선택하거나 선택 취소하여 다음 그림과 같이 헤더의 키를 사용하거나 비활성화합니다.
    조치 작업 - API 요청 탭 - 요청 섹션 - API 대화 추가 - 권한 부여 헤더
  9. 다음 그림과 같이 매개변수 탭에서 헤더에 포함할 권한 부여 매개변수 또는 매개변수를 선택하거나 선택 취소합니다.
    조치 작업 - API 요청 탭 - 요청 섹션 - API 대화 추가 - 매개 변수
  10. 저장을 클릭하여 저장하고 API 요청 설정을 닫습니다.
처리기

처리기를 사용하고 자바스크립트를 사용하여 웹 서비스에 API 요청 전, 요청 중, 요청 후에 사용자 세션에서 수집된 데이터를 수정할 수 있습니다. 처리기가 정의되고 API 요청 전 순차적으로 배치된 경우 이 처리기는 전처리기입니다. 전처리기를 사용하면 API 요청이 수행되기 전 세션 변수에서 입력 매개변수와 값을 관리할 수 있습니다. 처리기가 API 요청 후 순차적으로 배치된 경우 이 처리기는 후처리기입니다. 후처리기를 사용하여 API 요청에서 페이로드 응답 키에 액세스할 수 있습니다. 키에 액세스하려면, 다음 후처리기 유형 중 하나를 사용하세요.

  • 해결: 두 번째 요청에 대한 입력으로 하나의 페이로드 응답의 결과를 사용합니다.
  • 확장 – 페이로드에서 데이터 배열을 분리합니다.
  • 추출 – 여러 개체가 있는 페이로드의 특정 개체의 경로를 지정합니다.
  • 할당 – 페이로드 응답의 변수 이름을 지정합니다.
전처리기

세션 변수 및 매개 변수를 사용하여 API 요청을 실행하기 전에 전처리기를 사용해 요청 매개 변수를 관리할 수 있습니다. 전처리기를 정의할 때, 처리 유형사용자 정의로 설정한 다음 표시되는 JavaScript 편집기에 코드를 입력해야 합니다. 전처리기는 사용자 정의 유형만 될 수 있습니다.

전처리기 추가하기
  1. API 요청 페이지에서, 요청 탭을 확장한 다음 처리기 추가를 클릭합니다.
  2. 이름 필드에 처리기의 이름을 입력합니다.
  3. 처리 유형 드롭다운 목록에서, 전처리기에 대해 사용자 정의를 선택합니다.
  4. 다음 구문을 사용하여 필요에 따라 요청 매개 변수를 수정하기 위한 코드를 추가합니다.
    {
        "fields": {
            "payloadFields": { // to set value to a payload field
                "key1": "value1", // Payload fields are not applicable for Alert tasks.
                "key2": "value2"....
            },
            "headerFields": { // to set value to a header field
                "key1": "value1",
                "key2": "value2"....
            },
            "pathFields": { // to set value to a path field or query field.
                "key1": "value1",
                "key2": "value2"....
            }
        }
    }

    예: 다음 코드 조각을 사용하여 API 개체의 경로 필드 또는 쿼리 필드를 설정할 수 있습니다.

    var fields= {};
    var pathFields = {};
    pathFields.fullName = UserContext.get("firstName")+UserContext.get("lastName")
    fields.pathFields = pathFields;
    var finalObject = {};
    finalObject.fields = fields;
    print(JSON.stringify(finalObject));

    이전 코드에서, firstNamelastName이 세션 변수로 JohnSmith로 각각 저장된 경우 전처리기의 JSON 응답 페이로드는 다음과 같습니다.

    {
        fields: {
            "pathFields": {
                "key": "fullName",
                "value": "John Smith"
            }
        }
    }

    다음 전처리기 예시에서는, 실제 API 요청 호출 전에 변수를 세션 변수로 설정합니다.

    var fields = {};
    var pathFields = {};
    var UserEmailID = UserSession.get("rtmEmail");
    pathFields.userEmail = UserEmailID;
    fields.pathFields = pathFields;
    var finalObject = {};
    finalObject.fields = fields;
    print(JSON.stringify(finalObject));
  5. 저장을 클릭하여 저장하고 처리기 추가 대화 상자를 닫습니다.
API 요청 전에 처리기를 요청 섹션에 배치하면 처리기는 전처리기로 간주됩니다. API 요청 후에 처리기를 배치하면, 처리기는 후처리기로 간주됩니다.
후처리기 추가하기

Kore.ai 후처리기를 사용하여 웹 서비스에서 원하는 데이터 페이로드를 가져오려면 하나 이상의 API 요청이 필요합니다.

사용자 정의 후처리기 정의

사용자 정의 후처리기를 생성하려는 경우, 다음 구문을 사용하여 이전 API 요청의 응답 키에 액세스할 수 있습니다”

payload[0].{ key }

JSON 구문
{
 "payload":
   {
    "key1" : "value1",
    "key2" : "value2"
   }
}
var final = {};
var data = payload[0]; //Accessing the response of the previous API object
data.title[0] = 'New value for key here';
final.payload = data;  // Updating the response of the API object
print(JSON.stringify(final));  // This step is mandatory

사용자 정의 처리기의 경우, 이전 코드와 같이 최종 응답을 출력해야 합니다. 그렇지 않으면 빈 응답이 반환됩니다. 다음 구문을 사용합니다.

print(JSON.stringify( <<object>> ));

표준 후처리기 설정

표준 후처리기를 추가하려면 다음 단계를 따릅니다.

  1. API 요청 탭에서 요청 탭을 확장한 다음 처리기 추가를 클릭합니다.
  2. 또한 Kore.ai는 후처리기를 위한 사용자 정의 코드를 생성하는 대신 사용할 수 있는 일련의 표준 후처리기를 제공합니다. 처리 유형 필드에서, 다음 네 가지 표준 처리기 유형 중 하나를 선택합니다.
    1. 해결: 두 번째 요청에 대한 입력으로 하나의 페이로드 응답의 결과를 사용합니다. 예: 처리기 추가를 클릭하고 처리기의 이름을 입력하고 처리 유형resolve로 설정하고 를 변수의 이름으로 설정한 다음 첫 번째 API 요청의 변수를 사용하여 Post URL을 정의합니다. 예: https://app.asana.com/api/1.0/projects/{project_id}는 페이로드 응답에서 다음과 같이 id 필드를 반환합니다.
       ...
      "id":80468818418144, <br/>
      "created_at":"2016-01-14T05:34:35.848Z",
      "modified_at":"2016-01-20T04:29:52.505Z",
      "owner":{
      "id":73114591129714,
      "name":"jaganmohan.evuri" },
      ...

      그 이후 다음과 같이 변수 입력으로 사용됩니다 Post URL: https://app.asana.com/api/1.0/projects/{id}/tasks?opt_fields=completed,modified_at 페이로드 응답에서 예상되는 HTML 콘텐츠 유형 및 HTML 요청 메소드를 지정해야 합니다. 자세한 내용은, 작업에서 세션 변수 및 컨텍스트 변수 사용하기를 참조하세요.

    2. 확장: 분리해야 하는 데이터 배열이 포함된 페이로드입니다. 예: 처리기 추가를 클릭하고 처리기의 이름을 입력하고  필드를 데이터로 설정하고 처리 유형spread로 설정하여 다음 코드 예제에서 data 요소의 내용을 캡처하여 배열의 각 항목을 추출합니다.
       {
           "attribution": null,
           "tags": [],
           "type": "image",
           "location": null,
           "comments": {
               "count": 51,
               "data": [{
                   "created_time": "1453900980",
                   "text": "43rd",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1171728804843572377"
               }, {
                   "created_time": "1453901222",
                   "text": "44th",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1171730841379491107"
               }, {
                   "created_time": "1453901997",
                   "text": "45th",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1171737339782450909"
               }, {
                   "created_time": "1453902304",
                   "text": "46th and 47th",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1171739915923967873"
               }, {
                   "created_time": "1453902638",
                   "text": "48th",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1171742713994497101"
               }, {
                   "created_time": "1453964684",
                   "text": "49th",
                   "from": {
                       "username": "venkataphani.ailavarapu",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2679234818",
                       "full_name": "Phani"
                   },
                   "id": "1172263199715314941"
               }, {
                   "created_time": "1453964710",
                   "text": "50th",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1172263415747136776"
               }, {
                   "created_time": "1453964717",
                   "text": "51st",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1172263474056350986"
               }]
                 ...
    3. 추출: 여러 개체가 포함된 페이로드의 경우, 특정 개체에 대한 경로를 지정할 수 있습니다. 예: 처리기 추가를 클릭하고, 처리기의 이름을 입력하고,  필드를 data로 설정한 다음, 처리 유형을 extract로 설정하여 다음 페이로드 응답에서 개체 데이터를 사용합니다.
      {
          "user": {
              "full_name": "Kore.ai Hyd",
              "id": "2056218675",
              "profile_picture": "https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg",
              "username": "kore_hyd"
          },
          ...
      }, "likes": {
          "data": [{
                  "full_name": "kstream002",
                  "id": "2100724876",
                  "profile_picture": "https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg",
                  "username": "kstream002"
              }
          },
          ...
      }
    4. 할당: 할당 처리기를 사용하여, 필요한 경우 페이로드 응답의 변수 이름을 지정할 수 있습니다. 예: 페이로드에 페이로드 응답 데이터의 키가 포함되지 않은 경우. 예: 처리 유형을 assign으로 설정한 다음, 출력 변수 필드에서 세 개의 개체 배열로 구성된 다음 페이로드의 출력 변수를 정의할 수 있습니다.
      [
        {
          "Cost": "$0.00",
          "Desc1": "$150 bonus after $500 of purchases in the first 3 months from account opening. ",
          "Desc2": "Earn unlimited cash back Earn unlimited 1.5% cash back on every purchase – it's automatic. Redeem for cash back – any amount, any time. ",
          "Keywords": "weekend dining,online,groceries,fuel,rewards,rebate,365,allaround",
          "OfferName": "Freedom Unlimited",
          "OfferType": "CreditCard",
          "Status": "1",
          "imageURL": "http://www.psdgraphics.com/file/credit-card.jpg",
          "id": "5b5195e264bbd800"
        },
        {
          "Cost": "$95.00",
          "Desc1": "Pay 0 balance transfer fee when you transfer a balance during the first 60 days.",
          "Desc2": "Jumpstart your financial fitness Get an introductory fee for balance transfers, save on interest†, and get your free monthly credit score.",
          "Keywords": "privileges,rebate,health,wellness,great eastern,insurance,policy,installments,split,cashflo",
          "OfferName": "Premium Plus",
          "OfferType": "CreditCard",
          "Status": "1",
          "imageURL": "http://i.imgur.com/rMOXYql.jpg",
          "id": "5caf2155873f89c8"
        },
        {
          "Cost": "$10.00",
          "Desc1": "Pay 0 balance transfer fee when you transfer a balance during the first 60 days.",
          "Desc2": "Jumpstart your financial fitness Get an introductory fee for balance transfers, save on interest†, and get your free monthly credit score.",
          "Keywords": "privileges,rebate,health,wellness,great eastern,insurance,policy,installments,split,cashflo",
          "OfferName": "Frequent Flyer",
          "OfferType": "CreditCard",
          "Status": "1",
          "imageURL": "http://www.moneychoice.org/wp-content/uploads/2016/01/credit-card-calculator-image.png.jpeg",
          "id": "c0b05bc3062658ee"
        }
      ]

      출력 변수 필드에서, 배열을 나타낼 변수를 offers다음으로 지정합니다. UX 미리 보기 기능을 사용한 경우, Kore.ai의 응답은 다음과 같습니다.

      {
        "response": {
          "offers": [
            {
              "Cost": "$0.00",
              "Desc1": "$150 bonus after $500 of purchases in the first 3 months from account opening. ",
              "Desc2": "Earn unlimited cash back Earn unlimited 1.5% cash back on every purchase – it's automatic. Redeem for cash back – any amount, any time. ",
              "Keywords": "weekend dining,online,groceries,fuel,rewards,rebate,365,allaround",
              "OfferName": "Freedom Unlimited",
              "OfferType": "CreditCard",
              "Status": "1",
              "imageURL": "http://www.psdgraphics.com/file/credit-card.jpg",
              "id": "5b5195e264bbd800"
            },
            {
              "Cost": "$95.00",
              "Desc1": "Pay 0 balance transfer fee when you transfer a balance during the first 60 days.",
              "Desc2": "Jumpstart your financial fitness Get an introductory fee for balance transfers, save on interest†, and get your free monthly credit score.",
              "Keywords": "privileges,rebate,health,wellness,great eastern,insurance,policy,installments,split,cashflo",
              "OfferName": "Premium Plus",
              "OfferType": "CreditCard",
              "Status": "1",
              "imageURL": "http://vignette3.wikia.nocookie.net/objectmayhem/images/5/52/Credit_card.png/revision/latest?cb=20130629150408",
              "id": "5caf2155873f89c8"
            }
          ]
        }
      }

      출력 변수offers로 설정하면, 봇 빌더에서 변수를 다음과 같은 작업 응답 개체에서 response.offers로 사용할 수 있습니다.

      print(JSON.stringify(response));
      var data = response.offers
      for (i = 0; i < data.length; i++) {
          print('<a href="' + data[i].imageURL + '" target="_blank">' + data[i].OfferName + '</a><br>');
          print(data[i].Desc1)
          print('<br>');
          print('<br>');
          print('Cost: ' + data[i].Cost)
          print('<br>');
          if (i < data.length - 1) {
              print('<br>');
              print('<br>');
          }
      }
  3. 추가를 클릭하여 API 요청을 저장한 다음 다른 요청을 생성하거나, 추가 및 종료를 클릭하여 API 요청을 저장하고 대화 상자를 닫습니다.

여러 API 요청의 경우, 전체 데이터 응답을 얻는 데 필요한 요청을 순차적으로 순서를 정렬해야 합니다. 예: 작업 영역 목록, 프로젝트 목록, 마지막으로 사용자 목록을 요청해야 합니다. 위로 이동  및 아래로 이동  아이콘을 사용하여 API 요청을 재정렬합니다.

참고 사항: API 요청을 삭제할 때 확인 대화 상자가 표시되지 않습니다. 계속 또는 저장을 클릭한 경우 삭제 조치는 영구적이므로 취소할 수 없습니다.

응답 샘플 추가하기

응답 샘플 섹션에서, 작업 페이로드에서 수신할 것으로 예상되는 키-값 쌍의 예를 입력하거나 붙여넣을 수 있습니다. 응답 샘플을 정의할 때, 응답 샘플 섹션에 정의된 키는 출력 데이터를 처리하기 위한 드롭다운 선택 항목으로 사용할 수 있습니다.

샘플 응답 추가하기

  1. API 요청 탭에서, 샘플 응답 섹션을 확장합니다.
  2. JSON 응답 페이로드의 키-값 쌍을 포함하는 응답 샘플을 입력합니다. 다음 중 하나를 수행합니다.
    • 다음 그림과 같이 응답 보기를 들여쓰기가 있는 JSON 구조로 형식을 지정하려면, 서식화됨  아이콘을 클릭합니다.
    • 다음 그림과 같이 직렬화된 압축 형식으로 응답 보기의 형식을 지정하려면, 서식 없음  아이콘을 클릭합니다.

웹 사이트 링크 콘텐츠 미리 보기

일부 웹 서비스는 페이로드 응답의 일부로 미디어를 미리 볼 수 있는 링크를 보냅니다. 이 섹션에서는, 미리 보기 링크를 활성화 또는 비활성화하고 페이로드에 링크 경로를 정의할 수 있습니다. 기본적으로, 웹 사이트 미리 보기 링크는 비활성화되어 있습니다. 다음 그림은 를 선택할 때 게시물의 웹 사이트 링크 콘텐츠 미리 보기 섹션의 예입니다.API 요청 탭 - 미리 보기 섹션 활성화된 경우에 페이로드에서 미리 보기 링크에 대한 경로를 정의합니다. 경로가 페이로드의 루트에 없다면 링크에 대한 경로(toPreview) 필드에서 정의합니다. 예: RSS 페이로드의 다음 코드 예시에서 미리 보기의 경로는 다음과 같습니다

...
"item": [
    {
        "title": "U.S. to Boost Refugee Intake by 30,000 by 2017",
        "guid": {
            "-isPermaLink": "false",
            "#text": "SB12418904751422433479504581245034032986752"
        },
        "link": "http://www.wsj.com/articles/john-kerry-says-u-s-to-admit-30-000-more-refugees-in-next-2-years-1442768498?mod=fox_australian",
        ...

게시물에서 웹 사이트 링크 콘텐츠 미리 보기를 사용하도록 설정된 경우 다음과 같은 미리 보기 개체를 선택합니다.

  • 미리 보기 제목 – 웹 사이트 콘텐츠의 제목을 표시합니다.
  • 미리 보기 설명 – 웹 사이트 설명을 표시합니다.
  • 미디어(동영상) 미리 보기 – 웹 사이트 콘텐츠에서 동영상 링크 표시를 사용합니다.
  • 미디어(이미지) 미리 보기 – 웹 사이트 콘텐츠에서 이미지 링크 표시를 사용합니다.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

こちらで、Kore.aiのバーチャルアシスタントプラットフォームでの通知タスクの設定方法について確認しました。このセクションでは、RESTサービスのAPIリクエストを設定する方法について説明します。

以下の図は、一般タブで定義済みのウェブサービスとして指定された接続タイプおよびRESTに設定された接続モードの通知タスクの通知を編集―<タスク名>にあるAPIリクエストタブの一例です。
ウェブサービスとして指定された接続タイプおよびRESTに設定された接続モードには、以下を定義する必要があります。

  • コンテンツタイプ―Kore.aiおよびご使用のウェブアプリケーションの間に交換されるデータのタイプ。詳細は以下をご確認ください
  • 認証―通知タスクが必要な場合、APIにアクセスするために認証を定義する必要があります(例:基本認証、OAuth、APIキーなどを使用する)。詳しくはこちらを参照してください
  • パラメータ―APIリクエストの処理に使用される1つ以上のパラメータを定義します。例えば、ユーザープロンプトからの入力、エンドユーザーによる選択肢のリストからの選択、URLなどです。詳細は以下をご確認ください
  • イニシャライザー―Webサービスがコードの実行やセッション変数の設定、APIリクエストの実行前にユーザーコンテキストの詳細を変更する必要がある場合、タスクインスタンスを作成する前に実行とするカスタムJavaScriptを指定してください。詳細は以下をご確認ください
  • リクエスト―Webサービスからボットプラットフォームへのデータペイロードの配信を開始するために、URLとボットへのパースを使用してタスクを開始するためにWebサービスへのAPIコールを行うために使用するリクエストチェーンを定義します。リクエストチェーンはプリプロセッサー、APIリクエスト、およびポストプロセッサーが含めます。詳細は以下をご確認ください
  • 応答 サンプル – タスクのペイロードで受け取ることが求められるキー/値のペアを定義します。ご提供のキーは、エンドユーザーに表示するデータを処理するためのドロップダウンの選択肢として利用できます。詳細については、以下後ご確認ください
  • 投稿でウェブサイトのリンクコンテンツをプレビュー―タスク注意メッセージにあるウェブサイトのプレビューコンテンツを表示します。詳細は以下をご確認ください

保存をクリックしてAPIリクエストの設定を保存します。

コンテンツタイプの定義

コンテンツタイプは、Kore.aiとBotのウェブサイトやアプリケーションとの間で交換されるデータのタイプと、タスクのペイロード応答で予想されるキーと値のペアについて説明します。API リクエスト (REST) のコンテンツ タイプを定義するには、[コンテンツ タイプ] タブを開いて、次のオプションのうちの 1 つを選択します。

  • JSON – JavaScript Object Notation は、人間が判読できるテキストでデータ オブジェクトを属性と値のペアで送信する、オープンな標準フォーマットです。JSON を使って、Kore.ai サーバーとボット Web アプリケーションの間でデータを伝送することができます。
  • RSS―Rich Site SummaryやReally Simple Syndicationは、ブログのエントリー、ニュースの見出し、音声、動画など、頻繁に更新される情報を公開するために使用される標準化フォーマットの一群です。
  • XML―拡張可能なマークアップ言語とは、人間が読める形式と機械が読める形式の両方でドキュメントをエンコードするためのルールを定義したマークアップ言語です。Web サービスが XML データを処理するのに、XML スキーマがよく使用されます。
  • URL エンコードされた JSON – 予約文字のために JSON のエンコードを使った URL です。
  • CSV – カンマ区切りの値のリストです。
  • 文字―テキストベースのキー値ペア。
  • Twitter エンコードされた JSON – 予約文字のために JSON のエンコードを使った Twitter の URL です。
  • Multipart/Form-data – ユーザーがフォームからファイルをアップロードできるようにする場合に、HTTP POST リクエスト メソッドでファイル送信を可能にするエンコード タイプです
  • Multipart/Related – 同じ情報を、他のフォームの他のボディ パーツで表示する場合に使用します。ボディ パーツは複雑度の高い順に並べられています。
  • Oracle ADF – Oracle Application Development Framework に使用します。

パラメータの定義

以下の手順で、APIリクエスト(REST)のパラメータを定義します。

  1. パラメータのセクションをクリックして、次に追加をクリックします。  タスクパラメータの設定ダイアログが開きます。
  2. ご選択の次第、下記のテーブルの説明の通りに関連のフィールド値を入力してください。
    フィールド名 説明
    タスク パラメーターのタイプ 次のうちの 1 つを指定します。

    • ペイロード パラメーター – POST、PUT、GET、DELETE などの HTTP メソッドによるフィールド タイプでペイロード データを示します。例えば:
      { "taskId":"{payloadfield2}", "message":"{payloadfield1}" }
    • クエリ パラメーター – このフィールド タイプは URL パスの一部や URL にあるクエリとして使用されます。例えば: http://app.asana.com/api/workspaces/{queryfield1}/project/{queryfield2}?userId={queryfield3}
    パラメータ名 タスクのタイトルの入力フィールドはユーザーに表示します。例えば、アカウントを選択
    プロンプトメッセージ パラメータ名の下に表示するヘルプ説明です。例えば、アクセスとするアカウントはどちらですか?
    パラメータキー タスクキーは収集とするエンドユーザーの入力の値を示します、例えば、アカウントタイプ
    パラメータタイプ 上級オプションが選択された場合、エンドユーザーインターフェイスに表示されるフィールドのタイプを指定して、リクエストオブジェクトへのユーザー入力の割り当てキー値として収集します。デフォルト設定はテキストボックスですが、以下のうちの一つにカスタムすることは可能です :

    • 日付[フォーマット] フィールドを表示します。ここでは、エンドユーザーが自分のアカウントにタスクが設定されている場合に定義する日付フォーマットの構文を選択できます。[日付フォーマット選択] のドロップダウン リストから、次のうちの 1 つを選択します。
      • dd-MM-YYYY – 例:16-05-1999
      • MM-dd-YYYY – 例:05-16-1999
      • dd-MM-YY – 例:16-05-99
      • YYYY-MM-dd – 例:1999-05-16
    • URL – 正しい URL 構文のためのフィールド検証を含む、エンドユーザーによる URL 入力用のテキスト ボックスを表示します。[プレースホルダー] フィールドには、テキストボックスに表示されるヘルプヒントを入力します。たとえば、「こちらにウェブサイトのURLを入力してください」のようなものです。
    • テキストボックス―エンドユーザーにタスクの入力フィールドとして文字入力のためのテキストボックスを表示します(通常は数語程度)。[プレースホルダー] フィールドには、テキストフィールドに表示されるヘルプヒントを入力します。たとえば、「追加する名前を入力してください」のようなものです。
    • 静的ドロップダウン – エンドユーザーに選択肢のドロップダウン リストを表示します。オプションの追加をクリックして以下のパラメータでエンドユーザーに表示する項目リストの追加を始まります:
      • オプション名 – エンドユーザーに表示されるオプションの名前です。
      • オプション値―アプリケーションに返すオプション名という値と示します。
      • デフォルト値 – 1 点以上のオプションが定義されている場合、オプションのデフォルト値を選択します。
      • 検索可能―選択するとダイナミック検索、そしてこのフィールドにエンドユーザーが入力する文字の表示を可能にします、もし一致がない場合、フリーフォームのエントリが可能です。

      [保存] をクリックします。項目を追加する場合、オプションを追加をもう一度クリックします。動作コラムのオプション編集または削除します。

    • ダイナミックドロップダウン―BotのURLからの応答に基づいて、実行時に動的に生成されるドロップダウンリストを表示します(例:JIRA タスク通知用のプロジェクト一覧)。以下のダイナミックに配置されるドロップダウンへのプロパティを定義します。
      • エンドポイント URL – BotのエンドポイントのURLです。例:https://app.asana.com/api/1.0/workspaces
      • エンドポイントのコンテンツタイプ―指定されたエンドポイントURLから予想されるコンテンツタイプ。以下のうちの一つ:JSON、RSS、XML、URL エンコードされた JSON、CCV、文字、や Twitter エンコードされた JSON。
      • エンドポイント メソッド – 次のうちの 1 つになります。
        • GET– タスクフィールドのHTTPリクエストのGETメソッドを指定します。
        • POST– タスク フィールドの HTTP リクエストの POST メソッドを指定します。
      • 応答パース―希望するドロップダウンリストの値を含む応答内のパスです(例:データ)
      • ラベルキー – ドロップダウンオプションのラベルのキーです(例:名前)
      • オプション値キー – ドロップダウンオプションの値のキーです(例:ID)
      • idペイロード フィールドの追加 – 先行入力フィールドのオプションとして、 応答ペイロードから 1 つ以上のフィールドをクリックして追加します。各ペイロードフィルドについて、ペイロードフィールドのキーペイロードフィールドの値を入力し、保存をクリックします。動作列でペイロードフィールドを編集または削除します。
      • 検索可能―選択するとダイナミック検索、そしてこのフィールドにエンドユーザーが入力する文字の表示を可能にします、もし一致がない場合、フリーフォームのエントリが可能です。
    • テキストエリア―エンドユーザーがタスク入力としていくつのテキストを入力するためのテキストエリアを表示します。[プレースホルダー] フィールドに、テキスト ボックス内にエンドユーザーに対して表示するヘルプ ヒントを入力します。
    • 先行入力 – タスクに定義されたURLからの応答に基づく検索結果に一致する文字をユーザーが 3 文字以上入力すると、動的に入力されたドロップダウンリストの選択肢が実行時にエンドユーザーに表示されます。例えば、JIRAのタスク通知メッセージのプロジェクト一覧です。以下のダイナミックに配置されるドロップダウンへのプロパティを定義します。
      • エンドポイント URL – BotのエンドポイントのURLです。例:https://app.asana.com/api/1.0/workspaces
      • エンドポイントのコンテンツタイプ―指定されたエンドポイントURLから予想されるコンテンツタイプ。以下のうちの一つ:JSON、RSS、XML、URL エンコードされた JSON、CCV、テキスト、Twitter エンコードされた JSON、Multipart/Form-data または Multipart/Related。
      • エンドポイント メソッド – 次のうちの 1 つになります。
        • GET– タスクフィールドのHTTPリクエストのGETメソッドを指定します。
        • POST– タスク フィールドの HTTP リクエストの POST メソッドを指定します。
      • 応答パース―希望するドロップダウンリストの値を含む応答内のパスです(例:データ)
      • ラベルキー – ドロップダウンオプションのラベルのキーです(例:名前)
      • オプション値キー – ドロップダウンオプションの値のキーです(例:ID)
      • ペイロードフィールドの追加 先行入力フィールドのオプションとして、 応答ペイロードから 1 つ以上のフィールドをクリックして追加します。各先行入力のフィールドオプションについて、ペイロードフィールドのキーペイロードフィールドの値を入力し、保存をクリックします。動作列でペイロードフィールドを編集または削除します。
      • 編集可能―先行入力の検索結果が一致しない場合のオプションとして、エンドユーザーがフィールドに自由にテキストを入力できるようにします。
    • メール―エンドユーザーのメールアドレスを入力するためのテキストボックスを表示します。プレースホルダフィールドには、エンドユーザーに表示するのに役立つヒントをテキストボックス内に入力します。
    • 日付と時間―エンドユーザーの日付と時間を入力するためのテキストボックスを表示します。フォーマットフィールドに、エンドユーザーに表示される日付の文字枠に、予想の日付や時間のフォーマットを入力してください。日付フォーマットの選択ドロップダウンリストで、 時間付きの日付のフォーマットを選択してください。
    • タイムゾーン―操作システムの設定に基づくタイムゾーンのドロップダウンリストを表示します。
    • 位置―エンドユーザーが地理的位置を入力するための文字枠を表示します。例えば、Orlando, FLまたは32801
    • 入れ子フォーム – 親入力フィールドの下に、エンドユーザーの入力フィールドを入れ子形式で表示します。入力フィールドのネスト化済のフォームに以下のフィールドを指定してください:
      • 配列要素型 – 親の入力形式要素のデータ型を選択します。
      • 入れ子フォーム フィールドの追加 – 1 つ以上の入れ子のフォーム フィールドをクリックして追加します。
    • ファイル アップロード – アップロードするファイルの検索や選択ができるエンドユーザー コントロールを表示します。クリックして、[ファイル アップロード ペイロード キー] を入力します。ファイルアップロードペイロードキーが定義済の場合、ファイルアップロードペイロードフィールド値のドロップダウンリストで以下のうちの一つを選択してください:
      • ファイル名
      • ファイルサイズ
      • ファイルコンテンツタイプ
    データタイプ ユーザー入力タイプのうちの 1 つを選択します。

    • 文字列 – ユーザーは任意の一連の数字、文字や特殊文字を入力することができます。
    • 数字 – ユーザーは数字を入力することができます。特殊文字は使用できません。
    • ブール値 – ユーザーは true または false のブール値を入力できます。
    • メール – ユーザーは有効なメール アドレスを入力できます。
    • オブジェクト – データは、JSON オブジェクトとしてボットから受信できます。  “location” : { “lat” : 17.4374614, “lng” : 78.4482878 }ここでは、リクエストチェインやタスクリクエストのプロパティをlocation.latlocation.lngとして参照することができます。
    • 配列 – ユーザーは、カンマで区切った値のリストをボットに渡すことができます。例えば、グーグルカレンダーでは、複数の参加者のデータのパスは: “attendees”: [“user1”, “user2”, “user3”] 選択した場合、エンドユーザーの入力の配列のタイプを以下のいずれかに指定します。
  • 文字列
  • 数字
  • ブール値
  • メール
  • 配列
  • 日付
  • 日付―ユーザーは完全な日付を入力するか、日付の選択肢から選択することができます。

Is Multi Select ユーザーは 1 つ以上の選択や入力が可能になります。このフィールドは選択されたフィールドタイプに従って表示されます。

  • [詳細設定] タブをクリックして、タスク フィールドの追加のオプション設定を定義します。
    フィールド名 説明
    可視性 タスク入力フィールドをエンドユーザーから見えるようにするあるいは隠すかどうかを指定します。可視性フィールドはカスタム設定することもできます。ここでは、データはユーザーから取得されますが、クエリパラメータやペイロードフィールドとしては使用されません。例えば、JIRA Botの場合、以下のように@mentionタグを使用してチケットにコメントを投稿します。「@Mike、こちらの問題について調べてください」 JIRA APIで「コメントを投稿する」には1つのクエリフィールドおよび1つのペイロードフィールドが必須です:

    • IDの発行
    • コメント

    可視性フィールドをカスタムに設定すると、JIRA APIを使用して@Mikeと呼ばれるユーザーのユーザー情報をキャプチャし、データを取得してcommentフィールドの値に追加することができますが、ペイロードフィールドやクエリフィールドとしては使用できません。可視性フィールドのデフォルト設定は表示です。

    必須 エンドユーザーがこの設定を定義してタスクの設定を保存する必要があるかどうかを選択します。
    キーの置き換え Kore.ai によるキーの転置を無効にするかどうかを選択します。デフォルトでは、Kore.ai はキーと値のペアを転置します。例えば、”parameter”:”value” は Kore.ai によって “parameter:{value:”actualValue”} に転置されます。選択すると、キーは置換されません。
    セッションから取得 選択すると、このフィールドのユーザー入力値をセッション変数として格納します。選択すると、[セッションからのフィールド値] のフィールドを表示します。既存の変数や [新規のセッション変数を追加] を選択して新規の変数を定義します。新規のセッション変数を作成するには、変数のスコープを選択し、変数を格納するキーを定義する必要があります。[スコープ] フィールドでは、次のうちの 1 つを選択します。

    • EnterpriseContext – 企業全体のユーザーに使用できるキー/値ペアを定義します。
    • BotContext – このボットの全ユーザーに使用できるキー/値ペアを定義します。
    • UserSession – 企業内のすべてのボットに対して、このユーザーが使用できるキー/値のペアを定義します。
    • BotUserSession – ユーザーの入力に基づいて、ボットが使用できるキー/値のペアを定義します。
  • タスク要求のパラメータを保存して別のパラメータを追加する場合は、追加して続行を、タスク要求のパラメータを保存してダイアログを閉じる場合は、追加して終了をクリックします。複数のパラメータを、ボットユーザーが入力を提供する順番で整理する必要があります。アイコンを使用してパラメータを移動します。 Action Task - API Request Tab - Parameters Section - Sort

初期化子の定義

タスクを実行するには、セッションの値をputやgetしてから、Kore.ai セッション固有の変数でタスクを実行とする場合があります。  詳細については、タスクのセッション変数とコンテキスト変数を使用を参照してください。あるウェブサービスはAPIリクエスト実行の前に、実行済のコード、セッション変数、またはユーザーのコンテキスト詳細の調整が必要です。例えば、ウェブサービスは、最初のステップとしてユーザーログインを行い、次にパートナー認証を行う、2段階のユーザー認証を必要とする場合があります。これらの両方のステップを検証してから、アクセストークンが付与され、そのウェブサービスへの後続のAPIコールのヘッダーで使用されます。イニシャライザーを使用すれば、パートナー認証の完成、そしてユーザーの認証への応答からのアクセストークンの取り戻すことができます。アクセストークンはカスタムセッション変数、そして後続のAPIコールのヘッダーとしての貯蔵が可能です。

タスク初期化子を定義する

タスクの初期化子を設定する場合、初期化子タブをクリックしてください。必須のコードを書き込むためのJavaScript編集器を開きます。Action Task - API Request Tab - Initializer Section JavaScriptエディターで、以下のようにキースコープを定義します。

  • EnterpriseContext – 企業の全ボットおよび全ユーザーが使用可能なキー/値ペアです。たとえば GitHub ボットでは、ユーザーが単一または複数の企業のリポジトリにアクセスする必要があります。初期化子では、以下のJavaScriptコードでリポジトリデータをGitrepository(エンタープライズコンテキスト)として保持することができます:
    var userRepository = { "title": _labels_[repository], "value": repository }; EnterpriseContext.put('Gitrepository', userRepository, 200000);
  • BotContext – 当該ボットの全ユーザーが取得可能なキー/値のペアです。例えば、 ​ユーザーの場所に基づいて、セッション内の金融取引のデフォルト通貨を設定したい場合があります初期化子では、以下のJavaScriptコードでデフォルトの通過データをcurrency(Botコンテキスト)として保持することができます:
    var defaultCurrency = { TODO Custom JavaScript for location-based currency } BotContext.put('currency', defaultCurrency, 200000);
  • UserContext – 企業の全ボットおよび全ユーザーが使用可能なキー/値ペアです。これらのキーは読み取り専用で、ユーザー データとしてシステムが提供します。
    • _id – Kore.ai ユーザーの IDです。
    • emailId – ユーザー IDと関連するメール アドレスです。
    • lastName – ユーザーの姓です。
    • firstName – ユーザーの名です。
    • profImage – ユーザーの画像やアバター ファイル名です。
    • profColour – ユーザーアカウントの色です。
    • activationStatus – ユーザーのアカウント ステータスです。
    • title – ユーザーのタイトルです。(定義されている場合)
    • orgId – ユーザー アカウントの組織 ID です。(定義されている場合)
  • UserSession – 企業内のすべてのボットに対して、特定ユーザーが利用できるキー/値のペアを定義します。たとえば、ユーザーの所在地を保存して全ボットで利用できるようにします。その例といえばユーザーの通勤、移動、および宅配便のサービスなどの住所位置です。初期化子では、以下のJavaScriptコードでデフォルト位置データをHomeLocation (UserSession)として保持することができます:
    var location = { "title": labels[location], "value": { "latitude": location.latitude, "longitude": request.location.longitude } }; UserSession.put('HomeLocation', location, '20000');
  • BotUserSession―ユーザーの入力に基づいてBotが利用できるキー/値のペアを定義します。例えば、 1つ以上のBotタスクのユーザー位置を保持したい場合があります。旅行ボットの場合、ユーザーは、同じホームと目的地の住所に基づいて航空便とホテルを予約することができます。初期化子では、以下のJavaScriptコードでデフォルトのホームおよび行先データをHomeLocation (BotUserSession)DestinationLocation (BotUserSession)として保持することができます:
    var homelocation = { "title": labels[request.sourceLocation], "value": { "latitude": request.sourceLocation.latitude, "longitude": request.sourceLocation.longitude } }; BotUserSession.put('HomeLocation', homelocation, '20000'); var destlocation = { "title": labels[request.destLocation], "value": { "latitude": request.destLocation.latitude, "longitude": request.destLocation.longitude } }; BotUserSession.put('DestinationLocation', destlocation, '20000’);

GET および PUT 構文

以下のコードの例とは各コンテキストタイプのキー値ペアをGETやPUTのシンタックスを表示します。

"EnterpriseContext" : { "get" : function(key){...},//get the specified key "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes }, "BotContext" : { "get" : function(key){...},//get the specified key "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes }, "UserContext" : { "get" : function(key){...},//get the specified key }, "UserSession" : { "get" : function(key){...},//get the specified key "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes }, "BotUserSession" : { "get" : function(key){...},//get the specified key "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes }

例えば:

BotContext.put("topicSessionVariable","music",2000);     UserSession.put("firstName","Mary",20000);     UserContext.get("firstName");

Exception Syntax

また、タスクを設定する前に、認証失敗などのエラーを捕捉するためのカスタムエラーメッセージを定義することもできます。例外を捕捉した場合、タスクの設置は中止します。以下のシンタックスを使用して例外を外せます:

{ "exceptions": { "message": " Error Message" } }

例えば、

var ex ={}; var exceptions={}; exceptions.message ='You can not proceed further with out valid permissions'; ex.exceptions = exceptions; print(JSON.stringify(ex)); //print is mandatory.

初期化子セクションでは、セッションキーまたはその他のセッション変数を使用することができますが、値を設定したりアクセスしたりすることはできません。例えば、

var name = UserContext.get("firstName")+UserContext.get("lastName"); UserSession.put("fullName") = name;

先行コードの例では、タスクの詳細設定セクションのセッションから取得フィールドで定義されたタスクのパラメータを使用して、値をセッションに入力します。キーは、カスタム定義されたUserSessionコンテキスト変数のfullNameとして定義されます。

タスク初期化子の例

以下のコードは、タスクの初期化子でAPIリクエストに変数を先行発生するユーザーIDおよびメールのデータを取得する例です。

var x = UserContext.get("identities"); var isEmailFound = false; for (var i = 0; i < x.length; i++) { if (x[i].type === "mapped") { var identity = x[i].val var arr = identity.split("/"); var pattern = /^cs/i; var result = arr[0].match(pattern); if (result) { isEmailFound = true; UserSession.put("rtmEmail", arr[1], '20000'); } } } if (!isEmailFound) { for (var j = 0; j < x.length; j++) { if (x[j].type === "email") { UserSession.put("rtmEmail", x[j].val, '20000'); } } }

リクエストチェーンの定義

APIリクエストタブのリクエストセクションでは、プリプロセッサー、APIリクエスト、およびポストプロセッサーが含めるAPI リクエストチェーンの定義ができます。少なくとも一つのAPIリクエストが必須です。そしてプロセッサーは任意です。

APIリクエスト

あらゆるタスクにも、APIリクエストを定義してからウェブサービスへのコールでタスクを起始することができます。少なくとも各タスクに1点のAPIリクエストが必須です。各APIリクエストには、必ず単一や複数のリクエストURLsとパースをタスクに追加してからウェブサービスからのデータペイロード転送が始まります。

APIリクエストの設定
  1. APIリクエストタブで、リクエストタブを展開し、APIを追加をクリックします。
  2. 以下の処理の説明の通りに、APIの追加ダイアログでフィールドの値を指定します。
  3. 名前フィールドに、自分のAPIリクエストのように、APIリクエストの名前を入力します。
  4. [メソッド] ドロップダウン リストから、タスクに使用する HTTP メソッドを選択します。以下のうちの一つ:
    • POST―顧客情報やファイルのアップロード、HTMLフォームの使用など、サーバーにデータを送信するために使用します。
    • PUT ―対象となるリソースのコンテンツを、送信されたコンテンツに置き換えます。
    • PATCH―対象となるリソースのコンテンツを、送信されたコンテンツに置き換えます。
    • DELETE―既存のターゲットリソースのコンテンツを削除します。
    • GET―既存のターゲットリソースのコンテンツを削除します。
  5. URLフィールドには、Botタスクがプロセスに応答するためのURLを指定します。例:http://koremessenger.com/postURL下記の例のようにセッション変数URLを使用することもできます:
    https://mySite.crm.ondemand.com/sap/c4c/odata/v1/c4codata/ServiceRequestCollection?$filter=ID eq '{id}' and ReporterEmail eq '{userEmail}'&amp;$expand=ServiceRequestHistoricalVersion,ServiceRequestDescription
  6. コネクタを使用してアクセスのフィールドで、はいを選択してKore.ai Connectorエージェントを使用してKore.ai Botへのアクセスを有効にします。このオプションは、Kore.ai コネクタ エージェントが企業の社内ネットワークで構成、有効化されている場合に表示されます。詳細については、Kore.ai Connectorの使用をご覧ください。
  7. ヘッダータブのコンテンツタイプフィールドで、サンプル応答データに以下のサポートされているデータタイプのいずれかを選択します。
    • JSON – JavaScript Object Notation は、人間が判読できるテキストでデータ オブジェクトを属性と値のペアで送信する、オープンな標準フォーマットです。JSON を使って、Kore.ai サーバーとボット Web アプリケーションの間でデータを伝送することができます。
    • RSS―Rich Site SummaryやReally Simple Syndicationは、ブログのエントリー、ニュースの見出し、音声、動画など、頻繁に更新される情報を公開するために使用される標準化フォーマットの一群です。
    • XML―拡張可能なマークアップ言語とは、人間が読める形式と機械が読める形式の両方でドキュメントをエンコードするためのルールを定義したマークアップ言語です。Web サービスが XML データを処理するのに、XML スキーマがよく使用されます。
    • URL エンコードされた JSON – 予約文字のために JSON のエンコードを使った URL です。
    • CSV – カンマ区切りの値のリストです。
    • 文字―テキストベースのキー値ペア。
    • Twitter エンコードされた JSON – 予約文字のために JSON のエンコードを使った Twitter の URL です。
    • Multipart/Form-data – ユーザーがフォームからファイルをアップロードできるようにする場合に、HTTP POST リクエスト メソッドでファイル送信を可能にするエンコード タイプです
    • Multipart/Related – 同じ情報を、他のフォームの他のボディ パーツで表示する場合に使用します。ボディ パーツは複雑度の高い順に並べられています。
    • Oracle ADF – Oracle Application Development Framework に使用します。
  8. [認証ヘッダー] セクションで、次の図に示すようにヘッダーのキーを有効化または無効化します。 Action Task - API Request Tab - Request Section - Add API Dialog - Auth Headers
  9. パラメータタブで、下図のように認証パラメータまたはヘッダーに含めるパラメータを選択または削除します。 Action Task - API Request Tab - Request Section - Add API Dialog - Params
  10. 保存をクリックしてAPIリクエストの設定を保存して閉めます。
プロセッサー

プロセッサーでJavaScriptを使用してWebサービスへのAPIリクエストの前、途中、または後で、ユーザーセッションで収集されたデータの操作することができます。プロセッサーをAPIリクエストの前に定義し置ける場合、それはプリプロセッサーになります。プリプロセッサーはAPIリクエストの実行の前にセッションの変数から入力のパラメータと値の管理を可能にします。そのプロセッサーはAPIリクエストの後に順次配置とされた場合、ポストプロセッサーとなります。ポストプロセッサーを使用して、 APIリクエストからペイロード応答キーにアクセスできます。キーをアクセスするには、以下のうちの一つのポストプロセッサータイプを使用してください:

  • 解決: キーにアクセスするには、次のうちの 1 つのポストプロセッサ タイプを使用します。解決:
  • 展開 – ペイロードにあるデータ文字列を分けます。
  • 抽出 – 複数のオブジェクトがあるペイロードの特定オブジェクトへのパスを指定します。
  • 割り当て – ペイロード応答の変数名を指定します。
プリプロセッサ

プリプロセッサを使用すると、セッションの変数およびパラメーターで API リクエストの実行前にリクエスト パラメーターの管理ができます。プリプロセッサーを定義する場合、, 必ずプロセスのタイプカスタムに設置し、次に表示するJavaScriptエディターでコードを入力します。プリプロセッサーは、カスタムタイプのみとなります。

プリプロセッサーの追加
  1. APIリクエストページで、リクエストタブを展開し、プロセッサーを追加をクリックします。
  2. 名前フィールドにプロセッサーの名前を入力します。
  3. プロセッサーのタイプドロップダウンリストで、プリプロセッサーにカスタムを選択する必要があります。
  4. 必要に応じて、以下の構文でリクエストパラメータを操作するコードを追加します。
    { "fields": { "payloadFields": { // to set value to a payload field "key1": "value1", // Payload fields are not applicable for Alert tasks. "key2": "value2".... }, "headerFields": { // to set value to a header field "key1": "value1", "key2": "value2".... }, "pathFields": { // to set value to a path field or query field. "key1": "value1", "key2": "value2".... } } }

    例えば、以下のコードスニペットはパースフィールド、またはAPIオブジェクトのクエリーフィールドの設置に使用することが可能です:

    var fields= {}; var pathFields = {}; pathFields.fullName = UserContext.get("firstName")+UserContext.get("lastName") fields.pathFields = pathFields; var finalObject = {}; finalObject.fields = fields; print(JSON.stringify(finalObject));

    当該コードに、firstNameおよびlastNameがセッション変数として保存されていてJohnおよびSmithがそれぞれに対応している場合、プリプロセッサからの JSON ペイロード応答は次のようになります。

    { fields: { "pathFields": { "key": "fullName", "value": "John Smith" } } }

    下記のキー値ペアーの例では、実のAPIリクエストコールの先に変数はセッション変数に設定されます。

    var fields = {}; var pathFields = {}; var UserEmailID = UserSession.get("rtmEmail"); pathFields.userEmail = UserEmailID; fields.pathFields = pathFields; var finalObject = {}; finalObject.fields = fields; print(JSON.stringify(finalObject));
  5. [保存] をクリックして、プロセッサーを追加ダイアログを保存して閉じます。
APIリクエストの前にリクエストセクションにプロセッサーが配置されている場合、そのプロセッサーはプリプロセッサーとみなされます。API リクエストの後ろにプロセッサーが置いた場合、そのプロセッサーはポストプロセッサーとして思われます。
ポストプロセッサーの追加

ご使用のウェブサービスから1点以上のAPIリクエストで、Kore.ai ポストプロセッサーによりお望みのデータペイロードを取得する場合があります。

カスタムポストプロセッサーの定義

もしカスタムポストプロセッサーを作成とする場合、以下のシンタックスで前のAPIリクエストの応答キーをアクセスできます。

payload[0].{ key }

JSON Syntax
{ "payload": { "key1" : "value1", "key2" : "value2" } }
var final = {}; var data = payload[0]; //Accessing the response of the previous API object data.title[0] = 'New value for key here'; final.payload = data; // Updating the response of the API object print(JSON.stringify(final)); // This step is mandatory

カスタムプロセッサーの場合、必ず最後の応答を示した先行コードのとして印刷出してください、そうでなければ、空の応答が返します。以下のシンタックスを使用します:

print(JSON.stringify( <<object>> ));

標準なポストプロセッサーの設定

以下のステップに従って標準のポストプロセッサーを追加してください:

  1. APIリクエストタブで、リクエストタブを展開し、プロセッサーを追加をクリックします。
  2. Kore.aiは、ポストプロセッサー用のカスタムコードを作成する代わりに使用できる標準ポストプロセッサーのセットを提供します。プロセスのタイプフィールドに、以下の4つの標準プロセッサーのタイプのうちの一つを選択します:
    1. 解決:1つのペイロード応答の結果を、2つ目のリクエストの入力として使用することができます。例えば、プロセッサーを追加をクリックして、プロセッサーの名前を入力し、プロセッサーのタイプ解決に、キーを変数の名前に設定し、最初のAPIリクエストからの変数を使用して投稿URLを定義します。 For example, https://app.asana.com/api/1.0/projects/{project_id} that returns the id field in the payload response as:
      ... "id":80468818418144, <br/> "created_at":"2016-01-14T05:34:35.848Z", "modified_at":"2016-01-20T04:29:52.505Z", "owner":{ "id":73114591129714, "name":"jaganmohan.evuri" }, ...

      それは次に変数入力として下記のPost URLのように: https://app.asana.com/api/1.0/projects/{id}/tasks?opt_fields=completed,modified_at You must also specify the HTML Content Type expected in the payload response as well as the HTML Request method. 詳細については、タスクのセッション変数とコンテキスト変数を使用を参照してください。

    2. 展開:分けとするデータが含む文字列のペイロードの場合。例えば、プロセッサーを追加をクリックし、プロセッサーの名前を入力し、キーフィールドをデータなどに設定し、プロセッサータイプ展開に設定して、以下のコード例でdata要素の内容を取り込み、配列の各項目を抽出します。
      { "attribution": null, "tags": [], "type": "image", "location": null, "comments": { "count": 51, "data": [{ "created_time": "1453900980", "text": "43rd", "from": { "username": "kore_hyd", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg", "id": "2056218675", "full_name": "Kore.ai Hyd" }, "id": "1171728804843572377" }, { "created_time": "1453901222", "text": "44th", "from": { "username": "kore_hyd", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg", "id": "2056218675", "full_name": "Kore.ai Hyd" }, "id": "1171730841379491107" }, { "created_time": "1453901997", "text": "45th", "from": { "username": "kore_hyd", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg", "id": "2056218675", "full_name": "Kore.ai Hyd" }, "id": "1171737339782450909" }, { "created_time": "1453902304", "text": "46th and 47th", "from": { "username": "kore_hyd", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg", "id": "2056218675", "full_name": "Kore.ai Hyd" }, "id": "1171739915923967873" }, { "created_time": "1453902638", "text": "48th", "from": { "username": "kore_hyd", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg", "id": "2056218675", "full_name": "Kore.ai Hyd" }, "id": "1171742713994497101" }, { "created_time": "1453964684", "text": "49th", "from": { "username": "venkataphani.ailavarapu", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg", "id": "2679234818", "full_name": "Phani" }, "id": "1172263199715314941" }, { "created_time": "1453964710", "text": "50th", "from": { "username": "kore_hyd", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg", "id": "2056218675", "full_name": "Kore.ai Hyd" }, "id": "1172263415747136776" }, { "created_time": "1453964717", "text": "51st", "from": { "username": "kore_hyd", "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg", "id": "2056218675", "full_name": "Kore.ai Hyd" }, "id": "1172263474056350986" }] ...
    3. 抽出:複数オブジェクトが含むペイロードの場合、 s, 特定のオブジェクトにパースを指定することができます。例えば、プロセッサーを追加をクリックし、プロセッサーの名前を入力し、キーフィールドをdataに設定し、抽出するプロセスのタイプを選択して、次のペイロード応答でオブジェクトデータを使用します。
      { "user": { "full_name": "Kore.ai Hyd", "id": "2056218675", "profile_picture": "https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg", "username": "kore_hyd" }, ... }, "likes": { "data": [{ "full_name": "kstream002", "id": "2100724876", "profile_picture": "https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg", "username": "kstream002" } }, ... }
    4. 割り当て:  割り当てプロセッサーを使用すれば、ペイロードの応答への変数名の指定が出来ます、もし必要な場合、例えば、ペイロードにペイロード応答データのキーが含まれていない場合。例えば、プロセスのタイプを割り当てに設置し、次に 出力変数フィールドに、3つのオブジェクトの文字列である次のペイロードの出力変数を定義することができます。
      [ { "Cost": "$0.00", "Desc1": "$150 bonus after $500 of purchases in the first 3 months from account opening. ", "Desc2": "Earn unlimited cash back Earn unlimited 1.5% cash back on every purchase – it's automatic. Redeem for cash back – any amount, any time. ", "Keywords": "weekend dining,online,groceries,fuel,rewards,rebate,365,allaround", "OfferName": "Freedom Unlimited", "OfferType": "CreditCard", "Status": "1", "imageURL": "http://www.psdgraphics.com/file/credit-card.jpg", "id": "5b5195e264bbd800" }, { "Cost": "$95.00", "Desc1": "Pay 0 balance transfer fee when you transfer a balance during the first 60 days.", "Desc2": "Jumpstart your financial fitness Get an introductory fee for balance transfers, save on interest†, and get your free monthly credit score.", "Keywords": "privileges,rebate,health,wellness,great eastern,insurance,policy,installments,split,cashflo", "OfferName": "Premium Plus", "OfferType": "CreditCard", "Status": "1", "imageURL": "http://i.imgur.com/rMOXYql.jpg", "id": "5caf2155873f89c8" }, { "Cost": "$10.00", "Desc1": "Pay 0 balance transfer fee when you transfer a balance during the first 60 days.", "Desc2": "Jumpstart your financial fitness Get an introductory fee for balance transfers, save on interest†, and get your free monthly credit score.", "Keywords": "privileges,rebate,health,wellness,great eastern,insurance,policy,installments,split,cashflo", "OfferName": "Frequent Flyer", "OfferType": "CreditCard", "Status": "1", "imageURL": "http://www.moneychoice.org/wp-content/uploads/2016/01/credit-card-calculator-image.png.jpeg", "id": "c0b05bc3062658ee" } ]

      出力変数フィールドで、配列を表す変数をとして指定します。offers, 例えば、もしUXプレビュー機能を使用した場合、Kore.ai からの応答は以下の通りです。

      { "response": { "offers": [ { "Cost": "$0.00", "Desc1": "$150 bonus after $500 of purchases in the first 3 months from account opening.", "Desc2": "Earn unlimited cash back Earn unlimited 1.5% cash back on every purchase – it's automatic.Redeem for cash back – any amount, any time.", "Keywords": "weekend dining,online,groceries,fuel,rewards,rebate,365,allaround", "OfferName": "Freedom Unlimited", "OfferType": "CreditCard", "Status": "1", "imageURL": "http://www.psdgraphics.com/file/credit-card.jpg", "id": "5b5195e264bbd800" }, { "Cost": "$95.00", "Desc1": "Pay 0 balance transfer fee when you transfer a balance during the first 60 days.", "Desc2": "Jumpstart your financial fitness Get an introductory fee for balance transfers, save on interest†, and get your free monthly credit score.", "Keywords": "privileges,rebate,health,wellness,great eastern,insurance,policy,installments,split,cashflo", "OfferName": "Premium Plus", "OfferType": "CreditCard", "Status": "1", "imageURL": "http://vignette3.wikia.nocookie.net/objectmayhem/images/5/52/Credit_card.png/revision/latest?cb=20130629150408", "id": "5caf2155873f89c8" } ] } }

      出力変数offersに設定すると、Botビルダーで変数をresponse.offersとして、例えば以下のようにタスク応答オブジェクトで使用することができます。

      print(JSON.stringify(response)); var data = response.offers for (i = 0; i < data.length; i++) { print('<a href="' + data[i].imageURL + '" target="_blank">' + data[i].OfferName + '</a><br>'); print(data[i].Desc1) print('<br>'); print('<br>'); print('Cost: ' + data[i].Cost) print('<br>'); if (i < data.length - 1) { print('<br>'); print('<br>'); } }
  3. 追加をクリックしてAPIリクエストを保存してから別のAPIリクエストを作成するか、追加と終了をクリックしてAPIリクエストを保存してからダイアログをクローズ閉じます。

複数のAPIリクエストの場合、リクエストをシーケンシャルの並べで並べ直してから全体のデータ応答を取得するようにしてください。例えば、ワークスペースのリスト、プロジェクトのリスト、そして最後にユーザーのリストを要求する場合があります上に移動アイコンと下に移動アイコンを使用して、APIリクエストの順番を入れ替えることができます。

注意: APIリクエストを削除した場合、確認ダイアログは表示されません。続行または保存をクリックすると、削除操作は永続的に行われ、元に戻すことはできません。

応答サンプルの追加

応答サンプルセクションでは、タスクのペイロードで受け取ることが期待されるキーと値のペアの例を入力または貼り付けることができます。応答サンプルを定義する場合、出力データの処理に応答サンプルセクションで指定されたキーはドロップダウン選択肢として使用可能です。

サンプル応答の追加

  1. [API リクエスト] タブで、[サンプル応答] セクションを展開します。
  2. JSON応答のペイロードのキーと値の組み合わせを含む応答サンプルを入力してください。以下のうちの一つをしてください:
    • 応答の様式をシリアルナンバーが付けられたコンパクトな形式で書式設定するには、下図の通りに書式設定済みアイコンをクリックします。
    • 応答の様式を字下げ可能のJSON構造として書式設定するには、下図の通りに書式未設定アイコンをクリックします。

ウェブサイトのリンクコンテンツをプレビュー

あるウェブサービスはリンクを送りてペイロード応答の一部としてメディアをプレビューさせます。このセクションでは、プレビューリンクの有効や無効、そしてペイロードでパースからリンクの定義ができます。デフォルトでは、ウェブサイトプレビューリンクが無効されました。下図は、はいを選択した場合の投稿でウェブサイトのリンクコンテンツをプレビューセクションの例です。API Request Tab - Preview Section 有効にした場合、ペイロード内のプレビューリンクへのパスがペイロードのルートにない場合、リンクへのパス(toPreview)フィールドで定義します。例えば、下記のコードの例はRSSペイロード、パースからプレビューへとは

... "item": [ { "title": "U.S. to Boost Refugee Intake by 30,000 by 2017", "guid": { "-isPermaLink": "false", "#text": "SB12418904751422433479504581245034032986752" }, "link": "http://www.wsj.com/articles/john-kerry-says-u-s-to-admit-30-000-more-refugees-in-next-2-years-1442768498?mod=fox_australian", ...

投稿でウェブサイトのリンクコンテンツをプレビューが有効の場合、プレビューオブジェクトを選択します。たとえば、

  • タイトルのプレビュー – Web サイト コンテンツのタイトルを表示します。
  • 説明のプレビュー – Web サイト コンテンツ説明を表示します。
  • メディア (動画) のプレビュー – Web サイト コンテンツからの動画のリンクを表示できるようにします。
  • メディア (画像) のプレビュー – Web サイト コンテンツからの画像のリンクを表示できるようにします。

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

We have seen how an Alert task can be set up in Kore.ai virtual assistant platform here. In this section, we will see how to configure an API Request for a REST service.

The following illustration is an example of the API Request tab on the Edit Alert – < Task Name > page for an alert task with the Connection Type specified as Webservice and the Connection Mode set to REST defined on the General tab.

For a task with the Connection Type specified as Webservice and the Connection Mode set to REST you need to define:

  • Content Type – The type of data exchanged between Kore.ai and your web application, see below for details.
  • Authentication – If required for your alert task, you will need to define the authentication to access the API, for example, using basic authorization, OAuth, or API Key. Refer here for more details.
  • Parameters – Define one or more parameters used to process the API request, for example, input from user prompts, selection by an end-user from a list of choices, a URL, and so forth, see below for details, see below for details.
  • Initializer – Specify custom JavaScript to run, or set session variables prior to creating a task instance when web services require code to be executed, or session variables set, or modification of user context details before an API request is executed, see below for details.
  • Request – Define a request chain used to make an API call to a web service to initiate the task using URLs and paths to your Bot to initiate the delivery of the data payload from the web service to the Bots Platform. The request chain can consist of pre-processors, API requests, and post-processors, see below for details.
  • Response Sample – Define key/value pairs that you expect to receive in the task payload. The keys that you provide are available as drop-down choices for handling the data to display to the end-user, see below for details.
  • Preview Website Link Content in Post – The website preview content displayed in the task notification message, see below for details.

Click Save to save the API request settings.

Defining the Content Type

The Content Type describes the type of data exchanged between Kore.ai and your Bot website or application, and the key-value pairs expected in the task payload response. To define the Content Type for the API Request (REST), expand the Content Type tab and select one of these options:

  • JSON – JavaScript Object Notation is an open standard format using human-readable text to transmit data objects as attribute-value pairs. You can use JSON to transmit data between the Kore.ai servers and your Bot web application.
  • RSS – Rich Site Summary, or Really Simple Syndication, is a family of standardized formats used to publish frequently updated information such as blog entries, news headlines, audio, and video.
  • XML – Extensible Markup Language is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. Oftentimes, web services use XML schemas to process the XML data.
  • URL Encoded JSON – URLs using JSON encoding for reserved characters.
  • CSV – Comma-separated value lists.
  • Text – Text-based key-value pairs.
  • Twitter Encoded JSON – URLs for Twitter using JSON encoding for reserved characters.
  • Multipart/Form-data – An encoding type that allows files to be sent through an HTTP POST request method if you want to allow a user to upload a file from a form.
  • Multipart/Related – Used when the same information is presented in different body parts in different forms. The body parts are ordered by increasing complexity.
  • Oracle ADF – For Oracle Application Development Framework.

Defining Parameters

Follow these steps to define the API Request (REST) parameters:

  1. Click the Parameters section, and then click Add.  The Set Up Task Parameter dialog opens.
  2. Depending on your selection, enter the values for the relevant fields as described in the following table.
    Field Name Description
    Type of Task Parameter Specify one of the following:

    • Payload Parameter – Use this field type to represent payload data for an HTTP method, such as POST, PUT, GET, DELETE, and so forth. For example:
      {
         "taskId":"{payloadfield2}",
         "message":"{payloadfield1}"
      }
    • Query Parameter – This field type is used as part of a URL path or query within a URL. For example:
      http://app.asana.com/api/workspaces/{queryfield1}/project/{queryfield2}?userId={queryfield3}
    Parameter Name The title of the task input field displayed to the user, for example, Choose account
    Prompt Message The help description displayed below the parameter name, for example, Which account would you like to access?
    Parameter Key The task key that represents the end-user input value that you want to collect, for example, accountType.
    Parameter Type Specifies the type of task input field displayed in the end-user interface to collect user input for the request object to assign to the Key value. The default setting is Textbox, but can be customized to any one of the following:

    • Date – Displays the Format field where you can select the date format syntax for the end-user to define when the task is configured for their account. In the Select Date Format drop-down list, select one of the following:
      • dd-MM-YYYY – For example, 16-05-1999
      • MM-dd-YYYY – For example, 05-16-1999
      • dd-MM-YY – For example, 16-05-99
      • YYYY-MM-dd – For example, 1999-05-16
    • URL – Displays a text box for the end-user to enter a URL including field validation for correct URL syntax. In the Placeholder field, enter the help hint displayed in the text box, for example, Enter the URL for the website here.
    • Textbox – Displays a text box for the end-user to enter the text as the task input field, typically just a few words. In the Placeholder field, enter the help hint displayed in the text field, for example, Type in the name you want to embroider.
    • Static Dropdown – Displays a drop-down list of choices to the end-user. Click Add Option to begin adding the list of items to display to the end-user with the following parameters:
      • Option Name – The name of the option displayed to the end-user.
      • Option Value – The value the represents the Option Name returned to the application.
      • Default Value – Select the default value for the option when more than one option is defined.
      • Searchable – Select to enable dynamic search and display as the end-user enters text in this field, or if no matches, allow free-form entry.

      Click Save. To add additional items, click Add Option again. Edit or remove options in the Actions column for options.

    • Dynamic Dropdown – Displays a drop-down list dynamically populated at runtime based on the response from a URL for your Bot, for example, a list of projects for a JIRA task notification. Define the following properties for a dynamically populated dropdown.
      • Endpoint URL – The Bot endpoint URL, for example, https://app.asana.com/api/1.0/workspaces.
      • Endpoint Content Type – The content type expected from the specified endpoint URL. One of: JSON, RSS, XML, URL Encoded JSON, CCV, Text, or Twitter Encoded JSON.
      • Endpoint Method – One of:
        • GET – Specifies an HTTP Request GET method for the task field.
        • POST – Specifies an HTTP Request POST method for the task field.
      • Response Path – The path in the response that contains the desired drop-down list values, for example, data.
      • Label Key – The key for the label of the drop-down option, for example, name.
      • Option Value Key – The key for the value of the drop-down option, for example, id.
      • Add Payload Field – Click to add one or more fields from the response payload as options for the dynamic dropdown. For each payload field, enter the Payload field key and the Payload field value, and then click Save. Edit or delete payload fields in the Actions column.
      • Searchable – Select to enable dynamic search and display as the end-user enters text in this field, or if no matches, allow free-form entry.
    • Textarea – Displays a text area box for the end-user to enter the text as the task input, typically for several sentences. In the Placeholder field, enter the help hint displayed inside the text area.
    • Type Ahead – Displays a dynamically populated drop-down list of choices to the end-user at runtime when the user enters three or more characters that match the search results based on the response from the URL defined for the task. For example, a list of projects for a JIRA task notification message. Define the following properties for a dynamically populated drop-down.
      • Endpoint URL – The Bot endpoint URL, for example, https://app.asana.com/api/1.0/workspaces.
      • Endpoint Content Type – The content type expected from the specified endpoint URL. One of: JSON, RSS, XML, URL Encoded JSON, CCV, Text, Twitter Encoded JSON, Multipart/Form-data, or Multipart/Related.
      • Endpoint Method – One of:
        • GET – Specifies an HTTP Request GET method for the task field.
        • POST – Specifies an HTTP Request POST method for the task field.
      • Response Path – The path in the response that contains the desired drop-down list values, for example, data.
      • Label Key – The key for the label of the drop-down option, for example, name.
      • Option Value Key – The key for the value of the drop-down option, for example, id.
      • Add Payload Field – Click to add one or more fields from the response payload as options for the type ahead field. For each type ahead field option, enter the Payload field key and the Payload field value, and then click Save. Edit or delete payload fields in the Actions column.
      • Editable – Enables the end-user to enter text free-from in the field as an option when type-ahead search results do not match.
    • Email – Displays a text box for the end-user to input an email address. In the Placeholder field, enter the helpful hint to display to the end-user inside the text box.
    • Date & Time – Displays a text box for the end-user to input a date with time. In the Format field, enter the expected date or time format to display to the end-user in the date text box. In the Select Date Format drop-down list, select the date with time format.
    • Time Zone – Displays a drop-down list of time zones based on the operating system settings.
    • Location – Displays a text box for the end-user to enter a geographical location, for example, Orlando, FL, or 32801.
    • Nested Form – Displays end-user input fields in a nested format below the parent input field. Specify the following fields for a nested form input field:
      • Array Element Type – Select the data type of the parent input form element.
      • Add Nested Form Field – Click to add one or more nested form fields.
    • File Upload – Displays end-user control to search for, and select a file to upload. When clicked, enter the File Upload Payload Key. When the File Upload Payload Key is defined, in the File Upload Payload Field Value drop-down list, select one of the following types:
      • File Name
      • File Size
      • File Content Type
    Data Type Select one of these user input types:

    • String – Users can input any sequence of numbers, letters, or special characters.
    • Number – Users can input a number. No special characters are allowed.
    • Boolean – User can input a Boolean value of true or false.
    • Email – User can input a valid email address.
    • Object – Data from a Bot can be received as JSON objects, for example, as location details defined as:
       “location” : {
                     “lat” : 17.4374614,
                     “lng” : 78.4482878
                  }
      where you can refer to the properties in a request chain or task request as location.lat, and location.lng.
    • Array – Users can pass a comma-separated list of values to the Bot. For example, in Google Calendar, multiple attendees with data can be passed as:
      “attendees”: [“user1”, “user2”, “user3”]
      When selected, specify the Type for the array of end-user input as one of:
  • String
  • Number
  • Boolean
  • Email
  • Array
  • Date
  • Date – Users can type a complete date or select it from a date picker.

Is Multi SelectAllows the user to make more than one selection or entry. This field is displayed depending on the Field Type selected.

  • Click the Advanced Settings tab to define additional optional settings for the task fields.

    Field Name Description
    Visibility Specify if the task input field should be visible or hidden from the end-user.
    The Visibility field can also be set to Custom where data is captured from the user but not used as a query parameter or payload field. For example, with a JIRA bot, posting a comment on a ticket using an @mention tag as shown below:
    “@Mike, please look into this issue”
    The JIRA API to ‘Post a comment’ requires one query field and one payload field as:

    • Issue ID
    • Comment

    With the Visibility field set to Custom, you can capture the user information for the user mentioned as @Mike using the JIRA API to fetch data to append to the comment field value, but not to use as payload field or query field. The default Visibility field setting is Visible.

    Mandatory Select if the end-user must define this setting to save the task settings configuration.
    Untranspose the Key Select to disable key transposition by Kore.ai. By default, Kore.ai transposes a key/value pair, for example, “parameter”:”value” is transposed by Kore.ai to “parameter:{value:”actualValue”}. When selected, keys are not transposed.
    Fetch from Session Select to store the user input value for this field as a session variable. When selected, the Field Value from Session field is displayed. Select an existing variable, or select Add New Session Variable to define a new variable. To create a new session variable, you must select the Scope of the variable and define the Key to store the variable. In the Scope field, select one of:

    • EnterpriseContext – Define a key/value pair available to all users in an enterprise.
    • BotContext – Define a key/value pair available to all users of this bot.
    • UserSession – Define a key/value pair available for this user for any bots in an enterprise.
    • BotUserSession – Define a key/value pair available a bot based on user inputs.
  • Click Add & Continue to save the parameter for the task request and add another parameter, or click Add & Exit to save the parameter for the task request and close the dialog. You should organize multiple parameters in the order that the bot user should provide inputs. Use the  and  icons to move the parameters.
    Action Task - API Request Tab - Parameters Section - Sort

Defining an Initializer

To run a task, you may need to put or get values from a session before executing the task using Kore.ai session-specific variables.  For more information, see Using Session and Context Variables in Tasks. Some web services require executed code, session variables, or modification of user context details before executing an API request. For example, a web service may require two-factor user authorization where the first step is a user log in, and the second step is a partner authorization. After validating both these steps, an access token is granted and used in the header of subsequent API calls to that web service. Using the Initializer, you can complete partner authorization and retrieve the access token from the response of the user authentication. The access token can be stored as a custom session variable and set as the header for subsequent API calls.

Define Task Initializer

To configure the task initializer, click the Initializer tab. It opens a JavaScript editor in which you can write the required code.
Action Task - API Request Tab - Initializer Section
In the JavaScript editor, define the Key and the Scope as follows:

  • EnterpriseContext – A key-value pair available to all bots and all users in an enterprise. For example, for a GitHub bot, a user needs to access one or more enterprise repositories. In the Initializer, you can persist the repository data as Gitrepository (Enterprise Context) with the following JavaScript code:
    var userRepository = {
    "title": _labels_[repository],
    "value": repository
    };
    EnterpriseContext.put('Gitrepository', userRepository, 200000);
  • BotContext – A key-value pair available to all users of this specific bot. For example, you may want to set up a default currency for financial transactions in a session based on the user location. In the Initializer, you can persist the default currency data as currency (Bot Context) with the following JavaScript code:
    var defaultCurrency = { TODO Custom JavaScript for location-based currency }
    BotContext.put('currency', defaultCurrency, 200000);
  • UserContext – A key-value pair available to all bots for a user. These keys are read-only and provided by the system as user data for:
    • _id – The Kore.ai userId.
    • emailId – The email address associated with the userId.
    • lastName – The last name of the user.
    • firstName – The first name of the user.
    • profImage – The image or avatar filename of the user.
    • profColour – The account color for the user.
    • activationStatus – The account status of the user.
    • title – The title of the user, if defined.
    • orgId – The organizational ID of the user account, if defined.
  • UserSession – Define a key-value pair available for this specific user for all bots in an enterprise. For example, you may want to store a user location to make it available to all bots, such as a user home address for commerce, transportation, and home delivery services. In the Initializer, you can persist the default location data as HomeLocation (UserSession) with the following JavaScript code:
    var location = {
     "title": labels[location],
     "value": {
     "latitude": location.latitude,
     "longitude": request.location.longitude
     }
    };
    UserSession.put('HomeLocation', location, '20000');
  • BotUserSession – Define a key-value pair available to a specific bot based on a specific user’s inputs. For example, you may want to persist in a user location for more than one bot task. For a travel bot, the user may be able to book a flight and a hotel based on the same home and destination addresses. In the Initializer, you can persist the default home and destination data as HomeLocation (BotUserSession) and DestinationLocation (BotUserSession) with the following JavaScript code:
    var homelocation = {
     "title": labels[request.sourceLocation],
     "value": {
     "latitude": request.sourceLocation.latitude,
     "longitude": request.sourceLocation.longitude
     }
    };
    BotUserSession.put('HomeLocation', homelocation, '20000');
    var destlocation = {
     "title": labels[request.destLocation],
     "value": {
     "latitude": request.destLocation.latitude,
     "longitude": request.destLocation.longitude
     }
    };
    BotUserSession.put('DestinationLocation', destlocation, '20000’);

GET and PUT Syntax

The following code examples show the syntax to GET or PUT a key-value pair for each context type.

"EnterpriseContext" : {
       "get" : function(key){...},//get the specified key
       "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes
   },
   "BotContext" : {
       "get" : function(key){...},//get the specified key
       "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes
   },
   "UserContext" : {
       "get" : function(key){...},//get the specified key
   },
   "UserSession" : {
       "get" : function(key){...},//get the specified key
       "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes
   },
   "BotUserSession" : {
       "get" : function(key){...},//get the specified key
       "put" : function(key, value, ttl){...} //put the value at the key for the specified ttl, ttl is in minutes
   }

For example:

    BotContext.put("topicSessionVariable","music",2000);
    UserSession.put("firstName","Mary",20000);
    UserContext.get("firstName");

Exception Syntax

You can also define custom error messages to catch errors before setting up a task, for example, authentication failure. If an exception is captured, the task setup is halted. Use the following syntax to throw the exception:

{
    "exceptions": {
        "message": " Error Message"
    }
}

For example,

var ex ={};
var exceptions={};
exceptions.message ='You can not proceed further with out valid permissions';
ex.exceptions = exceptions;
print(JSON.stringify(ex)); //print is mandatory.

In the Initializer section, you can use session Keys, or other session variables, however, you cannot set or access values. For example,

var name = UserContext.get("firstName")+UserContext.get("lastName");
UserSession.put("fullName") = name;

In the preceding code example, you PUT a value into the session using a task Parameter defined with the Fetch from Session field in the Advanced Settings section for the task. The Key is defined as fullName for the custom defined UserSession context variable.

Task Initializer Example

The following code is an example of a Task Initializer to get the user ID and email data to pre-populate variables in the API request.

var x = UserContext.get("identities");
var isEmailFound = false;
for (var i = 0; i < x.length; i++) {
    if (x[i].type === "mapped") {
        var identity = x[i].val
        var arr = identity.split("/");
        var pattern = /^cs/i;
        var result = arr[0].match(pattern);
        if (result) {
            isEmailFound = true;
            UserSession.put("rtmEmail", arr[1], '20000');
        }
    }
}
if (!isEmailFound) {
    for (var j = 0; j < x.length; j++) {
        if (x[j].type === "email") {
            UserSession.put("rtmEmail", x[j].val, '20000');
        }
    }
}

Defining the Request Chain

In the Request section of the API Request tab, you can define an API request chain consisting of pre-processors, API Requests, and post-processors. At least one API Request is required, while processors are optional.

API Request

For any task, you will need to define an API request to make a call to a web service to initiate the task. At least one API request is required for each task. For each API request, you must add one or more request URLs and paths to your task to initiate the delivery of the data payload from the web service.

Configuring the API Request
  1. On the API Request tab, expand the Request tab, and then click, Add API.
  2. Specify the values for the fields in the Add API dialog as described in the following procedure.
  3. In the Name field, enter the name of your API request, for example, My API Request.
  4. In the Method drop-down list, select the HTTP method used for the task. One of:
    • POST – Used to send data to the server such as customer information, file upload, using HTML forms.
    • PUT – Replaces the content of the target resource with the content sent.
    • PATCH – Appends the content of an existing target resource with the content sent.
    • DELETE – Deletes the content of an existing target resource.
    • GET – Returns the content of an existing target resource.
  5. In the URL field, specify the URL for the bot task response to the process. For example, http://koremessenger.com/postURL. You can also use session variables in the URL as shown in the following example:
    https://mySite.crm.ondemand.com/sap/c4c/odata/v1/c4codata/ServiceRequestCollection?$filter=ID eq '{id}' and ReporterEmail eq '{userEmail}'&amp;$expand=ServiceRequestHistoricalVersion,ServiceRequestDescription
    Note: In some URLs, you may want to use proprietary Kore.ai parameter values for the end and start parameters. For more information about Kore.ai parameter values, see the Bot-specific documentation in Adding Bots.
  6. In the Access Using A Connector field, select Yes to enable access for Kore.ai Bots using the Kore.ai Connector agent. This option is only visible if a Kore.ai Connector agent is configured and enabled in your enterprise on-premises network. For more information, see Using the Kore.ai Connector.
  7. On the Headers tab, in the Content Type field, select one of the following supported data types for your sample response data.
    • JSON – JavaScript Object Notation is an open standard format using human-readable text to transmit data objects as attribute-value pairs. You can use JSON to transmit data between the Kore.ai servers and your Bot web application.
    • RSS – Rich Site Summary, or Really Simple Syndication, is a family of standardized formats used to publish frequently updated information such as blog entries, news headlines, audio, and video.
    • XML – Extensible Markup Language is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. Oftentimes, web services use XML schemas to process the XML data.
    • URL Encoded JSON – URLs using JSON encoding for reserved characters.
    • CSV – Comma-separated value lists.
    • Text – Text-based key-value pairs.
    • Twitter Encoded JSON – URLs for Twitter using JSON encoding for reserved characters.
    • Multipart/Form-data – An encoding type that allows files to be sent through an HTTP POST request method if you want to allow a user to upload a file from a form.
    • Multipart/Related – Used when the same information is presented in different body parts in different forms. The body parts are ordered by increasing complexity.
    • Oracle ADF – For Oracle Application Development Framework.
  8. In the Authorization Headers section, select or clear keys to enable or disable the key for the header as shown in the following illustration.
    Action Task - API Request Tab - Request Section - Add API Dialog - Auth Headers
  9. On the Parameters tab, select or clear any Auth Parameters or Parameters to include in the header as shown in the following illustration.
    Action Task - API Request Tab - Request Section - Add API Dialog - Params
  10. Click Save to save and close the API Request configuration.
Processors

Processors allow you to manipulate data collected in the user session before, during, or after an API request to a web service using JavaScript.
If you define and place a processor before the API Request, it is a pre-processor. Pre-processors allow you to manage input parameters and values from session variables before the API Request is made.
If the processor is sequentially placed after the API Request, it is a post-processor. You can use a post-processor to access payload response keys from the API request. To access keys, use one of the following post-processor types:

  • Resolve: To use the results of one payload response as input for a second request.
  • Spread – To separate arrays of data in a payload.
  • Extract – To specify a path to a specific object in a payload with multiple objects.
  • Assign – To specify a variable name for the payload response.
Pre-processors

You can use a pre-processor to manage request parameters before the API Request is executed, using session variables and parameters. When defining a pre-processor, you must set Type of Process to custom and then enter your code in the JavaScript editor displayed. A pre-processor can only be of Type custom.

Adding a Pre-Processor
  1. On the API Request page, expand the Request tab, and then click Add Processor.
  2. Enter the name of your processor in the Name field.
  3. In the Type of Process drop-down list, you must select Custom for a pre-processor.
  4. Add your code for manipulating the request parameters as needed using the following syntax:
    {
        "fields": {
            "payloadFields": { // to set value to a payload field
                "key1": "value1", // Payload fields are not applicable for Alert tasks.
                "key2": "value2"....
            },
            "headerFields": { // to set value to a header field
                "key1": "value1",
                "key2": "value2"....
            },
            "pathFields": { // to set value to a path field or query field.
                "key1": "value1",
                "key2": "value2"....
            }
        }
    }

    For example, the following code snippet can be used to set the path field or the query field of an API object:

    var fields= {};
    var pathFields = {};
    pathFields.fullName = UserContext.get("firstName")+UserContext.get("lastName")
    fields.pathFields = pathFields;
    var finalObject = {};
    finalObject.fields = fields;
    print(JSON.stringify(finalObject));

    In the previous code, if firstName and lastName are stored as session variables, as John and Smith respectively, then the JSON response payload from the pre-processor would be:

    {
        fields: {
            "pathFields": {
                "key": "fullName",
                "value": "John Smith"
            }
        }
    }

    In the following pre-processor example, variables are set with session variables prior to the actual API request call.

    var fields = {};
    var pathFields = {};
    var UserEmailID = UserSession.get("rtmEmail");
    pathFields.userEmail = UserEmailID;
    fields.pathFields = pathFields;
    var finalObject = {};
    finalObject.fields = fields;
    print(JSON.stringify(finalObject));
  5. Click Save to save and close the Add Processor dialog.
When a processor is placed in the Request section before the API Request, the processor is considered as a pre-processor. When placed after an API Request, the processor is considered a post-processor.
Adding a Post-Processor

You may need more than one API request to get the desired data payload from your web service, using Kore.ai post-processors.

Define a Custom Post-Processor

If you want to create a custom post-processor, you could access the response keys of the previous API Request using the following syntax”

payload[0].{ key }

JSON Syntax
{
 "payload":
   {
    "key1" : "value1",
    "key2" : "value2"
   }
}
Example
var final = {};
var data = payload[0]; //Accessing the response of the previous API object
data.title[0] = 'New value for key here';
final.payload = data;  // Updating the response of the API object
print(JSON.stringify(final));  // This step is mandatory

For custom processors, you must print the final response as shown in the preceding code, otherwise, an empty response is returned. Use the following syntax:

print(JSON.stringify( <<object>> ));

Configure Standard Post Processors

Follow these steps to add a standard post-processor:

  1. On the API Request tab, expand the Request tab, and then click Add Processor.
  2. Kore.ai also provides a set of standard post-processors that you can use instead of creating custom code for a post-processor. In Type of Process field, select one of the following four types of standard processors:
    1. Resolve: You can use the results of one payload response as input for a second request. For example, click Add Processor, enter a Name for your processor, set Type of Process to resolve, and Key to the name of the variable, and then define the Post URL using a variable from the first API Request. For example, https://app.asana.com/api/1.0/projects/{project_id} that returns the id field in the payload response as:
       ...
      "id":80468818418144, <br/>
      "created_at":"2016-01-14T05:34:35.848Z",
      "modified_at":"2016-01-20T04:29:52.505Z",
      "owner":{
      "id":73114591129714,
      "name":"jaganmohan.evuri" },
      ...

      that is then used as a variable input as shown in the following Post URL:
      https://app.asana.com/api/1.0/projects/{id}/tasks?opt_fields=completed,modified_at
      You must also specify the HTML Content Type expected in the payload response as well as the HTML Request method.
      For more information, see Using Session and Context Variables in Tasks.

    2. Spread: For payloads that contain arrays of data that you need to separate. For example, click Add Processor, enter a Name for your processor, set the Key field to, for example, data, and Type of Process to spread to capture the content in the data element in the following code example to extract each item of the array.
       {
           "attribution": null,
           "tags": [],
           "type": "image",
           "location": null,
           "comments": {
               "count": 51,
               "data": [{
                   "created_time": "1453900980",
                   "text": "43rd",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1171728804843572377"
               }, {
                   "created_time": "1453901222",
                   "text": "44th",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1171730841379491107"
               }, {
                   "created_time": "1453901997",
                   "text": "45th",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1171737339782450909"
               }, {
                   "created_time": "1453902304",
                   "text": "46th and 47th",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1171739915923967873"
               }, {
                   "created_time": "1453902638",
                   "text": "48th",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1171742713994497101"
               }, {
                   "created_time": "1453964684",
                   "text": "49th",
                   "from": {
                       "username": "venkataphani.ailavarapu",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2679234818",
                       "full_name": "Phani"
                   },
                   "id": "1172263199715314941"
               }, {
                   "created_time": "1453964710",
                   "text": "50th",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1172263415747136776"
               }, {
                   "created_time": "1453964717",
                   "text": "51st",
                   "from": {
                       "username": "kore_hyd",
                       "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/11906329_960233084022564_1448528159_a.jpg",
                       "id": "2056218675",
                       "full_name": "Kore.ai Hyd"
                   },
                   "id": "1172263474056350986"
               }]
                 ...
    3. Extract: For payloads that contain multiple objects, you can specify a path to the specific object. For example, click Add Processor, enter a Name for your processor, set the Key field to data, and then Type of Process to extract to use the object data in the following payload response.
      {
          "user": {
              "full_name": "Kore.ai Hyd",
              "id": "2056218675",
              "profile_picture": "https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg",
              "username": "kore_hyd"
          },
          ...
      }, "likes": {
          "data": [{
                  "full_name": "kstream002",
                  "id": "2100724876",
                  "profile_picture": "https://instagramimages-a.akamaihd.net/profiles/anonymousUser.jpg",
                  "username": "kstream002"
              }
          },
          ...
      }
    4. Assign:  Using the Assign processor, you can specify a variable name for the payload response, if needed, for example, when the payload does not contain a key for the payload response data. For example, set Type of Process to assign, and then in the Output Variable field, you can for example, define an output variable for the following payload that is an array of three objects.
      [
        {
          "Cost": "$0.00",
          "Desc1": "$150 bonus after $500 of purchases in the first 3 months from account opening. ",
          "Desc2": "Earn unlimited cash back Earn unlimited 1.5% cash back on every purchase – it's automatic. Redeem for cash back – any amount, any time. ",
          "Keywords": "weekend dining,online,groceries,fuel,rewards,rebate,365,allaround",
          "OfferName": "Freedom Unlimited",
          "OfferType": "CreditCard",
          "Status": "1",
          "imageURL": "http://www.psdgraphics.com/file/credit-card.jpg",
          "id": "5b5195e264bbd800"
        },
        {
          "Cost": "$95.00",
          "Desc1": "Pay 0 balance transfer fee when you transfer a balance during the first 60 days.",
          "Desc2": "Jumpstart your financial fitness Get an introductory fee for balance transfers, save on interest†, and get your free monthly credit score.",
          "Keywords": "privileges,rebate,health,wellness,great eastern,insurance,policy,installments,split,cashflo",
          "OfferName": "Premium Plus",
          "OfferType": "CreditCard",
          "Status": "1",
          "imageURL": "http://i.imgur.com/rMOXYql.jpg",
          "id": "5caf2155873f89c8"
        },
        {
          "Cost": "$10.00",
          "Desc1": "Pay 0 balance transfer fee when you transfer a balance during the first 60 days.",
          "Desc2": "Jumpstart your financial fitness Get an introductory fee for balance transfers, save on interest†, and get your free monthly credit score.",
          "Keywords": "privileges,rebate,health,wellness,great eastern,insurance,policy,installments,split,cashflo",
          "OfferName": "Frequent Flyer",
          "OfferType": "CreditCard",
          "Status": "1",
          "imageURL": "http://www.moneychoice.org/wp-content/uploads/2016/01/credit-card-calculator-image.png.jpeg",
          "id": "c0b05bc3062658ee"
        }
      ]

      In the Output Variable field, specify a variable to represent the array, as offers, for example. If you used the UX Preview feature, the response from Kore.ai would be:

      {
        "response": {
          "offers": [
            {
              "Cost": "$0.00",
              "Desc1": "$150 bonus after $500 of purchases in the first 3 months from account opening. ",
              "Desc2": "Earn unlimited cash back Earn unlimited 1.5% cash back on every purchase – it's automatic. Redeem for cash back – any amount, any time. ",
              "Keywords": "weekend dining,online,groceries,fuel,rewards,rebate,365,allaround",
              "OfferName": "Freedom Unlimited",
              "OfferType": "CreditCard",
              "Status": "1",
              "imageURL": "http://www.psdgraphics.com/file/credit-card.jpg",
              "id": "5b5195e264bbd800"
            },
            {
              "Cost": "$95.00",
              "Desc1": "Pay 0 balance transfer fee when you transfer a balance during the first 60 days.",
              "Desc2": "Jumpstart your financial fitness Get an introductory fee for balance transfers, save on interest†, and get your free monthly credit score.",
              "Keywords": "privileges,rebate,health,wellness,great eastern,insurance,policy,installments,split,cashflo",
              "OfferName": "Premium Plus",
              "OfferType": "CreditCard",
              "Status": "1",
              "imageURL": "http://vignette3.wikia.nocookie.net/objectmayhem/images/5/52/Credit_card.png/revision/latest?cb=20130629150408",
              "id": "5caf2155873f89c8"
            }
          ]
        }
      }

      With the Output Variable set to offers, you can use the variable as response.offers in Bot Builder, for example, in a task response object as follows:

      print(JSON.stringify(response));
      var data = response.offers
      for (i = 0; i < data.length; i++) {
          print('<a href="' + data[i].imageURL + '" target="_blank">' + data[i].OfferName + '</a><br>');
          print(data[i].Desc1)
          print('<br>');
          print('<br>');
          print('Cost: ' + data[i].Cost)
          print('<br>');
          if (i < data.length - 1) {
              print('<br>');
              print('<br>');
          }
      }
  3. Click Add to save the API request and then create another, or click Add & Exit to save the API request and close the dialog.

For multiple API requests, you should order the requests in the sequential order needed to get to entire data response. For example, you may need to request a list of workspaces, then a list of projects, and finally, a list of users. Use the Move Up  icon and the Move Down  icon to reorder the API requests.

Note: No confirmation dialog is displayed when deleting an API request. If you click Continue or Save, the delete action is permanent and cannot be undone.

Adding the Response Sample

In the Response Sample section, you can enter or paste examples of the key-value pairs that you expect to receive in the task payload. When you define the response sample, the keys specified in the Response Sample section are available as drop-down choices for handling the output data.

Adding the Sample Response

  1. On the API Request tab, Expand the Sample Response section.
  2. Enter your Response Sample that contains the key-value pairs from your JSON response payload. Do one of the following:
    • To format the view of the response as a JSON structure with indentation as shown in the following illustration, click the Formatted  icon.
    • To format the view of the response in serialized compact form as shown in the following illustration, click the Unformatted  icon.

Preview Website Link Content

Some web services send links to preview media as part of the payload response. In this section, you can enable or disable preview links, and define the path to the links in the payload. By default, website preview links are disabled. The following illustration is an example of the Preview Website Link Content in Post section when Yes is selected.API Request Tab - Preview Section When enabled, define the path to the preview links in the payload in the Path to the Link(toPreview) field, if the path is not in the root of the payload. For example, in the following code example from an RSS payload, the path to the preview is

...
"item": [
    {
        "title": "U.S. to Boost Refugee Intake by 30,000 by 2017",
        "guid": {
            "-isPermaLink": "false",
            "#text": "SB12418904751422433479504581245034032986752"
        },
        "link": "http://www.wsj.com/articles/john-kerry-says-u-s-to-admit-30-000-more-refugees-in-next-2-years-1442768498?mod=fox_australian",
        ...

When Preview website link content in Post is enabled, select preview objects such as:

  • Preview Title – Displays the title of the website content.
  • Preview Description – Displays the description of the website content.
  • Preview Media(Video) – Enables display of video links from the website content.
  • Preview Media(Image) – Enables display of image links from the website content.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed