시작하기
네이버 클라우드 회원가입이후에 콘솔 버튼을 통해서 네이버 클라이드가 제공중인 AI API를 확인할 수 있다.
이후 콘솔창에서 service -> chatbot을 클릭하면
도메인 생성창으로 이동하는데, 도메인 생성을 할 경우 아래와 같이 뜬다. (저는 11469 도메인을 만들었습니다)
이후 자기 도메인의 우측의 빌더 실행하기를 통해서 ChatBot을 시작할 수 있다.
응답 만들기
위에 노란색으로 색칠된 버튼을 통해서 대화를 만들고 확인할 수 있다.
우산 대화생성을 통해서 특정 입력값이 들어왔을 때, 어떻게 답변할 지 설정할 수 있다.
대화이름을 설정하고, 어떤 질문을 할지 결정한 다음에, 관련 답변을 등록하는 식으로 챗봇이 대답하게 할 수 있다.
이때 일반적인 대화로 할 경우에는 등록해야할 값이 너무 많아진다.
따라서 정규식을 이용하면 편하다.
정규식의 상세한 내용은 정규식 가이드를 보면서 만들면 된다.
이후 답변을 등록할 수 있는데,
이때 사용할 수 있는 답변으로는
이 있다.
이 외에도 폼을 통해서 추가적인 답변을 사용할 수 있다.
폼을 이용하면 , 답변식에 주고 받는 형태의 대화를 미리 등록할 수 있다.
나는 기분이라는 폼을 만들었는데 이후에
이를 답변 등록하면
특정 질문에 대한 답변으로 사용가능하다.
테스트하기
테스트는 우측하단 테스트를 통해서 할 수 있다.
하지만 태스트 전에 우선 상단의 대화모델 빌드를 해야한다.
테스트 결과가 제대로 나온다면 서비스 배포를 해야한다.
배포하기
자바에서 해당 챗봇을 사용하기 위해선 배포를 해야한다
그러기 위해선 아래 사진의 1번 챗봇설정, 이후 메신저 연동을 누르고 2번을 클릭하면 된다. ( Line이나 특정 앱에서 사용하려면 다른거 클릭)
이후 시크릿키 생성이후 해당 모달에서 나온 시크릿키와 주소를 나중에 있을 자바 코드에 사용하면 된다.
그리고 상단의 서비스 배포를 누르고 배포를 시작한다.
자바코드
채널 연동 가이드를 통해서 자세한 사용법을 확인할 수 있다.
예제 코드 링크
https://api.ncloud-docs.com/docs/ai-application-service-chatbot-chatbot#api-%EC%98%88%EC%A0%9C
CLOVA Chatbot Custom API
api.ncloud-docs.com
여기서 하단의 java 예시를 응용하여 코드를 만들었다.
package main;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.Timestamp;
import java.util.Date;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
public class MainClass {
public static void main(String[] args) {
String chatbotMessage = "";
String voiceMessage = "ㅎㅇ";
try {
String apiURL = "내uri복붙";
String secretKey = "시크릿키복붙";
URL url = new URL(apiURL);
String message = getReqMessage(voiceMessage);
// String message = voiceMessage;
System.out.println("##" + message);
String encodeBase64String = makeSignature(message, secretKey);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json;UTF-8");
con.setRequestProperty("X-NCP-CHATBOT_SIGNATURE", encodeBase64String);
// post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(message.getBytes("UTF-8"));
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader br;
if(responseCode==200) { // Normal call
System.out.println(con.getResponseMessage());
BufferedReader in = new BufferedReader(
new InputStreamReader(
con.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
chatbotMessage = decodedString;
}
//chatbotMessage = decodedString;
in.close();
} else { // Error occurred
chatbotMessage = con.getResponseMessage();
}
} catch (Exception e) {
System.out.println(e);
}
//choatbot 응답
System.out.println(chatbotMessage);
}
public static String makeSignature(String message, String secretKey) {
String encodeBase64String = "";
try {
byte[] secrete_key_bytes = secretKey.getBytes("UTF-8");
SecretKeySpec signingKey = new SecretKeySpec(secrete_key_bytes, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
encodeBase64String = Base64.encodeToString(rawHmac, Base64.NO_WRAP);
return encodeBase64String;
} catch (Exception e){
System.out.println(e);
}
return encodeBase64String;
}
public static String getReqMessage(String voiceMessage) {
String requestBody = "";
try {
JSONObject obj = new JSONObject();
long timestamp = new Date().getTime();
System.out.println("##"+timestamp);
obj.put("version", "v2");
obj.put("userId", "U47b00b58c90f8e47428af8b7bddc1231heo2");
//=> userId is a unique code for each chat user, not a fixed value, recommend use UUID. use different id for each user could help you to split chat history for users.
obj.put("timestamp", timestamp);
JSONObject bubbles_obj = new JSONObject();
bubbles_obj.put("type", "text");
JSONObject data_obj = new JSONObject();
data_obj.put("description", voiceMessage);
bubbles_obj.put("type", "text");
bubbles_obj.put("data", data_obj);
JSONArray bubbles_array = new JSONArray();
bubbles_array.put(bubbles_obj);
obj.put("bubbles", bubbles_array);
obj.put("event", "send");
requestBody = obj.toString();
} catch (Exception e){
System.out.println("## Exception : " + e);
}
return requestBody;
}
}
해당 예제는 안드로이드 음성까지 참조할 수 있도록 작성되어서 변수들을 그냥 일반 텍스트로 사용할 수 있도록 변경하였다.
이때 maven repository
https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
https://mvnrepository.com/artifact/org.json/json
https://mvnrepository.com/artifact/net.morimekta.utils/android-util
세가지를 다운받고
build path를 통해서 external library를 classpath에 등록하면 정상 작동한다.
결과물
##1692582719863
##{"bubbles":[{"data":{"description":"ㅎㅇ"},"type":"text"}],"event":"send","version":"v2","userId":"U47b00b58c90f8e47428af8b7bddc1231heo2","timestamp":1692582719863}
OK
{"version":"v2","userId":"U47b00b58c90f8e47428af8b7bddc1231heo2","timestamp":1692582720267,"bubbles":[{"type":"template","data":{"cover":{"type":"text","data":{"description":"오늘 기분이 어떠세요"}},"contentTable":[[{"rowSpan":1,"colSpan":1,"data":{"type":"button","title":"좋아요","data":{"type":"basic","action":{"type":"postback","data":{"postback":"UnexpiredForm␞77228␞0","displayText":"좋아요","postbackFull":"_T_UnexpiredForm␞77228␞0"}}}}}],[{"rowSpan":1,"colSpan":1,"data":{"type":"button","title":"별로에요","data":{"type":"basic","action":{"type":"postback","data":{"postback":"UnexpiredForm␞77228␞1","displayText":"별로에요","postbackFull":"_T_UnexpiredForm␞77228␞1"}}}}}]]},"information":[{"key":"imageOnly","value":"false"},{"key":"chatType","value":"SINGLEFORM"},{"key":"chatType","value":"SINGLEFORM"},{"key":"score","value":"1.0"},{"key":"scenarioName","value":"챗봇테스트"},{"key":"endOfBubble","value":"endOfBubble"},{"key":"matchingType","value":"exactMatch"},{"key":"domainCode","value":"ChatBotTestKSH"},{"key":"formStart","value":"true"}],"context":[]}],"scenario":{"name":"챗봇테스트","chatUtteranceSetId":5434254,"intent":[]},"entities":[],"keywords":[],"conversation":{"scenarioName":"챗봇테스트","chatUtteranceSetId":5434254,"types":[]},"normalizer":"null","event":"send"}
'벡엔드' 카테고리의 다른 글
spring으로 프로젝트 준비하기 (0) | 2023.07.13 |
---|