以前書いたLINE BOTをNode.jsで外部依存モジュールを使用せずに作るのコードをもとに先日ハンズオンを行いました。
その中で最後の感想で「SuperAgentを利用して試したら上手くいかなくて最後までハマった」という人がいたのでSuperAgentを使って書いてみたいと思います。
【優勝賞金1000万】 Node.jsでLINE Botを作るハンズオン!
【優勝賞金1000万】 Node.jsでLINE Botを作るハンズオン! ツイートまとめ! #botawards #gsacademy
SuperAgent
HTTPリクエストを行うライブラリです。expressなどの作者であるTJ氏が作っています。
基本の使い方は以下のような感じでメソッドチェーンで繋いでいくスタイルです。
var request = require('superagent');
request
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.end(function(err, res){
// Calling the end function will send the request
});
LINE Botを作る
Node.js v7.4.0
で試しています。
- 準備
$ mkdir mylinebot && cd mylinebot
$ npm init --yes
$ npm i --save superagent
- app.jsを作る
「LINE BOTをNode.jsで外部依存モジュールを使用せずに作る」で利用してるコードからHTTPクライアントの部分を主に差し替えてます。
'use strict';
const http = require('http');
const crypto = require('crypto');
const request = require('superagent');
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('');
}
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
if(body === ''){
console.log('bodyが空です。');
return;
}
let WebhookEventObject = JSON.parse(body).events[0];
console.log(WebhookEventObject);
//メッセージが送られて来た場合
if(WebhookEventObject.type === 'message'){
let SendMessageObject;
if(WebhookEventObject.message.type === 'text'){
SendMessageObject = [{
type: 'text',
text: WebhookEventObject.message.text
}];
}
request
.post(BASE_URL+REPLY_PATH)
.set('Content-Type','application/json; charset=UTF-8')
.set('X-Line-Signature', SIGNATURE)
.set('Authorization', `Bearer ${CH_ACCESS_TOKEN}`)
.send({replyToken: WebhookEventObject.replyToken, messages: SendMessageObject})
.end((err, res) => {
if(err){
console.log(`StatusCode: ${err.response.statusCode}`);
console.log(err.response.text);
return;
}
console.log(`StatusCode: ${res.statusCode}`);
});
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('success');
});
}).listen(PORT);
console.log(`Server running at ${PORT}`);
- 実行
(※)今回はprocess.env.SECRET
とprocess.env.TOKEN
からLINE BOTのchannel secret
とchannel access token
を受け取るようにしています。
$ SECRET=xxxx TOKEN=xxxxxxxx node app.js
これで実行するとおうむ返ししてくれるようになります。
おわりに
SuperAgentを使ってLINE BOT開発をしたい方の参考になれば幸いです。
もくもく会やるのできてくださいね〜