Help us understand the problem. What is going on with this article?

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}`);
n0bisuke
プロトタイピング専門スクール「プロトアウトスタジオ」で教えたりしてます。 プロフ -> https://dotstud.io/members/n0bisuke
https://protoout.studio
dotstudio
全ての人がモノづくりを楽しむ世界を目指して活動しています。
https://dotstud.io
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした