LoginSignup
11
10

More than 3 years have passed since last update.

LINE BOTに送った画像をNode.jsで受信して保存するサンプル

Posted at

LINE BOTからNode.jsで画像を受け取って保存するだとRequestモジュールを使ってたけど、公式のSDKを使ってやってみるサンプルです。

Node.jsでQRコードを読み込むに引き続き、ハッカソン仙台でのネタです。

コード

1時間でLINE BOTを作るハンズオンのコードをベースに handleEventの関数を差し替えて、downloadContentの関数を新規追加します。

server.js
//・
//・
//・
//省略

async function handleEvent(event) {
    if (event.type !== 'message' || event.message.type !== 'image') {
        return Promise.resolve(null);
    }

    const downloadPath = './qr.png';
    let getContent = await downloadContent(event.message.id, downloadPath);
    console.log(getContent);

    return client.replyMessage(event.replyToken, [
        {
        type: 'text',
        text: `${getContent}として保存しました。`
        }
    ]);

}

//ダウンロード関数
function downloadContent(messageId, downloadPath) {
    return client.getMessageContent(messageId)
      .then((stream) => new Promise((resolve, reject) => {
        const writable = fs.createWriteStream(downloadPath);
        stream.pipe(writable);
        stream.on('end', () => resolve(downloadPath));
        stream.on('error', reject);
    }));
}

//省略
//・
//・
//・

試してみる

$ node server.js

LINE BOTに画像を送るとimage.pngとして保存されます。

コピペ用

server.js
'use strict';

const express = require('express');
const line = require('@line/bot-sdk');
const PORT = process.env.PORT || 3000;
const fs = require('fs');

const config = {
    channelSecret: 'チャンネルシークレット',
    channelAccessToken: 'チャンネルアクセストークン'
};

const app = express();

app.get('/', (req, res) => res.send('Hello LINE BOT!(GET)')); //ブラウザ確認用(無くても問題ない)
app.post('/webhook', line.middleware(config), (req, res) => {
    console.log(req.body.events);

    //ここのif分はdeveloper consoleの"接続確認"用なので削除して問題ないです。
    if(req.body.events[0].replyToken === '00000000000000000000000000000000' && req.body.events[1].replyToken === 'ffffffffffffffffffffffffffffffff'){
        res.send('Hello LINE BOT!(POST)');
        console.log('疎通確認用');
        return; 
    }

    Promise
      .all(req.body.events.map(handleEvent))
      .then((result) => res.json(result));
});

const client = new line.Client(config);

async function handleEvent(event) {
    if (event.type !== 'message' || event.message.type !== 'image') {
        return Promise.resolve(null);
    }

    const downloadPath = './image.png';
    let getContent = await downloadContent(event.message.id, downloadPath);
    console.log(getContent);

    return client.replyMessage(event.replyToken, [
        {
        type: 'text',
        text: `${getContent}として保存しました。`
        }
    ]);

}

//ダウンロード関数
function downloadContent(messageId, downloadPath) {
    return client.getMessageContent(messageId)
      .then((stream) => new Promise((resolve, reject) => {
        const writable = fs.createWriteStream(downloadPath);
        stream.pipe(writable);
        stream.on('end', () => resolve(downloadPath));
        stream.on('error', reject);
      }));
  }

app.listen(PORT);
console.log(`Server running at ${PORT}`);
11
10
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
11
10