Skip to content

Instantly share code, notes, and snippets.

@yagitoshiro
Last active April 14, 2017 23:20
Show Gist options
  • Save yagitoshiro/d4fd6345aab010fbc29b94c02ef50914 to your computer and use it in GitHub Desktop.
Save yagitoshiro/d4fd6345aab010fbc29b94c02ef50914 to your computer and use it in GitHub Desktop.
LINE API v2
/*
Usage: yarn add request
```
var linebot = require('./line_bot');
var LineBot = bot.new({
channelSecret: <YOUR CHANNEL SECRET>,
channelAccessToken: <YOUR CHANNEL ACCESS TOKEN>
});
```
*/
var request = require('request');
var crypto;
var MAX_MESSAGES = 5;
var MAX_RECIPIENTS = 150;
var BASE_URL = 'https://api.line.me/v2/bot'
try {
crypto = require('crypto');
} catch(e) {
crypto = {};
console.log('crypto support is disabled!');
}
var Bot = function(args){
var headers = {
'Content-type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer ' + args.channelAccessToken
};
API = {};
API.validate_signature = function(req, res, buf, encoding) {
var signature = req['headers']['x-line-signature'];
var body = buf.toString(encoding);
if (!signature || !body) {
return false;
}
var hmac = crypto.createHmac('sha256', args.channelSecret)
hmac.update(body, 'utf8');
var hash = hmac.digest('base64');
if (new String(hash).valueOf() === new String(signature).valueOf()) {
return true;
} else {
throw new (function(){
this.message = 'Authentication error';
this.name = 'AuthenticationError';
this.status = false;
});
return false;
}
};
API.push = function(args){
var options = {
to: args.to,
messages: args.messages
};
return sendMessages('/message/push', options);
};
API.multicast = function(args){
var options = {
to: args.to,
messages: args.messages
};
return sendMessages('/message/multicast', options);
};
API.reply = function(args){
var options = {
replyToken: args.replyToken,
messages: args.messages
};
return sendMessages('/message/reply', options);
};
API.profile = function(args){
return new Promise(function(fullfil, reject){
get({}, '/profile/' + args.userId, function(err, response, body){
if (err) {
reject(body);
return;
}
try {
fullfil(JSON.parse(body));
} catch(e){
console.log(e);
fullfill(body);
}
});
});
};
API.leave = function(args){
var url;
if (args.groupId) {
url = '/group/' + args.groupId + '/leave';
} else if (args.roomId) {
url = '/room/' + args.roomId + '/leave';
}
return sendMessages(url, {});
};
function sendMessages(url, body){
var options = {
url: BASE_URL + url,
headers: headers,
json: true,
body: body
};
return new Promise(function(fullfil, reject){
if (body.messages && body.messages.length > MAX_MESSAGES) {
reject('Too many messages (maximum: '+ MAX_MESSAGES +')');
return;
}
if (body.to && body.to.constructor === Array) {
if (body.to.length > MAX_RECIPIENTS) {//multicast
reject('Too many recipients (maximum: ' + MAX_RECIPIENTS +')');
return;
}
}
request.post(options, function(err, response, body) {
if (err) {
reject(body);
return;
}
fullfil(body);
});
});
}
function get(options, url, callback){
var options = {
url: BASE_URL + url,
headers: headers
};
request(options, callback);
}
function post(body, url, callback){
var options = {
url: BASE_URL + url,
headers: headers,
json: true,
body: body
};
request.post(options, function(err, response, body){
if (callback) {
callback({
error: err,
message: body
});
}
});
};
return API;
};
module.exports = Bot;
@yagitoshiro
Copy link
Author

yagitoshiro commented Feb 5, 2017

with Express 4.x

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var bot = require('./line_bot');
var LineBot = new bot({
  channelSecret: '<YOUR CHANNEL SECRET>',
  channelAccessToken: '<YOUR CHANNEL ACCESS TOKEN>'
});

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({
  verify: LineBot.validate_signature
}));

app.post('/callback', function(req, res){
  var json = req.body;
  var events = json.events;
  for (var i = 0, l = events.length; i < l; i++) {
    var e = events[i];
    LineBot.reply({
      replyToken: e.replyToken,
      messages: [{type: 'text', 'text': 'Yo!'}]
    });

    LineBot.profile({
      userId: json.events[0].source.userId
    })
    .then(function(profile){
      LineBot.push({
        to: profile.userId,
        messages: [{type: 'text', text: 'Yo, ' + profile.displayName + '!'}]
      });
    })
    .catch(function(e){
      console.log(e);
    });
  }
});

app.listen(process.env.PORT || 4649, function(){
  console.log("Server is running...");
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment