dialogflow agent를 php 스크립트로 curl 호출해보자

in #kr6 years ago (edited)


과거 관련 포스팅

( 0) 어떤 chatbot framework를 사용할 것인가?
(1) 챗봇 개념 이해하기
(2) dialogflow agent 생성하기

웹페이지에서 직접 dialogflow 를 사용할 일이 있어서

php curl 로 dialogflow 서비스를 호출하는 스크립트를 작성했습니다.

dialogflow 참고 사이트

참고로 리눅스 터미널에서는 아래와 같이 직접 curl 호출을 할 수 있습니다.

curl 'https://api.dialogflow.com/v1/query?v=20170712&query=test&lang=ko&sessionId=95aadeec-***78dd939&timezone=Asia/Seoul' -H 'Authorization:Bearer 인증코드 '

여기서 본인의 인증 코드를 모르는 사람은

dialogflow 서비스의 설정의 General 탭에서 확인 가능합니다.

인증 코드 확인하기

링크한 문서의 access token을 보면 query 질의에는 client access token 을 사용하면 된다고 합니다.

인증방법

참고로 access token 설정이 잘못 될 경우

아래와 같은 에러 메세지가 나옵니다.

{"status":{"code":401,"errorType":"unauthorized","errorDetails":"You are not authorized for this operation. Invalid access token"}}

아래는 전체 php 스크립트입니다.

<?
// Get cURL resource
$curl = curl_init();
$accesstoken = "9***";
$headr = array();
$headr[] = 'Content-type: application/json';
$header[] = 'Authorization:Bearer '.$developertoken;

$query = "test";

curl_setopt_array($curl, array(

CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.dialogflow.com/v1/query?v=20170712&query='.$query.'&lang=ko&sessionId=***&timezone=Asia/Seoul',
CURLOPT_HTTPHEADER => $header

));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

?>

github link에서도 코드를 확인할 수 있습니다.

터미널에서 스크립트를 실행할 경우

아래와 같이 정상적으로 dialogflow 실행 결과가 나옵니다.

스크린샷 2018-04-04 13.44.56.png

  • 4월 10일 업데이트
    curl 속도가 느린 것 같아서 검색해보니 curl이 DNS look-ups 에서 시간이 걸린다고 합니다. resolve 옵션을 사용하면 속도가 빨라질 수 있다고 해서 변경해서 테스트해보니 확실히 시간이 반 이상 줄어드네요.

아래는 CURLOPT_RESOLVE 옵션이 추가된 버전입니다.

$hostname="api.dialogflow.com";
$port = 443;
$host_ip = "35.201.109.133";
$resolve = array(sprintf(
"%s:%d:%s",
$hostname,
$port,
$host_ip
));
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.dialogflow.com/v1/query?v=20170712&query='.urlencode($query).'&lang=ko&sessionId=95aa939&timezone=Asia/Seoul',
CURLOPT_RESOLVE => $resolve,
CURLOPT_HTTPHEADER => $header
));

Sort:  

이벤트 당첨되셨어요!! 확인점!!

오 지금 갈께요 당첨운 없는데 놀랐어요 ㅇㅇ

ㅋㅋㅋㅋ당첨 축하드려용 연락주세욧!!>_<!!

@adana you were flagged by a worthless gang of trolls, so, I gave you an upvote to counteract it! Enjoy!!

Congratulations @adana! You received a personal award!

1 Year on Steemit

Click here to view your Board of Honor

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @adana! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.25
TRX 0.11
JST 0.032
BTC 61830.08
ETH 2986.99
USDT 1.00
SBD 3.73