const express = require('express')
const request = require('request')
const bodyParser = require('body-parser');
const crypto = require("crypto");
const app = express()
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello world')
})
app.post('/hook', function (req, res) {
if (!validateSignature(req.headers['x-line-signature'], req.body)) {
return;
}
const events = req.body.events;
const userId = events[0].source.userId;
const type = events[0].source.type;
const message = events[0].message;
if(type == 'user'){
request.get( getProfileOption(userId), function (error, response, body) {
if (!error && response.statusCode == 200) {
const options = {
url: 'https://api.line.me/v2/bot/message/reply',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer {' + process.env.LINE_CHANNEL_ACCESS_TOKEN + '}',
},
json: true,
body: {
'replyToken': req.body['events'][0]['replyToken'],
'messages': [{
"type": "text",
"text": message.text + ' って言ったの?\n' + body['displayName'] + 'さん'
}]
}
};
request.post(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('success');
}
});
}
})
}
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
function getProfileOption(userId) {
return {
url: 'https://api.line.me/v2/bot/profile/' + userId,
json: true,
headers: {
'Authorization': 'Bearer {' + process.env.LINE_CHANNEL_ACCESS_TOKEN + '}'
}
};
}
function validateSignature(signature, body) {
const hmac = crypto.createHmac('sha256', process.env.LINE_CHANNEL_SECRET);
const data = new Buffer(JSON.stringify(body), 'utf8');
const result = hmac.update(data).digest('base64');
return signature == result;
}