GithubHelp home page GithubHelp logo

remixz / messenger-bot Goto Github PK

View Code? Open in Web Editor NEW
1.1K 41.0 209.0 158 KB

A Node client for the Facebook Messenger Platform

License: MIT License

JavaScript 100.00%
facebook facebook-messenger-platform bot

messenger-bot's Introduction

messenger-bot

Build Status Coverage Status npm version js-standard-style

A Node client for the Facebook Messenger Platform.

Requires Node >=4.0.0.

Installation

npm install messenger-bot

Example

See more examples in the examples folder.

Run this example in the cloud: Nitrous Quickstart

  • Setup PAGE_TOKEN, VERIFY_TOKEN, APP_SECRET and start the example by Run > Start Messenger Echo Bot.
  • Your Webhook URL is available at Preview > 3000 in the IDE.
const http = require('http')
const Bot = require('messenger-bot')

let bot = new Bot({
  token: 'PAGE_TOKEN',
  verify: 'VERIFY_TOKEN',
  app_secret: 'APP_SECRET'
})

bot.on('error', (err) => {
  console.log(err.message)
})

bot.on('message', (payload, reply) => {
  let text = payload.message.text

  bot.getProfile(payload.sender.id, (err, profile) => {
    if (err) throw err

    reply({ text }, (err) => {
      if (err) throw err

      console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
    })
  })
})

http.createServer(bot.middleware()).listen(3000)
console.log('Echo bot server running at port 3000.')

Usage

Functions

let bot = new Bot(opts)

Returns a new Bot instance.

opts - Object

  • token - String: Your Page Access Token, found in your App settings. Required.
  • verify - String: A verification token for the first-time setup of your webhook. Optional, but will be required by Facebook when you first set up your webhook.
  • app_secret - String: Your App Secret token used for message integrity check. If specified, every POST request will be tested for spoofing. Optional.

bot.middleware()

The main middleware for your bot's webhook. Returns a function. Usage:

const http = require('http')
const Bot = require('messenger-bot')

let bot = new Bot({
  token: 'PAGE_TOKEN',
  verify: 'VERIFY_TOKEN'
})

http.createServer(bot.middleware()).listen(3000)

As well, it mounts /_status, which will return {"status": "ok"} if the middleware is running. If verify is specified in the bot options, it will mount a handler for GET requests that verifies the webhook.

bot.sendMessage(recipient, payload, [callback], [messagingType], [tag])

Sends a message with the payload to the target recipient, and calls the callback if any. Returns a promise. See Send API.

  • recipient - Number: The Facebook ID of the intended recipient.
  • payload - Object: The message payload. Should follow the Send API format.
  • callback - (Optional) Function: Called with (err, info) once the request has completed. err contains an error, if any, and info contains the response from Facebook, usually with the new message's ID.
  • messagingType - (Optional) String: The message type. Supported Messaging Type.
  • tag - (Optional) String: The tag's message. Supported Tags.

bot.getAttachmentUploadId(url, is_reusable, type, [callback])

Sends the media to the Attachment Upload API and calls the callback if the upload is successful, including the attachment_id. See Attachment Upload API.

  • url - String: Link where can be fetched the media.
  • is_reusable - Boolean: Defined if the saved asset will be sendable to other message recipients.
  • type - String: The type of media. Can be one of: image, video, audio, file.
  • callback - (Optional) Function: Called with (err, info) once the request has completed. err contains an error, if any, and info contains the response from Facebook, usually with the media's ID.

bot.sendSenderAction(recipient, senderAction, [callback])

Sends the sender action senderAction to the target recipient, and calls the callback if any. Returns a promise.

  • recipient - Number: The Facebook ID of the intended recipient.
  • senderAction - String: The sender action to execute. Can be one of: typing_on, 'typing_off', 'mark_seen'. See the Sender Actions API reference for more information.
  • callback - (Optional) Function: Called with (err, info) once the request has completed. err contains an error, if any, and info contains the response from Facebook, usually with the new message's ID.

bot.unlinkAccount(psid, [callback])

Unlinks the user with the corresponding psid, and calls the callback if any. Returns a promise. See [Account Unlink Endpoint].(https://developers.facebook.com/docs/messenger-platform/identity/account-linking?locale=en_US#unlink)

  • psid - Number: The Facebook ID of the user who has to be logged out.
  • callback - (Optional) Function: Called with (err, info) once the request has completed. err contains an error, if any, and info contains the response from Facebook.

bot.setGetStartedButton(payload, [callback])

bot.setPersistentMenu(payload, [callback])

Sets settings for the Get Started Button / Persistent Menu. See the Messenger Profile Reference for what to put in the payload.

bot.removeGetStartedButton([callback])

bot.removePersistentMenu([callback])

Removes the Get Started Button / Persistent Menu.

bot.getProfile(target, [callback])

Returns a promise of the profile information of the target, also called in the callback if any. See User Profile API.

  • target - Number: The Facebook ID of the intended target.
  • callback - (Optional) Function: Called with (err, profile) once the request has completed. err contains an error, if any, and info contains the response from Facebook, in this format:
{
  "first_name": "Zach",
  "last_name": "Bruggeman",
  "profile_pic": "<url to profile picture>",
  "locale": "en",
  "timezone": "PST",
  "gender": "M"
}

bot._handleMessage(payload)

The underlying method used by bot.middleware() to parse the message payload, and fire the appropriate events. Use this if you've already implemented your own middleware or route handlers to receive the webhook request, and just want to fire the events on the bot instance. See the echo bot implemented in Express for an example.

  • payload - Object: The payload sent by Facebook to the webhook.

bot._verify(req, res)

The underlying method used by bot.middleware() for the initial webhook verification. Use this if you've already implemented your own middleware or route handlers, and wish to handle the request without implementing bot.middleware(). See the echo bot implemented in Express for an example.

  • req - Request: The http request object.
  • res - Response: The http response object.

Events

bot.on('message', (payload, reply, actions))

Triggered when a message is sent to the bot.

  • payload - Object: An object containing the message event's payload from Facebook. See Facebook's documentation for the format.
  • reply - Function: A convenience function that calls bot.sendMessage, with the recipient automatically set to the message sender's Facebook ID. Example usage:
bot.on('message', (payload, reply, actions) => {
  reply({ text: 'hey!'}, (err, info) => {})
})
  • actions - Object: An object with two functions: setTyping(status: Boolean), and markRead().

bot.on('postback', (payload, reply, actions))

Triggered when a postback is triggered by the sender in Messenger.

  • payload - Object: An object containing the postback event's payload from Facebook. See Facebook's documentation for the format.
  • reply - Function: A convenience function that calls bot.sendMessage, with the recipient automatically set to the message sender's Facebook ID. Example usage:
  • actions - Object: An object with two functions: setTyping(status: Boolean), and markRead().
bot.on('postback', (payload, reply, actions) => {
  reply({ text: 'hey!'}, (err, info) => {})
})

bot.on('delivery', (payload, reply, actions))

Triggered when a message has been successfully delivered.

  • payload - Object: An object containing the delivery event's payload from Facebook. See Facebook's documentation for the format.
  • reply - Function: A convenience function that calls bot.sendMessage, with the recipient automatically set to the message sender's Facebook ID. Example usage:
  • actions - Object: An object with two functions: setTyping(status: Boolean), and markRead().
bot.on('delivery', (payload, reply, actions) => {
  reply({ text: 'hey!'}, (err, info) => {})
})

bot.on('authentication', (payload, reply, actions))

Triggered when a user authenticates with the "Send to Messenger" plugin.

  • payload - Object: An object containing the authentication event's payload from Facebook. See Facebook's documentation for the format.
  • reply - Function: A convenience function that calls bot.sendMessage, with the recipient automatically set to the message sender's Facebook ID. Example usage:
  • actions - Object: An object with two functions: setTyping(status: Boolean), and markRead().
bot.on('authentication', (payload, reply, actions) => {
  reply({ text: 'thanks!'}, (err, info) => {})
})

bot.on('referral', (payload, reply, actions))

Triggered when an m.me link is used with a referral param and only in a case this user already has a thread with this bot (for new threads see 'postback' event)

  • payload - Object: An object containing the authentication event's payload from Facebook. See Facebook's documentation for the format.
  • reply - Function: A convenience function that calls bot.sendMessage, with the recipient automatically set to the message sender's Facebook ID. Example usage:
  • actions - Object: An object with two functions: setTyping(status: Boolean), and markRead().
bot.on('referral', (payload, reply, actions) => {
  reply({ text: 'welcome!'}, (err, info) => {})
})

bot.on('accountLinked', (payload, reply, actions))

Triggered when an account is linked with the Account Linking Process.

  • payload - Object: An object containing the linking account event's payload from Facebook. See Facebook's documentation for the format.
  • reply - Function: A convenience function that calls bot.sendMessage, with the recipient automatically set to the message sender's Facebook ID. Example usage:
  • actions - Object: An object with two functions: setTyping(status: Boolean), and markRead().
bot.on('accountLinked', (payload, reply, actions) => {
  reply({ text: 'Logged in!'}, (err, info) => {})
})

bot.on('accountUnlinked', (payload, reply, actions))

Triggered when an account is unlinked with the Account Unlink Endpoint or with an Log Out Button.

  • payload - Object: An object containing the unlinking account event's payload from Facebook. See Facebook's documentation for the format.
  • reply - Function: A convenience function that calls bot.sendMessage, with the recipient automatically set to the message sender's Facebook ID. Example usage:
  • actions - Object: An object with two functions: setTyping(status: Boolean), and markRead().
bot.on('accountLinked', (payload, reply, actions) => {
  reply({ text: 'Logged out!'}, (err, info) => {})
})

messenger-bot's People

Contributors

amitaigat avatar asc2030 avatar b-stefan avatar baudev avatar exedk avatar gautiert avatar greenkeeper[bot] avatar greenkeeperio-bot avatar icandivideby0 avatar maciekmm avatar psealock avatar remixz avatar victorcotap avatar yeouchien 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

messenger-bot's Issues

Error while conversing

Hello everyone,

I don't know why I keep having this problem :

message: '(#100) No matching user found', type: 'OAuthException', code: 100, fbtrace_id: 'CFuhU0qaJiv' }
I know it's coming from Facebook API, is there any fix to that ?

Thank you.

Payload paramater in bot.on('postback', (payload, reply, actions)) is null

Hi,

Not sure if its just me, but whenever I listen for a postback, the payload always returns null despite being assigned a value before the postback event triggers.

Whenever I use reply to echo the payload data to the user, I get an error message: Param message[text] must be a UTF-8 encoded string

bot.on('postback', (payload, reply, actions) => { reply({text: payload}, (err, info) => { if(err) { console.log(err.message) throw err } }) })

Unless I'm wrong and the payload object changes from a string before postback to a different object type?

Please advise guys
Thanks!

Debug Mode

The Facebook documentation here explains that you can get further details about your errors by providing debug: 'all'. However, it does not appear possible to provide debug: 'all' in messenger-bot. Could you please provide a way to set this flag when sending messages?

Add support for new webhook events

trigger specific message

hi,

Would like to ask how i am set for like specific message?
For example, if the user post hi, the bot would reply how may i help you?
if the user post i have a question, the bot would reply something else?

Thanks

Make 2.2.0 available on node

When trying to install the latest version by specifying 2.2.0 in package.json, nam install returns an error stating 2.2.0 doesn't exist and 2.10 is the latest version

Add support for Sender Actions

Facebook recently added "Sender Actions" to the platform, which let you toggle a typing state for the bot. https://developers.facebook.com/docs/messenger-platform/send-api-reference/sender-actions

Since they're not part of the message object in a payload, this library currently doesn't support them. We should add them somehow, likely as something separate from sendMessage / reply.

The first solution I can think of is add toggling sender actions as a third param in the event handler. Something like (event, reply, actions) => {}, with actions having functions like actions.setTyping(state: boolean, callback: function) and actions.markRead(callback: function). This would let adding actions not be a breaking change to the module, which would be nice.

Promise API

Hi,
Thanks for your work!
It would be great to have a promise API in this lib, allowing for async/await compatibility. Would you accept such a PR ?

Getting Cannot read property 'forEach' of undefined

I am getting error from this piece of code.
` _handleMessage (json) {
let entries = json.entry

entries.forEach((entry) => {
  let events = entry.messaging

  events.forEach((event) => {
    // handle inbound messages and echos
    if (event.message) {
      if (event.message.is_echo) {

`
events is undefined.

What could be the issue here?

App crashed at webhook

Hi,

I am trying to use your package in a Heroku server, but I get this error:`

2016-06-05T18:01:26.235314+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=POST path="/webhook" host=gentle-garden-48229.herokuapp.com request_id=e3e8494a-0acf-461c-9570-3cd07194e105 fwd="66.220.158.115" dyno= connect= service= status=503 bytes=

Any ideas why?

Thanks!

Cannot read property 'entry' of undefined

I'm having a problem every time I receive a message I got an error ': TypeError: Cannot read property 'entry' of undefined'

There is my code :

'use strict'

// dependencies
const http = require('http')
const Bot = require('messenger-bot')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()


let bot = new Bot({
  token: 'token',
  verify: 'verify_here',
})


bot.on('error', (err) => {
  console.log(err.message)
})

bot.on('message', (payload, reply) => {
  let text = payload.message.text

  console.log(text)

  bot.getProfile(payload.sender.id, (err, profile) => {
    if (err) throw err

    reply({ text }, (err) => {
      if (err) throw err
      console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
    })
  })
})

app.get('/', (req, res) => {
  res.send("Hello!!")
})

app.get('/webhook/', (req, res) => {
  return bot._verify(req, res)
})

app.post('/webhook/', (req, res) => {
  bot._handleMessage(req.body)
  res.end(JSON.stringify({status: 'ok'}))
})


app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}))

http.createServer(app).listen( process.env.PORT || 5000 )

Thanks.

Update on npm

The package on npm is the previous version.
Would you please upload the latest version?
I can't wait to use Promise for my bot 🤘

Thanks a lot! 🍻

How to run in Nitrous

Hello everyone.

I'm very new in node and messenger bot.
I clone the project in Nitrous but now I don't know how to make it work.

Please I need help.

Thanks for all and share your project.

Non-Message Actions (eg. persistent menus and greeting text)

If you want to set a persistent menu or change the welcome greeting you need to make a non-message request:

In order to configure the Thread Settings, make a POST call to /me/thread_settings
access_token=PAGE_ACCESS_TOKEN with the parameters in the body.

https://developers.facebook.com/docs/messenger-platform/thread-settings

And to configure a greeting ...

curl -X POST -H "Content-Type: application/json" -d '{
  "setting_type":"greeting",
  "greeting":{
    "text":"Timeless apparel for the masses."
  }
}' "https://graph.facebook.com/v2.6/me/thread_settings?access_token=PAGE_ACCESS_TOKEN"    

Is there any way to make these requests with messenger-bot, and if not is there any plan to support them in the future?

Serving an image

Hi,
I am trying to serve an image in a template but keep getting
Error, wrong validation token
I've tried setting a static directory for serving images but that dosent seem to work either
Any help would be appreciated.

Add support for authentication event

There's one type of event that I didn't implement that can be made to the webhook that's an "authentication" event. Looks like it happens when the user uses Facebook's "Send to Messenger" plugin: https://developers.facebook.com/docs/messenger-platform/implementation#send_to_messenger_plugin

The payload's format is here: https://developers.facebook.com/docs/messenger-platform/webhook-reference#auth Looks like it'd be pretty simple to detect, since it has some unique properties in its payload, so I'm going to make this a starter issue. I'm happy to help out if anyone runs into issues with this!

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Sending replies in sequential execution order

Hello everyone,

I am currently splitting my replies into an array, because the length is superior to 320, but I can't send them in order :

let answers = currentQuestion.answer.split("\n"); answers.forEach( (answer) => { reply({"text": answer}, (err) =>{ })

In Messenger, I'm receiving them in a random order, I looked a bit around Promises, is there any way I can use them ?

Thank you

verify error

I have digitalocean vps and try to place your code there.
But when I verify webhook (https://x.x.x.x:3000) get error

The URL couldn't be validated. Callback verification failed with the following errors: curl_errno = 35; curl_error = Unknown SSL protocol error in connection to x.x.x.x:3000 ; HTTP Status Code = 200; HTTP Message = Connection established

What i need to do?

Message structure has changed in the API

Hello everyone I'm getting this error

message: '(#100) Invalid keys "sayHi" were found in param "message".',

And I think the message structure has changed, please update your client.

Add support for uploading files

Facebook just recently added the ability to upload files (images, audio, videos, or a generic file) for a message, instead of having to specify a URL for an attachment.

They all share the same format of it being a multipart POST form, with the file being under the key of filedata. For our sendMessage / reply, we should have some sort of special key in the payload that accepts the same inputs as request does for multipart forms (https://github.com/request/request#forms), and is then added to the request as filedata.

Cannot read property 'forEach' of undefined

There's a error when running a simple echo test without middlware.

Error: Cannot read property 'forEach' of undefined. at (...) \node_modules\messenger-bot\index.js:188:12

Getting "Error, wrong validation token" with right page token

Trying to set up the example on Nitrous and my server keeps saying "Error, wrong validation token." I believe this is referring to the page_token variable in echo.js, but I've put in the right page_token. I've also tried multiple verification tokens, but the message remains. How should I fix this?

Does this functionality belong in the repo?

When I wrote a bot this weekend I found it useful to send messages one after the other. You cannot rely on the code order of calls tosendMessage because messages may arrive in different orders. Logically this requires that you wait for the on delivery event before you send the next message. When handling more than one conversation this requires a lookup-table to keep conversations separated.

I've added this functionality to separateMessages found here.

Use is as follows:

const SeparateMessages = require('./../separateMessages')

let bot = new Bot({...})

SeparateMessages.registerBot(bot)

// Pass a list of strings, each string will be sent separately
SeparateMessages.sendSeparateMessages(payload.sender.id,
        ["It was only a sunny smile, and little it cost in the giving,", 
         "but like morning light",
         "it scattered the night and made the day worth living."],
        (err, profile) => {
                       console.log("It is done");
                     })

Does this functionality have a place in your repo?
I know my code doesn't follow your JS conventions, but that can be fixed.

npm package on package.json

if I put on my package.json: "messenger-bot": "2.4.0", I get weird error
so I have to write: "messenger-bot": "github:remixz/messenger-bot",

any idea why?

An in-range update of request is breaking the build 🚨

☝️ Greenkeeper’s updated Terms of Service will come into effect on April 6th, 2018.

Version 2.84.0 of request was just published.

Branch Build failing 🚨
Dependency request
Current Version 2.83.0
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

request is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
  • coverage/coveralls First build on greenkeeper/request-2.84.0 at 3.704% Details

Commits

The new version differs by 6 commits.

  • d77c839 Update changelog
  • 4b46a13 2.84.0
  • 0b807c6 Merge pull request #2793 from dvishniakov/2792-oauth_body_hash
  • cfd2307 Update hawk to 7.0.7 (#2880)
  • efeaf00 Fixed calculation of oauth_body_hash, issue #2792
  • 253c5e5 2.83.1

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Support notification_type

Hi !

I would love to make a PR to add the support for notification_type see doc, but before doing that I would like to figure out the correct API. Here are some ideas, let me know what do you think:

Proposition 1
Wrap the current payload, and notification_type into an object.
Cons: Breaking change

sendMessage (recipient, {payload, notification_type} , cb) {
    return request({
      method: 'POST',
      uri: 'https://graph.facebook.com/v2.6/me/messages',
      qs: this._getQs(),
      json: {
        recipient: { id: recipient },
        message: payload,
        notification_type,
      }
    })
...

Proposition 2
Add notification_type as another parameter. We could check the type of the third param to decide in which case we are.
Pro: no breaking change

sendMessage (recipient, payload, notification_type , cb) {
    return request({
      method: 'POST',
      uri: 'https://graph.facebook.com/v2.6/me/messages',
      qs: this._getQs(),
      json: {
        recipient: { id: recipient },
        message: payload,
        notification_type,
      }
    })
...

Proposition 3
Wrap all params in an object.
Cons: Breaking Change (we could check params and support the old api)
Pro: Easy to add / remove params and avoid error with params order

sendMessage ({recipient, payload, notification_type, cb} ) {
    return request({
      method: 'POST',
      uri: 'https://graph.facebook.com/v2.6/me/messages',
      qs: this._getQs(),
      json: {
        recipient: { id: recipient },
        message: payload,
        notification_type,
      }
    })
...

Cheers !

Undefined Error on like

Great work on the library.

The reply function throws and error once the user replies with 👍 button.
But emojis work just fine.

getProfile() return undefined

Your documentation indicates that this method returns a promise. And this is really true if you look at the source code on the github.

messenger-bot/index.js

Lines 22 to 38 in ae2b408

getProfile (id, cb) {
return request({
method: 'GET',
uri: `https://graph.facebook.com/v2.6/${id}`,
qs: this._getQs({fields: 'first_name,last_name,profile_pic,locale,timezone,gender'}),
json: true
})
.then(body => {
if (body.error) return Promise.reject(body.error)
if (!cb) return body
cb(null, body)
})
.catch(err => {
if (!cb) return Promise.reject(err)
cb(err)
})
}

But I installed the package using npm. And the package code is different:

  getProfile (id, cb) {
    if (!cb) cb = Function.prototype

    request({
      method: 'GET',
      uri: `https://graph.facebook.com/v2.6/${id}`,
      qs: {
        fields: 'first_name,last_name,profile_pic,locale,timezone,gender',
        access_token: this.token
      },
      json: true
    }, (err, res, body) => {
      if (err) return cb(err)
      if (body.error) return cb(body.error)

      cb(null, body)
    })
  }

It seems that in the npp repository the outdated version
8f98af5#diff-168726dbe96b3ce427e7fedce31bb0bc

referral event handler is not working

Hi, I tried to use 'bot.on('referral', (payload, reply, actions) => {
console.log( ref info : ${payload.referral.ref})
}
then, through m.me/PAGE?ref=xxx, I entered the page messenger
but I couldn't track ref event.

I'd like to know how to solve the problem.

Temporary Error

Running version 2.3.0, started randomly getting the following error:

{ message: '(#1200) Temporary send message failure. Please try again later.',
type: 'OAuthException',
code: 1200,
error_subcode: 2018024,
fbtrace_id: 'FTsr5khdiKl' }

Any ideas on how I can fix this?

Bot throwing undefined 'forEach' on functions without parsed.entry[0].messaging[0]

TypeError: Cannot read property 'forEach' of undefined getting thrown when using

let getStartedPayloads = [
  {
    payload: 'click_on_welcome_button'
  }
]

bot.setGetStartedButton(getStartedPayloads, (err) => {
  if (err) console.log( err );
})

The issue is from line 183 on index.js. The _handleMessage method was looking for messages but this only exists in user sent messages.

Postback not triggered

Hi, I can't get the postback to work. My bot.on('message') is triggered and I am sending a generic template back in response.

var template_generic_example = {
       "attachment":
       {
           "type":"template",
           "payload":{
               "template_type":"generic",
               "elements":[
                   {
                       "title":"Welcome to Peter\'s Hats",
                       "item_url":"https://petersfancybrownhats.com",
                       "image_url":"https://petersfancybrownhats.com/company_image.png",
                       "subtitle":"We\'ve got the right hat for everyone.",
                       "buttons":[
                           {
                               "type":"web_url",
                               "url":"https://petersfancybrownhats.com",
                               "title":"View Website"
                           },
                           {
                               "type":"postback",
                               "title":"See more",
                               "payload":JSON.stringify({querystring:"abcd",start:0, end:3})
                           }              
                       ]
                   }
               ]
           }
       }
   }

It's the example template from the FB developer console.

I have a bot.on('postback') registered as well.

bot.on('postback', (payload, reply, actions) => 
{
  console.log("POSTBACK PAYLOAD");
  console.log(payload);
  reply({ text: 'hey!'}, (err, info) => {})
})

but it never triggers when I click on the "see more" button inside the Facebook Messenger.
Did I miss anything here?

Thanks a lot!

Support for multiple Facebook Pages

Hey, Is there any way to easily adapt the code so it can handle multiple Facebook Pages (Multiple Tokens) using the "same middleware" / incoming port.

Thanks in advance.

Trying to get setGetStartedButton working

I've activated all webhooks on Facebook.

I'm trying to configure the Get Started Button but it's not working. Not button at all. Any idea?

bot.setGetStartedButton({
    "get_started":{
        "payload":"GET_STARTED_PAYLOAD"
    }
}, null);

Not getting any messages events on the server

Hi, I used your example and modified it to add an HTTPS server as well.
My webhook is verified and setup. My events contains messages in the list (I checked).. but every time I send a message from the messenger to the bot, I don't get anything on my nodejs server.

Any idea what I am missing?

Below is my server code.

'use strict'
var express = require('express');
var bodyParser = require('body-parser');
var https = require('https');
var http = require('http');
var fs = require('fs');
var stringify = require('json-stringify-safe');
const Bot = require('messenger-bot')

let bot = new Bot({
  token: 'XXXXXXX', //XXXX it out for posting here
  verify: 'XXXXXXX',
  app_secret: 'XXXXXXX'
})

bot.on('error', (err) => {
  console.log(err.message)
})

bot.on('message', (payload, reply) => {
  let text = payload.message.text

  bot.getProfile(payload.sender.id, (err, profile) => {
    if (err) throw err

    reply({ text }, (err) => {
      if (err) throw err

      console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
    })
  })
})

let app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}))

app.get('/botapi/myappname/messages', (req, res) => {
  return bot._verify(req, res)
})

app.post('/botapi/myappname/messages', (req, res) => {
    console.log("incoming message"); //Not getting anything here.
  bot._handleMessage(req.body)
  res.end(JSON.stringify({status: 'ok'}))
})

var credentials = {
  key: fs.readFileSync('./certs/privatekey.pem'),
  cert: fs.readFileSync('./certs/ca-bundle.crt'),
};
var server = https.createServer(credentials, app);
server.listen(443, function() {
    console.log('Server up on port 443');
});

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.