Watson Coverasation API、Node.jsでChatbot
Node.jsでConversationAPIを使用したチュートリアルを探していたら以下の記事にたどり着きました。 qiita.com
こちらの記事ではクライアントとサーバーのやりとりに、socket.ioを使用している。socket.ioを使用することで、開発者は接続プロトコルを意識せずに非同期双方向通信を実現できます。
socket.ioの基本的な使用方法として、サーバーとクライアントの通信に、どちら側でもsocket.emit(eventname, data) でイベントを発火(=データの送信)をし、socket.on(eventname, callback) でイベントを検知(=データの受信)を行います。
クライアント→サーバー:
送信側
socket.emit('chat message',$('#m').val());
受信側
socket.on('chat message', function(msg){ //受信したメッセージをそのまま、チャット画面に表示 io.to(socket.id).emit('chat message',msg); // 受信したメッセージをAPIに投げる conversation.message({ input: { text: msg }, context : res[socket.id].context }, processResponse); });
サーバー→クライアント: 送信側
// 何らかの返答があれば、それをbotからの返答として全て返す(ループはjump to の時に必要) for (var i = 0, len = response.output.text.length; i < len; i++) { if(response.output.text[i] !== ''){ io.to(socket.id).emit('bot message', response.output.text[i]); } }
受信側
socket.on('bot message',function(msg){ $('#messages').append($('<li>').text('QA botくん:'+msg).addClass('chat-hukidashi').wrap('<div />')); });
公式サイト:Socket.IO
socket.ioを使用したチャットについては以下のチュートリアルを参考。 Socket.IO — Chat