LoginSignup
7
9

More than 5 years have passed since last update.

IBM Cloud Visual RecognitionとLINE Messaging APIを使って画像認識LINE BOTを作る

Last updated at Posted at 2018-09-08

概要

IBM Cloud Visual RecognitionLINE Messaging APIを使って画像認識LINE BOTを作ります。
こちらのリポジトリにコードと使い方があります。
またこちらから友達登録してもらえると使えるので、是非画像を送ってみてください。
xhack_nagaoka.png

イメージ

IMG_1014.PNG

使うもの

IBM Cloud Visual Recognition

LINE Messaging API

Heroku

codenvy(開発環境がある方はなしで可能)

BOTの流れ

LINE BOTにメッセージがくる

LINE Messaging APIのWebhook URLが呼ばれる(以下Herokuのnodeアプリ内での動き)

Herokuにデプロイされたアプリが画像データを取得するためにLINE Messaging APIにリクエストを投げる

LINE Messaging APIから画像のバイナリ(Buffer)が返ってくる

IBM Cloud Visual Recognitionにバイナリと共に分類のリクエストを投げる

レスポンスをLINE Messagin APIを通して返す

IBM Cloud Recognition API Key入手手順

  • IBM Cloudのアカウントを作成
  • こちらから価格プランでライトを選択して作成
  • 作成して移動した先でAPI 鍵をコピー
  • こちらで後から作ったサービス一覧が確認できます

はまったところ

LINE Developers API Referenceにある node.js のコードで、


const line = require('@line/bot-sdk');

const client = new line.Client({
  channelAccessToken: '<channel access token>'
});

client.getMessageContent('<messageId>')
  .then((stream) => {
    stream.on('data', (chunk) => {
      ...
    });
    stream.on('error', (err) => {
      // error handling
    });
  });

コンテンツを取得して chunk をそのまま送ると、

Invalid/corrupted image data. Supported image file formats are GIF, JPEG, PNG, and TIFF. 
Supported compression format is ZIP.","error_id":"input_error" ibm visual recognition

というエラーが出た。 chunk にreponseとbodyが一緒になっている?ここのやり方とかで分ける必要があるのかも(未検証)。

ここにあるこのコードを使って、bodyだけを送ることで解決。

app.post('/webhook', (req, res) => {
    if(req.body.events[0].message.type !== 'image') return;

    // 略

    Request(options, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            // bodyをIBM Cloud Visual Recognitionに送る
        } else {
            // @todo handle error
        }
    });
});

ワークショップ

https://connpass.com/event/99191/ で行ったワークショップでは5人の方に参加いただき、全員がBOTを動かすところまで出来ました!
ワークショップの様子1様子2

参考

https://qiita.com/n0bisuke/items/17c795fea4c2b5571ce0
https://github.com/ippei0605/line-bot

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