LoginSignup
2
2

More than 3 years have passed since last update.

chatwork で雑談botを試してみた

Posted at

背景

ChatWorkは、5年くらい使ってまして、時々Google Apps Scriptでchatwork APIを呼ぶスクリプトを試していました。今回実用的なchatwork botを作ろうとネットを見ていたところ、たまたま面白い雑談botを見つけました。
この記事です。
雑談に応答するLINE Botを爆速で作成する方法(Google Apps Script + Chaplus雑談対話API)
この雑談対話APIは、興味深いので、試しにchatworkと連携させてみることにしました。

余談ですが、私が20代の頃は、インターネットがなかったので、それははもう調べるのに苦労して、膨大な時間を費やしました。それに比べると、今ネットで瞬時に回答を得られるので、みなさんの情報提供に感謝しかありません。こうやってネットで便利になったはいいのですが、40年前のITエンジニアと比べて、生産性は本当に上がったのか?疑問に思うこともしばしばです。

前提

ChatWorkアカウントを持っていて、chatwork APIトークンを取得済みであること。
Google Apps Scriptの書き方に慣れていること。

手順

  1. Chaplus に行って、APIを取得する。
  2. Google Apps Script で以下のような、スクリプトを書く。
var API_TOKEN = '******************************'; //チャットワークAPIトークン

function doPost(e) {

  var json = JSON.parse(e.postData.contents);
  /* リクエスト用パラメータ・URLの準備 */
  var params = {
    headers : {"X-ChatWorkToken" : API_TOKEN},
    method : "post"
  };

  var roomId = json.webhook_event.room_id;

  url = "https://api.chatwork.com/v2/rooms/" + roomId + "/messages";

  var jsonBody = json.webhook_event.body;


  var tmpSplit = jsonBody.split(/:/);
  var keyword = tmpSplit[0];
  var usermessage = tmpSplit[1];


  if(jsonBody.slice(0, 3) == "bot"){   
    var accountId = json.webhook_event.account_id;
    var messageId = json.webhook_event.message_id;

    var body = ''
    body += '[rp aid=' + accountId;
    body += ' to=' + roomId + '-' + messageId + '] '

    var replyMessage = getChaplusMessage(usermessage, 'nakano');
    body += '[info]雑談bot:' + replyMessage  + '[/info]'

    params.payload = {body :body};

    UrlFetchApp.fetch(url, params);
  }  
}


function getChaplusMessage(mes, username) {
  var dialogue_options = {
    'utterance': mes,
    'username' : username,
    'agentState' : {
      'agentName' : 'sample_bot',
      'age' : '30歳',
      'tone' : 'kansai'
    }
  }
  var options = {
    'method': 'POST',
    'contentType': 'text/json',
    'payload': JSON.stringify(dialogue_options)
  };

  var chaplusUrl = "https://www.chaplus.jp/v1/chat?apikey=<APIキー>";
  var response = UrlFetchApp.fetch(chaplusUrl, options);
  var content = JSON.parse(response.getContentText());

  var answer = content.bestResponse.utterance;
  return answer;
}

3.Google Apps Script のWeb URLを公開する。(このあたりはネットの記事がたくさんあります。)
4.ChatWork のwebhook で上記URLを設定する。(このあたりはネットの記事がたくさんあります。)

5.試してみる。
zatudan.png
chatworkに投稿するときに先頭に bot:をつけたときに、雑談botを呼ぶ仕様にしています。

雑談APIの詳細は、Botが雑談に応えられるようにするWEB APIを公開してみた話【個人開発】 をご覧ください。

今後

こんな雑談対応APIを提供して頂けるのはとても嬉しいです。
より実用的な会話にできるか挑戦してみたい。

2
2
1

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
2
2