티스토리 뷰

안녕하세요 

Java와 Spring을 이용하여 카카오톡 플러스친구 자동응답 API로 간단한 챗봇을 구현하는 것을 설명해 보려 합니다. 

카카오톡 자동응답은 Rest형식의 api로 사용자 쪽에서 컨트롤러만 구현함으로써 쉽게 개발 할 수 있습니다. 




먼저 카카오톡 플러스친구 관리자 센터에서 계정 등록 후, 플러스 친구를 생성합니다. 

이 과정은 홈페이지에서 쉽게 가능하니 생략 하겠습니다.

https://center-pf.kakao.com




플러스 친구에서 지원하는 API는 크게 4가지로 이 중 keyboard와 message 기능만 구현 하셔도 무방합니다. 

API 주요 기능 순으로 설명드리겠습니다. 



1. Home Keyboard API


이용자가 최초로 채팅방에 들어 올 때 기본으로 키보드 영역에 표시될 자동응답 명령을 호출하는 API입니다. 

API형 URL을 등록 할 때 초기 테스트로 keyboard를 호출 하니 꼭 구현 해야할 부분 입니다. 


Specification
  • Method : GET
  • URL : http(s)://:your_server_url/keyboard
  • Content-Type : application/json; charset=utf-8

{
    "type" : "buttons",
    "buttons" : ["선택 1", "선택 2", "선택 3"]
}

위와 같이 keyboard URL을 호출하면 Json Object 타입의 객체를 리턴 해 줍니다. 

Type은 버튼 형인 "buttons"와 텍스트 형인 "text"가 있습니다. 



버튼일 경우 예제 

// 버튼
@RequestMapping(value = "/keyboard", method = RequestMethod.GET)
public String keyboard() {

System.out.println("/keyboard");

JSONObject jobjBtn = new JSONObject();
ArrayList<String> btns = new ArrayList<>();
btns.add("신청");
btns.add("나의 신청 내역 (고객센터)");

jobjBtn.put("type", "buttons");
jobjBtn.put("buttons",btns);

return jobjBtn.toJSONString();
}


키보드일 경우 예제

// 키보드
@RequestMapping(value = "/keyboard", method = RequestMethod.GET)
public String keyboard() {

System.out.println("/keyboard");

JSONObject jobjBtn = new JSONObject();
jobjBtn.put("type", "text");

return jobjBtn.toJSONString();
}



2. 메시지 수신 및 자동응답 API


사용자가 선택한 명령어를 서버로 전달해주는 API입니다. 답변방식은 주관식(text)과 객관식(buttons) 중 선택 할 수 있습니다. 


Specification
  • Method : POST
  • URL : http(s)://:your_server_url/message
  • Content-Type : application/json; charset=utf-8
  • Parameters

사용자 쪽에서 답변을 입력하면 서버에 아래와 같이 값이 들어옵니다. 

curl -XPOST 'https://:your_server_url/message' -d '{
  "user_key": "encryptedUserKey",
  "type": "text",
  "content": "차량번호등록"
}'

여기서 자동응답 명령어의 메시지 텍스트 혹은 미디어 파일 uri인 content를 이용하여 답변을 구현할 수 있습니다. 


{
  "message": {
    "text": "귀하의 차량이 성공적으로 등록되었습니다. 축하합니다!",
    "photo": {
      "url": "https://photo.src",
      "width": 640,
      "height": 480
    },
    "message_button": {
      "label": "주유 쿠폰받기",
      "url": "https://coupon/url"
    }
  },
  "keyboard": {
    "type": "buttons",
    "buttons": [
      "처음으로",
      "다시 등록하기",
      "취소하기"
    ]
  }
}

사진이나 링크를 첨부할 경우, JsonObject안에 또 다른 JsonObject를 삽입하는 형식으로 만듭니다. 메시지 출력 후에는 다시 Keyboard를 호출 함으로써 처음과 같은 키보드 환경으로 만들어 줍니다. 



버튼 일 경우 예제 (링크 첨부) 

@RequestMapping(value = "/message", method = RequestMethod.POST, headers = "Accept=application/json")
@ResponseBody
public String message(@RequestBody JSONObject resObj) {

System.out.println("/message");
System.out.println(resObj.toJSONString());

String content;
content = (String) resObj.get("content");
JSONObject jobjRes = new JSONObject();
JSONObject jobjText = new JSONObject();
JSONObject jobjmesBtn = new JSONObject();
JSONObject jobjBtn = new JSONObject();

ArrayList<String> btns = new ArrayList<>();
btns.add("신청");
btns.add("나의 신청 내역 (고객센터)");
jobjBtn.put("type", "buttons");
jobjBtn.put("buttons", btns);

if(content.contains("신청")){
System.out.println("click A");
jobjText.put("text","안녕하세요 고객님! 신청해주셔서 감사합니다. 아래의 URL을 클릭하여 작성해주세요.");
jobjmesBtn.put("label","신청서 작성");
jobjmesBtn.put("url"," http://www.abc.com");
jobjText.put("message_button",jobjmesBtn);

} else if(content.contains("나의 신청 내역")){
System.out.println("click B");
jobjText.put("text","안녕하세요 고객님! 신청하신 내역은 아래의 URL에서 확인하실 수 있습니다");
jobjmesBtn.put("label","고객센터 문의");
jobjmesBtn.put("url"," http://www.abc.com");
jobjText.put("message_button",jobjmesBtn);

}

jobjRes.put("message", jobjText);
jobjRes.put("keyboard", jobjBtn);
System.out.println(jobjRes.toJSONString());

return jobjRes.toJSONString();
}


메시지 일 경우 예제

// 메세지
@RequestMapping(value = "/message", method = RequestMethod.POST, headers = "Accept=application/json")
@ResponseBody
public String message(@RequestBody JSONObject resObj) {

System.out.println("/message");
System.out.println(resObj.toJSONString());

String content;
content = (String) resObj.get("content");
JSONObject jobjRes = new JSONObject();
JSONObject jobjText = new JSONObject();

// 사용자 구현
if(content.contains("안녕")){
jobjText.put("text","안녕 하세요");
} else if(content.contains("사랑")){
jobjText.put("text","나도 너무너무 사랑해");
} else if(content.contains("잘자")){
jobjText.put("text","꿈 속에서도 너를 볼꺼야");
} else if(content.contains("졸려")){
jobjText.put("text","졸리면 언능 세수하러 가용!");
} else if(content.contains("시간")||content.contains("몇 시")){
jobjText.put("text","섹시");
} else {
jobjText.put("text","흠... 아직 지정해 두지 않은 말인걸.");
}

jobjRes.put("message", jobjText);
System.out.println(jobjRes.toJSONString());

return jobjRes.toJSONString();
}




3. 친구 추가/차단 알림 API


특정 카카오톡 이용자가 플러스 친구를 친구로 추가하거나 차단하는 경우 알려주는 API입니다. 

Specification
  • Method : POST / DELETE
  • URL : http(s)://:your_server_url/friend
  • Content-Type : application/json; charset=utf-8


4. 채팅방 나가기 


사용자가 채팅방 나가기를 하여 채팅방을 목록에서 삭제 할 경우 알려주는 API입니다. 

Specification
  • Method : DELETE
  • URL : http(s)://:your_server_url/chat_room/:user_key
  • Content-Type : application/json; charset=utf-8






코드 작성을 완료 하였으면 실행가능한 .jar 파일을 만들어 서버에 올려 실행 시행시키고 다시 카카오톡 파트너 센터로 이동합니다. 

https://center-pf.kakao.com












왼쪽 사이드 바의 스마트 채팅을 클릭하면 자동응답형 / API 형을 선택 할 수 있습니다.

여기서 API형을 선택합니다.

 





정사각의 연필 버튼을 클릭하면 URL을 등록 할 수 있는 창이 뜹니다. 

앱 이름과 jar를 올려둔 서버 주소를 입력하고 API 테스트를 하여 작동 여부를 확인 후 저장하기를 누르면 완료됩니다. 





아래는 실행 화면 입니다. 






예제 소스 전체는 https://github.com/annajinee/kakaoAutoReplyExample.git에서 보실 수 있습니다. 


이 포스팅은 https://center-pf.kakao.com/term 를 참고하여 작성하였으며, 이 외 자세한 API 기술서는 위 링크에서 확인 하실 수 있습니다. 


+ ps. 며칠 전 다른 프로그램 구동을 위해 서버에서 내렸습니다. ㅎㅎ 

누군가가 테스트 하시나봐요 제대로 작동안된다고 간간히 메시지가 오네요; 

이미 내린 상태라 당분간 테스팅은 안될 수 있습니다 ^^; 


'ETC' 카테고리의 다른 글

RESTful 하다란?  (0) 2021.03.25
[오브젝트] 객체분해  (0) 2019.09.01
[Objects] 객체와 의존성  (0) 2019.08.19
[서베이몽키 API] Survey Monkey API 연동법  (0) 2018.08.29
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함