Git Product home page Git Product logo

linebot's Introduction

linebot

NPM Version NPM Downloads NPM Dependencies Build

🤖 SDK for the LINE Messaging API for Node.js

  • Come with built-in server for quick setup
  • Provide convenient addon functions to event object

About LINE Messaging API

Please refer to the official API documents for details.

Installation

$ npm install linebot --save

Usage

var linebot = require('linebot');

var bot = linebot({
  channelId: CHANNEL_ID,
  channelSecret: CHANNEL_SECRET,
  channelAccessToken: CHANNEL_ACCESS_TOKEN
});

bot.on('message', function (event) {
  event.reply(event.message.text).then(function (data) {
    // success
  }).catch(function (error) {
    // error
  });
});

bot.listen('/linewebhook', 3000);

Using with your own Express.js server

const app = express();
const linebotParser = bot.parser();
app.post('/linewebhook', linebotParser);
app.listen(3000);

See examples folder for more examples.

API

LineBot object

linebot(config)

Create LineBot instance with specified configuration.

var bot = linebot({
  channelId: CHANNEL_ID,
  channelSecret: CHANNEL_SECRET,
  channelAccessToken: CHANNEL_ACCESS_TOKEN,
  verify: true // Verify 'X-Line-Signature' header (default=true)
});

LineBot.listen(webHookPath, port, callback)

Start built-in http server on the specified port, and accept POST request callback on the specified webHookPath.

This method is provided for convenience. You can write you own server and use verify and parse methods to process webhook events. See examples/echo-express-long.js for example.

LineBot.parser()

Create Express.js middleware to parse the request.

The parser assumes that the request body has never been parsed by any body parser before, so it must be placed BEFORE any generic body parser e.g. app.use(bodyParser.json());

LineBot.verify(rawBody, signature)

Verify X-Line-Signature header.

LineBot.parse(body)

Process incoming webhook request, and raise an event.

LineBot.on(eventType, eventHandler)

Raised when a Webhook event is received.

bot.on('message',      function (event) { });
bot.on('follow',       function (event) { });
bot.on('unfollow',     function (event) { });
bot.on('join',         function (event) { });
bot.on('leave',        function (event) { });
bot.on('memberJoined', function (event) { });
bot.on('memberLeft',   function (event) { });
bot.on('postback',     function (event) { });
bot.on('beacon',       function (event) { });

LineBot.reply(replyToken, message)

Reply a message.

See: Event.reply(message)

LineBot.push(to, message)

Send push message.

to is a userId, or an array of userId. A userId can be saved from event.source.userId when added as a friend (follow event), or during the chat (message event).

message can be a string, an array of string, a Send message object, or an array of Send message objects.

LineBot.multicast(to, message)

Send push message to multiple users (Max: 150 users). This is more efficient than push as it will make api call only once.

to is an array of userId.

message can be a string, an array of string, a Send message object, or an array of Send message objects.

LineBot.broadcast(message)

Send push message to all users. This is more efficient than push as it will make api call only once.

message can be a string, an array of string, a Send message object, or an array of Send message objects.

LineBot.getMessageContent(messageId)

Get image, video, and audio data sent by users as a Buffer object.

See: Event.message.content()

LineBot.getUserProfile(userId)

Get user profile information of the user.

See: Event.source.profile()

LineBot.getGroupMemberProfile(groupId, userId)

Get user profile of a member in a group.

LineBot.getGroupMember(groupId)

Get userId of all members in a group.

See: Event.source.member()

LineBot.leaveGroup(groupId)

Leave a group.

LineBot.getRoomMemberProfile(roomId, userId)

Get user profile of a member in a chat room.

LineBot.getRoomMember(roomId)

Get userId of all members in a chat room.

See: Event.source.member()

LineBot.leaveRoom(roomId)

Leave a room.

LineBot.getTotalFollowers(date)

Get the number of users who have added this linebot on or before a specified date.

Default date is yesterday (UTC+9).

See: Get number of followers

LineBot.getQuota()

Get the number of messages quota in the current month.

See: Get the target limit for additional messages

LineBot.getTotalReplyMessages(date)

LineBot.getTotalPushMessages(date)

LineBot.getTotalBroadcastMessages(date)

LineBot.getTotalMulticastMessages(date)

Get the number of messages that this linebot reply, push, broadcast, or multicast.

Default date is yesterday (UTC+9).

See: Get number of sent reply messages

Event object

Provide convenient shorthands to call LineBot's functions which require parameter from a source event object.

Event.reply(message)

Respond to the event.

message can be a string, an array of string, a Send message object, or an array of Send message objects.

Return a Promise object from node-fetch module.

This is a shorthand for: LineBot.reply(event.replyToken, message)

// reply text message
event.reply('Hello, world').then(function (data) {
  // success
}).catch(function (error) {
  // error
});

// reply multiple text messages
event.reply(['Hello, world 1', 'Hello, world 2']);

// reply message object
event.reply({ type: 'text', text: 'Hello, world' });

// reply multiple message object
event.reply([
  { type: 'text', text: 'Hello, world 1' },
  { type: 'text', text: 'Hello, world 2' }
]);

event.reply({
  type: 'image',
  originalContentUrl: 'https://example.com/original.jpg',
  previewImageUrl: 'https://example.com/preview.jpg'
});

event.reply({
  type: 'video',
  originalContentUrl: 'https://example.com/original.mp4',
  previewImageUrl: 'https://example.com/preview.jpg'
});

event.reply({
  type: 'audio',
  originalContentUrl: 'https://example.com/original.m4a',
  duration: 240000
});

event.reply({
  type: 'location',
  title: 'my location',
  address: '〒150-0002 東京都渋谷区渋谷2丁目21−1',
  latitude: 35.65910807942215,
  longitude: 139.70372892916203
});

event.reply({
  type: 'sticker',
  packageId: '1',
  stickerId: '1'
});

event.reply({
  type: 'imagemap',
  baseUrl: 'https://example.com/bot/images/rm001',
  altText: 'this is an imagemap',
  baseSize: { height: 1040, width: 1040 },
  actions: [{
    type: 'uri',
    linkUri: 'https://example.com/',
    area: { x: 0, y: 0, width: 520, height: 1040 }
  }, {
    type: 'message',
    text: 'hello',
    area: { x: 520, y: 0, width: 520, height: 1040 }
  }]
});

event.reply({
  type: 'template',
  altText: 'this is a buttons template',
  template: {
    type: 'buttons',
    thumbnailImageUrl: 'https://example.com/bot/images/image.jpg',
    title: 'Menu',
    text: 'Please select',
    actions: [{
      type: 'postback',
      label: 'Buy',
      data: 'action=buy&itemid=123'
    }, {
      type: 'postback',
      label: 'Add to cart',
      data: 'action=add&itemid=123'
    }, {
      type: 'uri',
      label: 'View detail',
      uri: 'http://example.com/page/123'
    }]
  }
});

event.reply({
  type: 'template',
  altText: 'this is a confirm template',
  template: {
    type: 'confirm',
    text: 'Are you sure?',
    actions: [{
      type: 'message',
      label: 'Yes',
      text: 'yes'
    }, {
      type: 'message',
      label: 'No',
      text: 'no'
    }]
  }
});

event.reply({
  type: 'template',
  altText: 'this is a carousel template',
  template: {
    type: 'carousel',
    columns: [{
      thumbnailImageUrl: 'https://example.com/bot/images/item1.jpg',
      title: 'this is menu',
      text: 'description',
      actions: [{
        type: 'postback',
        label: 'Buy',
        data: 'action=buy&itemid=111'
      }, {
        type: 'postback',
        label: 'Add to cart',
        data: 'action=add&itemid=111'
      }, {
        type: 'uri',
        label: 'View detail',
        uri: 'http://example.com/page/111'
      }]
    }, {
      thumbnailImageUrl: 'https://example.com/bot/images/item2.jpg',
      title: 'this is menu',
      text: 'description',
      actions: [{
        type: 'postback',
        label: 'Buy',
        data: 'action=buy&itemid=222'
      }, {
        type: 'postback',
        label: 'Add to cart',
        data: 'action=add&itemid=222'
      }, {
        type: 'uri',
        label: 'View detail',
        uri: 'http://example.com/page/222'
      }]
    }]
  }
});

Event.source.profile()

Get user profile information of the sender.

This is a shorthand for:

  • LineBot.getUserProfile(event.source.userId) if it is 1:1 chat
  • LineBot.getGroupMemberProfile(event.source.groupId, event.source.userId) if bot is in a group
  • LineBot.getRoomMemberProfile(event.source.roomId, event.source.userId) if bot is in a chat room
event.source.profile().then(function (profile) {
  event.reply('Hello ' + profile.displayName);
});

Event.source.member()

Get userId of all members in a group or a chat room.

This is a shorthand for:

  • LineBot.getGroupMember(event.source.groupId) if bot is in a group
  • LineBot.getRoomMember(event.source.roomId) if bot is in a chat room
event.source.member().then(function (member) {
  console.log(member.memberIds);
});

Event.message.content()

Get image, video, and audio data sent by users as a Buffer object.

This is a shorthand for: LineBot.getMessageContent(event.message.messageId)

event.message.content().then(function (content) {
  console.log(content.toString('base64'));
});

License

MIT

linebot's People

Contributors

boybundit avatar deepakgd avatar elchroy avatar hearsilent avatar jonec76 avatar kamilogorek avatar mlix8hoblc avatar mohitbhatia1994 avatar pamornt avatar stu01509 avatar waynechang65 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

linebot's Issues

Decouple express.js dependency

Providing default built-in web server through LineBot.listen() makes it easy to use, but express.js has so many dependencies which will be installed even though user might not use this method.

how to install in centos7

i have installed apache and letencrypt in centos 7 server, also installed nodejs to run it but i am not able to get it working in webhook connection, do you have a guide for fresh centos server please

Reply return 'succcess', but the message can't be sent

Hi,
I have started to write a linebot for demo recently. However, I find I can't reply the user any message. In other words, I could receive the message from users and invoke linebot.reply successfully (Because this method will return a promise object and I could print some message after I send the message). I am not sure what's going on :S Could you please help me to give some hints or any troubles around the usage of Linebot library.

Here is the certain part of my codes related to the bot

var mLineBot = require("linebot");
var express = require("express");
var https = require("https");
var fs = require("fs");

var mBot = mLineBot({
channelId : "XXXXXXXXXXXX",
channelSecret: "XXXXXXXXXXXX",
channelAccessToken: "XXXXXXXXX",
verify: true
});
mBot.on('message', function(event){
if (event.message.type == 'text') {
var msg = event.message.text;
event.reply(msg).then(function(data) {
console.log(msg);
}).catch(function(err){
console.log("error");
});
}
});
const app = express();
const lineBotParser = mBot.parser();
var options = {
key: fs.readFileSync("./ssl/privatekey.pem"),
cert: fs.readFileSync("./ssl/certification.pem"),
ca : [
fs.readFileSync("./ssl/ca_bundle.crt","utf-8")
]
}
app.post("/", lineBotParser);
app.get("/testpage", function(req, res){
res.send("Hello!");
});

var server = https.createServer(options, app).listen(443, function(){
console.log("Express server is running now!");
});

BTW, I run all the service on GCP.

Thanks

About get the username

in the Event.source.profile(), I cant save the username to a variable from profile.displayName?

like this ...

let username;
event.source.profile().then(function (profile) {
	event.reply('Hello ' + profile.displayName);
}).catch(function (error) {
	// error
});
console.log(username); // undefined

Get userID

Can I just get the all userID who follows my channel ?
not just get userId from event Object

Bot reply specific person's message in group

Hello guys!~

I am trying to reply specific person's message in group, just like below picture.

IMG_9540

But I could't find the method in Message API document, or maybe I miss something.

Hope guys have solution, and thanks!~

Variables

First i want to thank you for your great work!

I'm really new to node and everything around it.
Since about 2 days im stuck. :(

What i'm trying to build is a query from a mongoDB an send the output as message.
In detail:

  • user sends message: '!nickname'
  • event starts a query ->
    Member.aggregate([
    { $group : { _id : '$nick', nick: {$first: '$nick'}, might:{$first: '$might'}}},
    { $sort: {date : -1}
    ]}
  • .then(member => {
    event.reply(member)
    });

In Text:

A user send a nick with an ! before as trigger.
Query in Mongo will search for all entries matching the username (without -> !)
Result will be sorted for the latest entry and the grouped output will be sent as Message.
like:
-username
-might
-date

I dont know what to do, i'm really so. Maybe im not getting the syntax right, or anything else ist wrong.

Please help me 🙈

Side node: im able to get the result i trying to archive with express + handlebars engine but this is different.

Get Group Name

Thank you for the good module of LINE bot.
I've used bot.on('join',...) and bot.on('message',...) to store and manage groups which linebot is in.
But how to get group name directly? (I mean boybundit/linebot function)
Is it available now? Thanks.

Using AWS lambda

Hello,
This is not an issue really, It just I'm currently using this SDK and deploy to AWS lambda using Serverless, but I'm unable to trigger any event when I send message from line app. How am I able to get bot.listen() to work when I'm using microservices like Lambda?

Get user agent

Is there anyway I can get the user agent info to detect whether it's mobile or desktop browser?

Push message to multiple users

In LineBot.push(to, message), if to is an array of string, loop through that array to push message to multiple users.

TypeError: Data must be a string or a buffer

I got error:

TypeError: Data must be a string or a buffer
    at TypeError (native)
    at Hmac.Hash.update (crypto.js:74:16)
    at LineBot.verify (C:\GitRepo\Warframe-Alert-BOT-LINE\node_modules\linebot\lib\linebot.js:30:5)
    at parser (C:\GitRepo\Warframe-Alert-BOT-LINE\node_modules\linebot\lib\linebot.js:149:38)
    at jsonParser (C:\GitRepo\Warframe-Alert-BOT-LINE\node_modules\body-parser\lib\types\json.js:103:7)
    at C:\GitRepo\Warframe-Alert-BOT-LINE\node_modules\linebot\lib\linebot.js:148:4
    at Layer.handle [as handle_request] (C:\GitRepo\Warframe-Alert-BOT-LINE\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\GitRepo\Warframe-Alert-BOT-LINE\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\GitRepo\Warframe-Alert-BOT-LINE\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\GitRepo\Warframe-Alert-BOT-LINE\node_modules\express\lib\router\layer.js:95:5)

I'm using linebot v1.3.0...
My code:

const express = require('express');
const app = express();
const linebot = require('linebot');
var bot = linebot({
	channelId: '15xxxxxxxx',
	channelSecret: '16f6862afec3d23b0ee02exxxxxxxxxx',
	channelAccessToken: '6x57DzbyGaSMEj9S4hTfhYsJERvwothosBwAoEJTwDqLuOncgvaWShD59OLpYFf9WdIZlgga5XjnyrTHIVPjLNGaHi7V0H4wGpI9w/0IyEjQtFmBVo74fCNjTiuwwSNAqZNa9fNlVaiRk5zTBsNaNAdB04t89/1O/xxxxxxxxxx=',
	verify: true
});

const linebotParser = bot.parser();
app.get('/linewebhook', linebotParser);
app.get('/test', function(req, res) {
  res.json({notes: "Hello"})
})
app.listen(3000);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.