1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LINEBotのカルーセル作成でハマった話

Posted at

#作ろうとしてたもの
写真をとって送信すると、受け取った画像に対して画像検索をして
その画像を同じであろう商品をリストアップして買取価格をカルーセル表示してくれるLinebot

#詰まった点
linesdkが画像を送ってくる仕組みが
メッセージの中にmessage.typeみたいなパラメータを持っていて、
それがimageとかデータが入ってるものだと


client.getMessageContent(message.id)

みたいな感じで自力でデータを取りに行かないといけない仕組みなんだけど


await client.getMessageContent(message.id)
.then(async(stream) => {
  stream.on('data', chunk =>{
     //ここにデータの受け取りの処理を書こうとした。
  });
});

こんな感じでデータを取ろうとしてここのデータの引数のchunkに画像データのバイナリが入ってるのかな〜みたいな予測で画像をFirebaseに保存してみた

すると
画像の上の部分だけ保存された変なデータが・・・

色々調べて、非同期の処理が途中で終了してしまってるのかとか色々考えるんだけど、答えなし。

ふとソースを見てみるとstreamとか書いてる。
そういえば昔C#で見たことあるような言葉だなぁと思い検索すると案の定
要はStreamはデータを小分けで送ってくれるような仕組みらしい
便利に使えれば処理のストップがなくて素晴らしいんだけど、
LineSDKのドキュメント、バイナリで返すって書いてるやん、
バイナリをStreamで返すって言ってよ・・・

#修正しました

こんな感じ


tempfilepath = "/tmp/example.jpg"
const dest = fs.createWriteStream(tempfilepath, 'binary')
await client.getMessageContent(message.id)
.then(async(stream) => {
  stream.on('data', chunk => dest.write(chunk));
  stream.on('end', async() => {
    dest.end()
    //ここでさっき保存したデータをリードして使う
  });
});	

こんな感じで修正しました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?