LoginSignup
1
5

More than 5 years have passed since last update.

Node.jsでオウム返しLINE BOT (axios利用) #botawards

Posted at

以前書いたLINE BOTをNode.jsで外部依存モジュールを使用せずに作るのコードをもとに先日SuperAgent利用版を書きました。今回はaxiosを利用してみます。

LINE BOTのもくもく会中に書いてます。

もくもく #BotAwards

n0bisukeさん(@n0bisuke)が投稿した写真 - 2017 2月 8 2:33午前 PST

axios

HTTPクライアントライブラリです。

先日の#nodeschool_tokyoで会長がライブコーディングで使っていました。

SuperAgentのメソッドチェーン利用がしっくりこない人はaxiosを使う場合が多いようです。

基本の使い方は以下のような感じでPromiseな書き方で使えます。

app.js
var axios = require('axios');

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

LINE Botを作る

Node.js v7.4.0で試しています。

  • 準備
$ mkdir mylinebot && cd mylinebot
$ npm init --yes
$ npm i --save axios
  • app.jsを作る

LINE BOTをNode.jsで外部依存モジュールを使用せずに作る」で利用してるコードからHTTPクライアントの部分を主に差し替えてます。

app.js
'use strict';

const http = require('http');
const crypto = require('crypto');
const axios = require('axios');
const BASE_URL = 'https://api.line.me';
const REPLY_PATH = '/v2/bot/message/reply';//リプライ用
const CH_SECRET = process.env.SECRET || ''; //Channel Secretを指定
const CH_ACCESS_TOKEN = process.env.TOKEN || ''; //Channel Access Tokenを指定
const SIGNATURE = crypto.createHmac('sha256', CH_SECRET);
const PORT = process.env.PORT || 3000;

http.createServer((req, res) => {    
    if(req.url !== '/' || req.method !== 'POST'){
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('hello');
    }

    let body = '';
    req.on('data', (chunk) => {
        body += chunk;
    });        
    req.on('end', () => {
        if(body === ''){
          console.log('bodyが空です。');
          return;
        }

        let WebhookEventObject = JSON.parse(body).events[0];

        //メッセージが送られて来た場合
        if(WebhookEventObject.type === 'message'){
            let SendMessageObject;
            if(WebhookEventObject.message.type === 'text'){
                SendMessageObject = [{
                    type: 'text',
                    text: WebhookEventObject.message.text
                }];
            }

            axios.request({
                method: 'post',
                baseURL: BASE_URL,
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8',
                    'X-Line-Signature': SIGNATURE,
                    'Authorization': `Bearer ${CH_ACCESS_TOKEN}`
                },
                url: REPLY_PATH,
                data: {replyToken: WebhookEventObject.replyToken, messages: SendMessageObject},
            }).then((res) => {
                console.log(res.status);
            })
            .catch((error) => {
                console.log(error);
            });
        }

        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('success');
    });
}).listen(PORT);

console.log(`Server running at ${PORT}`);
  • 実行

(※)今回はprocess.env.SECRETprocess.env.TOKENからLINE BOTのchannel secretchannel access tokenを受け取るようにしています。

$ SECRET=xxxx TOKEN=xxxxxxxx node app.js

これで実行するとおうむ返ししてくれるようになります。

おわりに

axiosを使ってLINE BOT開発をしたい方の参考になれば幸いです。

まだもくもく会やるのできてくださいね〜

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