GithubHelp home page GithubHelp logo

botly's Introduction

Built with Grunt Build Status Test Coverage npm version Dependency Status devDependency Status npm downloads license NPM

Simple Facebook Messenger Platform Bot API

Install

npm i botly --save

Example

const express = require("express");
const bodyParser = require("body-parser");
const Botly = require("botly");
const botly = new Botly({
    accessToken: pageAccessToken, // page access token provided by facebook
    verifyToken: verificationToken, // needed when using express - the verification token you provided when defining the webhook in facebook
    webHookPath: yourWebHookPath, // defaults to "/",
    notificationType: Botly.CONST.REGULAR, // already the default (optional)
    FB_URL: 'https://graph.facebook.com/v2.6/' // this is the default - allows overriding for testing purposes
});

botly.on("message", (senderId, message, data) => {
    let text = `echo: ${data.text}`;

    botly.sendText({
      id: senderId,
      text: text
    });
});

const app = express();
app.use(bodyParser.json({
    verify: botly.getVerifySignature(process.env.APP_SECRET) //allow signature verification based on the app secret
}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/webhook", botly.router());
app.listen(3000);

You can also clone the repository and run a complete bot example from the example folder.

API

send (options[, callback])

botly.send({
    id: userId,
    message: {text: "Hi There!"}
}, function (err, data) {
        //log it
});

upload (options[, callback])

botly.upload({
    type: Botly.CONST.ATTACHMENT_TYPE.IMAGE,
    payload: {url: "http://example.com/image.png"}
}, (err, data) => {
    //save data.attachment_id
});

sendText (options[, callback])

botly.sendText({id: userId, text: "Hi There!"}, function (err, data) {
        //log it
});

sendAttachment (options[, callback])

Also supports options.filedata = '@/tmp/receipt.pdf'.

botly.sendAttachment({
    id: userId,
    type: Botly.CONST.ATTACHMENT_TYPE.IMAGE,
    payload: {url: "http://example.com/image.png"}
}, (err, data) => {
        //log it
});

sendImage (options[, callback])

botly.sendImage({id: userId, url: "http://example.com/image.png"}, (err, data) => {
        //log it
});

sendButtons (options[, callback])

let buttons = [];
buttons.push(botly.createWebURLButton("Go to Askrround", "http://askrround.com"));
buttons.push(botly.createPostbackButton("Continue", "continue"));
botly.sendButtons({id: userId, text: "What do you want to do next?", buttons: buttons}
    , (err, data) => {
        //log it
});

sendGeneric (options[, callback])

let buttons = [];
buttons.push(botly.createWebURLButton("Go to Askrround", "http://askrround.com"));
buttons.push(botly.createPostbackButton("Continue", "continue"));
let element = {
  title: "What do you want to do next?",
  item_url: "http://example.com",
  image_url: "http://example.com/image.png",
  subtitle: "Choose now!",
  buttons: buttons
}
botly.sendGeneric({id: userId, elements: element, aspectRatio: Botly.CONST.IMAGE_ASPECT_RATIO.HORIZONTAL}, (err, data) => {
    console.log("send generic cb:", err, data);
});

sendList (options[, callback])

const element = botly.createListElement({
    title: 'First Element',
    image_url: 'https://peterssendreceiveapp.ngrok.io/img/collection.png',
    subtitle: 'subtitle text',
    buttons: [
        {title: 'Payload Button', payload: 'first_element'},
    ],
    default_action: {
        'url': 'https://peterssendreceiveapp.ngrok.io/shop_collection',
    }
});
const element2 = botly.createListElement({
    title: 'Other Element',
    image_url: 'https://peterssendreceiveapp.ngrok.io/img/collection.png',
    subtitle: 'even more subtitle',
    buttons: [
        {title: "Go to Askrround", url: "http://askrround.com"},
    ],
    default_action: {
        'url': 'https://peterssendreceiveapp.ngrok.io/shop_collection',
    }
});
botly.sendList({id: sender, elements: [element, element2], buttons: botly.createPostbackButton('More Plans', 'MORE_PLANS'), top_element_style: Botly.CONST.TOP_ELEMENT_STYLE.LARGE},function (err, data) {
      console.log('send list cb:', err, data);
});

sendAction (options[, callback])

botly.sendAction({id: userId, action: Botly.CONST.ACTION_TYPES.TYPING_ON}, (err, data) => {
        //log it
});

sendReceipt (options[, callback])

let payload = {
    "recipient_name": "Stephane Crozatier",
    "order_number": "12345678902",
    "currency": "USD",
    "payment_method": "Visa 2345",
    "order_url": "http://petersapparel.parseapp.com/order?order_id=123456",
    "timestamp": "1428444852",
    "elements": [
        {
            "title": "Classic White T-Shirt",
            "subtitle": "100% Soft and Luxurious Cotton",
            "quantity": 2,
            "price": 50,
            "currency": "USD",
            "image_url": "http://petersapparel.parseapp.com/img/whiteshirt.png"
        },
        {
            "title": "Classic Gray T-Shirt",
            "subtitle": "100% Soft and Luxurious Cotton",
            "quantity": 1,
            "price": 25,
            "currency": "USD",
            "image_url": "http://petersapparel.parseapp.com/img/grayshirt.png"
        }
    ],
    "address": {
        "street_1": "1 Hacker Way",
        "street_2": "",
        "city": "Menlo Park",
        "postal_code": "94025",
        "state": "CA",
        "country": "US"
    },
    "summary": {
        "subtotal": 75.00,
        "shipping_cost": 4.95,
        "total_tax": 6.19,
        "total_cost": 56.14
    },
    "adjustments": [
        {
            "name": "New Customer Discount",
            "amount": 20
        },
        {
            "name": "$10 Off Coupon",
            "amount": 10
        }
    ]
};
botly.sendReceipt({id: sender, payload: payload}, function (err, data) {
    console.log("send generic cb:", err, data);
});

setGetStarted (options[, callback])

botly.setGetStarted({pageId: "myPage", payload: "GET_STARTED_CLICKED"}, (err, body) => {
    //log it
});

setGreetingText (options[, callback])

botly.setGreetingText({
    pageId: "myPage",
     greeting: [{
           "locale":"default",
           "text":"Hello!"
       }, {
           "locale":"en_US",
           "text":"Timeless apparel for the masses."
   }]}, (err, body) => {
    //log it
});

setTargetAudience (options[, callback])

botly.setTargetAudience({
    pageId: "myPage",
    audience: {
         "audience_type":"custom",
         "countries":{
             "whitelist":["US", "CA"]
         }
     }}, (err, body) => {
    //log it
});

setWhitelist (options[, callback])

botly.setWhitelist({whiteList: ["https://askhaley.com"]}, (err, body) => {
    //log it
});

setPersistentMenu (options[, callback])

botly.setPersistentMenu({
    pageId: "myPage", 
    menu: [
            {
               "locale":"default",
               "composer_input_disabled":true,
               "call_to_actions":[
                 {
                   "title":"My Account",
                   "type":"nested",
                   "call_to_actions":[
                     {
                       "title":"Pay Bill",
                       "type":"postback",
                       "payload":"PAYBILL_PAYLOAD"
                     },
                     {
                       "title":"History",
                       "type":"postback",
                       "payload":"HISTORY_PAYLOAD"
                     },
                     {
                       "title":"Contact Info",
                       "type":"postback",
                       "payload":"CONTACT_INFO_PAYLOAD"
                     }
                   ]
                 },
                 {
                   "type":"web_url",
                   "title":"Latest News",
                   "url":"http://petershats.parseapp.com/hat-news",
                   "webview_height_ratio":"full"
                 }
               ]
             },
             {
               "locale":"zh_CN",
               "composer_input_disabled":false
             }
           ]}, (err, body) => {
    //log it
});

removePersistentMenu (options[, callback])

botly.removePersistentMenu(
    {
        pageId: "myPage",
    }, 
    (err, body) => {
        //log it
    });

getUserProfile (options[, callback])

Used to retrieve basic profile details by user page-scoped ID (PSID). You can pass the userID directly, in which case a default set of fields (first_name, last_name, profile_pic) are requested.

Also supports passing an object as

const options = {
    id: userId,
    fields: [
        Botly.CONST.USER_PROFILE_FIELD.FIRST_NAME,
        Botly.CONST.USER_PROFILE_FIELD.LAST_NAME
    ],
    accessToken: OTHER_TOKEN
}

botly.getUserProfile(options, function (err, info) {
    //cache it
});

or

botly.getUserProfile(userId, function (err, info) {
    //cache it
});

getPSID (accountLinkingToken[, callback])

Used to retrieve the user page-scoped ID (PSID) during the linking flow. Also supports passing an object as {token: accountLinkingToken, accessToken: OTHER_TOKEN}

botly.getUserProfile(accountLinkingToken, function (err, info) {
    //cache it
});

createWebURLButton (title, url[, heightRatio][, supportExtension][, fallbackURL][, disableShare])

createAccountLinkButton (url)

createPostbackButton (title, payload)

createShareButton ()

createQuickReply (title, payload[, imageURL])

sendAttachment and sendText both support optional quick_replies

createShareLocation ()

share location quick reply

createListElement (options)

Will create a list element. default_action will be added web_url type, and will create button according to properties (url means web_url and payload means postback)

createButtonTemplate (text, buttons)

Where buttons can be a single button or an array of buttons.

createGenericTemplate (elements[, aspectRatio])

Where elements can be a single element or an array of elements. and aspectRatio defaults to horizontal

createListTemplate (options)

Where options has bottons and elements - an array will be created automatically if a single item was passed.

handleMessage (req)

If you are not using express, you can use this function to parse the request from facebook in order to generate the proper events. req should have a body property.

Events

botly.on("message", (sender, message, data) => {
    /**
     * where data can be a text message or an attachment
     * data = {
     *   text: "text entered by user"
     * }
     * OR
     * data = {
     *   attachments: {
     *       image: ["imageURL1", "imageURL2"],
     *       video: ["videoURL"],
     *       audio: ["audioURL1"],
     *       location: [{coordinates}]
     *   }
     * }
     */
});

botly.on("postback", (sender, message, postback, ref) => {
    /**
     * where postback is the postback payload
     * and ref will arrive if m.me params were passed on a get started button (if defined)
     */
});

botly.on("delivery", (sender, message, mids) => {
    /**
     * where mids is an array of mids
     */
});

botly.on("optin", (sender, message, optin) => {
    /**
     * where optin is the ref pass through param
     */
});

botly.on("error", (ex) => {
    /* handle exceptions */
});

botly.on("sent", (to, message) => {
    /* track it */
});

botly.on("echo", (sender, message, content, recipient) => {
    /* track it */
});

botly.on("account_link",  (sender, message, link) => {
     /**
      * where link is the the object containing the status and authorization code
      */
});
botly.on("referral",  (sender, message, ref) => {
     /**
      * where ref is the data in the m.me param
      */
});

Change Log

version 1.5.0

  • added required messaging_type parameter when sending message
  • added the ability to override the FB_URL for testing purposes
  • added getVerifySignature(APP_SECRET) function to allow signature verification - provide the result to bodyParser.json({verify})

version 1.4.0

  • support version 1.4 of messenger api
  • new setPersistentMenu API aligned with v1.4
  • added setGreetingText, setAccountLinkingURL, setTargetAudience API
  • aligned all thread settings to the new profile API
  • added support for filedata upload in the sendAttachment
  • added support for the new upload attachment API,
  • support for new image_aspect_ratio in generic template

version 1.3.0

  • support version 1.3 of messenger including the new list template
  • support for referral params on m.me links

version 1.2.0

  • added support for webview height in web url button
  • added support setWhitelist for webview items
  • added createShare button
  • added support for location share quick reply
  • added imageURL to quick reply

version 1.1.6

  • Send 403 status code when verify token is invalid

version 1.1.5

  • fixed duplicate messages on echo
  • added echo event support

version 1.1.4

  • added support for account linking functionality (event, getPSID)
  • added ability to override accessToken on all APIs for multiple pages support

version 1.1.0

  • added support for sender actions using sendAction (mark seen/ typing on/ typing off)

version 1.0.3

  • added send event - useful for tracking

version 1.0.1

  • quick replies are considered as postback and not regular message

version 1.0.0

  • removed createTemplate function - was too verbose
  • moved to object parameters - too many parameters
  • added support for quick replies
  • add support for persistent menu
  • added support for audio/video/file attachments
  • renamed setWelcomeScreen to setGetStarted since no longer supported by facebook.

botly's People

Contributors

etiennea avatar freeworlder avatar matmar10 avatar miki2826 avatar sheksushant avatar umnagendra 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

botly's Issues

Handle FB User Profile API changes to default profile fields

With the launch of Graph API v3.1, Facebook has announced that the User Profile API will henceforth only return name, first_name, last_name, and profile_pic fields by default.

Access to additional profile fields (locale, timezone, gender) are denied by default unless apps request and get additional permissions.

In botly, the getUserProfile() function currently requests for first_name, last_name, profile_pic, locale, timezone, and gender fields explicitly. Due to the above changes by Facebook, this API request from botly now fails for all new apps (until they request additional permissions), and soon for existing apps too.

Can we have the getUserProfile() function accept the set of fields as an argument, so apps using botly can decide (based on their needs) what fields to request in the facebook API?

(We can make the function signature change non-breaking by also handling an undefined fields argument to simply request for default profile fields)

Advice for keeping the templates in different modules ?

Was thinking how to better organise my code and keep the menus in different files so I don't clutter the main app.js I can require but not sure how to go about it since they require lots of information from the main app.js ? Anyone got an example ?
Should I pass everything I need to return mainMenu(); ? like return mainMenu(botly,Botly,sender) ?

message after postback.?

In Short.. I am trying to save(in var) a message user sends me after a payload.

Longer Version..
Suppose a user clicks on the menu where he is supposed to tell me his/her phone number.
I get a payload "send_number"
Now i want to save the number to a variable.

How do i do this?
the message event takes in any message !```

botly.on("message", (sender, message, data) => {

});

Postback Persistent Menu Connection error

I am getting this connection error when I click on the postback call from the persistent menu, here is my menu code:

 setMenu(pageId) {
    this.setPersistentMenu({
      pageId: pageId,
      menu: [
            {
               "locale":"default",
               "composer_input_disabled":false,
               "call_to_actions":[
                  {
                    "title": "ℹ️  Menu",
                    "type": "postback",
                    "payload": "MENU",
                  },
                  {
                    "title": '💬  Contact Us',
                    "type": "web_url",
                    "url": "https://m.me/jsapp",
                  },
               ]
             },
           ]
    }, (err, body) => {
      console.log("MENU " + JSON.stringify(err))
      console.log("MENU " + JSON.stringify(body))
    })
  }

At first it works fine but after a while it keeps sending me this error. Anybody else had this issue?

try_again

No error log.

Botly Conversation

Is there a sample of conversation with bot / chain message using Botly? Cant find it in examples folder

For example
it will ask my name, save the value i entered then trigger next question and so on.

Implement file upload functions?

Do you have plan implementing file upload functions?
For now it only accept attachment from payload.
it would be great if botly can upload attachment from local files or streaming from other libs such as node-webshot.

curl  \
  -F recipient='{"id":"USER_ID"}' \
  -F message='{"attachment":{"type":"file", "payload":{}}}' \
  -F filedata=@/tmp/receipt.pdf \
  "https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN" 

Cannot find module grpc

Any idea why I am getting this error on Heroku:

Error: Cannot find module '/app/node_modules/grpc/src/node/extension_binary/grpc_node.node'
2017-03-16T22:45:46.206460+00:00 app[web.1]: at Function.Module._resolveFilename (module.js:469:15)
2017-03-16T22:45:46.206461+00:00 app[web.1]: at Function.Module._load (module.js:417:25)
2017-03-16T22:45:46.206461+00:00 app[web.1]: at Module.require (module.js:497:17)
2017-03-16T22:45:46.206462+00:00 app[web.1]: at require (internal/module.js:20:19)
2017-03-16T22:45:46.206463+00:00 app[web.1]: at Object. (/app/node_modules/grpc/src/node/src/grpc_extension.js:38:15)
2017-03-16T22:45:46.206463+00:00 app[web.1]: at Module._compile (module.js:570:32)
2017-03-16T22:45:46.206464+00:00 app[web.1]: at Object.Module._extensions..js (module.js:579:10)
2017-03-16T22:45:46.206464+00:00 app[web.1]: at Module.load (module.js:487:32)
2017-03-16T22:45:46.206465+00:00 app[web.1]: at tryModuleLoad (module.js:446:12)
2017-03-16T22:45:46.206466+00:00 app[web.1]: at Function.Module._load (module.js:438:3)
2017-03-16T22:45:56.884962+00:00 app[web.1]: module.js:471
2017-03-16T22:45:56.884973+00:00 app[web.1]: throw err;
2017-03-16T22:45:56.884974+00:00 app[web.1]: ^

problem with setPersistentMenu

When I first tried to add it, persistent menu was shown input text box disappeared. So I remove it but it's still there. Do you know why?

Here is the code I used:

botly.setPersistentMenu({
        pageId: fb_page_id, 
        menu: [
            {
            "locale":"default",
            "composer_input_disabled":true,
            "call_to_actions":[
                {
                "title":"My Account",
                "type":"nested",
                "call_to_actions":[
                    {
                    "title":"Pay Bill",
                    "type":"postback",
                    "payload":"PAYBILL_PAYLOAD"
                    },
                    {
                    "title":"History",
                    "type":"postback",
                    "payload":"HISTORY_PAYLOAD"
                    },
                    {
                    "title":"Contact Info",
                    "type":"postback",
                    "payload":"CONTACT_INFO_PAYLOAD"
                    }
                ]
                },
                {
                "type":"web_url",
                "title":"Latest News",
                "url":"http://petershats.parseapp.com/hat-news",
                "webview_height_ratio":"full"
                }
            ]
            },
            {
                "locale":"zh_CN",
                "composer_input_disabled":false
            }
    ]}, (err, body) => {
        //log it
    });

One bot for multiple pages

Hi,

My use case involves one single bot taking care of multiple pages. I needed to get it done quickly so I made my own fork and added this function to it.This way I can change the access token based on the pageID that I get on every message.

I was wondering if a similar feature is already provided by botly and if so, what the proper way to switch tokens?

Thanks!

Breaking Changes to the API: "messaging_type" Property Required

Any plans on making this fix ?

"Breaking Change Notice - messaging_type Property Required (Effective May 7, 2018)

As of the release of Messenger Platform v2.2, we are requesting developers to include the messaging_type property in all message sends.

Beginning May 7, 2018, this property will be required for all message sends. After this date, message sends that do not include messaging_type will return an error and not be delivered.

For more information on the messaging_type property, see Sending Messages - Messaging Types below."

Please see here: https://developers.facebook.com/docs/messenger-platform/reference/send-api/

Unable to Run Example on heroku

my code is :

const express = require("express");
const Botly = require("botly");
//const startup = require('./staticstuff');

const pageAccessToken =  'page_access_token_from_facebook'
const verificationToken = 'some_text';
const botly = new Botly({
   accessToken: pageAccessToken, //page access token provided by facebook
    verifyToken: verificationToken, //needed when using express - the verification token you provided when defining the webhook in facebook
    webHookPath: '/', //defaults to "/",
    notificationType: Botly.CONST.REGULAR //already the default (optional),
});

botly.on("message", (senderId, message, data) => {
    let text = `echo: ${data.text}`;

    botly.sendText({
      id: senderId,
      text: text
    });
});


const app = express();
app.use("/webhook", botly.router());
app.listen(process.env.PORT || 3000);

Webhook is successfully verified ! but.....
WHEN I SEND A MESSAGE ON THE BOT... THIS HAPPENS
Error from heroku Logs :

2017-08-09T22:37:59.865092+00:00 app[web.1]: SyntaxError: Unexpected token u in JSON at position 0 2017-08-09T22:37:59.865108+00:00 app[web.1]: at Object.parse (native) 2017-08-09T22:37:59.865109+00:00 app[web.1]: at _clone (/app/node_modules/botly/lib/Botly.js:600:17) 2017-08-09T22:37:59.865123+00:00 app[web.1]: at Botly.handleMessage (/app/node_modules/botly/lib/Botly.js:511:18) 2017-08-09T22:37:59.865123+00:00 app[web.1]: at router.post.ex (/app/node_modules/botly/lib/Botly.js:99:18) 2017-08-09T22:37:59.865129+00:00 app[web.1]: at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) 2017-08-09T22:37:59.865129+00:00 app[web.1]: at next (/app/node_modules/express/lib/router/route.js:137:13) 2017-08-09T22:37:59.865130+00:00 app[web.1]: at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3) 2017-08-09T22:37:59.865130+00:00 app[web.1]: at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5) 2017-08-09T22:37:59.865131+00:00 app[web.1]: at /app/node_modules/express/lib/router/index.js:281:22 2017-08-09T22:37:59.865131+00:00 app[web.1]: at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12)

Unexpected token u in JSON at position 0

I get this error when im trying to message the bot

SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse ()
at _clone (somepath\BotlyBot\node_modules\botly\lib\Botly.js:575:17)
at Botly.handleMessage (somepath\BotlyBot\node_modules\botly\lib\Botly.js:494:18)
at router.post (somepath\BotlyBot\node_modules\botly\lib\Botly.js:99:18)
at Layer.handle [as handle_request] (somepath\BotlyBot\node_modules\express\lib\router\layer.
js:95:5)
at next (somepath\BotlyBot\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (somepath\BotlyBot\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (somepath\BotlyBot\node_modules\express\lib\router\layer.
js:95:5)
at somepath\BotlyBot\node_modules\express\lib\router\index.js:281:22
at Function.process_params (somepath\BotlyBot\node_modules\express\lib\router\index.js:335:12
)

Mandatory TypeScript Question

Hey, came across this today when searching NPM, I'm going to give botly a try. Do you have plans of supporting TypeScript? I think the FB Messenger API is simple enough not to need it, but just asking in case there are some plans to.

How do we set sender actions?

Hello, this is my first bot and I would like to provide a typing indicator to allow users to see whether the message they sent is being processed or not.

I took a look at the Facebook Send API reference and wrote the following code:

botly.send({recipient: {id: senderId}, sender_action: "typing_on"}, function(err, data) { console.log(data); });

I am getting the following console output:

{ error: { message: '(#100) Must send either message or state', type: 'OAuthException', code: 100, error_subcode: 2018015, fbtrace_id: 'H1BxIEyCbKk' } }

Any help with this will be immensely appreciated. Thank you!

Unable to setup setGreetingText.

I put PageID in a variable, then here is my code:

botly.setGreetingText({
    pageId: fb_page_id,
    "greeting":[
        {
        "locale":"default",
        "text":"Hello!"
        }, {
        "locale":"en_us",
        "text":"Timeless apparel for the masses."
        }
    ]}, (err, body) => {
    //log it
});

Any help would be really appreciated. Thanks.

pass params through postback button

Hello botly users,

I have a question, how could i pass parameters through a postback button ?

I explain my issue : i have a carousel that is generated by a loop from a mongoDB search (i search from tags and my carousel is generated by the number of docs that contain this tag), on this carousel i have a button to view it on webview and one else that will be send to a payload.

This payload is called "Add to favorites" but i have a problem, i want to pass the element parameter (so it's something like docs[number] because it's an array of elements) from the carousel to this payload and others (like show my favorites etc) but i can't or at least i don't know how. Anyone has an answer ? 😞

My english is really bad and i'm sorry for that, if you need more explaination or maybe screens or something else, feel free to tell me !

error: TypeError: Cannot read property 'forEach' of undefined

Hello , got this message error :

error: TypeError: Cannot read property 'forEach' of undefined at Botly.body.entry.forEach.entry (/data/web/nodjs-botnik/web/node_modules/botly/lib/Botly.js:515:24) at Array.forEach (<anonymous>) at Botly.handleMessage (/data/web/nodjs-botnik/web/node_modules/botly/lib/Botly.js:514:16) at router.post (/data/web/nodjs-botnik/web/node_modules/botly/lib/Botly.js:99:18) at Layer.handle [as handle_request] (/data/web/nodjs-botnik/web/node_modules/express/lib/router/layer.js:95:5) at next (/data/web/nodjs-botnik/web/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/data/web/nodjs-botnik/web/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/data/web/nodjs-botnik/web/node_modules/express/lib/router/layer.js:95:5) at /data/web/nodjs-botnik/web/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/data/web/nodjs-botnik/web/node_modules/express/lib/router/index.js:335:12)

Don't really understand why... This error come anytime i interact with the Chatbot, but this one is working anyway. It don't shut down the server but it's quite annoying to see an error message like this.
Hope someone could have an answer ! 👍

question

hey - just found this here. very interesting and good to see you implement the full FB APIs.

do you plan to add anything for conversations etc? like botkit and msbot framework?

setGetStarted working problems?

After I use setGetStarted as it showed in the readme, I can't figure it out, why not working for me?

The Readme button is shown, but on action it won't disappear and change back to text input.

botly.setGetStarted({pageId: process.env.PAGE_ID, payload: 'GET_STARTED_CLICKED'}, function (err, body) {
        console.log("welcome cb:", err, body);
});

X-Hub-Signature configuration missing

Hi,
I miss the configuration for custom and pre-configurable headers like X-Hub-Signature.

The HTTP request will contain an X-Hub-Signature header which contains the SHA1 signature of the request payload, using the app secret as the key, and prefixed with sha1=. Your callback endpoint can verify this signature to validate the integrity and origin of the payload

setGreetingText missing from readme

Hello, setGreetingText is exists on the botly.js, but not mentioned in the readme.

AND if I use it, like this:

botly.setGreetingText({pageId: process.env.PAGE_ID, text: 'Hi my name is ...!'}, function (err, body) {
        console.log("greeting cb:", err, body);
    });

... nothing happend.

List Template doesn't owner

in Botly.js @ line 474 within method Botly.prototype.createListTemplate
the code top_element_style: TOP_ELEMENT_STYLE.LARGE || options.top_element_style
should be changed to
top_element_style: options.top_element_style || TOP_ELEMENT_STYLE.LARGE

otherwise it is always the style is always set to large

createShareButton() not working

I am trying to create a share button like this:

                let buttons = [];
    buttons.push(botly.create());
    botly.sendButtons({
        id: senderId,
        text: "some text",
        buttons: buttons
    }, ((err, resp) => {
        console.log("Err: ", JSON.stringify(err));
        console.log("resp: ", JSON.stringify(resp));
    }));

But nothing shows up and on console.log shows this:

Err:  null
resp:  {"error":{"message":"(#100) Invalid button type","type":"OAuthException","code":100,"error_subcode":2018037,"fbtrace_id":"FhJ0FhIk6C2"}}

Hapi.js botly

I have made a plugin for Hapi.js to work with botly.
Is it OK for you that I publish it to NPM?

Stefan

TypeError: Cannot read property 'forEach' of undefined

I get this error at every Payload.

TypeError: Cannot read property 'forEach' of undefined
    at Botly.body.entry.forEach.entry (/Users/sushantshekhar/Work/BOTUPON/bookingbotdemo/node_modules/botly/lib/Botly.js:515:24)
    at Array.forEach (native)
    at Botly.handleMessage (/Users/sushantshekhar/Work/BOTUPON/bookingbotdemo/node_modules/botly/lib/Botly.js:514:16)
    at router.post (/Users/sushantshekhar/Work/BOTUPON/bookingbotdemo/node_modules/botly/lib/Botly.js:99:18)
    at Layer.handle [as handle_request] (/Users/sushantshekhar/Work/BOTUPON/bookingbotdemo/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/sushantshekhar/Work/BOTUPON/bookingbotdemo/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/sushantshekhar/Work/BOTUPON/bookingbotdemo/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/sushantshekhar/Work/BOTUPON/bookingbotdemo/node_modules/express/lib/router/layer.js:95:5)
    at /Users/sushantshekhar/Work/BOTUPON/bookingbotdemo/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/sushantshekhar/Work/BOTUPON/bookingbotdemo/node_modules/express/lib/router/index.js:335:12)

Unexpected token u in JSON at position 0

Hi, I just trying the sample code and keep getting the following error when I try to sent message to the bot. Could not figure out what caused it.

SyntaxError: Unexpected token u in JSON at position 0
at Object.parse (native)
at _clone (/opt/bitnami/apps/yeepee-messenger-bot/node_modules/botly/lib/Botly.js:569:17)
at Botly.handleMessage (/opt/bitnami/apps/yeepee-messenger-bot/node_modules/botly/lib/Botly.js:488:18)
at router.post.ex (/opt/bitnami/apps/yeepee-messenger-bot/node_modules/botly/lib/Botly.js:94:18)
at Layer.handle [as handle_request] (/opt/bitnami/apps/yeepee-messenger-bot/node_modules/express/lib/router/layer.js:95:5)
at next (/opt/bitnami/apps/yeepee-messenger-bot/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/opt/bitnami/apps/yeepee-messenger-bot/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/opt/bitnami/apps/yeepee-messenger-bot/node_modules/express/lib/router/layer.js:95:5)
at /opt/bitnami/apps/yeepee-messenger-bot/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/opt/bitnami/apps/yeepee-messenger-bot/node_modules/express/lib/router/index.js:330:12)

FB_URL hardcoded - can it be configurable for better testability?

PROBLEM

In Botly.js, the URL to graph.facebook.com is hard-coded.

const FB_URL = 'https://graph.facebook.com/v2.6/';
const FB_MESSENGER_URL = `${FB_URL}/me/messages`;

Apps (such as mine) using this module are not able to do functional automation testing using a facebook simulator because the hardcoded URLs always force all interactions towards graph.facebook.com.

PROPOSAL

Without breaking compatibility, can we optionally override this URL using process.env?
Something like this:

const FB_URL = process.env.FB_URL || 'https://graph.facebook.com/v2.6/';

This way, apps that want to plug in a simulator for tests can do so without breaking other apps that are already using this module?

I have the change ready and working. I can raise a PR for this.

Wrong parameter in demo example causes TypeError

Steps to reproduce:

  • Follow intro demo instructions

Actual behavior:

TypeError: Cannot assign to read only property 'message' of 1214502681935759
   at Botly.router.Botly.getPSID.Botly.getUserProfile.Botly.setGetStarted.Botly.setPersistentMenu.Botly.send.Botly.sendAction.Botly.sendText (/app/node_modules/botly/lib/Botly.js:245:21)
   at Botly.<anonymous> (/app/index.js:24:11)
   at Botly.emit (events.js:188:7)
   at Botly._handleUserMessage (/app/node_modules/botly/lib/Botly.js:386:14)
   at emitThree (events.js:110:13)
   at Botly.<anonymous> (/app/node_modules/botly/lib/Botly.js:334:32)
   at Array.forEach (native)
   at Botly.<anonymous> (/app/node_modules/botly/lib/Botly.js:329:25)
   at Botly.router.Botly.getPSID.Botly.getUserProfile.Botly.setGetStarted.Botly.setPersistentMenu.Botly.send.Botly.sendAction.Botly.handleMessage.body.entry.forEach [as handleMessage] (/app/node_modules/botly/lib/Botly.js:328:16)
   at Array.forEach (native)
   at=info method=POST path="/webhook/" host=lit-fjord-55925.herokuapp.com request_id=3450cd2d-9b2f-4485-9e1b-4210842b104a fwd="173.252.88.183" dyno=web.1 connect=1ms service=4ms status=200 bytes=196
   at Botly.<anonymous> (/app/index.js:24:11)
TypeError: Cannot assign to read only property 'message' of 1214502681935759
   at Botly.router.Botly.getPSID.Botly.getUserProfile.Botly.setGetStarted.Botly.setPersistentMenu.Botly.send.Botly.sendAction.Botly.sendText (/app/node_modules/botly/lib/Botly.js:245:21)
   at Botly.emit (events.js:188:7)
   at Botly.<anonymous> (/app/node_modules/botly/lib/Botly.js:334:32)
   at emitThree (events.js:110:13)
   at Botly._handleUserMessage (/app/node_modules/botly/lib/Botly.js:386:14)
   at Botly.<anonymous> (/app/node_modules/botly/lib/Botly.js:329:25)
   at Array.forEach (native)
   at Array.forEach (native)
   at Botly.router.Botly.getPSID.Botly.getUserProfile.Botly.setGetStarted.Botly.setPersistentMenu.Botly.send.Botly.sendAction.Botly.handleMessage.body.entry.forEach [as handleMessage] (/app/node_modules/botly/lib/Botly.js:328:16)
  • Expected behavior: acks Facebook callback without erro

Due to invalid argument (should be object)

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.