LoginSignup
14
7

More than 5 years have passed since last update.

HapiでLINE Botをサクッと試す

Posted at

Node.jsのフレームワークであるHapi.jsでLINE Botを作ります。
ローカル環境だけで試せるのでSSLとかサーバー用意いらないです。

GoとlocaltunnelでLine Messaging APIを使ってオウム返しLINE Botを試す #golangjpで書いたlocaltunnelを使ってます。

LINE Messaging APIの利用準備

ドキュメントはこちらです。

https://devdocs.line.me/ja/

必要な値を取得

LINE Developersのページを開きます。

  • Channel Secret
  • Channel Access Token

の二つの値を取得します。

BotのWebhook利用を許可

LINE@ MANAGERのページを開きます。

BotのWebhook利用を許可します。
他の自動応答メッセージなどはオフにした方が開発時のウザさはなくなります。
(スクショで)

コード書いていきます。

  • バージョン確認
$ node -v
v7.0.0

依存パッケージ インストール

$ npm i --save hapi superagent

実際のコード

app.js

'use strict';

const Hapi = require('hapi');
const request = require('superagent');
const crypto = require('crypto');

const REPLY_URL = 'https://api.line.me/v2/bot/message/reply'; //リプライ用
const CH_SECRET = 'xxxxxxxx'; //Channel Secretを指定
const CH_ACCESS_TOKEN = 'xxxxxx'; //Channel Access Tokenを指定
const SIGNATURE = crypto.createHmac('sha256', CH_SECRET);

//
let client = (replyToken, SendMessageObject) => {
    request
        .post(REPLY_URL)
        .send({ replyToken: replyToken, messages: SendMessageObject })
        .set('X-Line-Signature', SIGNATURE)
        .set('Content-Type', 'application/json')
        .set('Authorization', `Bearer ${CH_ACCESS_TOKEN}`)
        .end(function(err, res){
            console.log(res.body);
        });
};

const server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 3000
});

server.route({
    method: 'POST',
    path:'/callback',
    handler: (request, reply) => {
        console.log(request.payload.events);
        console.log('-------\n');

        let WebhookEventObject = request.payload.events[0];

        if(WebhookEventObject.type === 'message'){
            let SendMessageObject;
            if(WebhookEventObject.message.type === 'text'){
                SendMessageObject = [{
                    type: 'text',
                    text: WebhookEventObject.message.text
                }];
            }

            client(WebhookEventObject.replyToken, SendMessageObject);
        }
        return reply('success').code(200);
    }
});

// Start the server
server.start((err) => {
    if (err) throw err;
    console.log('Server running at:', server.info.uri);
});

試す

  • アプリをローカル環境で起動
$ node app.js
  • localtunnelを起動させてグローバルアクセスできるようにする
$ lt --port 3000
your url is: https://jyyhbdxhwp.localtunnel.me
  • 設定画面からWebhook URLにlocaltunnelが生成したURLを設定する

  • 実際にへいへい言ってみる

ちゃんとオウム返ししてくれますね :)

hapiもサクッとかけるし、やはりlocaltunnelが便利すぎる。

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