LoginSignup
26
21

More than 5 years have passed since last update.

簡単にLINE Botとそれとない会話を実現する方法

Last updated at Posted at 2016-04-23

先人の知恵を使えば、本当に簡単にできてびっくり

作るもの

ユーザの投稿に対してそれとない返しをしてくれるbot

必要なもの

  • LINE Bot API Trialのアカウント
  • Herokuのアカウント
  • Yahoo!のアカウント

とりあえず3種のアカウント

手順

スターターキットを入れる

下記に従って、ありがたくスターターキットをHerokuに入れる
http://qiita.com/tmtysk/items/2f33c7e08caefbf55548
※LINE側に登録したHerokuの設定値の反映に半日〜1日かかったので注意

Yahoo!の形態素解析APIを使う

API keyをHerokuのENVか何かに登録しておいて
呼び出す形式にしとく

web/index.php
~~省略~~
    // ユーザからの投稿に対して処理をする
    if ($content['text']) {
      // YahooAPIに投げるクエリを作る
      $query = $content['text'];
      $apiKey = getenv('YAHOO_API_KEY');;

      $url = "http://jlp.yahooapis.jp/MAService/V1/parse?appid=" . $apiKey . "&sentence=" . $query ."&response=surface,reading,pos,baseform,feature";

   // 形態素解析を取得
      $rss = file_get_contents($url);
      $xml = simplexml_load_string($rss);

      // 形態素解析結果を単語ごとに詰める
      $pos_list = array();
      $word_list = array();
      $base_list = array();

      $i = 0;
      foreach($xml->ma_result->word_list->word as $item) {
        $pos_list[$i] = $item->pos;
        $word_list[$i] = $item->surface;
        $base_list[$i] = $item->baseform;
        $i++;
      }

     $return_text = 'うんうん';
     // 感動詞(ex.こんにちは、おはよう)はそのままを繰り返す
     if(in_array('感動詞', $pos_list)) {
       $key = array_search('感動詞', $pos_list);
       $return_text = $base_list[$key];
   // 名詞は「〜なんだね」と返す
     } elseif(in_array('名詞', $pos_list)) {
       $key = array_search('名詞', $pos_list);
       $return_text = $base_list[$key] . 'なんだね';
     // 辛い、眠いが含まれるワードは「頑張ってるんだね」って慰める
     } elseif(in_array('つらい', $base_list) || in_array('眠い', $base_list) || in_array('ねむい', $base_list) || in_array('辛い', $base_list)) {
       $return_text = '頑張ってるんだね';
     }
     // 返答を送る
     $bot->sendText($from, sprintf('%s', $return_text));
    }
  }
~~省略~~

動作

スクリーンショット 2016-04-23 16.58.08.png

「おやすみ」は感動詞のはずなんだけど
Yahooの形態素解析的には名詞らしく上手く返してくれなかった(´・ω・`)

これで暇な時に構ってくれる相手ができた!!!素晴らしい!ライフハックだ!

26
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
21