docomo が提供してくれている 雑談対話API をさくっと php で使う方法。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/***** | |
* https://dev.smt.docomo.ne.jp/?p=docs.api.page&api_docs_id=5 | |
*****/ | |
function webnist($text) { | |
$context_file = dirname(__FILE__).'/.docomoapi.context'; | |
$api_key = 'your API key here'; | |
$api_url = sprintf('https://api.apigw.smt.docomo.ne.jp/dialogue/v1/dialogue?APIKEY=%s', $api_key); | |
$req_body = array('utt' => $text); | |
if ( file_exists($context_file) ) { | |
$req_body['context'] = file_get_contents($context_file); | |
} | |
$headers = array( | |
'Content-Type: application/json; charset=UTF-8', | |
); | |
$options = array( | |
'http'=>array( | |
'method' => 'POST', | |
'header' => implode( "\r\n", $headers ), | |
'content' => json_encode($req_body), | |
) | |
); | |
$stream = stream_context_create( $options ); | |
$res = json_decode(file_get_contents($api_url, false, $stream)); | |
if (isset($res->context)) { | |
file_put_contents($context_file, $res->context); | |
} | |
return isset($res->utt) ? $res->utt : ''; | |
} |
curl で試したいときは、こんな感じ
curl -s --insecure \
-H "Content-Type: application/json; charset=UTF-8" \
https://api.apigw.smt.docomo.ne.jp/dialogue/v1/dialogue?APIKEY=XXXXXX \
-d "{\"utt\":\"アイス食べたい\"}"
まともに使いたければ https://github.com/fetus-hina/docomo-dialogue とかのライブラリ使うといいと思うよ。
コメントを残す