Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
10
Help us understand the problem. What is going on with this article?

More than 1 year has passed since last update.

@n0bisuke

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

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}`);
10
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
10
Help us understand the problem. What is going on with this article?